changeset 16991:da335cb02480

Merge
author prr
date Mon, 10 Apr 2017 08:31:37 -0700
parents 204b01546b68 d263a4cb0621
children c69e8ca0008e
files src/java.base/share/classes/java/lang/reflect/Layer.java src/java.base/share/classes/java/lang/reflect/LayerInstantiationException.java src/java.base/share/classes/java/lang/reflect/Module.java src/java.base/share/classes/java/lang/reflect/WeakPairMap.java src/java.base/share/classes/jdk/internal/misc/JavaLangReflectModuleAccess.java src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFBaseJPEGCompressor.java src/java.desktop/share/classes/java/awt/color/ICC_Profile.java src/java.desktop/share/classes/javax/swing/text/PlainView.java test/java/lang/reflect/Layer/BasicLayerTest.java test/java/lang/reflect/Layer/LayerAndLoadersTest.java test/java/lang/reflect/Layer/LayerControllerTest.java test/java/lang/reflect/Layer/layertest/Test.java test/java/lang/reflect/Layer/src/m1/module-info.java test/java/lang/reflect/Layer/src/m1/p/Main.java test/java/lang/reflect/Layer/src/m1/p/Service.java test/java/lang/reflect/Layer/src/m2/module-info.java test/java/lang/reflect/Layer/src/m2/q/Hello.java test/java/lang/reflect/Layer/src/m3/module-info.java test/java/lang/reflect/Layer/src/m3/w/Hello.java test/java/lang/reflect/Layer/src/m4/impl/ServiceImpl.java test/java/lang/reflect/Layer/src/m4/module-info.java test/java/lang/reflect/Module/AddExportsTest.java test/java/lang/reflect/Module/AnnotationsTest.java test/java/lang/reflect/Module/BasicModuleTest.java test/java/lang/reflect/Module/WithSecurityManager.java test/java/lang/reflect/Module/access/AccessTest.java test/java/lang/reflect/Module/access/src/target/module-info.java test/java/lang/reflect/Module/access/src/target/p1/Helper.java test/java/lang/reflect/Module/access/src/target/p1/Public.java test/java/lang/reflect/Module/access/src/target/p2/NonPublic.java test/java/lang/reflect/Module/access/src/target/q1/Public.java test/java/lang/reflect/Module/access/src/target/q2/NonPublic.java test/java/lang/reflect/Module/access/src/test/module-info.java test/java/lang/reflect/Module/access/src/test/test/Main.java test/java/lang/reflect/Module/addXXX/Driver.java test/java/lang/reflect/Module/addXXX/m1/module-info.java test/java/lang/reflect/Module/addXXX/m1/p1/C.java test/java/lang/reflect/Module/addXXX/m2/module-info.java test/java/lang/reflect/Module/addXXX/m2/p2/C.java test/java/lang/reflect/Module/addXXX/m2/p2/internal/C.java test/java/lang/reflect/Module/addXXX/m3/module-info.java test/java/lang/reflect/Module/addXXX/m3/p3/C.java test/java/lang/reflect/Module/addXXX/m4/module-info.java test/java/lang/reflect/Module/addXXX/m4/p4/C.java test/java/lang/reflect/Module/addXXX/test/module-info.java test/java/lang/reflect/Module/addXXX/test/test/C.java test/java/lang/reflect/Module/addXXX/test/test/Main.java test/java/lang/reflect/Module/addXXX/test/test/Service.java test/java/lang/reflect/Module/allow.policy test/java/lang/reflect/Module/annotation/Basic.java test/java/lang/reflect/Module/annotation/src/m/module-info.java test/java/lang/reflect/Module/annotation/src/m/p/annotation/Bar.java test/java/lang/reflect/Module/annotation/src/m/p/annotation/Baz.java test/java/lang/reflect/Module/annotation/src/m/p/annotation/Foo.java test/java/lang/reflect/WeakPairMap/Driver.java test/java/lang/reflect/WeakPairMap/java.base/java/lang/reflect/WeakPairMapTest.java
diffstat 952 files changed, 15300 insertions(+), 10807 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Mon Apr 10 16:20:40 2017 +0530
+++ b/.hgtags	Mon Apr 10 08:31:37 2017 -0700
@@ -405,3 +405,5 @@
 cac788454598b95d8b0153c021a7fae3cd7e6fda jdk-9+160
 09b92d3067a38ee07bc14efa336b14790c93f7e7 jdk-9+161
 f6bf027e88e9a4dd19f721001a7af00157af42c4 jdk-9+162
+50171f8c47961710cbf87aead6f03fa431d8d240 jdk-9+163
+6dea581453d7c0e767e3169cfec8b423a381e71d jdk-9+164
--- a/make/GenerateModuleSummary.gmk	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/GenerateModuleSummary.gmk	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
 include ModuleTools.gmk
 
 GENGRAPHS_DIR := $(IMAGES_OUTPUTDIR)/gengraphs
-SPEC_DOTFILES_DIR := $(IMAGES_OUTPUTDIR)/spec-dotfiles
+SPEC_DOTFILES_DIR := $(GENGRAPHS_DIR)/spec-dotfiles
 TOOLS_MODULE_SRCDIR := $(JDK_TOPDIR)/make/src/classes/build/tools/jigsaw
 
 $(GENGRAPHS_DIR)/jdk.dot: $(BUILD_JIGSAW_TOOLS)
--- a/make/ModuleTools.gmk	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/ModuleTools.gmk	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,9 @@
 # questions.
 #
 
-include $(SPEC)
-include MakeBase.gmk
+ifndef _MODULE_TOOLS_GMK
+_MODULE_TOOLS_GMK := 1
+
 include JavaCompilation.gmk
 
 TOOLS_CLASSES_DIR := $(BUILDTOOLS_OUTPUTDIR)/tools_jigsaw_classes
@@ -32,7 +33,7 @@
 # To avoid reevaluating the compilation setup for the tools each time this file
 # is included, the actual compilation is handled by CompileModuleTools.gmk. The
 # following trick is used to be able to declare a dependency on the built tools.
-BUILD_TOOLS_JDK := $(call SetupJavaCompilationCompileTarget, \
+BUILD_JIGSAW_TOOLS := $(call SetupJavaCompilationCompileTarget, \
     BUILD_JIGSAW_TOOLS, $(TOOLS_CLASSES_DIR))
 
 TOOL_GENGRAPHS := $(BUILD_JAVA) -esa -ea -cp $(TOOLS_CLASSES_DIR) \
@@ -47,3 +48,5 @@
     -cp $(TOOLS_CLASSES_DIR) \
     --add-exports java.base/jdk.internal.module=ALL-UNNAMED \
     build.tools.jigsaw.AddPackagesAttribute
+
+endif # _MODULE_TOOLS_GMK
--- a/make/data/tzdata/VERSION	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/data/tzdata/VERSION	Mon Apr 10 08:31:37 2017 -0700
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2017a
+tzdata2017b
--- a/make/data/tzdata/africa	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/data/tzdata/africa	Mon Apr 10 08:31:37 2017 -0700
@@ -443,18 +443,25 @@
 # See Africa/Johannesburg.
 
 # Liberia
-# From Paul Eggert (2006-03-22):
-# In 1972 Liberia was the last country to switch
-# from a UTC offset that was not a multiple of 15 or 20 minutes.
-# Howse reports that it was in honor of their president's birthday.
-# Shank & Pottenger report the date as May 1, whereas Howse reports Jan;
-# go with Shanks & Pottenger.
-# For Liberia before 1972, Shanks & Pottenger report -0:44, whereas Howse and
-# Whitman each report -0:44:30; go with the more precise figure.
+#
+# From Paul Eggert (2017-03-02):
+#
+# The Nautical Almanac for the Year 1970, p 264, is the source for -0:44:30.
+#
+# In 1972 Liberia was the last country to switch from a UTC offset
+# that was not a multiple of 15 or 20 minutes.  The 1972 change was on
+# 1972-01-07, according to an entry dated 1972-01-04 on p 330 of:
+# Presidential Papers: First year of the administration of
+# President William R. Tolbert, Jr., July 23, 1971-July 31, 1972.
+# Monrovia: Executive Mansion.
+#
+# Use the abbreviation "MMT" before 1972, as the more-accurate numeric
+# abbreviation "-004430" would be one byte over the POSIX limit.
+#
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Africa/Monrovia	-0:43:08 -	LMT	1882
 			-0:43:08 -	MMT	1919 Mar # Monrovia Mean Time
-			-0:44:30 -	-004430	1972 May
+			-0:44:30 -	MMT	1972 Jan 7 # approximately MMT
 			 0:00	-	GMT
 
 ###############################################################################
--- a/make/data/tzdata/iso3166.tab	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/data/tzdata/iso3166.tab	Mon Apr 10 08:31:37 2017 -0700
@@ -32,8 +32,8 @@
 # All text uses UTF-8 encoding.  The columns of the table are as follows:
 #
 # 1.  ISO 3166-1 alpha-2 country code, current as of
-#     ISO 3166-1 Newsletter VI-16 (2013-07-11).  See: Updates on ISO 3166
-#   http://www.iso.org/iso/home/standards/country_codes/updates_on_iso_3166.htm
+#     ISO 3166-1 N905 (2016-11-15).  See: Updates on ISO 3166-1
+#     http://isotc.iso.org/livelink/livelink/Open/16944257
 # 2.  The usual English name for the coded region,
 #     chosen so that alphabetic sorting of subsets produces helpful lists.
 #     This is not the same as the English name in the ISO 3166 tables.
--- a/make/data/tzdata/northamerica	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/data/tzdata/northamerica	Mon Apr 10 08:31:37 2017 -0700
@@ -3162,6 +3162,12 @@
 # http://www.vantbefinfo.com/changement-dheure-pas-pour-haiti/
 # http://news.anmwe.com/haiti-lheure-nationale-ne-sera-ni-avancee-ni-reculee-cette-annee/
 
+# From Steffen Thorsen (2017-03-12):
+# We have received 4 mails from different people telling that Haiti
+# has started DST again today, and this source seems to confirm that,
+# I have not been able to find a more authoritative source:
+# https://www.haitilibre.com/en/news-20319-haiti-notices-time-change-in-haiti.html
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Haiti	1983	only	-	May	8	0:00	1:00	D
 Rule	Haiti	1984	1987	-	Apr	lastSun	0:00	1:00	D
@@ -3174,6 +3180,8 @@
 Rule	Haiti	2005	2006	-	Oct	lastSun	0:00	0	S
 Rule	Haiti	2012	2015	-	Mar	Sun>=8	2:00	1:00	D
 Rule	Haiti	2012	2015	-	Nov	Sun>=1	2:00	0	S
+Rule	Haiti	2017	max	-	Mar	Sun>=8	2:00	1:00	D
+Rule	Haiti	2017	max	-	Nov	Sun>=1	2:00	0	S
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone America/Port-au-Prince -4:49:20 -	LMT	1890
 			-4:49	-	PPMT	1917 Jan 24 12:00 # P-a-P MT
--- a/make/mapfiles/libjava/mapfile-vers	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/mapfiles/libjava/mapfile-vers	Mon Apr 10 08:31:37 2017 -0700
@@ -273,12 +273,12 @@
                 Java_jdk_internal_misc_VM_getRuntimeArguments;
                 Java_jdk_internal_misc_VM_initialize;
 
-                Java_java_lang_reflect_Module_defineModule0;
-                Java_java_lang_reflect_Module_addReads0;
-                Java_java_lang_reflect_Module_addExports0;
-                Java_java_lang_reflect_Module_addExportsToAll0;
-                Java_java_lang_reflect_Module_addExportsToAllUnnamed0;
-                Java_java_lang_reflect_Module_addPackage0;
+                Java_java_lang_Module_defineModule0;
+                Java_java_lang_Module_addReads0;
+                Java_java_lang_Module_addExports0;
+                Java_java_lang_Module_addExportsToAll0;
+                Java_java_lang_Module_addExportsToAllUnnamed0;
+                Java_java_lang_Module_addPackage0;
 
 		Java_jdk_internal_loader_BootLoader_getSystemPackageLocation;
 		Java_jdk_internal_loader_BootLoader_getSystemPackageNames;
--- a/make/src/classes/build/tools/jigsaw/GenGraphs.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/make/src/classes/build/tools/jigsaw/GenGraphs.java	Mon Apr 10 08:31:37 2017 -0700
@@ -26,7 +26,6 @@
 package build.tools.jigsaw;
 
 import com.sun.tools.jdeps.ModuleDotGraph;
-import com.sun.tools.jdeps.ModuleDotGraph.DotGraphBuilder;
 
 import java.io.IOException;
 import java.lang.module.Configuration;
@@ -36,10 +35,15 @@
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
+import java.util.Properties;
 import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 
 /**
  * Generate the DOT file for a module graph for each module in the JDK
@@ -50,13 +54,19 @@
     public static void main(String[] args) throws Exception {
         Path dir = null;
         boolean spec = false;
+        Properties props = null;
         for (int i=0; i < args.length; i++) {
             String arg = args[i];
             if (arg.equals("--spec")) {
                 spec = true;
+            } else if (arg.equals("--dot-attributes")) {
+                if (i++ == args.length) {
+                    throw new IllegalArgumentException("Missing argument: --dot-attributes option");
+                }
+                props = new Properties();
+                props.load(Files.newInputStream(Paths.get(args[i])));
             } else if (arg.equals("--output")) {
-                i++;
-                dir = i < args.length ? Paths.get(args[i]) : null;
+                dir = ++i < args.length ? Paths.get(args[i]) : null;
             } else if (arg.startsWith("-")) {
                 throw new IllegalArgumentException("Invalid option: " + arg);
             }
@@ -67,11 +77,14 @@
             System.exit(1);
         }
 
-        // setup and configure the dot graph attributes
-        initDotGraphAttributes();
         Files.createDirectories(dir);
-
-        GenGraphs genGraphs = new GenGraphs(dir, spec);
+        ModuleGraphAttributes attributes;
+        if (props != null) {
+            attributes = new ModuleGraphAttributes(props);
+        } else {
+            attributes = new ModuleGraphAttributes();
+        }
+        GenGraphs genGraphs = new GenGraphs(dir, spec, attributes);
 
         // print dot file for each module
         Map<String, Configuration> configurations = new HashMap<>();
@@ -99,49 +112,149 @@
         genGraphs.genDotFiles(configurations);
     }
 
-    static void initDotGraphAttributes() {
-        int h = 1000;
-        DotGraphBuilder.weight("java.se", "java.sql.rowset", h * 10);
-        DotGraphBuilder.weight("java.sql.rowset", "java.sql", h * 10);
-        DotGraphBuilder.weight("java.sql", "java.xml", h * 10);
-        DotGraphBuilder.weight("java.xml", "java.base", h * 10);
+    /**
+     * Custom dot file attributes.
+     */
+    static class ModuleGraphAttributes implements ModuleDotGraph.Attributes {
+        static Map<String, String> DEFAULT_ATTRIBUTES = Map.of(
+            "ranksep", "0.6",
+            "fontsize", "12",
+            "fontcolor", BLACK,
+            "fontname", "DejaVuSans",
+            "arrowsize", "1",
+            "arrowwidth", "2",
+            "arrowcolor", DARK_GRAY,
+            // custom
+            "requiresMandatedColor", LIGHT_GRAY,
+            "javaSubgraphColor", ORANGE,
+            "jdkSubgraphColor", BLUE
+        );
 
-        DotGraphBuilder.sameRankNodes(Set.of("java.logging", "java.scripting", "java.xml"));
-        DotGraphBuilder.sameRankNodes(Set.of("java.sql"));
-        DotGraphBuilder.sameRankNodes(Set.of("java.compiler", "java.instrument"));
-        DotGraphBuilder.sameRankNodes(Set.of("java.desktop", "java.management"));
-        DotGraphBuilder.sameRankNodes(Set.of("java.corba", "java.xml.ws"));
-        DotGraphBuilder.sameRankNodes(Set.of("java.xml.bind", "java.xml.ws.annotation"));
-        DotGraphBuilder.setRankSep(0.7);
-        DotGraphBuilder.setFontSize(12);
-        DotGraphBuilder.setArrowSize(1);
-        DotGraphBuilder.setArrowWidth(2);
+        final Map<String, Integer> weights = new HashMap<>();
+        final List<Set<String>> ranks = new ArrayList<>();
+        final Map<String, String> attrs;
+        ModuleGraphAttributes(Map<String, String> attrs) {
+            int h = 1000;
+            weight("java.se", "java.sql.rowset", h * 10);
+            weight("java.sql.rowset", "java.sql", h * 10);
+            weight("java.sql", "java.xml", h * 10);
+            weight("java.xml", "java.base", h * 10);
+
+            ranks.add(Set.of("java.logging", "java.scripting", "java.xml"));
+            ranks.add(Set.of("java.sql"));
+            ranks.add(Set.of("java.compiler", "java.instrument"));
+            ranks.add(Set.of("java.desktop", "java.management"));
+            ranks.add(Set.of("java.corba", "java.xml.ws"));
+            ranks.add(Set.of("java.xml.bind", "java.xml.ws.annotation"));
+
+            this.attrs = attrs;
+        }
+
+        ModuleGraphAttributes() {
+            this(DEFAULT_ATTRIBUTES);
+        }
+        ModuleGraphAttributes(Properties props) {
+            this(toAttributes(props));
+        }
+
+        @Override
+        public double rankSep() {
+            return Double.valueOf(attrs.get("ranksep"));
+        }
+
+        @Override
+        public int fontSize() {
+            return Integer.valueOf(attrs.get("fontsize"));
+        }
+
+        @Override
+        public String fontName() {
+            return attrs.get("fontname");
+        }
+
+        @Override
+        public String fontColor() {
+            return attrs.get("fontcolor");
+        }
+
+        @Override
+        public int arrowSize() {
+            return Integer.valueOf(attrs.get("arrowsize"));
+        }
+
+        @Override
+        public int arrowWidth() {
+            return Integer.valueOf(attrs.get("arrowwidth"));
+        }
+
+        @Override
+        public String arrowColor() {
+            return attrs.get("arrowcolor");
+        }
+
+        @Override
+        public List<Set<String>> ranks() {
+            return ranks;
+        }
+
+        @Override
+        public String requiresMandatedColor() {
+            return attrs.get("requiresMandatedColor");
+        }
+
+        @Override
+        public String javaSubgraphColor() {
+            return attrs.get("javaSubgraphColor");
+        }
+
+        @Override
+        public String jdkSubgraphColor() {
+            return attrs.get("jdkSubgraphColor");
+        }
+
+        @Override
+        public int weightOf(String s, String t) {
+            int w = weights.getOrDefault(s + ":" + t, 1);
+            if (w != 1)
+                return w;
+            if (s.startsWith("java.") && t.startsWith("java."))
+                return 10;
+            return 1;
+        }
+
+        public void weight(String s, String t, int w) {
+            weights.put(s + ":" + t, w);
+        }
+
+        static Map<String, String> toAttributes(Properties props) {
+            return DEFAULT_ATTRIBUTES.keySet().stream()
+                .collect(Collectors.toMap(Function.identity(),
+                    k -> props.getProperty(k, DEFAULT_ATTRIBUTES.get(k))));
+        }
     }
 
     private final Path dir;
     private final boolean spec;
-    GenGraphs(Path dir, boolean spec) {
+    private final ModuleGraphAttributes attributes;
+    GenGraphs(Path dir, boolean spec, ModuleGraphAttributes attributes) {
         this.dir = dir;
         this.spec = spec;
+        this.attributes = attributes;
     }
 
     void genDotFiles(Map<String, Configuration> configurations) throws IOException {
         ModuleDotGraph dotGraph = new ModuleDotGraph(configurations, spec);
-        dotGraph.genDotFiles(dir);
+        dotGraph.genDotFiles(dir, attributes);
     }
 
+    /**
+     * Returns true for any name if generating graph for non-spec;
+     * otherwise, returns true except "jdk" and name with "jdk.internal." prefix
+     */
     boolean accept(String name, ModuleDescriptor descriptor) {
-        if (!spec) return true;
-
-        if (name.equals("jdk"))
-            return false;
-
-        if (name.equals("java.se") || name.equals("java.se.ee"))
+        if (!spec)
             return true;
 
-        // only the module that has exported API
-        return descriptor.exports().stream()
-                         .filter(e -> !e.isQualified())
-                         .findAny().isPresent();
+        return !name.equals("jdk") && !name.startsWith("jdk.internal.");
     }
-}
\ No newline at end of file
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/src/classes/build/tools/jigsaw/javadoc-graphs.properties	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,2 @@
+arrowcolor=#999999
+requiresMandatedColor=#999999
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/src/classes/build/tools/taglet/ModuleGraph.java	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package build.tools.taglet;
+
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Set;
+import javax.lang.model.element.Element;
+import com.sun.source.doctree.DocTree;
+import jdk.javadoc.doclet.Taglet;
+import static jdk.javadoc.doclet.Taglet.Location.*;
+
+/**
+ * A block tag to optionally insert a reference to a module graph.
+ */
+public class ModuleGraph implements Taglet {
+    private static final boolean enableModuleGraph =
+        Boolean.getBoolean("enableModuleGraph");
+
+    /** Returns the set of locations in which a taglet may be used. */
+    @Override
+    public Set<Location> getAllowedLocations() {
+        return EnumSet.of(MODULE);
+    }
+
+    @Override
+    public boolean isInlineTag() {
+        return false;
+    }
+
+    @Override
+    public String getName() {
+        return "moduleGraph";
+    }
+
+    @Override
+    public String toString(List<? extends DocTree> tags, Element element) {
+        if (!enableModuleGraph) {
+            return "";
+        }
+
+        String moduleName = element.getSimpleName().toString();
+        String imageFile = moduleName + "-graph.png";
+        int thumbnailHeight = -1;
+        String hoverImage = "";
+        if (!moduleName.equals("java.base")) {
+            thumbnailHeight = 100; // also appears in the stylesheet
+            hoverImage = "<span>"
+                + getImage(moduleName, imageFile, -1, true)
+                + "</span>";
+        }
+        return "<dt>"
+            + "<span class=\"simpleTagLabel\">Module Graph:</span>\n"
+            + "</dt>"
+            + "<dd>"
+            + "<a class=moduleGraph href=\"" + imageFile + "\">"
+            + getImage(moduleName, imageFile, thumbnailHeight, false)
+            + hoverImage
+            + "</a>"
+            + "</dd>";
+    }
+
+    private static final String VERTICAL_ALIGN = "vertical-align:top";
+    private static final String BORDER = "border: solid lightgray 1px;";
+
+    private String getImage(String moduleName, String file, int height, boolean useBorder) {
+        return String.format("<img style=\"%s\" alt=\"Module graph for %s\" src=\"%s\"%s>",
+                             useBorder ? BORDER + " " + VERTICAL_ALIGN : VERTICAL_ALIGN,
+                             moduleName,
+                             file,
+                             (height <= 0 ? "" : " height=\"" + height + "\""));
+    }
+}
--- a/src/java.base/macosx/classes/java/net/DefaultInterface.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/macosx/classes/java/net/DefaultInterface.java	Mon Apr 10 08:31:37 2017 -0700
@@ -50,10 +50,11 @@
     }
 
     /**
-     * Choose a default interface. This method returns an interface that is
-     * both "up" and supports multicast. This method choses an interface in
+     * Choose a default interface. This method returns the first interface that
+     * is both "up" and supports multicast. This method chooses an interface in
      * order of preference:
      * 1. neither loopback nor point to point
+     *    ( prefer interfaces with dual IP support )
      * 2. point to point
      * 3. loopback
      *
@@ -66,32 +67,56 @@
         try {
            nifs = NetworkInterface.getNetworkInterfaces();
         } catch (IOException ignore) {
-            // unable to enumate network interfaces
+            // unable to enumerate network interfaces
             return null;
         }
 
+        NetworkInterface preferred = null;
         NetworkInterface ppp = null;
         NetworkInterface loopback = null;
 
         while (nifs.hasMoreElements()) {
             NetworkInterface ni = nifs.nextElement();
             try {
-                if (ni.isUp() && ni.supportsMulticast()) {
-                    boolean isLoopback = ni.isLoopback();
-                    boolean isPPP = ni.isPointToPoint();
-                    if (!isLoopback && !isPPP) {
-                        // found an interface that is not the loopback or a
-                        // point-to-point interface
+                if (!ni.isUp() || !ni.supportsMulticast())
+                    continue;
+
+                boolean ip4 = false, ip6 = false;
+                Enumeration<InetAddress> addrs = ni.getInetAddresses();
+                while (addrs.hasMoreElements()) {
+                    InetAddress addr = addrs.nextElement();
+                    if (!addr.isAnyLocalAddress()) {
+                        if (addr instanceof Inet4Address) {
+                            ip4 = true;
+                        } else if (addr instanceof Inet6Address) {
+                            ip6 = true;
+                        }
+                    }
+                }
+
+                boolean isLoopback = ni.isLoopback();
+                boolean isPPP = ni.isPointToPoint();
+                if (!isLoopback && !isPPP) {
+                    // found an interface that is not the loopback or a
+                    // point-to-point interface
+                    if (preferred == null) {
+                        preferred = ni;
+                    } else if (ip4 && ip6){
                         return ni;
                     }
-                    if (ppp == null && isPPP)
-                        ppp = ni;
-                    if (loopback == null && isLoopback)
-                        loopback = ni;
                 }
+                if (ppp == null && isPPP)
+                    ppp = ni;
+                if (loopback == null && isLoopback)
+                    loopback = ni;
+
             } catch (IOException skip) { }
         }
 
-        return (ppp != null) ? ppp : loopback;
+        if (preferred != null) {
+            return preferred;
+        } else {
+            return (ppp != null) ? ppp : loopback;
+        }
     }
 }
--- a/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -149,6 +149,7 @@
      * Ensures that the bytes of this key are
      * set to zero when there are no more references to it.
      */
+    @SuppressWarnings("deprecation")
     protected void finalize() throws Throwable {
         try {
             if (this.key != null) {
--- a/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -150,6 +150,7 @@
      * Ensures that the bytes of this key are
      * set to zero when there are no more references to it.
      */
+    @SuppressWarnings("deprecation")
     protected void finalize() throws Throwable {
         try {
             if (this.key != null) {
--- a/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -145,6 +145,7 @@
      * Ensures that the password bytes of this key are
      * set to zero when there are no more references to it.
      */
+    @SuppressWarnings("deprecation")
     protected void finalize() throws Throwable {
         try {
             if (this.key != null) {
--- a/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -267,6 +267,7 @@
      * Ensures that the password bytes of this key are
      * erased when there are no more references to it.
      */
+    @SuppressWarnings("deprecation")
     protected void finalize() throws Throwable {
         try {
             if (this.passwd != null) {
--- a/src/java.base/share/classes/java/io/BufferedReader.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/io/BufferedReader.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -297,14 +297,15 @@
 
     /**
      * Reads a line of text.  A line is considered to be terminated by any one
-     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
-     * followed immediately by a linefeed.
+     * of a line feed ('\n'), a carriage return ('\r'), a carriage return
+     * followed immediately by a line feed, or by reaching the end-of-file
+     * (EOF).
      *
      * @param      ignoreLF  If true, the next '\n' will be skipped
      *
      * @return     A String containing the contents of the line, not including
      *             any line-termination characters, or null if the end of the
-     *             stream has been reached
+     *             stream has been reached without reading any characters
      *
      * @see        java.io.LineNumberReader#readLine()
      *
@@ -375,12 +376,13 @@
 
     /**
      * Reads a line of text.  A line is considered to be terminated by any one
-     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
-     * followed immediately by a linefeed.
+     * of a line feed ('\n'), a carriage return ('\r'), a carriage return
+     * followed immediately by a line feed, or by reaching the end-of-file
+     * (EOF).
      *
      * @return     A String containing the contents of the line, not including
      *             any line-termination characters, or null if the end of the
-     *             stream has been reached
+     *             stream has been reached without reading any characters
      *
      * @exception  IOException  If an I/O error occurs
      *
--- a/src/java.base/share/classes/java/io/FileInputStream.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/io/FileInputStream.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -413,9 +413,19 @@
      * Ensures that the <code>close</code> method of this file input stream is
      * called when there are no more references to it.
      *
+     * @deprecated The {@code finalize} method has been deprecated.
+     *     Subclasses that override {@code finalize} in order to perform cleanup
+     *     should be modified to use alternative cleanup mechanisms and
+     *     to remove the overriding {@code finalize} method.
+     *     When overriding the {@code finalize} method, its implementation must explicitly
+     *     ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}.
+     *     See the specification for {@link Object#finalize()} for further
+     *     information about migration options.
+     *
      * @exception  IOException  if an I/O error occurs.
      * @see        java.io.FileInputStream#close()
      */
+    @Deprecated(since="9")
     protected void finalize() throws IOException {
         if ((fd != null) &&  (fd != FileDescriptor.in)) {
             /* if fd is shared, the references in FileDescriptor
--- a/src/java.base/share/classes/java/io/FileOutputStream.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/io/FileOutputStream.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -427,9 +427,18 @@
      * <code>close</code> method of this file output stream is
      * called when there are no more references to this stream.
      *
+     * @deprecated The {@code finalize} method has been deprecated.
+     * Subclasses that override {@code finalize} in order to perform cleanup
+     * should be modified to use alternative cleanup mechanisms and
+     * to remove the overriding {@code finalize} method.
+     * When overriding the {@code finalize} method, its implementation must explicitly
+     * ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}.
+     * See the specification for {@link Object#finalize()} for further
+     * information about migration options.
      * @exception  IOException  if an I/O error occurs.
      * @see        java.io.FileInputStream#close()
      */
+    @Deprecated(since="9")
     protected void finalize() throws IOException {
         if (fd != null) {
             if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
--- a/src/java.base/share/classes/java/io/ObjectInputFilter.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/io/ObjectInputFilter.java	Mon Apr 10 08:31:37 2017 -0700
@@ -322,7 +322,7 @@
          * Other patterns match or reject class or package name
          * as returned from {@link Class#getName() Class.getName()} and
          * if an optional module name is present
-         * {@link java.lang.reflect.Module#getName() class.getModule().getName()}.
+         * {@link Module#getName() class.getModule().getName()}.
          * Note that for arrays the element type is used in the pattern,
          * not the array type.
          * <ul>
--- a/src/java.base/share/classes/java/lang/Class.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/Class.java	Mon Apr 10 08:31:37 2017 -0700
@@ -43,7 +43,6 @@
 import java.lang.reflect.Member;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.lang.reflect.Module;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.Type;
 import java.lang.reflect.TypeVariable;
@@ -2561,21 +2560,16 @@
     public InputStream getResourceAsStream(String name) {
         name = resolveName(name);
 
-        Module module = getModule();
-        if (module.isNamed()) {
-            if (Resources.canEncapsulate(name)) {
-                Module caller = Reflection.getCallerClass().getModule();
-                if (caller != module) {
-                    Set<String> packages = module.getDescriptor().packages();
-                    String pn = Resources.toPackageName(name);
-                    if (packages.contains(pn) && !module.isOpen(pn, caller)) {
-                        // resource is in package not open to caller
-                        return null;
-                    }
-                }
+        Module thisModule = getModule();
+        if (thisModule.isNamed()) {
+            // check if resource can be located by caller
+            if (Resources.canEncapsulate(name)
+                && !isOpenToCaller(name, Reflection.getCallerClass())) {
+                return null;
             }
 
-            String mn = module.getName();
+            // resource not encapsulated or in package open to caller
+            String mn = thisModule.getName();
             ClassLoader cl = getClassLoader0();
             try {
 
@@ -2663,20 +2657,16 @@
     public URL getResource(String name) {
         name = resolveName(name);
 
-        Module module = getModule();
-        if (module.isNamed()) {
-            if (Resources.canEncapsulate(name)) {
-                Module caller = Reflection.getCallerClass().getModule();
-                if (caller != module) {
-                    Set<String> packages = module.getDescriptor().packages();
-                    String pn = Resources.toPackageName(name);
-                    if (packages.contains(pn) && !module.isOpen(pn, caller)) {
-                        // resource is in package not open to caller
-                        return null;
-                    }
-                }
+        Module thisModule = getModule();
+        if (thisModule.isNamed()) {
+            // check if resource can be located by caller
+            if (Resources.canEncapsulate(name)
+                && !isOpenToCaller(name, Reflection.getCallerClass())) {
+                return null;
             }
-            String mn = getModule().getName();
+
+            // resource not encapsulated or in package open to caller
+            String mn = thisModule.getName();
             ClassLoader cl = getClassLoader0();
             try {
                 if (cl == null) {
@@ -2698,10 +2688,36 @@
         }
     }
 
+    /**
+     * Returns true if a resource with the given name can be located by the
+     * given caller. All resources in a module can be located by code in
+     * the module. For other callers, then the package needs to be open to
+     * the caller.
+     */
+    private boolean isOpenToCaller(String name, Class<?> caller) {
+        // assert getModule().isNamed();
+        Module thisModule = getModule();
+        Module callerModule = (caller != null) ? caller.getModule() : null;
+        if (callerModule != thisModule) {
+            String pn = Resources.toPackageName(name);
+            if (thisModule.getDescriptor().packages().contains(pn)) {
+                if (callerModule == null && !thisModule.isOpen(pn)) {
+                    // no caller, package not open
+                    return false;
+                }
+                if (!thisModule.isOpen(pn, callerModule)) {
+                    // package not open to caller
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+
     /** protection domain returned when the internal domain is null */
     private static java.security.ProtectionDomain allPermDomain;
 
-
     /**
      * Returns the {@code ProtectionDomain} of this class.  If there is a
      * security manager installed, this method first calls the security
--- a/src/java.base/share/classes/java/lang/ClassLoader.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/ClassLoader.java	Mon Apr 10 08:31:37 2017 -0700
@@ -31,7 +31,6 @@
 import java.io.File;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
-import java.lang.reflect.Module;
 import java.net.URL;
 import java.security.AccessController;
 import java.security.AccessControlContext;
@@ -352,9 +351,7 @@
     private ClassLoader(Void unused, String name, ClassLoader parent) {
         this.name = name;
         this.parent = parent;
-        this.unnamedModule
-            = SharedSecrets.getJavaLangReflectModuleAccess()
-                           .defineUnnamedModule(this);
+        this.unnamedModule = new Module(this);
         if (ParallelLoaders.isRegistered(this.getClass())) {
             parallelLockMap = new ConcurrentHashMap<>();
             package2certs = new ConcurrentHashMap<>();
@@ -2348,6 +2345,7 @@
             this.isBuiltin = isBuiltin;
         }
 
+        @SuppressWarnings("deprecation")
         protected void finalize() {
             synchronized (loadedLibraryNames) {
                 if (fromClass.getClassLoader() != null && loaded) {
--- a/src/java.base/share/classes/java/lang/Comparable.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/Comparable.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -124,7 +124,7 @@
      * {@code sgn(}<i>expression</i>{@code )} designates the mathematical
      * <i>signum</i> function, which is defined to return one of {@code -1},
      * {@code 0}, or {@code 1} according to whether the value of
-     * <i>expression</i> is negative, zero or positive.
+     * <i>expression</i> is negative, zero, or positive, respectively.
      *
      * @param   o the object to be compared.
      * @return  a negative integer, zero, or a positive integer as this object
--- a/src/java.base/share/classes/java/lang/Enum.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/Enum.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -243,6 +243,7 @@
     /**
      * enum classes cannot have finalize methods.
      */
+    @SuppressWarnings("deprecation")
     protected final void finalize() { }
 
     /**
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/lang/LayerInstantiationException.java	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+/**
+ * Thrown when creating a {@linkplain ModuleLayer module layer} fails.
+ *
+ * @see ModuleLayer
+ * @since 9
+ * @spec JPMS
+ */
+public class LayerInstantiationException extends RuntimeException {
+    private static final long serialVersionUID = -906239691613568347L;
+
+    /**
+     * Constructs a {@code LayerInstantiationException} with no detail message.
+     */
+    public LayerInstantiationException() {
+    }
+
+    /**
+     * Constructs a {@code LayerInstantiationException} with the given detail
+     * message.
+     *
+     * @param msg
+     *        The detail message; can be {@code null}
+     */
+    public LayerInstantiationException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Constructs a {@code LayerInstantiationException} with the given cause.
+     *
+     * @param cause
+     *        The cause; can be {@code null}
+     */
+    public LayerInstantiationException(Throwable cause) {
+        super(cause);
+    }
+
+    /**
+     * Constructs a {@code FindException} with the given detail message
+     * and cause.
+     *
+     * @param msg
+     *        The detail message; can be {@code null}
+     * @param cause
+     *        The cause; can be {@code null}
+     */
+    public LayerInstantiationException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/lang/Module.java	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,1586 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.annotation.Annotation;
+import java.lang.module.Configuration;
+import java.lang.module.ModuleReference;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleDescriptor.Exports;
+import java.lang.module.ModuleDescriptor.Opens;
+import java.lang.module.ModuleDescriptor.Version;
+import java.lang.module.ResolvedModule;
+import java.lang.reflect.AnnotatedElement;
+import java.net.URI;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import jdk.internal.loader.BuiltinClassLoader;
+import jdk.internal.loader.BootLoader;
+import jdk.internal.misc.JavaLangAccess;
+import jdk.internal.misc.SharedSecrets;
+import jdk.internal.module.ServicesCatalog;
+import jdk.internal.module.Resources;
+import jdk.internal.org.objectweb.asm.AnnotationVisitor;
+import jdk.internal.org.objectweb.asm.Attribute;
+import jdk.internal.org.objectweb.asm.ClassReader;
+import jdk.internal.org.objectweb.asm.ClassVisitor;
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.Opcodes;
+import jdk.internal.reflect.CallerSensitive;
+import jdk.internal.reflect.Reflection;
+import sun.security.util.SecurityConstants;
+
+/**
+ * Represents a run-time module, either {@link #isNamed() named} or unnamed.
+ *
+ * <p> Named modules have a {@link #getName() name} and are constructed by the
+ * Java Virtual Machine when a graph of modules is defined to the Java virtual
+ * machine to create a {@linkplain ModuleLayer module layer}. </p>
+ *
+ * <p> An unnamed module does not have a name. There is an unnamed module for
+ * each {@link ClassLoader ClassLoader}, obtained by invoking its {@link
+ * ClassLoader#getUnnamedModule() getUnnamedModule} method. All types that are
+ * not in a named module are members of their defining class loader's unnamed
+ * module. </p>
+ *
+ * <p> The package names that are parameters or returned by methods defined in
+ * this class are the fully-qualified names of the packages as defined in
+ * section 6.5.3 of <cite>The Java&trade; Language Specification</cite>, for
+ * example, {@code "java.lang"}. </p>
+ *
+ * <p> Unless otherwise specified, passing a {@code null} argument to a method
+ * in this class causes a {@link NullPointerException NullPointerException} to
+ * be thrown. </p>
+ *
+ * @since 9
+ * @spec JPMS
+ * @see Class#getModule()
+ */
+
+public final class Module implements AnnotatedElement {
+
+    // the layer that contains this module, can be null
+    private final ModuleLayer layer;
+
+    // module name and loader, these fields are read by VM
+    private final String name;
+    private final ClassLoader loader;
+
+    // the module descriptor
+    private final ModuleDescriptor descriptor;
+
+
+    /**
+     * Creates a new named Module. The resulting Module will be defined to the
+     * VM but will not read any other modules, will not have any exports setup
+     * and will not be registered in the service catalog.
+     */
+    Module(ModuleLayer layer,
+           ClassLoader loader,
+           ModuleDescriptor descriptor,
+           URI uri)
+    {
+        this.layer = layer;
+        this.name = descriptor.name();
+        this.loader = loader;
+        this.descriptor = descriptor;
+
+        // define module to VM
+
+        boolean isOpen = descriptor.isOpen();
+        Version version = descriptor.version().orElse(null);
+        String vs = Objects.toString(version, null);
+        String loc = Objects.toString(uri, null);
+        String[] packages = descriptor.packages().toArray(new String[0]);
+        defineModule0(this, isOpen, vs, loc, packages);
+    }
+
+
+    /**
+     * Create the unnamed Module for the given ClassLoader.
+     *
+     * @see ClassLoader#getUnnamedModule
+     */
+    Module(ClassLoader loader) {
+        this.layer = null;
+        this.name = null;
+        this.loader = loader;
+        this.descriptor = null;
+    }
+
+
+    /**
+     * Creates a named module but without defining the module to the VM.
+     *
+     * @apiNote This constructor is for VM white-box testing.
+     */
+    Module(ClassLoader loader, ModuleDescriptor descriptor) {
+        this.layer = null;
+        this.name = descriptor.name();
+        this.loader = loader;
+        this.descriptor = descriptor;
+    }
+
+
+
+    /**
+     * Returns {@code true} if this module is a named module.
+     *
+     * @return {@code true} if this is a named module
+     *
+     * @see ClassLoader#getUnnamedModule()
+     */
+    public boolean isNamed() {
+        return name != null;
+    }
+
+    /**
+     * Returns the module name or {@code null} if this module is an unnamed
+     * module.
+     *
+     * @return The module name
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Returns the {@code ClassLoader} for this module.
+     *
+     * <p> If there is a security manager then its {@code checkPermission}
+     * method if first called with a {@code RuntimePermission("getClassLoader")}
+     * permission to check that the caller is allowed to get access to the
+     * class loader. </p>
+     *
+     * @return The class loader for this module
+     *
+     * @throws SecurityException
+     *         If denied by the security manager
+     */
+    public ClassLoader getClassLoader() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
+        }
+        return loader;
+    }
+
+    /**
+     * Returns the module descriptor for this module or {@code null} if this
+     * module is an unnamed module.
+     *
+     * @return The module descriptor for this module
+     */
+    public ModuleDescriptor getDescriptor() {
+        return descriptor;
+    }
+
+    /**
+     * Returns the layer that contains this module or {@code null} if this
+     * module is not in a layer.
+     *
+     * A module layer contains named modules and therefore this method always
+     * returns {@code null} when invoked on an unnamed module.
+     *
+     * <p> <a href="reflect/Proxy.html#dynamicmodule">Dynamic modules</a> are
+     * named modules that are generated at runtime. A dynamic module may or may
+     * not be in a module layer. </p>
+     *
+     * @return The module layer that contains this module
+     *
+     * @see java.lang.reflect.Proxy
+     */
+    public ModuleLayer getLayer() {
+        if (isNamed()) {
+            ModuleLayer layer = this.layer;
+            if (layer != null)
+                return layer;
+
+            // special-case java.base as it is created before the boot layer
+            if (loader == null && name.equals("java.base")) {
+                return ModuleLayer.boot();
+            }
+        }
+        return null;
+    }
+
+
+    // --
+
+    // special Module to mean "all unnamed modules"
+    private static final Module ALL_UNNAMED_MODULE = new Module(null);
+
+    // special Module to mean "everyone"
+    private static final Module EVERYONE_MODULE = new Module(null);
+
+    // set contains EVERYONE_MODULE, used when a package is opened or
+    // exported unconditionally
+    private static final Set<Module> EVERYONE_SET = Set.of(EVERYONE_MODULE);
+
+
+    // -- readability --
+
+    // the modules that this module reads
+    private volatile Set<Module> reads;
+
+    // additional module (2nd key) that some module (1st key) reflectively reads
+    private static final WeakPairMap<Module, Module, Boolean> reflectivelyReads
+        = new WeakPairMap<>();
+
+
+    /**
+     * Indicates if this module reads the given module. This method returns
+     * {@code true} if invoked to test if this module reads itself. It also
+     * returns {@code true} if invoked on an unnamed module (as unnamed
+     * modules read all modules).
+     *
+     * @param  other
+     *         The other module
+     *
+     * @return {@code true} if this module reads {@code other}
+     *
+     * @see #addReads(Module)
+     */
+    public boolean canRead(Module other) {
+        Objects.requireNonNull(other);
+
+        // an unnamed module reads all modules
+        if (!this.isNamed())
+            return true;
+
+        // all modules read themselves
+        if (other == this)
+            return true;
+
+        // check if this module reads other
+        if (other.isNamed()) {
+            Set<Module> reads = this.reads; // volatile read
+            if (reads != null && reads.contains(other))
+                return true;
+        }
+
+        // check if this module reads the other module reflectively
+        if (reflectivelyReads.containsKeyPair(this, other))
+            return true;
+
+        // if other is an unnamed module then check if this module reads
+        // all unnamed modules
+        if (!other.isNamed()
+            && reflectivelyReads.containsKeyPair(this, ALL_UNNAMED_MODULE))
+            return true;
+
+        return false;
+    }
+
+    /**
+     * If the caller's module is this module then update this module to read
+     * the given module.
+     *
+     * This method is a no-op if {@code other} is this module (all modules read
+     * themselves), this module is an unnamed module (as unnamed modules read
+     * all modules), or this module already reads {@code other}.
+     *
+     * @implNote <em>Read edges</em> added by this method are <em>weak</em> and
+     * do not prevent {@code other} from being GC'ed when this module is
+     * strongly reachable.
+     *
+     * @param  other
+     *         The other module
+     *
+     * @return this module
+     *
+     * @throws IllegalCallerException
+     *         If this is a named module and the caller's module is not this
+     *         module
+     *
+     * @see #canRead
+     */
+    @CallerSensitive
+    public Module addReads(Module other) {
+        Objects.requireNonNull(other);
+        if (this.isNamed()) {
+            Module caller = getCallerModule(Reflection.getCallerClass());
+            if (caller != this) {
+                throw new IllegalCallerException(caller + " != " + this);
+            }
+            implAddReads(other, true);
+        }
+        return this;
+    }
+
+    /**
+     * Updates this module to read another module.
+     *
+     * @apiNote Used by the --add-reads command line option.
+     */
+    void implAddReads(Module other) {
+        implAddReads(other, true);
+    }
+
+    /**
+     * Updates this module to read all unnamed modules.
+     *
+     * @apiNote Used by the --add-reads command line option.
+     */
+    void implAddReadsAllUnnamed() {
+        implAddReads(Module.ALL_UNNAMED_MODULE, true);
+    }
+
+    /**
+     * Updates this module to read another module without notifying the VM.
+     *
+     * @apiNote This method is for VM white-box testing.
+     */
+    void implAddReadsNoSync(Module other) {
+        implAddReads(other, false);
+    }
+
+    /**
+     * Makes the given {@code Module} readable to this module.
+     *
+     * If {@code syncVM} is {@code true} then the VM is notified.
+     */
+    private void implAddReads(Module other, boolean syncVM) {
+        Objects.requireNonNull(other);
+        if (!canRead(other)) {
+            // update VM first, just in case it fails
+            if (syncVM) {
+                if (other == ALL_UNNAMED_MODULE) {
+                    addReads0(this, null);
+                } else {
+                    addReads0(this, other);
+                }
+            }
+
+            // add reflective read
+            reflectivelyReads.putIfAbsent(this, other, Boolean.TRUE);
+        }
+    }
+
+
+    // -- exported and open packages --
+
+    // the packages are open to other modules, can be null
+    // if the value contains EVERYONE_MODULE then the package is open to all
+    private volatile Map<String, Set<Module>> openPackages;
+
+    // the packages that are exported, can be null
+    // if the value contains EVERYONE_MODULE then the package is exported to all
+    private volatile Map<String, Set<Module>> exportedPackages;
+
+    // additional exports or opens added at run-time
+    // this module (1st key), other module (2nd key)
+    // (package name, open?) (value)
+    private static final WeakPairMap<Module, Module, Map<String, Boolean>>
+        reflectivelyExports = new WeakPairMap<>();
+
+
+    /**
+     * Returns {@code true} if this module exports the given package to at
+     * least the given module.
+     *
+     * <p> This method returns {@code true} if invoked to test if a package in
+     * this module is exported to itself. It always returns {@code true} when
+     * invoked on an unnamed module. A package that is {@link #isOpen open} to
+     * the given module is considered exported to that module at run-time and
+     * so this method returns {@code true} if the package is open to the given
+     * module. </p>
+     *
+     * <p> This method does not check if the given module reads this module. </p>
+     *
+     * @param  pn
+     *         The package name
+     * @param  other
+     *         The other module
+     *
+     * @return {@code true} if this module exports the package to at least the
+     *         given module
+     *
+     * @see ModuleDescriptor#exports()
+     * @see #addExports(String,Module)
+     */
+    public boolean isExported(String pn, Module other) {
+        Objects.requireNonNull(pn);
+        Objects.requireNonNull(other);
+        return implIsExportedOrOpen(pn, other, /*open*/false);
+    }
+
+    /**
+     * Returns {@code true} if this module has <em>opened</em> a package to at
+     * least the given module.
+     *
+     * <p> This method returns {@code true} if invoked to test if a package in
+     * this module is open to itself. It returns {@code true} when invoked on an
+     * {@link ModuleDescriptor#isOpen open} module with a package in the module.
+     * It always returns {@code true} when invoked on an unnamed module. </p>
+     *
+     * <p> This method does not check if the given module reads this module. </p>
+     *
+     * @param  pn
+     *         The package name
+     * @param  other
+     *         The other module
+     *
+     * @return {@code true} if this module has <em>opened</em> the package
+     *         to at least the given module
+     *
+     * @see ModuleDescriptor#opens()
+     * @see #addOpens(String,Module)
+     * @see AccessibleObject#setAccessible(boolean)
+     * @see java.lang.invoke.MethodHandles#privateLookupIn
+     */
+    public boolean isOpen(String pn, Module other) {
+        Objects.requireNonNull(pn);
+        Objects.requireNonNull(other);
+        return implIsExportedOrOpen(pn, other, /*open*/true);
+    }
+
+    /**
+     * Returns {@code true} if this module exports the given package
+     * unconditionally.
+     *
+     * <p> This method always returns {@code true} when invoked on an unnamed
+     * module. A package that is {@link #isOpen(String) opened} unconditionally
+     * is considered exported unconditionally at run-time and so this method
+     * returns {@code true} if the package is opened unconditionally. </p>
+     *
+     * <p> This method does not check if the given module reads this module. </p>
+     *
+     * @param  pn
+     *         The package name
+     *
+     * @return {@code true} if this module exports the package unconditionally
+     *
+     * @see ModuleDescriptor#exports()
+     */
+    public boolean isExported(String pn) {
+        Objects.requireNonNull(pn);
+        return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/false);
+    }
+
+    /**
+     * Returns {@code true} if this module has <em>opened</em> a package
+     * unconditionally.
+     *
+     * <p> This method always returns {@code true} when invoked on an unnamed
+     * module. Additionally, it always returns {@code true} when invoked on an
+     * {@link ModuleDescriptor#isOpen open} module with a package in the
+     * module. </p>
+     *
+     * <p> This method does not check if the given module reads this module. </p>
+     *
+     * @param  pn
+     *         The package name
+     *
+     * @return {@code true} if this module has <em>opened</em> the package
+     *         unconditionally
+     *
+     * @see ModuleDescriptor#opens()
+     */
+    public boolean isOpen(String pn) {
+        Objects.requireNonNull(pn);
+        return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/true);
+    }
+
+
+    /**
+     * Returns {@code true} if this module exports or opens the given package
+     * to the given module. If the other module is {@code EVERYONE_MODULE} then
+     * this method tests if the package is exported or opened unconditionally.
+     */
+    private boolean implIsExportedOrOpen(String pn, Module other, boolean open) {
+        // all packages in unnamed modules are open
+        if (!isNamed())
+            return true;
+
+        // all packages are exported/open to self
+        if (other == this && containsPackage(pn))
+            return true;
+
+        // all packages in open and automatic modules are open
+        if (descriptor.isOpen() || descriptor.isAutomatic())
+            return containsPackage(pn);
+
+        // exported/opened via module declaration/descriptor
+        if (isStaticallyExportedOrOpen(pn, other, open))
+            return true;
+
+        // exported via addExports/addOpens
+        if (isReflectivelyExportedOrOpen(pn, other, open))
+            return true;
+
+        // not exported or open to other
+        return false;
+    }
+
+    /**
+     * Returns {@code true} if this module exports or opens a package to
+     * the given module via its module declaration.
+     */
+    private boolean isStaticallyExportedOrOpen(String pn, Module other, boolean open) {
+        // package is open to everyone or <other>
+        Map<String, Set<Module>> openPackages = this.openPackages;
+        if (openPackages != null) {
+            Set<Module> targets = openPackages.get(pn);
+            if (targets != null) {
+                if (targets.contains(EVERYONE_MODULE))
+                    return true;
+                if (other != EVERYONE_MODULE && targets.contains(other))
+                    return true;
+            }
+        }
+
+        if (!open) {
+            // package is exported to everyone or <other>
+            Map<String, Set<Module>> exportedPackages = this.exportedPackages;
+            if (exportedPackages != null) {
+                Set<Module> targets = exportedPackages.get(pn);
+                if (targets != null) {
+                    if (targets.contains(EVERYONE_MODULE))
+                        return true;
+                    if (other != EVERYONE_MODULE && targets.contains(other))
+                        return true;
+                }
+            }
+        }
+
+        return false;
+    }
+
+
+    /**
+     * Returns {@code true} if this module reflectively exports or opens given
+     * package package to the given module.
+     */
+    private boolean isReflectivelyExportedOrOpen(String pn, Module other, boolean open) {
+        // exported or open to all modules
+        Map<String, Boolean> exports = reflectivelyExports.get(this, EVERYONE_MODULE);
+        if (exports != null) {
+            Boolean b = exports.get(pn);
+            if (b != null) {
+                boolean isOpen = b.booleanValue();
+                if (!open || isOpen) return true;
+            }
+        }
+
+        if (other != EVERYONE_MODULE) {
+
+            // exported or open to other
+            exports = reflectivelyExports.get(this, other);
+            if (exports != null) {
+                Boolean b = exports.get(pn);
+                if (b != null) {
+                    boolean isOpen = b.booleanValue();
+                    if (!open || isOpen) return true;
+                }
+            }
+
+            // other is an unnamed module && exported or open to all unnamed
+            if (!other.isNamed()) {
+                exports = reflectivelyExports.get(this, ALL_UNNAMED_MODULE);
+                if (exports != null) {
+                    Boolean b = exports.get(pn);
+                    if (b != null) {
+                        boolean isOpen = b.booleanValue();
+                        if (!open || isOpen) return true;
+                    }
+                }
+            }
+
+        }
+
+        return false;
+    }
+
+
+    /**
+     * If the caller's module is this module then update this module to export
+     * the given package to the given module.
+     *
+     * <p> This method has no effect if the package is already exported (or
+     * <em>open</em>) to the given module. </p>
+     *
+     * @apiNote As specified in section 5.4.3 of the <cite>The Java&trade;
+     * Virtual Machine Specification </cite>, if an attempt to resolve a
+     * symbolic reference fails because of a linkage error, then subsequent
+     * attempts to resolve the reference always fail with the same error that
+     * was thrown as a result of the initial resolution attempt.
+     *
+     * @param  pn
+     *         The package name
+     * @param  other
+     *         The module
+     *
+     * @return this module
+     *
+     * @throws IllegalArgumentException
+     *         If {@code pn} is {@code null}, or this is a named module and the
+     *         package {@code pn} is not a package in this module
+     * @throws IllegalCallerException
+     *         If this is a named module and the caller's module is not this
+     *         module
+     *
+     * @jvms 5.4.3 Resolution
+     * @see #isExported(String,Module)
+     */
+    @CallerSensitive
+    public Module addExports(String pn, Module other) {
+        if (pn == null)
+            throw new IllegalArgumentException("package is null");
+        Objects.requireNonNull(other);
+
+        if (isNamed()) {
+            Module caller = getCallerModule(Reflection.getCallerClass());
+            if (caller != this) {
+                throw new IllegalCallerException(caller + " != " + this);
+            }
+            implAddExportsOrOpens(pn, other, /*open*/false, /*syncVM*/true);
+        }
+
+        return this;
+    }
+
+    /**
+     * If this module has <em>opened</em> a package to at least the caller
+     * module then update this module to open the package to the given module.
+     * Opening a package with this method allows all types in the package,
+     * and all their members, not just public types and their public members,
+     * to be reflected on by the given module when using APIs that support
+     * private access or a way to bypass or suppress default Java language
+     * access control checks.
+     *
+     * <p> This method has no effect if the package is already <em>open</em>
+     * to the given module. </p>
+     *
+     * @param  pn
+     *         The package name
+     * @param  other
+     *         The module
+     *
+     * @return this module
+     *
+     * @throws IllegalArgumentException
+     *         If {@code pn} is {@code null}, or this is a named module and the
+     *         package {@code pn} is not a package in this module
+     * @throws IllegalCallerException
+     *         If this is a named module and this module has not opened the
+     *         package to at least the caller's module
+     *
+     * @see #isOpen(String,Module)
+     * @see AccessibleObject#setAccessible(boolean)
+     * @see java.lang.invoke.MethodHandles#privateLookupIn
+     */
+    @CallerSensitive
+    public Module addOpens(String pn, Module other) {
+        if (pn == null)
+            throw new IllegalArgumentException("package is null");
+        Objects.requireNonNull(other);
+
+        if (isNamed()) {
+            Module caller = getCallerModule(Reflection.getCallerClass());
+            if (caller != this && (caller == null || !isOpen(pn, caller)))
+                throw new IllegalCallerException(pn + " is not open to " + caller);
+            implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true);
+        }
+
+        return this;
+    }
+
+
+    /**
+     * Updates this module to export a package unconditionally.
+     *
+     * @apiNote This method is for JDK tests only.
+     */
+    void implAddExports(String pn) {
+        implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, false, true);
+    }
+
+    /**
+     * Updates this module to export a package to another module.
+     *
+     * @apiNote Used by Instrumentation::redefineModule and --add-exports
+     */
+    void implAddExports(String pn, Module other) {
+        implAddExportsOrOpens(pn, other, false, true);
+    }
+
+    /**
+     * Updates this module to export a package to all unnamed modules.
+     *
+     * @apiNote Used by the --add-exports command line option.
+     */
+    void implAddExportsToAllUnnamed(String pn) {
+        implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, false, true);
+    }
+
+    /**
+     * Updates this export to export a package unconditionally without
+     * notifying the VM.
+     *
+     * @apiNote This method is for VM white-box testing.
+     */
+    void implAddExportsNoSync(String pn) {
+        implAddExportsOrOpens(pn.replace('/', '.'), Module.EVERYONE_MODULE, false, false);
+    }
+
+    /**
+     * Updates a module to export a package to another module without
+     * notifying the VM.
+     *
+     * @apiNote This method is for VM white-box testing.
+     */
+    void implAddExportsNoSync(String pn, Module other) {
+        implAddExportsOrOpens(pn.replace('/', '.'), other, false, false);
+    }
+
+    /**
+     * Updates this module to open a package unconditionally.
+     *
+     * @apiNote This method is for JDK tests only.
+     */
+    void implAddOpens(String pn) {
+        implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, true, true);
+    }
+
+    /**
+     * Updates this module to open a package to another module.
+     *
+     * @apiNote Used by Instrumentation::redefineModule and --add-opens
+     */
+    void implAddOpens(String pn, Module other) {
+        implAddExportsOrOpens(pn, other, true, true);
+    }
+
+    /**
+     * Updates this module to export a package to all unnamed modules.
+     *
+     * @apiNote Used by the --add-opens command line option.
+     */
+    void implAddOpensToAllUnnamed(String pn) {
+        implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, true, true);
+    }
+
+
+    /**
+     * Updates a module to export or open a module to another module.
+     *
+     * If {@code syncVM} is {@code true} then the VM is notified.
+     */
+    private void implAddExportsOrOpens(String pn,
+                                       Module other,
+                                       boolean open,
+                                       boolean syncVM) {
+        Objects.requireNonNull(other);
+        Objects.requireNonNull(pn);
+
+        // all packages are open in unnamed, open, and automatic modules
+        if (!isNamed() || descriptor.isOpen() || descriptor.isAutomatic())
+            return;
+
+        // nothing to do if already exported/open to other
+        if (implIsExportedOrOpen(pn, other, open))
+            return;
+
+        // can only export a package in the module
+        if (!containsPackage(pn)) {
+            throw new IllegalArgumentException("package " + pn
+                                               + " not in contents");
+        }
+
+        // update VM first, just in case it fails
+        if (syncVM) {
+            if (other == EVERYONE_MODULE) {
+                addExportsToAll0(this, pn);
+            } else if (other == ALL_UNNAMED_MODULE) {
+                addExportsToAllUnnamed0(this, pn);
+            } else {
+                addExports0(this, pn, other);
+            }
+        }
+
+        // add package name to reflectivelyExports if absent
+        Map<String, Boolean> map = reflectivelyExports
+            .computeIfAbsent(this, other,
+                             (m1, m2) -> new ConcurrentHashMap<>());
+
+        if (open) {
+            map.put(pn, Boolean.TRUE);  // may need to promote from FALSE to TRUE
+        } else {
+            map.putIfAbsent(pn, Boolean.FALSE);
+        }
+    }
+
+
+    // -- services --
+
+    // additional service type (2nd key) that some module (1st key) uses
+    private static final WeakPairMap<Module, Class<?>, Boolean> reflectivelyUses
+        = new WeakPairMap<>();
+
+    /**
+     * If the caller's module is this module then update this module to add a
+     * service dependence on the given service type. This method is intended
+     * for use by frameworks that invoke {@link java.util.ServiceLoader
+     * ServiceLoader} on behalf of other modules or where the framework is
+     * passed a reference to the service type by other code. This method is
+     * a no-op when invoked on an unnamed module or an automatic module.
+     *
+     * <p> This method does not cause {@link Configuration#resolveAndBind
+     * resolveAndBind} to be re-run. </p>
+     *
+     * @param  service
+     *         The service type
+     *
+     * @return this module
+     *
+     * @throws IllegalCallerException
+     *         If this is a named module and the caller's module is not this
+     *         module
+     *
+     * @see #canUse(Class)
+     * @see ModuleDescriptor#uses()
+     */
+    @CallerSensitive
+    public Module addUses(Class<?> service) {
+        Objects.requireNonNull(service);
+
+        if (isNamed() && !descriptor.isAutomatic()) {
+            Module caller = getCallerModule(Reflection.getCallerClass());
+            if (caller != this) {
+                throw new IllegalCallerException(caller + " != " + this);
+            }
+            implAddUses(service);
+        }
+
+        return this;
+    }
+
+    /**
+     * Update this module to add a service dependence on the given service
+     * type.
+     */
+    void implAddUses(Class<?> service) {
+        if (!canUse(service)) {
+            reflectivelyUses.putIfAbsent(this, service, Boolean.TRUE);
+        }
+    }
+
+
+    /**
+     * Indicates if this module has a service dependence on the given service
+     * type. This method always returns {@code true} when invoked on an unnamed
+     * module or an automatic module.
+     *
+     * @param  service
+     *         The service type
+     *
+     * @return {@code true} if this module uses service type {@code st}
+     *
+     * @see #addUses(Class)
+     */
+    public boolean canUse(Class<?> service) {
+        Objects.requireNonNull(service);
+
+        if (!isNamed())
+            return true;
+
+        if (descriptor.isAutomatic())
+            return true;
+
+        // uses was declared
+        if (descriptor.uses().contains(service.getName()))
+            return true;
+
+        // uses added via addUses
+        return reflectivelyUses.containsKeyPair(this, service);
+    }
+
+
+
+    // -- packages --
+
+    // Additional packages that are added to the module at run-time.
+    private volatile Map<String, Boolean> extraPackages;
+
+    private boolean containsPackage(String pn) {
+        if (descriptor.packages().contains(pn))
+            return true;
+        Map<String, Boolean> extraPackages = this.extraPackages;
+        if (extraPackages != null && extraPackages.containsKey(pn))
+            return true;
+        return false;
+    }
+
+
+    /**
+     * Returns the set of package names for the packages in this module.
+     *
+     * <p> For named modules, the returned set contains an element for each
+     * package in the module. </p>
+     *
+     * <p> For unnamed modules, this method is the equivalent to invoking the
+     * {@link ClassLoader#getDefinedPackages() getDefinedPackages} method of
+     * this module's class loader and returning the set of package names. </p>
+     *
+     * @return the set of the package names of the packages in this module
+     */
+    public Set<String> getPackages() {
+        if (isNamed()) {
+
+            Set<String> packages = descriptor.packages();
+            Map<String, Boolean> extraPackages = this.extraPackages;
+            if (extraPackages == null) {
+                return packages;
+            } else {
+                return Stream.concat(packages.stream(),
+                                     extraPackages.keySet().stream())
+                        .collect(Collectors.toSet());
+            }
+
+        } else {
+            // unnamed module
+            Stream<Package> packages;
+            if (loader == null) {
+                packages = BootLoader.packages();
+            } else {
+                packages = SharedSecrets.getJavaLangAccess().packages(loader);
+            }
+            return packages.map(Package::getName).collect(Collectors.toSet());
+        }
+    }
+
+    /**
+     * Add a package to this module without notifying the VM.
+     *
+     * @apiNote This method is VM white-box testing.
+     */
+    void implAddPackageNoSync(String pn) {
+        implAddPackage(pn.replace('/', '.'), false);
+    }
+
+    /**
+     * Add a package to this module.
+     *
+     * If {@code syncVM} is {@code true} then the VM is notified. This method is
+     * a no-op if this is an unnamed module or the module already contains the
+     * package.
+     *
+     * @throws IllegalArgumentException if the package name is not legal
+     * @throws IllegalStateException if the package is defined to another module
+     */
+    private void implAddPackage(String pn, boolean syncVM) {
+        // no-op if unnamed module
+        if (!isNamed())
+            return;
+
+        // no-op if module contains the package
+        if (containsPackage(pn))
+            return;
+
+        // check package name is legal for named modules
+        if (pn.isEmpty())
+            throw new IllegalArgumentException("Cannot add <unnamed> package");
+        for (int i=0; i<pn.length(); i++) {
+            char c = pn.charAt(i);
+            if (c == '/' || c == ';' || c == '[') {
+                throw new IllegalArgumentException("Illegal character: " + c);
+            }
+        }
+
+        // create extraPackages if needed
+        Map<String, Boolean> extraPackages = this.extraPackages;
+        if (extraPackages == null) {
+            synchronized (this) {
+                extraPackages = this.extraPackages;
+                if (extraPackages == null)
+                    this.extraPackages = extraPackages = new ConcurrentHashMap<>();
+            }
+        }
+
+        // update VM first in case it fails. This is a no-op if another thread
+        // beats us to add the package first
+        if (syncVM) {
+            // throws IllegalStateException if defined to another module
+            addPackage0(this, pn);
+            if (descriptor.isOpen() || descriptor.isAutomatic()) {
+                addExportsToAll0(this, pn);
+            }
+        }
+        extraPackages.putIfAbsent(pn, Boolean.TRUE);
+    }
+
+
+    // -- creating Module objects --
+
+    /**
+     * Defines all module in a configuration to the runtime.
+     *
+     * @return a map of module name to runtime {@code Module}
+     *
+     * @throws IllegalArgumentException
+     *         If defining any of the modules to the VM fails
+     */
+    static Map<String, Module> defineModules(Configuration cf,
+                                             Function<String, ClassLoader> clf,
+                                             ModuleLayer layer)
+    {
+        Map<String, Module> nameToModule = new HashMap<>();
+        Map<String, ClassLoader> moduleToLoader = new HashMap<>();
+
+        boolean isBootLayer = (ModuleLayer.boot() == null);
+        Set<ClassLoader> loaders = new HashSet<>();
+
+        // map each module to a class loader
+        for (ResolvedModule resolvedModule : cf.modules()) {
+            String name = resolvedModule.name();
+            ClassLoader loader = clf.apply(name);
+            if (loader != null) {
+                moduleToLoader.put(name, loader);
+                loaders.add(loader);
+            } else if (!isBootLayer) {
+                throw new IllegalArgumentException("loader can't be 'null'");
+            }
+        }
+
+        // define each module in the configuration to the VM
+        for (ResolvedModule resolvedModule : cf.modules()) {
+            ModuleReference mref = resolvedModule.reference();
+            ModuleDescriptor descriptor = mref.descriptor();
+            String name = descriptor.name();
+            URI uri = mref.location().orElse(null);
+            ClassLoader loader = moduleToLoader.get(resolvedModule.name());
+            Module m;
+            if (loader == null && isBootLayer && name.equals("java.base")) {
+                // java.base is already defined to the VM
+                m = Object.class.getModule();
+            } else {
+                m = new Module(layer, loader, descriptor, uri);
+            }
+            nameToModule.put(name, m);
+            moduleToLoader.put(name, loader);
+        }
+
+        // setup readability and exports
+        for (ResolvedModule resolvedModule : cf.modules()) {
+            ModuleReference mref = resolvedModule.reference();
+            ModuleDescriptor descriptor = mref.descriptor();
+
+            String mn = descriptor.name();
+            Module m = nameToModule.get(mn);
+            assert m != null;
+
+            // reads
+            Set<Module> reads = new HashSet<>();
+
+            // name -> source Module when in parent layer
+            Map<String, Module> nameToSource = Collections.emptyMap();
+
+            for (ResolvedModule other : resolvedModule.reads()) {
+                Module m2 = null;
+                if (other.configuration() == cf) {
+                    // this configuration
+                    m2 = nameToModule.get(other.name());
+                    assert m2 != null;
+                } else {
+                    // parent layer
+                    for (ModuleLayer parent: layer.parents()) {
+                        m2 = findModule(parent, other);
+                        if (m2 != null)
+                            break;
+                    }
+                    assert m2 != null;
+                    if (nameToSource.isEmpty())
+                        nameToSource = new HashMap<>();
+                    nameToSource.put(other.name(), m2);
+                }
+                reads.add(m2);
+
+                // update VM view
+                addReads0(m, m2);
+            }
+            m.reads = reads;
+
+            // automatic modules read all unnamed modules
+            if (descriptor.isAutomatic()) {
+                m.implAddReads(ALL_UNNAMED_MODULE, true);
+            }
+
+            // exports and opens
+            initExportsAndOpens(m, nameToSource, nameToModule, layer.parents());
+        }
+
+        // register the modules in the boot layer
+        if (isBootLayer) {
+            for (ResolvedModule resolvedModule : cf.modules()) {
+                ModuleReference mref = resolvedModule.reference();
+                ModuleDescriptor descriptor = mref.descriptor();
+                if (!descriptor.provides().isEmpty()) {
+                    String name = descriptor.name();
+                    Module m = nameToModule.get(name);
+                    ClassLoader loader = moduleToLoader.get(name);
+                    ServicesCatalog catalog;
+                    if (loader == null) {
+                        catalog = BootLoader.getServicesCatalog();
+                    } else {
+                        catalog = ServicesCatalog.getServicesCatalog(loader);
+                    }
+                    catalog.register(m);
+                }
+            }
+        }
+
+        // record that there is a layer with modules defined to the class loader
+        for (ClassLoader loader : loaders) {
+            layer.bindToLoader(loader);
+        }
+
+        return nameToModule;
+    }
+
+
+    /**
+     * Find the runtime Module corresponding to the given ResolvedModule
+     * in the given parent layer (or its parents).
+     */
+    private static Module findModule(ModuleLayer parent,
+                                     ResolvedModule resolvedModule) {
+        Configuration cf = resolvedModule.configuration();
+        String dn = resolvedModule.name();
+        return parent.layers()
+                .filter(l -> l.configuration() == cf)
+                .findAny()
+                .map(layer -> {
+                    Optional<Module> om = layer.findModule(dn);
+                    assert om.isPresent() : dn + " not found in layer";
+                    Module m = om.get();
+                    assert m.getLayer() == layer : m + " not in expected layer";
+                    return m;
+                })
+                .orElse(null);
+    }
+
+
+    /**
+     * Initialize the maps of exported and open packages for module m.
+     */
+    private static void initExportsAndOpens(Module m,
+                                            Map<String, Module> nameToSource,
+                                            Map<String, Module> nameToModule,
+                                            List<ModuleLayer> parents) {
+        // The VM doesn't special case open or automatic modules so need to
+        // export all packages
+        ModuleDescriptor descriptor = m.getDescriptor();
+        if (descriptor.isOpen() || descriptor.isAutomatic()) {
+            assert descriptor.opens().isEmpty();
+            for (String source : descriptor.packages()) {
+                addExportsToAll0(m, source);
+            }
+            return;
+        }
+
+        Map<String, Set<Module>> openPackages = new HashMap<>();
+        Map<String, Set<Module>> exportedPackages = new HashMap<>();
+
+        // process the open packages first
+        for (Opens opens : descriptor.opens()) {
+            String source = opens.source();
+
+            if (opens.isQualified()) {
+                // qualified opens
+                Set<Module> targets = new HashSet<>();
+                for (String target : opens.targets()) {
+                    Module m2 = findModule(target, nameToSource, nameToModule, parents);
+                    if (m2 != null) {
+                        addExports0(m, source, m2);
+                        targets.add(m2);
+                    }
+                }
+                if (!targets.isEmpty()) {
+                    openPackages.put(source, targets);
+                }
+            } else {
+                // unqualified opens
+                addExportsToAll0(m, source);
+                openPackages.put(source, EVERYONE_SET);
+            }
+        }
+
+        // next the exports, skipping exports when the package is open
+        for (Exports exports : descriptor.exports()) {
+            String source = exports.source();
+
+            // skip export if package is already open to everyone
+            Set<Module> openToTargets = openPackages.get(source);
+            if (openToTargets != null && openToTargets.contains(EVERYONE_MODULE))
+                continue;
+
+            if (exports.isQualified()) {
+                // qualified exports
+                Set<Module> targets = new HashSet<>();
+                for (String target : exports.targets()) {
+                    Module m2 = findModule(target, nameToSource, nameToModule, parents);
+                    if (m2 != null) {
+                        // skip qualified export if already open to m2
+                        if (openToTargets == null || !openToTargets.contains(m2)) {
+                            addExports0(m, source, m2);
+                            targets.add(m2);
+                        }
+                    }
+                }
+                if (!targets.isEmpty()) {
+                    exportedPackages.put(source, targets);
+                }
+
+            } else {
+                // unqualified exports
+                addExportsToAll0(m, source);
+                exportedPackages.put(source, EVERYONE_SET);
+            }
+        }
+
+        if (!openPackages.isEmpty())
+            m.openPackages = openPackages;
+        if (!exportedPackages.isEmpty())
+            m.exportedPackages = exportedPackages;
+    }
+
+    /**
+     * Find the runtime Module with the given name. The module name is the
+     * name of a target module in a qualified exports or opens directive.
+     *
+     * @param target The target module to find
+     * @param nameToSource The modules in parent layers that are read
+     * @param nameToModule The modules in the layer under construction
+     * @param parents The parent layers
+     */
+    private static Module findModule(String target,
+                                     Map<String, Module> nameToSource,
+                                     Map<String, Module> nameToModule,
+                                     List<ModuleLayer> parents) {
+        Module m = nameToSource.get(target);
+        if (m == null) {
+            m = nameToModule.get(target);
+            if (m == null) {
+                for (ModuleLayer parent : parents) {
+                    m = parent.findModule(target).orElse(null);
+                    if (m != null) break;
+                }
+            }
+        }
+        return m;
+    }
+
+
+    // -- annotations --
+
+    /**
+     * {@inheritDoc}
+     * This method returns {@code null} when invoked on an unnamed module.
+     */
+    @Override
+    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
+        return moduleInfoClass().getDeclaredAnnotation(annotationClass);
+    }
+
+    /**
+     * {@inheritDoc}
+     * This method returns an empty array when invoked on an unnamed module.
+     */
+    @Override
+    public Annotation[] getAnnotations() {
+        return moduleInfoClass().getAnnotations();
+    }
+
+    /**
+     * {@inheritDoc}
+     * This method returns an empty array when invoked on an unnamed module.
+     */
+    @Override
+    public Annotation[] getDeclaredAnnotations() {
+        return moduleInfoClass().getDeclaredAnnotations();
+    }
+
+    // cached class file with annotations
+    private volatile Class<?> moduleInfoClass;
+
+    private Class<?> moduleInfoClass() {
+        Class<?> clazz = this.moduleInfoClass;
+        if (clazz != null)
+            return clazz;
+
+        synchronized (this) {
+            clazz = this.moduleInfoClass;
+            if (clazz == null) {
+                if (isNamed()) {
+                    PrivilegedAction<Class<?>> pa = this::loadModuleInfoClass;
+                    clazz = AccessController.doPrivileged(pa);
+                }
+                if (clazz == null) {
+                    class DummyModuleInfo { }
+                    clazz = DummyModuleInfo.class;
+                }
+                this.moduleInfoClass = clazz;
+            }
+            return clazz;
+        }
+    }
+
+    private Class<?> loadModuleInfoClass() {
+        Class<?> clazz = null;
+        try (InputStream in = getResourceAsStream("module-info.class")) {
+            if (in != null)
+                clazz = loadModuleInfoClass(in);
+        } catch (Exception ignore) { }
+        return clazz;
+    }
+
+    /**
+     * Loads module-info.class as a package-private interface in a class loader
+     * that is a child of this module's class loader.
+     */
+    private Class<?> loadModuleInfoClass(InputStream in) throws IOException {
+        final String MODULE_INFO = "module-info";
+
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS
+                                         + ClassWriter.COMPUTE_FRAMES);
+
+        ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
+            @Override
+            public void visit(int version,
+                              int access,
+                              String name,
+                              String signature,
+                              String superName,
+                              String[] interfaces) {
+                cw.visit(version,
+                        Opcodes.ACC_INTERFACE
+                            + Opcodes.ACC_ABSTRACT
+                            + Opcodes.ACC_SYNTHETIC,
+                        MODULE_INFO,
+                        null,
+                        "java/lang/Object",
+                        null);
+            }
+            @Override
+            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
+                // keep annotations
+                return super.visitAnnotation(desc, visible);
+            }
+            @Override
+            public void visitAttribute(Attribute attr) {
+                // drop non-annotation attributes
+            }
+        };
+
+        ClassReader cr = new ClassReader(in);
+        cr.accept(cv, 0);
+        byte[] bytes = cw.toByteArray();
+
+        ClassLoader cl = new ClassLoader(loader) {
+            @Override
+            protected Class<?> findClass(String cn)throws ClassNotFoundException {
+                if (cn.equals(MODULE_INFO)) {
+                    return super.defineClass(cn, bytes, 0, bytes.length);
+                } else {
+                    throw new ClassNotFoundException(cn);
+                }
+            }
+        };
+
+        try {
+            return cl.loadClass(MODULE_INFO);
+        } catch (ClassNotFoundException e) {
+            throw new InternalError(e);
+        }
+    }
+
+
+    // -- misc --
+
+
+    /**
+     * Returns an input stream for reading a resource in this module.
+     * The {@code name} parameter is a {@code '/'}-separated path name that
+     * identifies the resource. As with {@link Class#getResourceAsStream
+     * Class.getResourceAsStream}, this method delegates to the module's class
+     * loader {@link ClassLoader#findResource(String,String)
+     * findResource(String,String)} method, invoking it with the module name
+     * (or {@code null} when the module is unnamed) and the name of the
+     * resource. If the resource name has a leading slash then it is dropped
+     * before delegation.
+     *
+     * <p> A resource in a named module may be <em>encapsulated</em> so that
+     * it cannot be located by code in other modules. Whether a resource can be
+     * located or not is determined as follows: </p>
+     *
+     * <ul>
+     *     <li> If the resource name ends with  "{@code .class}" then it is not
+     *     encapsulated. </li>
+     *
+     *     <li> A <em>package name</em> is derived from the resource name. If
+     *     the package name is a {@link #getPackages() package} in the module
+     *     then the resource can only be located by the caller of this method
+     *     when the package is {@link #isOpen(String,Module) open} to at least
+     *     the caller's module. If the resource is not in a package in the module
+     *     then the resource is not encapsulated. </li>
+     * </ul>
+     *
+     * <p> In the above, the <em>package name</em> for a resource is derived
+     * from the subsequence of characters that precedes the last {@code '/'} in
+     * the name and then replacing each {@code '/'} character in the subsequence
+     * with {@code '.'}. A leading slash is ignored when deriving the package
+     * name. As an example, the package name derived for a resource named
+     * "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name
+     * with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated
+     * because "{@code META-INF}" is not a legal package name. </p>
+     *
+     * <p> This method returns {@code null} if the resource is not in this
+     * module, the resource is encapsulated and cannot be located by the caller,
+     * or access to the resource is denied by the security manager. </p>
+     *
+     * @param  name
+     *         The resource name
+     *
+     * @return An input stream for reading the resource or {@code null}
+     *
+     * @throws IOException
+     *         If an I/O error occurs
+     *
+     * @see Class#getResourceAsStream(String)
+     */
+    @CallerSensitive
+    public InputStream getResourceAsStream(String name) throws IOException {
+        if (name.startsWith("/")) {
+            name = name.substring(1);
+        }
+
+        if (isNamed() && Resources.canEncapsulate(name)) {
+            Module caller = getCallerModule(Reflection.getCallerClass());
+            if (caller != this && caller != Object.class.getModule()) {
+                String pn = Resources.toPackageName(name);
+                if (getPackages().contains(pn)) {
+                    if (caller == null && !isOpen(pn)) {
+                        // no caller, package not open
+                        return null;
+                    }
+                    if (!isOpen(pn, caller)) {
+                        // package not open to caller
+                        return null;
+                    }
+                }
+            }
+        }
+
+        String mn = this.name;
+
+        // special-case built-in class loaders to avoid URL connection
+        if (loader == null) {
+            return BootLoader.findResourceAsStream(mn, name);
+        } else if (loader instanceof BuiltinClassLoader) {
+            return ((BuiltinClassLoader) loader).findResourceAsStream(mn, name);
+        }
+
+        // locate resource in module
+        JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
+        URL url = jla.findResource(loader, mn, name);
+        if (url != null) {
+            try {
+                return url.openStream();
+            } catch (SecurityException e) { }
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns the string representation of this module. For a named module,
+     * the representation is the string {@code "module"}, followed by a space,
+     * and then the module name. For an unnamed module, the representation is
+     * the string {@code "unnamed module"}, followed by a space, and then an
+     * implementation specific string that identifies the unnamed module.
+     *
+     * @return The string representation of this module
+     */
+    @Override
+    public String toString() {
+        if (isNamed()) {
+            return "module " + name;
+        } else {
+            String id = Integer.toHexString(System.identityHashCode(this));
+            return "unnamed module @" + id;
+        }
+    }
+
+    /**
+     * Returns the module that a given caller class is a member of. Returns
+     * {@code null} if the caller is {@code null}.
+     */
+    private Module getCallerModule(Class<?> caller) {
+        return (caller != null) ? caller.getModule() : null;
+    }
+
+
+    // -- native methods --
+
+    // JVM_DefineModule
+    private static native void defineModule0(Module module,
+                                             boolean isOpen,
+                                             String version,
+                                             String location,
+                                             String[] pns);
+
+    // JVM_AddReadsModule
+    private static native void addReads0(Module from, Module to);
+
+    // JVM_AddModuleExports
+    private static native void addExports0(Module from, String pn, Module to);
+
+    // JVM_AddModuleExportsToAll
+    private static native void addExportsToAll0(Module from, String pn);
+
+    // JVM_AddModuleExportsToAllUnnamed
+    private static native void addExportsToAllUnnamed0(Module from, String pn);
+
+    // JVM_AddModulePackage
+    private static native void addPackage0(Module m, String pn);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/lang/ModuleLayer.java	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,944 @@
+/*
+ * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.lang.module.Configuration;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ResolvedModule;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import jdk.internal.loader.ClassLoaderValue;
+import jdk.internal.loader.Loader;
+import jdk.internal.loader.LoaderPool;
+import jdk.internal.module.ServicesCatalog;
+import sun.security.util.SecurityConstants;
+
+
+/**
+ * A layer of modules in the Java virtual machine.
+ *
+ * <p> A layer is created from a graph of modules in a {@link Configuration}
+ * and a function that maps each module to a {@link ClassLoader}.
+ * Creating a layer informs the Java virtual machine about the classes that
+ * may be loaded from the modules so that the Java virtual machine knows which
+ * module that each class is a member of. </p>
+ *
+ * <p> Creating a layer creates a {@link Module} object for each {@link
+ * ResolvedModule} in the configuration. For each resolved module that is
+ * {@link ResolvedModule#reads() read}, the {@code Module} {@link
+ * Module#canRead reads} the corresponding run-time {@code Module}, which may
+ * be in the same layer or a {@link #parents() parent} layer. </p>
+ *
+ * <p> The {@link #defineModulesWithOneLoader defineModulesWithOneLoader} and
+ * {@link #defineModulesWithManyLoaders defineModulesWithManyLoaders} methods
+ * provide convenient ways to create a module layer where all modules are
+ * mapped to a single class loader or where each module is mapped to its own
+ * class loader. The {@link #defineModules defineModules} method is for more
+ * advanced cases where modules are mapped to custom class loaders by means of
+ * a function specified to the method. Each of these methods has an instance
+ * and static variant. The instance methods create a layer with the receiver
+ * as the parent layer. The static methods are for more advanced cases where
+ * there can be more than one parent layer or where a {@link
+ * ModuleLayer.Controller Controller} is needed to control modules in the layer
+ * </p>
+ *
+ * <p> A Java virtual machine has at least one non-empty layer, the {@link
+ * #boot() boot} layer, that is created when the Java virtual machine is
+ * started. The boot layer contains module {@code java.base} and is the only
+ * layer in the Java virtual machine with a module named "{@code java.base}".
+ * The modules in the boot layer are mapped to the bootstrap class loader and
+ * other class loaders that are <a href="../ClassLoader.html#builtinLoaders">
+ * built-in</a> into the Java virtual machine. The boot layer will often be
+ * the {@link #parents() parent} when creating additional layers. </p>
+ *
+ * <p> Each {@code Module} in a layer is created so that it {@link
+ * Module#isExported(String) exports} and {@link Module#isOpen(String) opens}
+ * the packages described by its {@link ModuleDescriptor}. Qualified exports
+ * (where a package is exported to a set of target modules rather than all
+ * modules) are reified when creating the layer as follows: </p>
+ * <ul>
+ *     <li> If module {@code X} exports a package to {@code Y}, and if the
+ *     runtime {@code Module} {@code X} reads {@code Module} {@code Y}, then
+ *     the package is exported to {@code Module} {@code Y} (which may be in
+ *     the same layer as {@code X} or a parent layer). </li>
+ *
+ *     <li> If module {@code X} exports a package to {@code Y}, and if the
+ *     runtime {@code Module} {@code X} does not read {@code Y} then target
+ *     {@code Y} is located as if by invoking {@link #findModule(String)
+ *     findModule} to find the module in the layer or its parent layers. If
+ *     {@code Y} is found then the package is exported to the instance of
+ *     {@code Y} that was found. If {@code Y} is not found then the qualified
+ *     export is ignored. </li>
+ * </ul>
+ *
+ * <p> Qualified opens are handled in same way as qualified exports. </p>
+ *
+ * <p> As when creating a {@code Configuration},
+ * {@link ModuleDescriptor#isAutomatic() automatic} modules receive special
+ * treatment when creating a layer. An automatic module is created in the
+ * Java virtual machine as a {@code Module} that reads every unnamed {@code
+ * Module} in the Java virtual machine. </p>
+ *
+ * <p> Unless otherwise specified, passing a {@code null} argument to a method
+ * in this class causes a {@link NullPointerException NullPointerException} to
+ * be thrown. </p>
+ *
+ * <h3> Example usage: </h3>
+ *
+ * <p> This example creates a configuration by resolving a module named
+ * "{@code myapp}" with the configuration for the boot layer as the parent. It
+ * then creates a new layer with the modules in this configuration. All modules
+ * are defined to the same class loader. </p>
+ *
+ * <pre>{@code
+ *     ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
+ *
+ *     ModuleLayer parent = ModuleLayer.boot();
+ *
+ *     Configuration cf = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("myapp"));
+ *
+ *     ClassLoader scl = ClassLoader.getSystemClassLoader();
+ *
+ *     ModuleLayer layer = parent.defineModulesWithOneLoader(cf, scl);
+ *
+ *     Class<?> c = layer.findLoader("myapp").loadClass("app.Main");
+ * }</pre>
+ *
+ * @since 9
+ * @spec JPMS
+ * @see Module#getLayer()
+ */
+
+public final class ModuleLayer {
+
+    // the empty layer
+    private static final ModuleLayer EMPTY_LAYER
+        = new ModuleLayer(Configuration.empty(), List.of(), null);
+
+    // the configuration from which this ;ayer was created
+    private final Configuration cf;
+
+    // parent layers, empty in the case of the empty layer
+    private final List<ModuleLayer> parents;
+
+    // maps module name to jlr.Module
+    private final Map<String, Module> nameToModule;
+
+    /**
+     * Creates a new module layer from the modules in the given configuration.
+     */
+    private ModuleLayer(Configuration cf,
+                        List<ModuleLayer> parents,
+                        Function<String, ClassLoader> clf)
+    {
+        this.cf = cf;
+        this.parents = parents; // no need to do defensive copy
+
+        Map<String, Module> map;
+        if (parents.isEmpty()) {
+            map = Collections.emptyMap();
+        } else {
+            map = Module.defineModules(cf, clf, this);
+        }
+        this.nameToModule = map; // no need to do defensive copy
+    }
+
+    /**
+     * Controls a module layer. The static methods defined by {@link ModuleLayer}
+     * to create module layers return a {@code Controller} that can be used to
+     * control modules in the layer.
+     *
+     * <p> Unless otherwise specified, passing a {@code null} argument to a
+     * method in this class causes a {@link NullPointerException
+     * NullPointerException} to be thrown. </p>
+     *
+     * @apiNote Care should be taken with {@code Controller} objects, they
+     * should never be shared with untrusted code.
+     *
+     * @since 9
+     * @spec JPMS
+     */
+    public static final class Controller {
+        private final ModuleLayer layer;
+
+        Controller(ModuleLayer layer) {
+            this.layer = layer;
+        }
+
+        /**
+         * Returns the layer that this object controls.
+         *
+         * @return the module layer
+         */
+        public ModuleLayer layer() {
+            return layer;
+        }
+
+        private void ensureInLayer(Module source) {
+            if (source.getLayer() != layer)
+                throw new IllegalArgumentException(source + " not in layer");
+        }
+
+
+        /**
+         * Updates module {@code source} in the layer to read module
+         * {@code target}. This method is a no-op if {@code source} already
+         * reads {@code target}.
+         *
+         * @implNote <em>Read edges</em> added by this method are <em>weak</em>
+         * and do not prevent {@code target} from being GC'ed when {@code source}
+         * is strongly reachable.
+         *
+         * @param  source
+         *         The source module
+         * @param  target
+         *         The target module to read
+         *
+         * @return This controller
+         *
+         * @throws IllegalArgumentException
+         *         If {@code source} is not in the module layer
+         *
+         * @see Module#addReads
+         */
+        public Controller addReads(Module source, Module target) {
+            ensureInLayer(source);
+            source.implAddReads(target);
+            return this;
+        }
+
+        /**
+         * Updates module {@code source} in the layer to open a package to
+         * module {@code target}. This method is a no-op if {@code source}
+         * already opens the package to at least {@code target}.
+         *
+         * @param  source
+         *         The source module
+         * @param  pn
+         *         The package name
+         * @param  target
+         *         The target module to read
+         *
+         * @return This controller
+         *
+         * @throws IllegalArgumentException
+         *         If {@code source} is not in the module layer or the package
+         *         is not in the source module
+         *
+         * @see Module#addOpens
+         */
+        public Controller addOpens(Module source, String pn, Module target) {
+            ensureInLayer(source);
+            source.implAddOpens(pn, target);
+            return this;
+        }
+    }
+
+
+    /**
+     * Creates a new module layer, with this layer as its parent, by defining the
+     * modules in the given {@code Configuration} to the Java virtual machine.
+     * This method creates one class loader and defines all modules to that
+     * class loader. The {@link ClassLoader#getParent() parent} of each class
+     * loader is the given parent class loader. This method works exactly as
+     * specified by the static {@link
+     * #defineModulesWithOneLoader(Configuration,List,ClassLoader)
+     * defineModulesWithOneLoader} method when invoked with this layer as the
+     * parent. In other words, if this layer is {@code thisLayer} then this
+     * method is equivalent to invoking:
+     * <pre> {@code
+     *     ModuleLayer.defineModulesWithOneLoader(cf, List.of(thisLayer), parentLoader).layer();
+     * }</pre>
+     *
+     * @param  cf
+     *         The configuration for the layer
+     * @param  parentLoader
+     *         The parent class loader for the class loader created by this
+     *         method; may be {@code null} for the bootstrap class loader
+     *
+     * @return The newly created layer
+     *
+     * @throws IllegalArgumentException
+     *         If the parent of the given configuration is not the configuration
+     *         for this layer
+     * @throws LayerInstantiationException
+     *         If the layer cannot be created for any of the reasons specified
+     *         by the static {@code defineModulesWithOneLoader} method
+     * @throws SecurityException
+     *         If {@code RuntimePermission("createClassLoader")} or
+     *         {@code RuntimePermission("getClassLoader")} is denied by
+     *         the security manager
+     *
+     * @see #findLoader
+     */
+    public ModuleLayer defineModulesWithOneLoader(Configuration cf,
+                                                  ClassLoader parentLoader) {
+        return defineModulesWithOneLoader(cf, List.of(this), parentLoader).layer();
+    }
+
+
+    /**
+     * Creates a new module layer, with this layer as its parent, by defining the
+     * modules in the given {@code Configuration} to the Java virtual machine.
+     * Each module is defined to its own {@link ClassLoader} created by this
+     * method. The {@link ClassLoader#getParent() parent} of each class loader
+     * is the given parent class loader. This method works exactly as specified
+     * by the static {@link
+     * #defineModulesWithManyLoaders(Configuration,List,ClassLoader)
+     * defineModulesWithManyLoaders} method when invoked with this layer as the
+     * parent. In other words, if this layer is {@code thisLayer} then this
+     * method is equivalent to invoking:
+     * <pre> {@code
+     *     ModuleLayer.defineModulesWithManyLoaders(cf, List.of(thisLayer), parentLoader).layer();
+     * }</pre>
+     *
+     * @param  cf
+     *         The configuration for the layer
+     * @param  parentLoader
+     *         The parent class loader for each of the class loaders created by
+     *         this method; may be {@code null} for the bootstrap class loader
+     *
+     * @return The newly created layer
+     *
+     * @throws IllegalArgumentException
+     *         If the parent of the given configuration is not the configuration
+     *         for this layer
+     * @throws LayerInstantiationException
+     *         If the layer cannot be created for any of the reasons specified
+     *         by the static {@code defineModulesWithManyLoaders} method
+     * @throws SecurityException
+     *         If {@code RuntimePermission("createClassLoader")} or
+     *         {@code RuntimePermission("getClassLoader")} is denied by
+     *         the security manager
+     *
+     * @see #findLoader
+     */
+    public ModuleLayer defineModulesWithManyLoaders(Configuration cf,
+                                                    ClassLoader parentLoader) {
+        return defineModulesWithManyLoaders(cf, List.of(this), parentLoader).layer();
+    }
+
+
+    /**
+     * Creates a new module layer, with this layer as its parent, by defining the
+     * modules in the given {@code Configuration} to the Java virtual machine.
+     * Each module is mapped, by name, to its class loader by means of the
+     * given function. This method works exactly as specified by the static
+     * {@link #defineModules(Configuration,List,Function) defineModules}
+     * method when invoked with this layer as the parent. In other words, if
+     * this layer is {@code thisLayer} then this method is equivalent to
+     * invoking:
+     * <pre> {@code
+     *     ModuleLayer.defineModules(cf, List.of(thisLayer), clf).layer();
+     * }</pre>
+     *
+     * @param  cf
+     *         The configuration for the layer
+     * @param  clf
+     *         The function to map a module name to a class loader
+     *
+     * @return The newly created layer
+     *
+     * @throws IllegalArgumentException
+     *         If the parent of the given configuration is not the configuration
+     *         for this layer
+     * @throws LayerInstantiationException
+     *         If the layer cannot be created for any of the reasons specified
+     *         by the static {@code defineModules} method
+     * @throws SecurityException
+     *         If {@code RuntimePermission("getClassLoader")} is denied by
+     *         the security manager
+     */
+    public ModuleLayer defineModules(Configuration cf,
+                                     Function<String, ClassLoader> clf) {
+        return defineModules(cf, List.of(this), clf).layer();
+    }
+
+    /**
+     * Creates a new module layer by defining the modules in the given {@code
+     * Configuration} to the Java virtual machine. This method creates one
+     * class loader and defines all modules to that class loader.
+     *
+     * <p> The class loader created by this method implements <em>direct
+     * delegation</em> when loading types from modules. When its {@link
+     * ClassLoader#loadClass(String, boolean) loadClass} method is invoked to
+     * load a class then it uses the package name of the class to map it to a
+     * module. This may be a module in this layer and hence defined to the same
+     * class loader. It may be a package in a module in a parent layer that is
+     * exported to one or more of the modules in this layer. The class
+     * loader delegates to the class loader of the module, throwing {@code
+     * ClassNotFoundException} if not found by that class loader.
+     * When {@code loadClass} is invoked to load classes that do not map to a
+     * module then it delegates to the parent class loader. </p>
+     *
+     * <p> Attempting to create a layer with all modules defined to the same
+     * class loader can fail for the following reasons:
+     *
+     * <ul>
+     *
+     *     <li><p> <em>Overlapping packages</em>: Two or more modules in the
+     *     configuration have the same package. </p></li>
+     *
+     *     <li><p> <em>Split delegation</em>: The resulting class loader would
+     *     need to delegate to more than one class loader in order to load types
+     *     in a specific package. </p></li>
+     *
+     * </ul>
+     *
+     * <p> In addition, a layer cannot be created if the configuration contains
+     * a module named "{@code java.base}", or a module contains a package named
+     * "{@code java}" or a package with a name starting with "{@code java.}". </p>
+     *
+     * <p> If there is a security manager then the class loader created by
+     * this method will load classes and resources with privileges that are
+     * restricted by the calling context of this method. </p>
+     *
+     * @param  cf
+     *         The configuration for the layer
+     * @param  parentLayers
+     *         The list of parent layers in search order
+     * @param  parentLoader
+     *         The parent class loader for the class loader created by this
+     *         method; may be {@code null} for the bootstrap class loader
+     *
+     * @return A controller that controls the newly created layer
+     *
+     * @throws IllegalArgumentException
+     *         If the parent configurations do not match the configuration of
+     *         the parent layers, including order
+     * @throws LayerInstantiationException
+     *         If all modules cannot be defined to the same class loader for any
+     *         of the reasons listed above
+     * @throws SecurityException
+     *         If {@code RuntimePermission("createClassLoader")} or
+     *         {@code RuntimePermission("getClassLoader")} is denied by
+     *         the security manager
+     *
+     * @see #findLoader
+     */
+    public static Controller defineModulesWithOneLoader(Configuration cf,
+                                                        List<ModuleLayer> parentLayers,
+                                                        ClassLoader parentLoader)
+    {
+        List<ModuleLayer> parents = new ArrayList<>(parentLayers);
+        checkConfiguration(cf, parents);
+
+        checkCreateClassLoaderPermission();
+        checkGetClassLoaderPermission();
+
+        try {
+            Loader loader = new Loader(cf.modules(), parentLoader);
+            loader.initRemotePackageMap(cf, parents);
+            ModuleLayer layer =  new ModuleLayer(cf, parents, mn -> loader);
+            return new Controller(layer);
+        } catch (IllegalArgumentException | IllegalStateException e) {
+            throw new LayerInstantiationException(e.getMessage());
+        }
+    }
+
+    /**
+     * Creates a new module layer by defining the modules in the given {@code
+     * Configuration} to the Java virtual machine. Each module is defined to
+     * its own {@link ClassLoader} created by this method. The {@link
+     * ClassLoader#getParent() parent} of each class loader is the given parent
+     * class loader.
+     *
+     * <p> The class loaders created by this method implement <em>direct
+     * delegation</em> when loading types from modules. When {@link
+     * ClassLoader#loadClass(String, boolean) loadClass} method is invoked to
+     * load a class then it uses the package name of the class to map it to a
+     * module. The package may be in the module defined to the class loader.
+     * The package may be exported by another module in this layer to the
+     * module defined to the class loader. It may be in a package exported by a
+     * module in a parent layer. The class loader delegates to the class loader
+     * of the module, throwing {@code ClassNotFoundException} if not found by
+     * that class loader.
+     * When {@code loadClass} is invoked to load classes that do not map to a
+     * module then it delegates to the parent class loader. </p>
+     *
+     * <p> If there is a security manager then the class loaders created by
+     * this method will load classes and resources with privileges that are
+     * restricted by the calling context of this method. </p>
+     *
+     * @param  cf
+     *         The configuration for the layer
+     * @param  parentLayers
+     *         The list of parent layers in search order
+     * @param  parentLoader
+     *         The parent class loader for each of the class loaders created by
+     *         this method; may be {@code null} for the bootstrap class loader
+     *
+     * @return A controller that controls the newly created layer
+     *
+     * @throws IllegalArgumentException
+     *         If the parent configurations do not match the configuration of
+     *         the parent layers, including order
+     * @throws LayerInstantiationException
+     *         If the layer cannot be created because the configuration contains
+     *         a module named "{@code java.base}" or a module contains a package
+     *         named "{@code java}" or a package with a name starting with
+     *         "{@code java.}"
+     *
+     * @throws SecurityException
+     *         If {@code RuntimePermission("createClassLoader")} or
+     *         {@code RuntimePermission("getClassLoader")} is denied by
+     *         the security manager
+     *
+     * @see #findLoader
+     */
+    public static Controller defineModulesWithManyLoaders(Configuration cf,
+                                                          List<ModuleLayer> parentLayers,
+                                                          ClassLoader parentLoader)
+    {
+        List<ModuleLayer> parents = new ArrayList<>(parentLayers);
+        checkConfiguration(cf, parents);
+
+        checkCreateClassLoaderPermission();
+        checkGetClassLoaderPermission();
+
+        LoaderPool pool = new LoaderPool(cf, parents, parentLoader);
+        try {
+            ModuleLayer layer = new ModuleLayer(cf, parents, pool::loaderFor);
+            return new Controller(layer);
+        } catch (IllegalArgumentException | IllegalStateException e) {
+            throw new LayerInstantiationException(e.getMessage());
+        }
+    }
+
+    /**
+     * Creates a new module layer by defining the modules in the given {@code
+     * Configuration} to the Java virtual machine. The given function maps each
+     * module in the configuration, by name, to a class loader. Creating the
+     * layer informs the Java virtual machine about the classes that may be
+     * loaded so that the Java virtual machine knows which module that each
+     * class is a member of.
+     *
+     * <p> The class loader delegation implemented by the class loaders must
+     * respect module readability. The class loaders should be
+     * {@link ClassLoader#registerAsParallelCapable parallel-capable} so as to
+     * avoid deadlocks during class loading. In addition, the entity creating
+     * a new layer with this method should arrange that the class loaders be
+     * ready to load from these modules before there are any attempts to load
+     * classes or resources. </p>
+     *
+     * <p> Creating a layer can fail for the following reasons: </p>
+     *
+     * <ul>
+     *
+     *     <li><p> Two or more modules with the same package are mapped to the
+     *     same class loader. </p></li>
+     *
+     *     <li><p> A module is mapped to a class loader that already has a
+     *     module of the same name defined to it. </p></li>
+     *
+     *     <li><p> A module is mapped to a class loader that has already
+     *     defined types in any of the packages in the module. </p></li>
+     *
+     * </ul>
+     *
+     * <p> In addition, a layer cannot be created if the configuration contains
+     * a module named "{@code java.base}", a configuration contains a module
+     * with a package named "{@code java}" or a package name starting with
+     * "{@code java.}" and the module is mapped to a class loader other than
+     * the {@link ClassLoader#getPlatformClassLoader() platform class loader},
+     * or the function to map a module name to a class loader returns
+     * {@code null}. </p>
+     *
+     * <p> If the function to map a module name to class loader throws an error
+     * or runtime exception then it is propagated to the caller of this method.
+     * </p>
+     *
+     * @apiNote It is implementation specific as to whether creating a layer
+     * with this method is an atomic operation or not. Consequentially it is
+     * possible for this method to fail with some modules, but not all, defined
+     * to the Java virtual machine.
+     *
+     * @param  cf
+     *         The configuration for the layer
+     * @param  parentLayers
+     *         The list of parent layers in search order
+     * @param  clf
+     *         The function to map a module name to a class loader
+     *
+     * @return A controller that controls the newly created layer
+     *
+     * @throws IllegalArgumentException
+     *         If the parent configurations do not match the configuration of
+     *         the parent layers, including order
+     * @throws LayerInstantiationException
+     *         If creating the layer fails for any of the reasons listed above
+     * @throws SecurityException
+     *         If {@code RuntimePermission("getClassLoader")} is denied by
+     *         the security manager
+     */
+    public static Controller defineModules(Configuration cf,
+                                           List<ModuleLayer> parentLayers,
+                                           Function<String, ClassLoader> clf)
+    {
+        List<ModuleLayer> parents = new ArrayList<>(parentLayers);
+        checkConfiguration(cf, parents);
+        Objects.requireNonNull(clf);
+
+        checkGetClassLoaderPermission();
+
+        // The boot layer is checked during module system initialization
+        if (boot() != null) {
+            checkForDuplicatePkgs(cf, clf);
+        }
+
+        try {
+            ModuleLayer layer = new ModuleLayer(cf, parents, clf);
+            return new Controller(layer);
+        } catch (IllegalArgumentException | IllegalStateException e) {
+            throw new LayerInstantiationException(e.getMessage());
+        }
+    }
+
+
+    /**
+     * Checks that the parent configurations match the configuration of
+     * the parent layers.
+     */
+    private static void checkConfiguration(Configuration cf,
+                                           List<ModuleLayer> parentLayers)
+    {
+        Objects.requireNonNull(cf);
+
+        List<Configuration> parentConfigurations = cf.parents();
+        if (parentLayers.size() != parentConfigurations.size())
+            throw new IllegalArgumentException("wrong number of parents");
+
+        int index = 0;
+        for (ModuleLayer parent : parentLayers) {
+            if (parent.configuration() != parentConfigurations.get(index)) {
+                throw new IllegalArgumentException(
+                        "Parent of configuration != configuration of this Layer");
+            }
+            index++;
+        }
+    }
+
+    private static void checkCreateClassLoaderPermission() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null)
+            sm.checkPermission(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);
+    }
+
+    private static void checkGetClassLoaderPermission() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null)
+            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
+    }
+
+    /**
+     * Checks a configuration and the module-to-loader mapping to ensure that
+     * no two modules mapped to the same class loader have the same package.
+     * It also checks that no two automatic modules have the same package.
+     *
+     * @throws LayerInstantiationException
+     */
+    private static void checkForDuplicatePkgs(Configuration cf,
+                                              Function<String, ClassLoader> clf)
+    {
+        // HashMap allows null keys
+        Map<ClassLoader, Set<String>> loaderToPackages = new HashMap<>();
+        for (ResolvedModule resolvedModule : cf.modules()) {
+            ModuleDescriptor descriptor = resolvedModule.reference().descriptor();
+            ClassLoader loader = clf.apply(descriptor.name());
+
+            Set<String> loaderPackages
+                = loaderToPackages.computeIfAbsent(loader, k -> new HashSet<>());
+
+            for (String pkg : descriptor.packages()) {
+                boolean added = loaderPackages.add(pkg);
+                if (!added) {
+                    throw fail("More than one module with package %s mapped" +
+                               " to the same class loader", pkg);
+                }
+            }
+        }
+    }
+
+    /**
+     * Creates a LayerInstantiationException with the a message formatted from
+     * the given format string and arguments.
+     */
+    private static LayerInstantiationException fail(String fmt, Object ... args) {
+        String msg = String.format(fmt, args);
+        return new LayerInstantiationException(msg);
+    }
+
+
+    /**
+     * Returns the configuration for this layer.
+     *
+     * @return The configuration for this layer
+     */
+    public Configuration configuration() {
+        return cf;
+    }
+
+
+    /**
+     * Returns the list of this layer's parents unless this is the
+     * {@linkplain #empty empty layer}, which has no parents and so an
+     * empty list is returned.
+     *
+     * @return The list of this layer's parents
+     */
+    public List<ModuleLayer> parents() {
+        return parents;
+    }
+
+
+    /**
+     * Returns an ordered stream of layers. The first element is is this layer,
+     * the remaining elements are the parent layers in DFS order.
+     *
+     * @implNote For now, the assumption is that the number of elements will
+     * be very low and so this method does not use a specialized spliterator.
+     */
+    Stream<ModuleLayer> layers() {
+        List<ModuleLayer> allLayers = this.allLayers;
+        if (allLayers != null)
+            return allLayers.stream();
+
+        allLayers = new ArrayList<>();
+        Set<ModuleLayer> visited = new HashSet<>();
+        Deque<ModuleLayer> stack = new ArrayDeque<>();
+        visited.add(this);
+        stack.push(this);
+
+        while (!stack.isEmpty()) {
+            ModuleLayer layer = stack.pop();
+            allLayers.add(layer);
+
+            // push in reverse order
+            for (int i = layer.parents.size() - 1; i >= 0; i--) {
+                ModuleLayer parent = layer.parents.get(i);
+                if (!visited.contains(parent)) {
+                    visited.add(parent);
+                    stack.push(parent);
+                }
+            }
+        }
+
+        this.allLayers = allLayers = Collections.unmodifiableList(allLayers);
+        return allLayers.stream();
+    }
+
+    private volatile List<ModuleLayer> allLayers;
+
+    /**
+     * Returns the set of the modules in this layer.
+     *
+     * @return A possibly-empty unmodifiable set of the modules in this layer
+     */
+    public Set<Module> modules() {
+        Set<Module> modules = this.modules;
+        if (modules == null) {
+            this.modules = modules =
+                Collections.unmodifiableSet(new HashSet<>(nameToModule.values()));
+        }
+        return modules;
+    }
+
+    private volatile Set<Module> modules;
+
+
+    /**
+     * Returns the module with the given name in this layer, or if not in this
+     * layer, the {@linkplain #parents parent} layers. Finding a module in
+     * parent layers is equivalent to invoking {@code findModule} on each
+     * parent, in search order, until the module is found or all parents have
+     * been searched. In a <em>tree of layers</em>  then this is equivalent to
+     * a depth-first search.
+     *
+     * @param  name
+     *         The name of the module to find
+     *
+     * @return The module with the given name or an empty {@code Optional}
+     *         if there isn't a module with this name in this layer or any
+     *         parent layer
+     */
+    public Optional<Module> findModule(String name) {
+        Objects.requireNonNull(name);
+        if (this == EMPTY_LAYER)
+            return Optional.empty();
+        Module m = nameToModule.get(name);
+        if (m != null)
+            return Optional.of(m);
+
+        return layers()
+                .skip(1)  // skip this layer
+                .map(l -> l.nameToModule)
+                .filter(map -> map.containsKey(name))
+                .map(map -> map.get(name))
+                .findAny();
+    }
+
+
+    /**
+     * Returns the {@code ClassLoader} for the module with the given name. If
+     * a module of the given name is not in this layer then the {@link #parents
+     * parent} layers are searched in the manner specified by {@link
+     * #findModule(String) findModule}.
+     *
+     * <p> If there is a security manager then its {@code checkPermission}
+     * method is called with a {@code RuntimePermission("getClassLoader")}
+     * permission to check that the caller is allowed to get access to the
+     * class loader. </p>
+     *
+     * @apiNote This method does not return an {@code Optional<ClassLoader>}
+     * because `null` must be used to represent the bootstrap class loader.
+     *
+     * @param  name
+     *         The name of the module to find
+     *
+     * @return The ClassLoader that the module is defined to
+     *
+     * @throws IllegalArgumentException if a module of the given name is not
+     *         defined in this layer or any parent of this layer
+     *
+     * @throws SecurityException if denied by the security manager
+     */
+    public ClassLoader findLoader(String name) {
+        Optional<Module> om = findModule(name);
+
+        // can't use map(Module::getClassLoader) as class loader can be null
+        if (om.isPresent()) {
+            return om.get().getClassLoader();
+        } else {
+            throw new IllegalArgumentException("Module " + name
+                                               + " not known to this layer");
+        }
+    }
+
+    /**
+     * Returns a string describing this module layer.
+     *
+     * @return A possibly empty string describing this module layer
+     */
+    @Override
+    public String toString() {
+        return modules().stream()
+                .map(Module::getName)
+                .collect(Collectors.joining(", "));
+    }
+
+    /**
+     * Returns the <em>empty</em> layer. There are no modules in the empty
+     * layer. It has no parents.
+     *
+     * @return The empty layer
+     */
+    public static ModuleLayer empty() {
+        return EMPTY_LAYER;
+    }
+
+
+    /**
+     * Returns the boot layer. The boot layer contains at least one module,
+     * {@code java.base}. Its parent is the {@link #empty() empty} layer.
+     *
+     * @apiNote This method returns {@code null} during startup and before
+     *          the boot layer is fully initialized.
+     *
+     * @return The boot layer
+     */
+    public static ModuleLayer boot() {
+        return System.bootLayer;
+    }
+
+    /**
+     * Returns the ServicesCatalog for this Layer, creating it if not
+     * already created.
+     */
+    ServicesCatalog getServicesCatalog() {
+        ServicesCatalog servicesCatalog = this.servicesCatalog;
+        if (servicesCatalog != null)
+            return servicesCatalog;
+
+        synchronized (this) {
+            servicesCatalog = this.servicesCatalog;
+            if (servicesCatalog == null) {
+                servicesCatalog = ServicesCatalog.create();
+                nameToModule.values().forEach(servicesCatalog::register);
+                this.servicesCatalog = servicesCatalog;
+            }
+        }
+
+        return servicesCatalog;
+    }
+
+    private volatile ServicesCatalog servicesCatalog;
+
+
+    /**
+     * Record that this layer has at least one module defined to the given
+     * class loader.
+     */
+    void bindToLoader(ClassLoader loader) {
+        // CLV.computeIfAbsent(loader, (cl, clv) -> new CopyOnWriteArrayList<>())
+        List<ModuleLayer> list = CLV.get(loader);
+        if (list == null) {
+            list = new CopyOnWriteArrayList<>();
+            List<ModuleLayer> previous = CLV.putIfAbsent(loader, list);
+            if (previous != null) list = previous;
+        }
+        list.add(this);
+    }
+
+    /**
+     * Returns a stream of the layers that have at least one module defined to
+     * the given class loader.
+     */
+    static Stream<ModuleLayer> layers(ClassLoader loader) {
+        List<ModuleLayer> list = CLV.get(loader);
+        if (list != null) {
+            return list.stream();
+        } else {
+            return Stream.empty();
+        }
+    }
+
+    // the list of layers with modules defined to a class loader
+    private static final ClassLoaderValue<List<ModuleLayer>> CLV = new ClassLoaderValue<>();
+}
--- a/src/java.base/share/classes/java/lang/NamedPackage.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/NamedPackage.java	Mon Apr 10 08:31:37 2017 -0700
@@ -26,7 +26,6 @@
 
 import java.lang.module.Configuration;
 import java.lang.module.ModuleReference;
-import java.lang.reflect.Module;
 import java.net.URI;
 
 /**
--- a/src/java.base/share/classes/java/lang/Object.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/Object.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -561,10 +561,53 @@
      * the finalization of this object to be halted, but is otherwise
      * ignored.
      *
+     * @apiNote
+     * Classes that embed non-heap resources have many options
+     * for cleanup of those resources. The class must ensure that the
+     * lifetime of each instance is longer than that of any resource it embeds.
+     * {@link java.lang.ref.Reference#reachabilityFence} can be used to ensure that
+     * objects remain reachable while resources embedded in the object are in use.
+     * <p>
+     * A subclass should avoid overriding the {@code finalize} method
+     * unless the subclass embeds non-heap resources that must be cleaned up
+     * before the instance is collected.
+     * Finalizer invocations are not automatically chained, unlike constructors.
+     * If a subclass overrides {@code finalize} it must invoke the superclass
+     * finalizer explicitly.
+     * To guard against exceptions prematurely terminating the finalize chain,
+     * the subclass should use a {@code try-finally} block to ensure
+     * {@code super.finalize()} is always invoked. For example,
+     * <pre>{@code      @Override
+     *     protected void finalize() throws Throwable {
+     *         try {
+     *             ... // cleanup subclass state
+     *         } finally {
+     *             super.finalize();
+     *         }
+     *     }
+     * }</pre>
+     *
+     * @deprecated The finalization mechanism is inherently problematic.
+     * Finalization can lead to performance issues, deadlocks, and hangs.
+     * Errors in finalizers can lead to resource leaks; there is no way to cancel
+     * finalization if it is no longer necessary; and no ordering is specified
+     * among calls to {@code finalize} methods of different objects.
+     * Furthermore, there are no guarantees regarding the timing of finalization.
+     * The {@code finalize} method might be called on a finalizable object
+     * only after an indefinite delay, if at all.
+     *
+     * Classes whose instances hold non-heap resources should provide a method
+     * to enable explicit release of those resources, and they should also
+     * implement {@link AutoCloseable} if appropriate.
+     * The {@link java.lang.ref.Cleaner} and {@link java.lang.ref.PhantomReference}
+     * provide more flexible and efficient ways to release resources when an object
+     * becomes unreachable.
+     *
      * @throws Throwable the {@code Exception} raised by this method
      * @see java.lang.ref.WeakReference
      * @see java.lang.ref.PhantomReference
      * @jls 12.6 Finalization of Class Instances
      */
+    @Deprecated(since="9")
     protected void finalize() throws Throwable { }
 }
--- a/src/java.base/share/classes/java/lang/Package.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/Package.java	Mon Apr 10 08:31:37 2017 -0700
@@ -27,7 +27,6 @@
 
 import java.lang.annotation.Annotation;
 import java.lang.reflect.AnnotatedElement;
-import java.lang.reflect.Module;
 import java.net.MalformedURLException;
 import java.net.URI;
 import java.net.URL;
--- a/src/java.base/share/classes/java/lang/SecurityManager.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/SecurityManager.java	Mon Apr 10 08:31:37 2017 -0700
@@ -29,9 +29,7 @@
 import java.lang.module.ModuleDescriptor;
 import java.lang.module.ModuleDescriptor.Exports;
 import java.lang.module.ModuleDescriptor.Opens;
-import java.lang.reflect.Layer;
 import java.lang.reflect.Member;
-import java.lang.reflect.Module;
 import java.io.FileDescriptor;
 import java.io.File;
 import java.io.FilePermission;
@@ -1441,7 +1439,7 @@
 
     static {
         // Get the modules in the boot layer
-        Stream<Module> bootLayerModules = Layer.boot().modules().stream();
+        Stream<Module> bootLayerModules = ModuleLayer.boot().modules().stream();
 
         // Filter out the modules loaded by the boot or platform loader
         PrivilegedAction<Set<Module>> pa = () ->
--- a/src/java.base/share/classes/java/lang/StackTraceElement.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/StackTraceElement.java	Mon Apr 10 08:31:37 2017 -0700
@@ -33,8 +33,6 @@
 import java.lang.module.ModuleDescriptor.Version;
 import java.lang.module.ModuleReference;
 import java.lang.module.ResolvedModule;
-import java.lang.reflect.Layer;
-import java.lang.reflect.Module;
 import java.util.HashSet;
 import java.util.Objects;
 import java.util.Optional;
@@ -191,7 +189,7 @@
      *         if the module name is not available.
      * @since 9
      * @spec JPMS
-     * @see java.lang.reflect.Module#getName()
+     * @see Module#getName()
      */
     public String getModuleName() {
         return moduleName;
@@ -480,7 +478,7 @@
         if (!VM.isModuleSystemInited())
             return true;
 
-        return Layer.boot() == m.getLayer() && HashedModules.contains(m);
+        return ModuleLayer.boot() == m.getLayer() && HashedModules.contains(m);
     }
 
     /*
@@ -492,7 +490,7 @@
 
         static Set<String> hashedModules() {
 
-            Optional<ResolvedModule> resolvedModule = Layer.boot()
+            Optional<ResolvedModule> resolvedModule = ModuleLayer.boot()
                     .configuration()
                     .findModule("java.base");
             assert resolvedModule.isPresent();
--- a/src/java.base/share/classes/java/lang/String.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/String.java	Mon Apr 10 08:31:37 2017 -0700
@@ -2672,7 +2672,6 @@
      * point</a> is passed through uninterpreted.
      *
      * @return an IntStream of char values from this sequence
-     * @since 9
      */
     @Override
     public IntStream chars() {
@@ -2692,7 +2691,6 @@
      * {@code int} values which are then passed to the stream.
      *
      * @return an IntStream of Unicode code points from this sequence
-     * @since 9
      */
     @Override
     public IntStream codePoints() {
--- a/src/java.base/share/classes/java/lang/System.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/System.java	Mon Apr 10 08:31:37 2017 -0700
@@ -35,33 +35,32 @@
 import java.io.PrintStream;
 import java.io.UnsupportedEncodingException;
 import java.lang.annotation.Annotation;
+import java.lang.module.ModuleDescriptor;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Executable;
-import java.lang.reflect.Layer;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.lang.reflect.Module;
+import java.net.URI;
 import java.net.URL;
 import java.security.AccessControlContext;
 import java.security.ProtectionDomain;
-import java.util.Properties;
-import java.util.PropertyPermission;
-import java.util.Map;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.nio.channels.Channel;
 import java.nio.channels.spi.SelectorProvider;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+import java.util.PropertyPermission;
+import java.util.ResourceBundle;
+import java.util.function.Supplier;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.stream.Stream;
 
-import java.util.Objects;
-import java.util.ResourceBundle;
-import java.util.function.Supplier;
-import sun.nio.ch.Interruptible;
+import jdk.internal.module.ModuleBootstrap;
+import jdk.internal.module.ServicesCatalog;
 import jdk.internal.reflect.CallerSensitive;
 import jdk.internal.reflect.Reflection;
-import sun.security.util.SecurityConstants;
-import sun.reflect.annotation.AnnotationType;
 import jdk.internal.HotSpotIntrinsicCandidate;
 import jdk.internal.misc.JavaLangAccess;;
 import jdk.internal.misc.SharedSecrets;;
@@ -69,8 +68,9 @@
 import jdk.internal.logger.LoggerFinderLoader;
 import jdk.internal.logger.LazyLoggers;
 import jdk.internal.logger.LocalizedLoggerWrapper;
-
-import jdk.internal.module.ModuleBootstrap;
+import sun.reflect.annotation.AnnotationType;
+import sun.nio.ch.Interruptible;
+import sun.security.util.SecurityConstants;
 
 /**
  * The <code>System</code> class contains several useful class fields
@@ -1160,7 +1160,7 @@
          * @param msg the string message (or a key in the message catalog, if
          * this logger is a {@link
          * LoggerFinder#getLocalizedLogger(java.lang.String,
-         * java.util.ResourceBundle, java.lang.reflect.Module) localized logger});
+         * java.util.ResourceBundle, java.lang.Module) localized logger});
          * can be {@code null}.
          *
          * @throws NullPointerException if {@code level} is {@code null}.
@@ -1228,7 +1228,7 @@
          * @param msg the string message (or a key in the message catalog, if
          * this logger is a {@link
          * LoggerFinder#getLocalizedLogger(java.lang.String,
-         * java.util.ResourceBundle, java.lang.reflect.Module) localized logger});
+         * java.util.ResourceBundle, java.lang.Module) localized logger});
          * can be {@code null}.
          * @param thrown a {@code Throwable} associated with the log message;
          *        can be {@code null}.
@@ -1277,7 +1277,7 @@
          * java.text.MessageFormat} format, (or a key in the message
          * catalog, if this logger is a {@link
          * LoggerFinder#getLocalizedLogger(java.lang.String,
-         * java.util.ResourceBundle, java.lang.reflect.Module) localized logger});
+         * java.util.ResourceBundle, java.lang.Module) localized logger});
          * can be {@code null}.
          * @param params an optional list of parameters to the message (may be
          * none).
@@ -1482,7 +1482,7 @@
          * message localization.
          *
          * @implSpec By default, this method calls {@link
-         * #getLogger(java.lang.String, java.lang.reflect.Module)
+         * #getLogger(java.lang.String, java.lang.Module)
          * this.getLogger(name, module)} to obtain a logger, then wraps that
          * logger in a {@link Logger} instance where all methods that do not
          * take a {@link ResourceBundle} as parameter are redirected to one
@@ -1566,12 +1566,20 @@
      * @implSpec
      * Instances returned by this method route messages to loggers
      * obtained by calling {@link LoggerFinder#getLogger(java.lang.String,
-     * java.lang.reflect.Module) LoggerFinder.getLogger(name, module)}, where
+     * java.lang.Module) LoggerFinder.getLogger(name, module)}, where
      * {@code module} is the caller's module.
+     * In cases where {@code System.getLogger} is called from a context where
+     * there is no caller frame on the stack (e.g when called directly
+     * from a JNI attached thread), {@code IllegalCallerException} is thrown.
+     * To obtain a logger in such a context, use an auxiliary class that will
+     * implicitly be identified as the caller, or use the system {@link
+     * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead.
+     * Note that doing the latter may eagerly initialize the underlying
+     * logging system.
      *
      * @apiNote
      * This method may defer calling the {@link
-     * LoggerFinder#getLogger(java.lang.String, java.lang.reflect.Module)
+     * LoggerFinder#getLogger(java.lang.String, java.lang.Module)
      * LoggerFinder.getLogger} method to create an actual logger supplied by
      * the logging backend, for instance, to allow loggers to be obtained during
      * the system initialization time.
@@ -1580,6 +1588,8 @@
      * @return an instance of {@link Logger} that can be used by the calling
      *         class.
      * @throws NullPointerException if {@code name} is {@code null}.
+     * @throws IllegalCallerException if there is no Java caller frame on the
+     *         stack.
      *
      * @since 9
      */
@@ -1587,6 +1597,9 @@
     public static Logger getLogger(String name) {
         Objects.requireNonNull(name);
         final Class<?> caller = Reflection.getCallerClass();
+        if (caller == null) {
+            throw new IllegalCallerException("no caller frame");
+        }
         return LazyLoggers.getLogger(name, caller.getModule());
     }
 
@@ -1599,9 +1612,17 @@
      * @implSpec
      * The returned logger will perform message localization as specified
      * by {@link LoggerFinder#getLocalizedLogger(java.lang.String,
-     * java.util.ResourceBundle, java.lang.reflect.Module)
-     * LoggerFinder.getLocalizedLogger(name, bundle, module}, where
+     * java.util.ResourceBundle, java.lang.Module)
+     * LoggerFinder.getLocalizedLogger(name, bundle, module)}, where
      * {@code module} is the caller's module.
+     * In cases where {@code System.getLogger} is called from a context where
+     * there is no caller frame on the stack (e.g when called directly
+     * from a JNI attached thread), {@code IllegalCallerException} is thrown.
+     * To obtain a logger in such a context, use an auxiliary class that
+     * will implicitly be identified as the caller, or use the system {@link
+     * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead.
+     * Note that doing the latter may eagerly initialize the underlying
+     * logging system.
      *
      * @apiNote
      * This method is intended to be used after the system is fully initialized.
@@ -1620,6 +1641,8 @@
      * resource bundle for message localization.
      * @throws NullPointerException if {@code name} is {@code null} or
      *         {@code bundle} is {@code null}.
+     * @throws IllegalCallerException if there is no Java caller frame on the
+     *         stack.
      *
      * @since 9
      */
@@ -1628,6 +1651,9 @@
         final ResourceBundle rb = Objects.requireNonNull(bundle);
         Objects.requireNonNull(name);
         final Class<?> caller = Reflection.getCallerClass();
+        if (caller == null) {
+            throw new IllegalCallerException("no caller frame");
+        }
         final SecurityManager sm = System.getSecurityManager();
         // We don't use LazyLoggers if a resource bundle is specified.
         // Bootstrap sensitive classes in the JDK do not use resource bundles
@@ -1951,7 +1977,7 @@
     }
 
     // @see #initPhase2()
-    private static Layer bootLayer;
+    static ModuleLayer bootLayer;
 
     /*
      * Invoked by VM.  Phase 2 module system initialization.
@@ -2071,12 +2097,10 @@
             public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
                 return new Thread(target, acc);
             }
+            @SuppressWarnings("deprecation")
             public void invokeFinalize(Object o) throws Throwable {
                 o.finalize();
             }
-            public Layer getBootLayer() {
-                return bootLayer;
-            }
             public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) {
                 return cl.createOrGetClassLoaderValueMap();
             }
@@ -2101,6 +2125,44 @@
             public void invalidatePackageAccessCache() {
                 SecurityManager.invalidatePackageAccessCache();
             }
+            public Module defineModule(ClassLoader loader,
+                                       ModuleDescriptor descriptor,
+                                       URI uri) {
+                return new Module(null, loader, descriptor, uri);
+            }
+            public Module defineUnnamedModule(ClassLoader loader) {
+                return new Module(loader);
+            }
+            public void addReads(Module m1, Module m2) {
+                m1.implAddReads(m2);
+            }
+            public void addReadsAllUnnamed(Module m) {
+                m.implAddReadsAllUnnamed();
+            }
+            public void addExports(Module m, String pn, Module other) {
+                m.implAddExports(pn, other);
+            }
+            public void addExportsToAllUnnamed(Module m, String pn) {
+                m.implAddExportsToAllUnnamed(pn);
+            }
+            public void addOpens(Module m, String pn, Module other) {
+                m.implAddOpens(pn, other);
+            }
+            public void addOpensToAllUnnamed(Module m, String pn) {
+                m.implAddOpensToAllUnnamed(pn);
+            }
+            public void addUses(Module m, Class<?> service) {
+                m.implAddUses(service);
+            }
+            public ServicesCatalog getServicesCatalog(ModuleLayer layer) {
+                return layer.getServicesCatalog();
+            }
+            public Stream<ModuleLayer> layers(ModuleLayer layer) {
+                return layer.layers();
+            }
+            public Stream<ModuleLayer> layers(ClassLoader loader) {
+                return ModuleLayer.layers(loader);
+            }
         });
     }
 }
--- a/src/java.base/share/classes/java/lang/Thread.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/Thread.java	Mon Apr 10 08:31:37 2017 -0700
@@ -927,7 +927,7 @@
      *       for example), the <code>interrupt</code> method should be used to
      *       interrupt the wait.
      *       For more information, see
-     *       <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
+     *       <a href="{@docRoot}/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
      *       are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
      */
     @Deprecated(since="1.2")
@@ -960,7 +960,7 @@
      *        could be used to generate exceptions that the target thread was
      *        not prepared to handle.
      *        For more information, see
-     *        <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
+     *        <a href="{@docRoot}/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
      *        are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
      *        This method is subject to removal in a future version of Java SE.
      */
@@ -1082,7 +1082,7 @@
      *     If another thread ever attempted to lock this resource, deadlock
      *     would result. Such deadlocks typically manifest themselves as
      *     "frozen" processes. For more information, see
-     *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">
+     *     <a href="{@docRoot}/java/lang/doc-files/threadPrimitiveDeprecation.html">
      *     Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
      *     This method is subject to removal in a future version of Java SE.
      * @throws NoSuchMethodError always
@@ -1122,7 +1122,7 @@
      *   monitor prior to calling <code>resume</code>, deadlock results.  Such
      *   deadlocks typically manifest themselves as "frozen" processes.
      *   For more information, see
-     *   <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
+     *   <a href="{@docRoot}/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
      *   are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
      */
     @Deprecated(since="1.2")
@@ -1148,7 +1148,7 @@
      * @deprecated This method exists solely for use with {@link #suspend},
      *     which has been deprecated because it is deadlock-prone.
      *     For more information, see
-     *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
+     *     <a href="{@docRoot}/java/lang/doc-files/threadPrimitiveDeprecation.html">Why
      *     are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
      */
     @Deprecated(since="1.2")
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/lang/WeakPairMap.java	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,354 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package java.lang;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.Collection;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiFunction;
+
+/**
+ * A WeakHashMap-like data structure that uses a pair of weakly-referenced keys
+ * with identity equality semantics to associate a strongly-referenced value.
+ * Unlike WeakHashMap, this data structure is thread-safe.
+ *
+ * @param <K1> the type of 1st key in key pair
+ * @param <K2> the type of 2nd key in key pair
+ * @param <V>  the type of value
+ * @author Peter Levart
+ */
+final class WeakPairMap<K1, K2, V> {
+
+    private final ConcurrentHashMap<Pair<K1, K2>, V> map = new ConcurrentHashMap<>();
+    private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
+
+    /**
+     * Tests if the specified pair of keys are associated with a value
+     * in the WeakPairMap.
+     *
+     * @param k1 the 1st of the pair of keys
+     * @param k2 the 2nd of the pair of keys
+     * @return true if and only if the specified key pair is in this WeakPairMap,
+     * as determined by the identity comparison; false otherwise
+     * @throws NullPointerException if any of the specified keys is null
+     */
+    public boolean containsKeyPair(K1 k1, K2 k2) {
+        expungeStaleAssociations();
+        return map.containsKey(Pair.lookup(k1, k2));
+    }
+
+    /**
+     * Returns the value to which the specified pair of keys is mapped, or null
+     * if this WeakPairMap contains no mapping for the key pair.
+     * <p>More formally, if this WeakPairMap contains a mapping from a key pair
+     * {@code (_k1, _k2)} to a value {@code v} such that
+     * {@code k1 == _k1 && k2 == _k2}, then this method returns {@code v};
+     * otherwise it returns {@code null}.
+     * (There can be at most one such mapping.)
+     *
+     * @param k1 the 1st of the pair of keys for which the mapped value is to
+     *           be returned
+     * @param k2 the 2nd of the pair of keys for which the mapped value is to
+     *           be returned
+     * @return the value to which the specified key pair is mapped, or null if
+     * this map contains no mapping for the key pair
+     * @throws NullPointerException if any of the specified keys is null
+     */
+    public V get(K1 k1, K2 k2) {
+        expungeStaleAssociations();
+        return map.get(Pair.lookup(k1, k2));
+    }
+
+    /**
+     * Maps the specified key pair to the specified value in this WeakPairMap.
+     * Neither the keys nor the value can be null.
+     * <p>The value can be retrieved by calling the {@link #get} method
+     * with the the same keys (compared by identity).
+     *
+     * @param k1 the 1st of the pair of keys with which the specified value is to
+     *           be associated
+     * @param k2 the 2nd of the pair of keys with which the specified value is to
+     *           be associated
+     * @param v  value to be associated with the specified key pair
+     * @return the previous value associated with key pair, or {@code null} if
+     * there was no mapping for key pair
+     * @throws NullPointerException if any of the specified keys or value is null
+     */
+    public V put(K1 k1, K2 k2, V v) {
+        expungeStaleAssociations();
+        return map.put(Pair.weak(k1, k2, queue), v);
+    }
+
+    /**
+     * If the specified key pair is not already associated with a value,
+     * associates it with the given value and returns {@code null}, else does
+     * nothing and returns the currently associated value.
+     *
+     * @param k1 the 1st of the pair of keys with which the specified value is to
+     *           be associated
+     * @param k2 the 2nd of the pair of keys with which the specified value is to
+     *           be associated
+     * @param v  value to be associated with the specified key pair
+     * @return the previous value associated with key pair, or {@code null} if
+     * there was no mapping for key pair
+     * @throws NullPointerException if any of the specified keys or value is null
+     */
+    public V putIfAbsent(K1 k1, K2 k2, V v) {
+        expungeStaleAssociations();
+        return map.putIfAbsent(Pair.weak(k1, k2, queue), v);
+    }
+
+    /**
+     * If the specified key pair is not already associated with a value,
+     * attempts to compute its value using the given mapping function
+     * and enters it into this WeakPairMap unless {@code null}. The entire
+     * method invocation is performed atomically, so the function is
+     * applied at most once per key pair. Some attempted update operations
+     * on this WeakPairMap by other threads may be blocked while computation
+     * is in progress, so the computation should be short and simple,
+     * and must not attempt to update any other mappings of this WeakPairMap.
+     *
+     * @param k1              the 1st of the pair of keys with which the
+     *                        computed value is to be associated
+     * @param k2              the 2nd of the pair of keys with which the
+     *                        computed value is to be associated
+     * @param mappingFunction the function to compute a value
+     * @return the current (existing or computed) value associated with
+     * the specified key pair, or null if the computed value is null
+     * @throws NullPointerException  if any of the specified keys or
+     *                               mappingFunction is null
+     * @throws IllegalStateException if the computation detectably
+     *                               attempts a recursive update to this map
+     *                               that would otherwise never complete
+     * @throws RuntimeException      or Error if the mappingFunction does so, in
+     *                               which case the mapping is left unestablished
+     */
+    public V computeIfAbsent(K1 k1, K2 k2,
+                             BiFunction<? super K1, ? super K2, ? extends V>
+                                 mappingFunction) {
+        expungeStaleAssociations();
+        try {
+            return map.computeIfAbsent(
+                Pair.weak(k1, k2, queue),
+                pair -> mappingFunction.apply(pair.first(), pair.second()));
+        } finally {
+            Reference.reachabilityFence(k1);
+            Reference.reachabilityFence(k2);
+        }
+    }
+
+    /**
+     * Returns a {@link Collection} view of the values contained in this
+     * WeakPairMap. The collection is backed by the WeakPairMap, so changes to
+     * the map are reflected in the collection, and vice-versa.  The collection
+     * supports element removal, which removes the corresponding
+     * mapping from this map, via the {@code Iterator.remove},
+     * {@code Collection.remove}, {@code removeAll},
+     * {@code retainAll}, and {@code clear} operations.  It does not
+     * support the {@code add} or {@code addAll} operations.
+     *
+     * @return the collection view
+     */
+    public Collection<V> values() {
+        expungeStaleAssociations();
+        return map.values();
+    }
+
+    /**
+     * Removes associations from this WeakPairMap for which at least one of the
+     * keys in key pair has been found weakly-reachable and corresponding
+     * WeakRefPeer(s) enqueued. Called as part of each public operation.
+     */
+    private void expungeStaleAssociations() {
+        WeakRefPeer<?> peer;
+        while ((peer = (WeakRefPeer<?>) queue.poll()) != null) {
+            map.remove(peer.weakPair());
+        }
+    }
+
+    /**
+     * Common interface of both {@link Weak} and {@link Lookup} key pairs.
+     */
+    private interface Pair<K1, K2> {
+
+        static <K1, K2> Pair<K1, K2> weak(K1 k1, K2 k2,
+                                          ReferenceQueue<Object> queue) {
+            return new Weak<>(k1, k2, queue);
+        }
+
+        static <K1, K2> Pair<K1, K2> lookup(K1 k1, K2 k2) {
+            return new Lookup<>(k1, k2);
+        }
+
+        /**
+         * @return The 1st of the pair of keys (may be null for {@link Weak}
+         * when it gets cleared)
+         */
+        K1 first();
+
+        /**
+         * @return The 2nd of the pair of keys (may be null for {@link Weak}
+         * when it gets cleared)
+         */
+        K2 second();
+
+        static int hashCode(Object first, Object second) {
+            // assert first != null && second != null;
+            return System.identityHashCode(first) ^
+                   System.identityHashCode(second);
+        }
+
+        static boolean equals(Object first, Object second, Pair<?, ?> p) {
+            return first != null && second != null &&
+                   first == p.first() && second == p.second();
+        }
+
+        /**
+         * A Pair where both keys are weakly-referenced.
+         * It is composed of two instances of {@link WeakRefPeer}s:
+         * <pre>{@code
+         *
+         *     +-referent-> [K1]                +-referent-> [K2]
+         *     |                                |
+         *   +----------------+               +----------------+
+         *   | Pair.Weak <:   |-----peer----->| (anonymous) <: |
+         *   | WeakRefPeer,   |               | WeakRefPeer    |
+         *   | Pair           |<--weakPair()--|                |
+         *   +----------------+               +----------------+
+         *     |            ^
+         *     |            |
+         *     +-weakPair()-+
+         *
+         * }</pre>
+         * <p>
+         * Pair.Weak is used for CHM keys. Both peers are associated with the
+         * same {@link ReferenceQueue} so when either of their referents
+         * becomes weakly-reachable, the corresponding entries can be
+         * {@link #expungeStaleAssociations() expunged} from the map.
+         */
+        final class Weak<K1, K2> extends WeakRefPeer<K1> implements Pair<K1, K2> {
+
+            // saved hash so it can be retrieved after the reference is cleared
+            private final int hash;
+            // link to <K2> peer
+            private final WeakRefPeer<K2> peer;
+
+            Weak(K1 k1, K2 k2, ReferenceQueue<Object> queue) {
+                super(k1, queue);
+                hash = Pair.hashCode(k1, k2);
+                peer = new WeakRefPeer<>(k2, queue) {
+                    // link back to <K1> peer
+                    @Override
+                    Weak<?, ?> weakPair() { return Weak.this; }
+                };
+            }
+
+            @Override
+            Weak<?, ?> weakPair() {
+                return this;
+            }
+
+            @Override
+            public K1 first() {
+                return get();
+            }
+
+            @Override
+            public K2 second() {
+                return peer.get();
+            }
+
+            @Override
+            public int hashCode() {
+                return hash;
+            }
+
+            @Override
+            public boolean equals(Object obj) {
+                return this == obj ||
+                       (obj instanceof Pair &&
+                        Pair.equals(first(), second(), (Pair<?, ?>) obj));
+            }
+        }
+
+        /**
+         * Optimized lookup Pair, used as lookup key in methods like
+         * {@link java.util.Map#get(Object)} or
+         * {@link java.util.Map#containsKey(Object)}) where
+         * there is a great chance its allocation is eliminated
+         * by escape analysis when such lookups are inlined by JIT.
+         * All its methods are purposely designed so that 'this' is never
+         * passed to any other method or used as identity.
+         */
+        final class Lookup<K1, K2> implements Pair<K1, K2> {
+            private final K1 k1;
+            private final K2 k2;
+
+            Lookup(K1 k1, K2 k2) {
+                this.k1 = Objects.requireNonNull(k1);
+                this.k2 = Objects.requireNonNull(k2);
+            }
+
+            @Override
+            public K1 first() {
+                return k1;
+            }
+
+            @Override
+            public K2 second() {
+                return k2;
+            }
+
+            @Override
+            public int hashCode() {
+                return Pair.hashCode(k1, k2);
+            }
+
+            @Override
+            public boolean equals(Object obj) {
+                return obj instanceof Pair &&
+                       Pair.equals(k1, k2, (Pair<?, ?>) obj);
+            }
+        }
+    }
+
+    /**
+     * Common abstract supertype of a pair of WeakReference peers.
+     */
+    private static abstract class WeakRefPeer<K> extends WeakReference<K> {
+
+        WeakRefPeer(K k, ReferenceQueue<Object> queue) {
+            super(Objects.requireNonNull(k), queue);
+        }
+
+        /**
+         * @return the {@link Pair.Weak} side of the pair of peers.
+         */
+        abstract Pair.Weak<?, ?> weakPair();
+    }
+}
--- a/src/java.base/share/classes/java/lang/annotation/ElementType.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/annotation/ElementType.java	Mon Apr 10 08:31:37 2017 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,7 @@
 /**
  * The constants of this enumerated type provide a simple classification of the
  * syntactic locations where annotations may appear in a Java program. These
- * constants are used in {@link Target java.lang.annotation.Target}
+ * constants are used in {@link java.lang.annotation.Target Target}
  * meta-annotations to specify where it is legal to write annotations of a
  * given type.
  *
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/lang/doc-files/threadPrimitiveDeprecation.html	Mon Apr 10 08:31:37 2017 -0700
@@ -0,0 +1,364 @@
+<!--
+ Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
+ DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+ This code is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License version 2 only, as
+ published by the Free Software Foundation.  Oracle designates this
+ particular file as subject to the "Classpath" exception as provided
+ by Oracle in the LICENSE file that accompanied this code.
+
+ This code is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ version 2 for more details (a copy is included in the LICENSE file that
+ accompanied this code).
+
+ You should have received a copy of the GNU General Public License version
+ 2 along with this work; if not, write to the Free Software Foundation,
+ Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+
+ Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ or visit www.oracle.com if you need additional information or have any
+ questions.
+-->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html lang="en">
+<head>
+  <title>Java Thread Primitive Deprecation</title>
+  <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
+</head>
+<body>
+<h2>Java Thread Primitive Deprecation</h2>
+<hr size="3" noshade="noshade" />
+<h3>Why is <code>Thread.stop</code> deprecated?</h3>
+<p>Because it is inherently unsafe. Stopping a thread causes it to
+unlock all the monitors that it has locked. (The monitors are
+unlocked as the <code>ThreadDeath</code> exception propagates up
+the stack.) If any of the objects previously protected by these
+monitors were in an inconsistent state, other threads may now view
+these objects in an inconsistent state. Such objects are said to be
+<i>damaged</i>. When threads operate on damaged objects, arbitrary
+behavior can result. This behavior may be subtle and difficult to
+detect, or it may be pronounced. Unlike other unchecked exceptions,
+<code>ThreadDeath</code> kills threads silently; thus, the user has
+no warning that his program may be corrupted. The corruption can
+manifest itself at any time after the actual damage occurs, even
+hours or days in the future.</p>
+<hr />
+<h3>Couldn't I just catch the <code>ThreadDeath</code> exception
+and fix the damaged object?</h3>
+<p>In theory, perhaps, but it would <em>vastly</em> complicate the
+task of writing correct multithreaded code. The task would be
+nearly insurmountable for two reasons:</p>
+<ol>
+<li>A thread can throw a <code>ThreadDeath</code> exception
+<i>almost anywhere</i>. All synchronized methods and blocks would
+have to be studied in great detail, with this in mind.</li>
+<li>A thread can throw a second <code>ThreadDeath</code> exception
+while cleaning up from the first (in the <code>catch</code> or
+<code>finally</code> clause). Cleanup would have to be repeated till
+it succeeded. The code to ensure this would be quite complex.</li>
+</ol>
+In sum, it just isn't practical.
+<hr />
+<h3>What about <code>Thread.stop(Throwable)</code>?</h3>
+<p>In addition to all of the problems noted above, this method may
+be used to generate exceptions that its target thread is unprepared
+to handle (including checked exceptions that the thread could not
+possibly throw, were it not for this method). For example, the
+following method is behaviorally identical to Java's
+<code>throw</code> operation, but circumvents the compiler's
+attempts to guarantee that the calling method has declared all of
+the checked exceptions that it may throw:</p>
+<pre>
+    static void sneakyThrow(Throwable t) {
+        Thread.currentThread().stop(t);
+    }
+</pre>
+<hr />
+<h3>What should I use instead of <code>Thread.stop</code>?</h3>
+<p>Most uses of <code>stop</code> should be replaced by code that
+simply modifies some variable to indicate that the target thread
+should stop running. The target thread should check this variable
+regularly, and return from its run method in an orderly fashion if
+the variable indicates that it is to stop running. To ensure prompt
+communication of the stop-request, the variable must be
+<tt>volatile</tt> (or access to the variable must be
+synchronized).</p>
+<p>For example, suppose your applet contains the following
+<code>start</code>, <code>stop</code> and <code>run</code>
+methods:</p>
+<pre>
+    private Thread blinker;
+
+    public void start() {
+        blinker = new Thread(this);
+        blinker.start();
+    }
+
+    public void stop() {
+        blinker.stop();  // UNSAFE!
+    }
+
+    public void run() {
+        while (true) {
+            try {
+                Thread.sleep(interval);
+            } catch (InterruptedException e){
+            }
+            repaint();
+        }
+    }
+</pre>
+You can avoid the use of <code>Thread.stop</code> by replacing the
+applet's <code>stop</code> and <code>run</code> methods with:
+<pre>
+    private volatile Thread blinker;
+
+    public void stop() {
+        blinker = null;
+    }
+
+    public void run() {
+        Thread thisThread = Thread.currentThread();
+        while (blinker == thisThread) {
+            try {
+                Thread.sleep(interval);
+            } catch (InterruptedException e){
+            }
+            repaint();
+        }
+    }
+</pre>
+<hr />
+<h3>How do I stop a thread that waits for long periods (e.g., for
+input)?</h3>
+<p>That's what the <code>Thread.interrupt</code> method is for. The
+same "state based" signaling mechanism shown above can be used, but
+the state change (<code>blinker = null</code>, in the previous
+example) can be followed by a call to
+<code>Thread.interrupt</code>, to interrupt the wait:</p>
+<pre>
+    public void stop() {
+        Thread moribund = waiter;
+        waiter = null;
+        moribund.interrupt();
+    }
+</pre>
+For this technique to work, it's critical that any method that
+catches an interrupt exception and is not prepared to deal with it
+immediately reasserts the exception. We say <em>reasserts</em>
+rather than <em>rethrows</em>, because it is not always possible to
+rethrow the exception. If the method that catches the
+<code>InterruptedException</code> is not declared to throw this
+(checked) exception, then it should "reinterrupt itself" with the
+following incantation:
+<pre>
+    Thread.currentThread().interrupt();
+</pre>
+This ensures that the Thread will reraise the
+<code>InterruptedException</code> as soon as it is able.
+<hr />
+<h3>What if a thread doesn't respond to
+<code>Thread.interrupt</code>?</h3>
+<p>In some cases, you can use application specific tricks. For
+example, if a thread is waiting on a known socket, you can close
+the socket to cause the thread to return immediately.
+Unfortunately, there really isn't any technique that works in
+general. <em>It should be noted that in all situations where a
+waiting thread doesn't respond to <code>Thread.interrupt</code>, it
+wouldn't respond to <code>Thread.stop</code> either.</em> Such
+cases include deliberate denial-of-service attacks, and I/O
+operations for which thread.stop and thread.interrupt do not work
+properly.</p>
+<hr />
+<h3>Why are <code>Thread.suspend</code> and
+<code>Thread.resume</code> deprecated?</h3>
+<p><code>Thread.suspend</code> is inherently deadlock-prone. If the
+target thread holds a lock on the monitor protecting a critical
+system resource when it is suspended, no thread can access this
+resource until the target thread is resumed. If the thread that
+would resume the target thread attempts to lock this monitor prior
+to calling <code>resume</code>, deadlock results. Such deadlocks
+typically manifest themselves as "frozen" processes.</p>
+<hr />
+<h3>What should I use instead of <code>Thread.suspend</code> and
+<code>Thread.resume</code>?</h3>
+<p>As with <code>Thread.stop</code>, the prudent approach is to
+have the "target thread" poll a variable indicating the desired
+state of the thread (active or suspended). When the desired state
+is suspended, the thread waits using <code>Object.wait</code>. When
+the thread is resumed, the target thread is notified using
+<code>Object.notify</code>.</p>
+<p>For example, suppose your applet contains the following
+mousePressed event handler, which toggles the state of a thread
+called <code>blinker</code>:</p>
+<pre>
+    private boolean threadSuspended;
+
+    Public void mousePressed(MouseEvent e) {
+        e.consume();
+
+        if (threadSuspended)
+            blinker.resume();
+        else
+            blinker.suspend();  // DEADLOCK-PRONE!
+
+        threadSuspended = !threadSuspended;
+    }
+</pre>
+You can avoid the use of <code>Thread.suspend</code> and
+<code>Thread.resume</code> by replacing the event handler above
+with:
+<pre>
+    public synchronized void mousePressed(MouseEvent e) {
+        e.consume();
+
+        threadSuspended = !threadSuspended;
+
+        if (!threadSuspended)
+            notify();
+    }
+</pre>
+and adding the following code to the "run loop":
+<pre>
+                synchronized(this) {
+                    while (threadSuspended)
+                        wait();
+                }
+</pre>
+The <code>wait</code> method throws the
+<code>InterruptedException</code>, so it must be inside a <code>try
+... catch</code> clause. It's fine to put it in the same clause as
+the <code>sleep</code>. The check should follow (rather than
+precede) the <code>sleep</code> so the window is immediately
+repainted when the thread is "resumed." The resulting
+<code>run</code> method follows:
+<pre>
+    public void run() {
+        while (true) {
+            try {
+                Thread.sleep(interval);
+
+                synchronized(this) {
+                    while (threadSuspended)
+                        wait();
+                }
+            } catch (InterruptedException e){
+            }
+            repaint();
+        }
+    }
+</pre>
+Note that the <code>notify</code> in the <code>mousePressed</code>
+method and the <code>wait</code> in the <code>run</code> method are
+inside <code>synchronized</code> blocks. This is required by the
+language, and ensures that <code>wait</code> and
+<code>notify</code> are properly serialized. In practical terms,
+this eliminates race conditions that could cause the "suspended"
+thread to miss a <code>notify</code> and remain suspended
+indefinitely.
+<p>While the cost of synchronization in Java is decreasing as the
+platform matures, it will never be free. A simple trick can be used
+to remove the synchronization that we've added to each iteration of
+the "run loop." The synchronized block that was added is replaced
+by a slightly more complex piece of code that enters a synchronized
+block only if the thread has actually been suspended:</p>
+<pre>
+                if (threadSuspended) {
+                    synchronized(this) {
+                        while (threadSuspended)
+                            wait();
+                    }
+                }
+</pre>
+<p>In the absence of explicit synchronization,
+<tt>threadSuspended</tt> must be made <tt>volatile</tt> to ensure
+prompt communication of the suspend-request.</p>
+The resulting <code>run</code> method is:
+<pre>
+    private volatile boolean threadSuspended;
+
+    public void run() {
+        while (true) {
+            try {
+                Thread.sleep(interval);
+
+                if (threadSuspended) {
+                    synchronized(this) {
+                        while (threadSuspended)
+                            wait();
+                    }
+                }
+            } catch (InterruptedException e){
+            }
+            repaint();
+        }
+    }
+</pre>
+<hr size="3" noshade="noshade" />
+<h3>Can I combine the two techniques to produce a thread that may
+be safely "stopped" or "suspended"?</h3>
+Yes, it's reasonably straightforward. The one subtlety is that the
+target thread may already be suspended at the time that another
+thread tries to stop it. If the <tt>stop</tt> method merely sets
+the state variable (<tt>blinker</tt>) to null, the target thread
+will remain suspended (waiting on the monitor), rather than exiting
+gracefully as it should. If the applet is restarted, multiple
+threads could end up waiting on the monitor at the same time,
+resulting in erratic behavior.
+<p>To rectify this situation, the <tt>stop</tt> method must ensure
+that the target thread resumes immediately if it is suspended. Once
+the target thread resumes, it must recognize immediately that it
+has been stopped, and exit gracefully. Here's how the resulting
+<tt>run</tt> and <tt>stop</tt> methods look:</p>
+<pre>
+    public void run() {
+        Thread thisThread = Thread.currentThread();
+        while (blinker == thisThread) {
+            try {
+                Thread.sleep(interval);
+
+                synchronized(this) {
+                    while (threadSuspended &amp;&amp; blinker==thisThread)
+                        wait();
+                }
+            } catch (InterruptedException e){
+            }
+            repaint();
+        }
+    }
+
+    public synchronized void stop() {
+        blinker = null;
+        notify();
+    }
+</pre>
+If the <tt>stop</tt> method calls <tt>Thread.interrupt</tt>, as
+described above, it needn't call <tt>notify</tt> as well, but it
+still must be synchronized. This ensures that the target thread
+won't miss an interrupt due to a race condition.
+<hr />
+<h3>What about <code>Thread.destroy</code>?</h3>
+<code>Thread.destroy</code> was never implemented and has been
+deprecated. If it were implemented, it would be deadlock-prone in
+the manner of <code>Thread.suspend</code>. (In fact, it is roughly
+equivalent to <code>Thread.suspend</code> without the possibility
+of a subsequent <code>Thread.resume</code>.)
+<hr />
+<h3>Why is <code>Runtime.runFinalizersOnExit</code>
+deprecated?</h3>
+Because it is inherently unsafe. It may result in finalizers being
+called on live objects while other threads are concurrently
+manipulating those objects, resulting in erratic behavior or
+deadlock. While this problem could be prevented if the class whose
+objects are being finalized were coded to "defend against" this
+call, most programmers do <i>not</i> defend against it. They assume
+that an object is dead at the time that its finalizer is called.
+<p>Further, the call is not "thread-safe" in the sense that it sets
+a VM-global flag. This forces <i>every</i> class with a finalizer
+to defend against the finalization of live objects!</p>
+<p><!-- Body text ends here --></p>
+</body>
+</html>
--- a/src/java.base/share/classes/java/lang/invoke/MemberName.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/MemberName.java	Mon Apr 10 08:31:37 2017 -0700
@@ -33,7 +33,6 @@
 import java.lang.reflect.Member;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.lang.reflect.Module;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Iterator;
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Mon Apr 10 08:31:37 2017 -0700
@@ -43,7 +43,6 @@
 import java.lang.reflect.Member;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.lang.reflect.Module;
 import java.lang.reflect.ReflectPermission;
 import java.nio.ByteOrder;
 import java.security.AccessController;
@@ -668,11 +667,11 @@
          *  The value is {@code 0x20}, which does not correspond meaningfully to
          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
          *  A {@code Lookup} with this lookup mode assumes {@linkplain
-         *  java.lang.reflect.Module#canRead(java.lang.reflect.Module) readability}.
+         *  java.lang.Module#canRead(java.lang.Module) readability}.
          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
          *  with this lookup mode can access all public members of public types
          *  of all modules where the type is in a package that is {@link
-         *  java.lang.reflect.Module#isExported(String) exported unconditionally}.
+         *  java.lang.Module#isExported(String) exported unconditionally}.
          *  @since 9
          *  @spec JPMS
          *  @see #publicLookup()
--- a/src/java.base/share/classes/java/lang/module/Configuration.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/module/Configuration.java	Mon Apr 10 08:31:37 2017 -0700
@@ -64,11 +64,11 @@
  * with the receiver as the parent configuration. The static methods are for
  * more advanced cases where there can be more than one parent configuration. </p>
  *
- * <p> Each {@link java.lang.reflect.Layer layer} of modules in the Java virtual
+ * <p> Each {@link java.lang.ModuleLayer layer} of modules in the Java virtual
  * machine is created from a configuration. The configuration for the {@link
- * java.lang.reflect.Layer#boot() boot} layer is obtained by invoking {@code
- * Layer.boot().configuration()}. The configuration for the boot layer will
- * often be the parent when creating new configurations. </p>
+ * java.lang.ModuleLayer#boot() boot} layer is obtained by invoking {@code
+ * ModuleLayer.boot().configuration()}. The configuration for the boot layer
+ * will often be the parent when creating new configurations. </p>
  *
  * <h3> Example </h3>
  *
@@ -81,7 +81,7 @@
  * <pre>{@code
  *    ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
  *
- *    Configuration parent = Layer.boot().configuration();
+ *    Configuration parent = ModuleLayer.boot().configuration();
  *
  *    Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("myapp"));
  *    cf.modules().forEach(m -> {
@@ -95,7 +95,7 @@
  *
  * @since 9
  * @spec JPMS
- * @see java.lang.reflect.Layer
+ * @see java.lang.ModuleLayer
  */
 public final class Configuration {
 
--- a/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java	Mon Apr 10 08:31:37 2017 -0700
@@ -60,7 +60,7 @@
  * <p> A module descriptor describes a named module and defines methods to
  * obtain each of its components. The module descriptor for a named module
  * in the Java virtual machine is obtained by invoking the {@link
- * java.lang.reflect.Module Module}'s {@link java.lang.reflect.Module#getDescriptor
+ * java.lang.Module Module}'s {@link java.lang.Module#getDescriptor
  * getDescriptor} method. Module descriptors can also be created using the
  * {@link ModuleDescriptor.Builder} class or by reading the binary form of a
  * module declaration ({@code module-info.class}) using the {@link
@@ -85,7 +85,7 @@
  * <p> {@code ModuleDescriptor} objects are immutable and safe for use by
  * multiple concurrent threads.</p>
  *
- * @see java.lang.reflect.Module
+ * @see java.lang.Module
  * @since 9
  * @spec JPMS
  */
@@ -2110,7 +2110,9 @@
 
         /**
          * Sets the module main class. The package for the main class is added
-         * to the module if not already added.
+         * to the module if not already added. In other words, this method is
+         * equivalent to first invoking this builder's {@link #packages(Set)
+         * packages} method to add the package name of the main class.
          *
          * @param  mc
          *         The module main class
@@ -2134,8 +2136,8 @@
                     throw new IllegalArgumentException(mc + ": unnamed package");
                 }
             }
+            packages.add(pn);
             mainClass = mc;
-            packages.add(pn);
             return this;
         }
 
--- a/src/java.base/share/classes/java/lang/module/ModuleFinder.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/module/ModuleFinder.java	Mon Apr 10 08:31:37 2017 -0700
@@ -228,14 +228,14 @@
      * directory is treated as an exploded module rather than a directory of
      * modules. </p>
      *
-     * <p> The module finder returned by this method supports modules that are
-     * packaged as JAR files. A JAR file with a {@code module-info.class} in
-     * the top-level directory of the JAR file (or overridden by a versioned
-     * entry in a {@link java.util.jar.JarFile#isMultiRelease() multi-release}
-     * JAR file) is a modular JAR and is an <em>explicit module</em>.
-     * A JAR file that does not have a {@code module-info.class} in the
-     * top-level directory is created as an automatic module. The components
-     * for the automatic module are derived as follows:
+     * <p id="automatic-modules"> The module finder returned by this method
+     * supports modules packaged as JAR files. A JAR file with a {@code
+     * module-info.class} in its top-level directory, or in a versioned entry
+     * in a {@linkplain java.util.jar.JarFile#isMultiRelease() multi-release}
+     * JAR file, is a modular JAR file and thus defines an <em>explicit</em>
+     * module. A JAR file that does not have a {@code module-info.class} in its
+     * top-level directory defines an <em>automatic module</em>, as follows:
+     * </p>
      *
      * <ul>
      *
@@ -254,16 +254,16 @@
      *         ModuleDescriptor.Version} and ignored if it cannot be parsed as
      *         a {@code Version}. </p></li>
      *
-     *         <li><p> For the module name, then any trailing digits and dots
-     *         are removed, all non-alphanumeric characters ({@code [^A-Za-z0-9]})
-     *         are replaced with a dot ({@code "."}), all repeating dots are
-     *         replaced with one dot, and all leading and trailing dots are
-     *         removed. </p></li>
+     *         <li><p> All non-alphanumeric characters ({@code [^A-Za-z0-9]})
+     *         in the module name are replaced with a dot ({@code "."}), all
+     *         repeating dots are replaced with one dot, and all leading and
+     *         trailing dots are removed. </p></li>
      *
      *         <li><p> As an example, a JAR file named {@code foo-bar.jar} will
      *         derive a module name {@code foo.bar} and no version. A JAR file
-     *         named {@code foo-1.2.3-SNAPSHOT.jar} will derive a module name
-     *         {@code foo} and {@code 1.2.3-SNAPSHOT} as the version. </p></li>
+     *         named {@code foo-bar-1.2.3-SNAPSHOT.jar} will derive a module
+     *         name {@code foo.bar} and {@code 1.2.3-SNAPSHOT} as the version.
+     *         </p></li>
      *
      *     </ul></li>
      *
@@ -312,7 +312,9 @@
      *
      * <p> As with automatic modules, the contents of a packaged or exploded
      * module may need to be <em>scanned</em> in order to determine the packages
-     * in the module. If a {@code .class} file (other than {@code
+     * in the module. Whether {@linkplain java.nio.file.Files#isHidden(Path)
+     * hidden files} are ignored or not is implementation specific and therefore
+     * not specified. If a {@code .class} file (other than {@code
      * module-info.class}) is found in the top-level directory then it is
      * assumed to be a class in the unnamed package and so {@code FindException}
      * is thrown. </p>
--- a/src/java.base/share/classes/java/lang/module/Resolver.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/module/Resolver.java	Mon Apr 10 08:31:37 2017 -0700
@@ -28,7 +28,6 @@
 import java.io.PrintStream;
 import java.lang.module.ModuleDescriptor.Provides;
 import java.lang.module.ModuleDescriptor.Requires.Modifier;
-import java.lang.reflect.Layer;
 import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -67,6 +66,9 @@
     // maps module name to module reference
     private final Map<String, ModuleReference> nameToReference = new HashMap<>();
 
+    // true if all automatic modules have been found
+    private boolean haveAllAutomaticModules;
+
     // module constraints on target platform
     private String osName;
     private String osArch;
@@ -171,6 +173,21 @@
             ModuleDescriptor descriptor = q.poll();
             assert nameToReference.containsKey(descriptor.name());
 
+            // if the module is an automatic module then all automatic
+            // modules need to be resolved
+            if (descriptor.isAutomatic() && !haveAllAutomaticModules) {
+                addFoundAutomaticModules().forEach(mref -> {
+                    ModuleDescriptor other = mref.descriptor();
+                    q.offer(other);
+                    if (isTracing()) {
+                        trace("Automatic module %s located, required by %s",
+                              other.name(), descriptor.name());
+                        mref.location().ifPresent(uri -> trace("  (%s)", uri));
+                    }
+                });
+                haveAllAutomaticModules = true;
+            }
+
             // process dependences
             for (ModuleDescriptor.Requires requires : descriptor.requires()) {
 
@@ -199,10 +216,15 @@
                 if (!nameToReference.containsKey(dn)) {
                     addFoundModule(mref);
                     q.offer(mref.descriptor());
-                    resolved.add(mref.descriptor());
 
                     if (isTracing()) {
-                        trace("Module %s located, required by %s",
+                        String prefix;
+                        if (mref.descriptor().isAutomatic()) {
+                            prefix = "Automatic module";
+                        } else {
+                            prefix = "Module";
+                        }
+                        trace(prefix + " %s located, required by %s",
                               dn, descriptor.name());
                         mref.location().ifPresent(uri -> trace("  (%s)", uri));
                     }
@@ -250,7 +272,7 @@
 
         // the initial set of modules that may use services
         Set<ModuleDescriptor> initialConsumers;
-        if (Layer.boot() == null) {
+        if (ModuleLayer.boot() == null) {
             initialConsumers = new HashSet<>();
         } else {
             initialConsumers = parents.stream()
@@ -301,6 +323,21 @@
         return this;
     }
 
+    /**
+     * Add all automatic modules that have not already been found to the
+     * nameToReference map.
+     */
+    private Set<ModuleReference> addFoundAutomaticModules() {
+        Set<ModuleReference> result = new HashSet<>();
+        findAll().forEach(mref -> {
+            String mn = mref.descriptor().name();
+            if (mref.descriptor().isAutomatic() && !nameToReference.containsKey(mn)) {
+                addFoundModule(mref);
+                result.add(mref);
+            }
+        });
+        return result;
+    }
 
     /**
      * Add the module to the nameToReference map. Also check any constraints on
@@ -534,7 +571,7 @@
         // need "requires transitive" from the modules in parent configurations
         // as there may be selected modules that have a dependency on modules in
         // the parent configuration.
-        if (Layer.boot() == null) {
+        if (ModuleLayer.boot() == null) {
             g2 = new HashMap<>(capacity);
         } else {
             g2 = parents.stream()
--- a/src/java.base/share/classes/java/lang/module/package-info.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/module/package-info.java	Mon Apr 10 08:31:37 2017 -0700
@@ -70,7 +70,7 @@
  * } </pre>
  *
  * <p> If module {@code m1} is resolved with the configuration for the {@link
- * java.lang.reflect.Layer#boot() boot} layer as the parent then the resulting
+ * java.lang.ModuleLayer#boot() boot} layer as the parent then the resulting
  * configuration contains two modules ({@code m1}, {@code m2}). The edges in
  * its readability graph are:
  * <pre> {@code
@@ -92,10 +92,10 @@
  *
  * <p> {@link java.lang.module.ModuleDescriptor#isAutomatic() Automatic} modules
  * receive special treatment during resolution. Each automatic module is resolved
- * so that it reads all other modules in the configuration and all parent
- * configurations. Each automatic module is also resolved as if it
- * "{@code requires transitive}" all other automatic modules in the configuration
- * (and all automatic modules in parent configurations). </p>
+ * as if it "{@code requires transitive}" all observable automatic modules and
+ * all automatic modules in the parent configurations. Each automatic module is
+ * resolved so that it reads all other modules in the resulting configuration and
+ * all modules in parent configurations. </p>
  *
  * <h2><a name="servicebinding">Service binding</a></h2>
  *
--- a/src/java.base/share/classes/java/lang/reflect/Constructor.java	Mon Apr 10 16:20:40 2017 +0530
+++ b/src/java.base/share/classes/java/lang/reflect/Constructor.java	Mon Apr 10 08:31:37 2017 -0700
@@ -174,7 +174,6 @@
      * @throws SecurityException if the request is denied by the security manager
      *         or this is a constructor for {@code java.lang.Class}
      *
-     * @since 9
      * @spec JPMS
      */
     @Override
--- a/src/java.base/share/classes/java/lang/reflect/Layer.java	Mon Apr 10 16:20:40 2017 +0530
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,949 +0,0 @@
-/*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.lang.reflect;
-
-import java.lang.module.Configuration;
-import java.lang.module.ModuleDescriptor;
-import java.lang.module.ResolvedModule;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import jdk.internal.loader.ClassLoaderValue;
-import jdk.internal.loader.Loader;
-import jdk.internal.loader.LoaderPool;
-import jdk.internal.misc.SharedSecrets;
-import jdk.internal.module.Modules;
-import jdk.internal.module.ServicesCatalog;
-import sun.security.util.SecurityConstants;
-
-
-/**
- * A layer of modules in the Java virtual machine.
- *
- * <p> A layer is created from a graph of modules in a {@link Configuration}
- * and a function that maps each module to a {@link ClassLoader}.
- * Creating a layer informs the Java virtual machine about the classes that
- * may be loaded from the modules so that the Java virtual machine knows which
- * module that each class is a member of. </p>
- *
- * <p> Creating a layer creates a {@link Module} object for each {@link
- * ResolvedModule} in the configuration. For each resolved module that is
- * {@link ResolvedModule#reads() read}, the {@code Module} {@link
- * Module#canRead reads} the corresponding run-time {@code Module}, which may
- * be in the same layer or a {@link #parents() parent} layer. </p>
- *
- * <p> The {@link #defineModulesWithOneLoader defineModulesWithOneLoader} and
- * {@link #defineModulesWithManyLoaders defineModulesWithManyLoaders} methods
- * provide convenient ways to create a {@code Layer} where all modules are
- * mapped to a single class loader or where each module is mapped to its own
- * class loader. The {@link #defineModules defineModules} method is for more
- * advanced cases where modules are mapped to custom class loaders by means of
- * a function specified to the method. Each of these methods has an instance
- * and static variant. The instance methods create a layer with the receiver
- * as the parent layer. The static methods are for more advanced cases where
- * there can be more than one parent layer or where a {@link Layer.Controller
- * Controller} is needed to control modules in the layer. </p>
- *
- * <p> A Java virtual machine has at least one non-empty layer, the {@link
- * #boot() boot} layer, that is created when the Java virtual machine is
- * started. The boot layer contains module {@code java.base} and is the only
- * layer in the Java virtual machine with a module named "{@code java.base}".
- * The modules in the boot layer are mapped to the bootstrap class loader and
- * other class loaders that are <a href="../ClassLoader.html#builtinLoaders">
- * built-in</a> into the Java virtual machine. The boot layer will often be
- * the {@link #parents() parent} when creating additional layers. </p>
- *
- * <p> Each {@code Module} in a layer is created so that it {@link
- * Module#isExported(String) exports} and {@link Module#isOpen(String) opens}
- * the packages described by its {@link ModuleDescriptor}. Qualified exports
- * (where a package is exported to a set of target modules rather than all
- * modules) are reified when creating the layer as follows: </p>
- * <ul>
- *     <li> If module {@code X} exports a package to {@code Y}, and if the
- *     runtime {@code Module} {@code X} reads {@code Module} {@code Y}, then
- *     the package is exported to {@code Module} {@code Y} (which may be in
- *     the same layer as {@code X} or a parent layer). </li>
- *
- *     <li> If module {@code X} exports a package to {@code Y}, and if the
- *     runtime {@code Module} {@code X} does not read {@code Y} then target
- *     {@code Y} is located as if by invoking {@link #findModule(String)
- *     findModule} to find the module in the layer or its parent layers. If
- *     {@code Y} is found then the package is exported to the instance of
- *     {@code Y} that was found. If {@code Y} is not found then the qualified
- *     export is ignored. </li>
- * </ul>
- *
- * <p> Qualified opens are handled in same way as qualified exports. </p>
- *
- * <p> As when creating a {@code Configuration},
- * {@link ModuleDescriptor#isAutomatic() automatic} modules receive special
- * treatment when creating a layer. An automatic module is created in the
- * Java virtual machine as a {@code Module} that reads every unnamed {@code
- * Module} in the Java virtual machine. </p>
- *
- * <p> Unless otherwise specified, passing a {@code null} argument to a method
- * in this class causes a {@link NullPointerException NullPointerException} to
- * be thrown. </p>
- *
- * <h3> Example usage: </h3>
- *
- * <p> This example creates a configuration by resolving a module named
- * "{@code myapp}" with the configuration for the boot layer as the parent. It
- * then creates a new layer with the modules in this configuration. All modules
- * are defined to the same class loader. </p>
- *
- * <pre>{@code
- *     ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
- *
- *     Layer parent = Layer.boot();
- *
- *     Configuration cf = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("myapp"));
- *
- *     ClassLoader scl = ClassLoader.getSystemClassLoader();
- *
- *     Layer layer = parent.defineModulesWithOneLoader(cf, scl);
- *
- *     Class<?> c = layer.findLoader("myapp").loadClass("app.Main");
- * }</pre>
- *
- * @since 9
- * @spec JPMS
- * @see Module#getLayer()
- */
-
-public final class Layer {
-
-    // the empty Layer
-    private static final Layer EMPTY_LAYER
-        = new Layer(Configuration.empty(), List.of(), null);
-
-    // the configuration from which this Layer was created
-    private final Configuration cf;
-
-    // parent layers, empty in the case of the empty layer
-    private final List<Layer> parents;
-
-    // maps module name to jlr.Module
-    private final Map<String, Module> nameToModule;
-
-    /**
-     * Creates a new Layer from the modules in the given configuration.
-     */
-    private Layer(Configuration cf,
-                  List<Layer> parents,
-                  Function<String, ClassLoader> clf)
-    {
-        this.cf = cf;
-        this.parents = parents; // no need to do defensive copy
-
-        Map<String, Module> map;
-        if (parents.isEmpty()) {
-            map = Collections.emptyMap();
-        } else {
-            map = Module.defineModules(cf, clf, this);
-        }
-        this.nameToModule = map; // no need to do defensive copy
-    }
-
-    /**
-     * Controls a layer. The static methods defined by {@link Layer} to create
-     * module layers return a {@code Controller} that can be used to control
-     * modules in the layer.
-     *
-     * <p> Unless otherwise specified, passing a {@code null} argument to a
-     * method in this class causes a {@link NullPointerException
-     * NullPointerException} to be thrown. </p>
-     *
-     * @apiNote Care should be taken with {@code Controller} objects, they
-     * should never be shared with untrusted code.
-     *
-     * @since 9
-     * @spec JPMS
-     */
-    public static final class Controller {
-        private final Layer layer;
-
-        Controller(Layer layer) {
-            this.layer = layer;
-        }
-
-        /**
-         * Returns the layer that this object controls.
-         *
-         * @return the layer
-         */
-        public Layer layer() {
-            return layer;
-        }
-
-        private void ensureInLayer(Module source) {
-            if (source.getLayer() != layer)
-                throw new IllegalArgumentException(source + " not in layer");
-        }
-
-
-        /**
-         * Updates module {@code source} in the layer to read module
-         * {@code target}. This method is a no-op if {@code source} already
-         * reads {@code target}.
-         *
-         * @implNote <em>Read edges</em> added by this method are <em>weak</em>
-         * and do not prevent {@code target} from being GC'ed when {@code source}
-         * is strongly reachable.
-         *
-         * @param  source
-         *         The source module
-         * @param  target
-         *         The target module to read
-         *
-         * @return This controller
-         *
-         * @throws IllegalArgumentException
-         *         If {@code source} is not in the layer
-         *
-         * @see Module#addReads
-         */
-        public Controller addReads(Module source, Module target) {
-            ensureInLayer(source);
-            Objects.requireNonNull(target);
-            Modules.addReads(source, target);
-            return this;
-        }
-
-        /**
-         * Updates module {@code source} in the layer to open a package to
-         * module {@code target}. This method is a no-op if {@code source}
-         * already opens the package to at least {@code target}.
-         *
-         * @param  source
-         *         The source module
-         * @param  pn
-         *         The package name
-         * @param  target
-         *         The target module to read
-         *
-         * @return This controller
-         *
-         * @throws IllegalArgumentException
-         *         If {@code source} is not in the layer or the package is not
-         *         in the source module
-         *
-         * @see Module#addOpens
-         */
-        public Controller addOpens(Module source, String pn, Module target) {
-            ensureInLayer(source);
-            Objects.requireNonNull(pn);
-            Objects.requireNonNull(target);
-            Modules.addOpens(source, pn, target);
-            return this;
-        }
-    }
-
-
-    /**
-     * Creates a new layer, with this layer as its parent, by defining the
-     * modules in the given {@code Configuration} to the Java virtual machine.
-     * This method creates one class loader and defines all modules to that
-     * class loader. The {@link ClassLoader#getParent() parent} of each class
-     * loader is the given parent class loader. This method works exactly as
-     * specified by the static {@link
-     * #defineModulesWithOneLoader(Configuration,List,ClassLoader)
-     * defineModulesWithOneLoader} method when invoked with this layer as the
-     * parent. In other words, if this layer is {@code thisLayer} then this
-     * method is equivalent to invoking:
-     * <pre> {@code
-     *     Layer.defineModulesWithOneLoader(cf, List.of(thisLayer), parentLoader).layer();
-     * }</pre>
-     *
-     * @param  cf
-     *         The configuration for the layer
-     * @param  parentLoader
-     *         The parent class loader for the class loader created by this
-     *         method; may be {@code null} for the bootstrap class loader
-     *
-     * @return The newly created layer
-     *
-     * @throws IllegalArgumentException
-     *         If the parent of the given configuration is not the configuration
-     *         for this layer
-     * @throws LayerInstantiationException
-     *         If the layer cannot be created for any of the reasons specified
-     *         by the static {@code defineModulesWithOneLoader} method
-     * @throws SecurityException
-     *         If {@code RuntimePermission("createClassLoader")} or
-     *         {@code RuntimePermission("getClassLoader")} is denied by
-     *         the security manager
-     *
-     * @see #findLoader
-     */
-    public Layer defineModulesWithOneLoader(Configuration cf,
-                                            ClassLoader parentLoader) {
-        return defineModulesWithOneLoader(cf, List.of(this), parentLoader).layer();
-    }
-
-
-    /**
-     * Creates a new layer, with this layer as its parent, by defining the
-     * modules in the given {@code Configuration} to the Java virtual machine.
-     * Each module is defined to its own {@link ClassLoader} created by this
-     * method. The {@link ClassLoader#getParent() parent} of each class loader
-     * is the given parent class loader. This method works exactly as specified
-     * by the static {@link
-     * #defineModulesWithManyLoaders(Configuration,List,ClassLoader)
-     * defineModulesWithManyLoaders} method when invoked with this layer as the
-     * parent. In other words, if this layer is {@code thisLayer} then this
-     * method is equivalent to invoking:
-     * <pre> {@code
-     *     Layer.defineModulesWithManyLoaders(cf, List.of(thisLayer), parentLoader).layer();
-     * }</pre>
-     *
-     * @param  cf
-     *         The configuration for the layer
-     * @param  parentLoader
-     *         The parent class loader for each of the class loaders created by
-     *         this method; may be {@code null} for the bootstrap class loader
-     *
-     * @return The newly created layer
-     *
-     * @throws IllegalArgumentException
-     *         If the parent of the given configuration is not the configuration
-     *         for this layer
-     * @throws LayerInstantiationException
-     *         If the layer cannot be created for any of the reasons specified
-     *         by the static {@code defineModulesWithManyLoaders} method
-     * @throws SecurityException
-     *         If {@code RuntimePermission("createClassLoader")} or
-     *         {@code RuntimePermission("getClassLoader")} is denied by
-     *         the security manager
-     *
-     * @see #findLoader
-     */
-    public Layer defineModulesWithManyLoaders(Configuration cf,
-                                              ClassLoader parentLoader) {
-        return defineModulesWithManyLoaders(cf, List.of(this), parentLoader).layer();
-    }
-
-
-    /**
-     * Creates a new layer, with this layer as its parent, by defining the
-     * modules in the given {@code Configuration} to the Java virtual machine.
-     * Each module is mapped, by name, to its class loader by means of the
-     * given function. This method works exactly as specified by the static
-     * {@link #defineModules(Configuration,List,Function) defineModules}
-     * method when invoked with this layer as the parent. In other words, if
-     * this layer is {@code thisLayer} then this method is equivalent to
-     * invoking:
-     * <pre> {@code
-     *     Layer.defineModules(cf, List.of(thisLayer), clf).layer();
-     * }</pre>
-     *
-     * @param  cf
-     *         The configuration for the layer
-     * @param  clf
-     *         The function to map a module name to a class loader
-     *
-     * @return The newly created layer
-     *
-     * @throws IllegalArgumentException
-     *         If the parent of the given configuration is not the configuration
-     *         for this layer
-     * @throws LayerInstantiationException
-     *         If the layer cannot be created for any of the reasons specified
-     *         by the static {@code defineModules} method
-     * @throws SecurityException
-     *         If {@code RuntimePermission("getClassLoader")} is denied by
-     *         the security manager
-     */
-    public Layer defineModules(Configuration cf,
-                               Function<String, ClassLoader> clf) {
-        return defineModules(cf, List.of(this), clf).layer();
-    }
-
-    /**
-     * Creates a new layer by defining the modules in the given {@code
-     * Configuration} to the Java virtual machine. This method creates one
-     * class loader and defines all modules to that class loader.
-     *
-     * <p> The class loader created by this method implements <em>direct
-     * delegation</em> when loading types from modules. When its {@link
-     * ClassLoader#loadClass(String, boolean) loadClass} method is invoked to
-     * load a class then it uses the package name of the class to map it to a
-     * module. This may be a module in this layer and hence defined to the same
-     * class loader. It may be a package in a module in a parent layer that is
-     * exported to one or more of the modules in this layer. The class
-     * loader delegates to the class loader of the module, throwing {@code
-     * ClassNotFoundException} if not found by that class loader.
-     * When {@code loadClass} is invoked to load classes that do not map to a
-     * module then it delegates to the parent class loader. </p>
-     *
-     * <p> Attempting to create a layer with all modules defined to the same
-     * class loader can fail for the following reasons:
-     *
-     * <ul>
-     *
-     *     <li><p> <em>Overlapping packages</em>: Two or more modules in the
-     *     configuration have the same package. </p></li>
-     *
-     *     <li><p> <em>Split delegation</em>: The resulting class loader would
-     *     need to delegate to more than one class loader in order to load types
-     *     in a specific package. </p></li>
-     *
-     * </ul>
-     *
-     * <p> In addition, a layer cannot be created if the configuration contains
-     * a module named "{@code java.base}", or a module contains a package named
-     * "{@code java}" or a package with a name starting with "{@code java.}". </p>
-     *
-     * <p> If there is a security manager then the class loader created by
-     * this method will load classes and resources with privileges that are
-     * restricted by the calling context of this method. </p>
-     *
-     * @param  cf
-     *         The configuration for the layer
-     * @param  parentLayers
-     *         The list of parent layers in search order
-     * @param  parentLoader
-     *         The parent class loader for the class loader created by this
-     *         method; may be {@code null} for the bootstrap class loader
-     *
-     * @return A controller that controls the newly created layer
-     *
-     * @throws IllegalArgumentException
-     *         If the parent configurations do not match the configuration of
-     *         the parent layers, including order
-     * @throws LayerInstantiationException
-     *         If all modules cannot be defined to the same class loader for any
-     *         of the reasons listed above
-     * @throws SecurityException
-     *         If {@code RuntimePermission("createClassLoader")} or
-     *         {@code RuntimePermission("getClassLoader")} is denied by
-     *         the security manager
-     *
-     * @see #findLoader
-     */
-    public static Controller defineModulesWithOneLoader(Configuration cf,
-                                                        List<Layer> parentLayers,
-                                                        ClassLoader parentLoader)
-    {
-        List<Layer> parents = new ArrayList<>(parentLayers);
-        checkConfiguration(cf, parents);
-
-        checkCreateClassLoaderPermission();
-        checkGetClassLoaderPermission();
-
-        try {
-            Loader loader = new Loader(cf.modules(), parentLoader);
-            loader.initRemotePackageMap(cf, parents);
-            Layer layer =  new Layer(cf, parents, mn -> loader);
-            return new Controller(layer);
-        } catch (IllegalArgumentException | IllegalStateException e) {
-            throw new LayerInstantiationException(e.getMessage());
-        }
-    }
-
-    /**
-     * Creates a new layer by defining the modules in the given {@code
-     * Configuration} to the Java virtual machine. Each module is defined to
-     * its own {@link ClassLoader} created by this method. The {@link
-     * ClassLoader#getParent() parent} of each class loader is the given parent
-     * class loader.
-     *
-     * <p> The class loaders created by this method implement <em>direct
-     * delegation</em> when loading types from modules. When {@link
-     * ClassLoader#loadClass(String, boolean) loadClass} method is invoked to
-     * load a class then it uses the package name of the class to map it to a
-     * module. The package may be in the module defined to the class loader.
-     * The package may be exported by another module in this layer to the
-     * module defined to the class loader. It may be in a package exported by a
-     * module in a parent layer. The class loader delegates to the class loader
-     * of the module, throwing {@code ClassNotFoundException} if not found by
-     * that class loader.
-     * When {@code loadClass} is invoked to load classes that do not map to a
-     * module then it delegates to the parent class loader. </p>
-     *
-     * <p> If there is a security manager then the class loaders created by
-     * this method will load classes and resources with privileges that are
-     * restricted by the calling context of this method. </p>
-     *
-     * @param  cf
-     *         The configuration for the layer
-     * @param  parentLayers
-     *         The list of parent layers in search order
-     * @param  parentLoader
-     *         The parent class loader for each of the class loaders created by
-     *         this method; may be {@code null} for the bootstrap class loader
-     *
-     * @return A controller that controls the newly created layer
-     *
-     * @throws IllegalArgumentException
-     *         If the parent configurations do not match the configuration of
-     *         the parent layers, including order
-     * @throws LayerInstantiationException
-     *         If the layer cannot be created because the configuration contains
-     *         a module named "{@code java.base}" or a module contains a package
-     *         named "{@code java}" or a package with a name starting with
-     *         "{@code java.}"
-     *
-     * @throws SecurityException
-     *         If {@code RuntimePermission("createClassLoader")} or
-     *         {@code RuntimePermission("getClassLoader")} is denied by
-     *         the security manager
-     *
-     * @see #findLoader
-     */
-    public static Controller defineModulesWithManyLoaders(Configuration cf,
-                                                          List<Layer> parentLayers,
-                                                          ClassLoader parentLoader)
-    {
-        List<Layer> parents = new ArrayList<>(parentLayers);
-        checkConfiguration(cf, parents);
-
-        checkCreateClassLoaderPermission();
-        checkGetClassLoaderPermission();
-
-        LoaderPool pool = new LoaderPool(cf, parents, parentLoader);
-        try {
-            Layer layer = new Layer(cf, parents, pool::loaderFor);
-            return new Controller(layer);
-        } catch (IllegalArgumentException | IllegalStateException e) {
-            throw new LayerInstantiationException(e.getMessage());
-        }
-    }
-
-    /**
-     * Creates a new layer by defining the modules in the given {@code
-     * Configuration} to the Java virtual machine. The given function maps each
-     * module in the configuration, by name, to a class loader. Creating the
-     * layer informs the Java virtual machine about the classes that may be
-     * loaded so that the Java virtual machine knows which module that each
-     * class is a member of.
-     *
-     * <p> The class loader delegation implemented by the class loaders must
-     * respect module readability. The class loaders should be
-     * {@link ClassLoader#registerAsParallelCapable parallel-capable} so as to
-     * avoid deadlocks during class loading. In addition, the entity creating
-     * a new layer with this method should arrange that the class loaders be
-     * ready to load from these modules before there are any attempts to load
-     * classes or resources. </p>
-     *
-     * <p> Creating a {@code Layer} can fail for the following reasons: </p>
-     *
-     * <ul>
-     *
-     *     <li><p> Two or more modules with the same package are mapped to the
-     *     same class loader. </p></li>
-     *
-     *     <li><p> A module is mapped to a class loader that already has a
-     *     module of the same name defined to it. </p></li>
-     *
-     *     <li><p> A module is mapped to a class loader that has already
-     *     defined types in any of the packages in the module. </p></li>
-     *
-     * </ul>
-     *
-     * <p> In addition, a layer cannot be created if the configuration contains
-     * a module named "{@code java.base}", a configuration contains a module
-     * with a package named "{@code java}" or a package name starting with
-     * "{@code java.}" and the module is mapped to a class loader other than
-     * the {@link ClassLoader#getPlatformClassLoader() platform class loader},
-     * or the function to map a module name to a class loader returns
-     * {@code null}. </p>
-     *
-     * <p> If the function to map a module name to class loader throws an error
-     * or runtime exception then it is propagated to the caller of this method.
-     * </p>
-     *
-     * @apiNote It is implementation specific as to whether creating a Layer
-     * with this method is an atomic operation or not. Consequentially it is
-     * possible for this method to fail with some modules, but not all, defined
-     * to the Java virtual machine.
-     *
-     * @param  cf
-     *         The configuration for the layer
-     * @param  parentLayers
-     *         The list of parent layers in search order
-     * @param  clf
-     *         The function to map a module name to a class loader
-     *
-     * @return A controller that controls the newly created layer
-     *
-     * @throws IllegalArgumentException
-     *         If the parent configurations do not match the configuration of
-     *         the parent layers, including order
-     * @throws LayerInstantiationException
-     *         If creating the layer fails for any of the reasons listed above
-     * @throws SecurityException
-     *         If {@code RuntimePermission("getClassLoader")} is denied by
-     *         the security manager
-     */
-    public static Controller defineModules(Configuration cf,
-                                           List<Layer> parentLayers,
-                                           Function<String, ClassLoader> clf)
-    {
-        List<Layer> parents = new ArrayList<>(parentLayers);
-        checkConfiguration(cf, parents);
-        Objects.requireNonNull(clf);
-
-        checkGetClassLoaderPermission();
-
-        // The boot layer is checked during module system initialization
-        if (boot() != null) {
-            checkForDuplicatePkgs(cf, clf);
-        }
-
-        try {
-            Layer layer = new Layer(cf, parents, clf);
-            return new Controller(layer);
-        } catch (IllegalArgumentException | IllegalStateException e) {
-            throw new LayerInstantiationException(e.getMessage());
-        }
-    }
-
-
-    /**
-     * Checks that the parent configurations match the configuration of
-     * the parent layers.
-     */
-    private static void checkConfiguration(Configuration cf,
-                                           List<Layer> parentLayers)
-    {
-        Objects.requireNonNull(cf);
-
-        List<Configuration> parentConfigurations = cf.parents();
-        if (parentLayers.size() != parentConfigurations.size())
-            throw new IllegalArgumentException("wrong number of parents");
-
-        int index = 0;
-        for (Layer parent : parentLayers) {
-            if (parent.configuration() != parentConfigurations.get(index)) {
-                throw new IllegalArgumentException(
-                        "Parent of configuration != configuration of this Layer");
-            }
-            index++;
-        }
-    }
-
-    private static void checkCreateClassLoaderPermission() {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null)
-            sm.checkPermission(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);
-    }
-
-    private static void checkGetClassLoaderPermission() {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null)
-            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
-    }
-
-    /**
-     * Checks a configuration and the module-to-loader mapping to ensure that
-     * no two modules mapped to the same class loader have the same package.
-     * It also checks that no two automatic modules have the same package.
-     *
-     * @throws LayerInstantiationException
-     */
-    private static void checkForDuplicatePkgs(Configuration cf,
-                                              Function<String, ClassLoader> clf)
-    {
-        // HashMap allows null keys
-        Map<ClassLoader, Set<String>> loaderToPackages = new HashMap<>();
-        for (ResolvedModule resolvedModule : cf.modules()) {
-            ModuleDescriptor descriptor = resolvedModule.reference().descriptor();
-            ClassLoader loader = clf.apply(descriptor.name());
-
-            Set<String> loaderPackages
-                = loaderToPackages.computeIfAbsent(loader, k -> new HashSet<>());
-
-            for (String pkg : descriptor.packages()) {
-                boolean added = loaderPackages.add(pkg);
-                if (!added) {
-                    throw fail("More than one module with package %s mapped" +
-                               " to the same class loader", pkg);
-                }
-            }
-        }
-    }
-
-    /**
-     * Creates a LayerInstantiationException with the a message formatted from
-     * the given format string and arguments.
-     */
-    private static LayerInstantiationException fail(String fmt, Object ... args) {
-        String msg = String.format(fmt, args);
-        return new LayerInstantiationException(msg);
-    }
-
-
-    /**
-     * Returns the configuration for this layer.
-     *
-     * @return The configuration for this layer
-     */
-    public Configuration configuration() {
-        return cf;
-    }
-
-
-    /**
-     * Returns the list of this layer's parents unless this is the
-     * {@linkplain #empty empty layer}, which has no parents and so an
-     * empty list is returned.
-     *
-     * @return The list of this layer's parents
-     */
-    public List<Layer> parents() {
-        return parents;
-    }
-
-
-    /**
-     * Returns an ordered stream of layers. The first element is is this layer,
-     * the remaining elements are the parent layers in DFS order.
-     *
-     * @implNote For now, the assumption is that the number of elements will
-     * be very low and so this method does not use a specialized spliterator.
-     */
-    Stream<Layer> layers() {
-        List<Layer> allLayers = this.allLayers;
-        if (allLayers != null)
-            return allLayers.stream();
-
-        allLayers = new ArrayList<>();
-        Set<Layer> visited = new HashSet<>();
-        Deque<Layer> stack = new ArrayDeque<>();
-        visited.add(this);
-        stack.push(this);
-
-        while (!stack.isEmpty()) {
-            Layer layer = stack.pop();
-            allLayers.add(layer);
-
-            // push in reverse order
-            for (int i = layer.parents.size() - 1; i >= 0; i--) {
-                Layer parent = layer.parents.get(i);
-                if (!visited.contains(parent)) {
-                    visited.add(parent);
-                    stack.push(parent);
-                }
-            }
-        }
-
-        this.allLayers = allLayers = Collections.unmodifiableList(allLayers);
-        return allLayers.stream();
-    }
-
-    private volatile List<Layer> allLayers;
-
-    /**
-     * Returns the set of the modules in this layer.
-     *
-     * @return A possibly-empty unmodifiable set of the modules in this layer
-     */
-    public Set<Module> modules() {
-        Set<Module> modules = this.modules;
-        if (modules == null) {
-            this.modules = modules =
-                Collections.unmodifiableSet(new HashSet<>(nameToModule.values()));
-        }
-        return modules;
-    }
-
-    private volatile Set<Module> modules;
-
-
-    /**
-     * Returns the module with the given name in this layer, or if not in this
-     * layer, the {@linkplain #parents parent} layers. Finding a module in
-     * parent layers is equivalent to invoking {@code findModule} on each
-     * parent, in search order, until the module is found or all parents have
-     * been searched. In a <em>tree of layers</em>  then this is equivalent to
-     * a depth-first search.
-     *
-     * @param  name
-     *         The name of the module to find
-     *
-     * @return The module with the given name or an empty {@code Optional}
-     *         if there isn't a module with this name in this layer or any
-     *         parent layer
-     */
-    public Optional<Module> findModule(String name) {
-        Objects.requireNonNull(name);
-        if (this == EMPTY_LAYER)
-            return Optional.empty();
-        Module m = nameToModule.get(name);
-        if (m != null)
-            return Optional.of(m);
-
-        return layers()
-                .skip(1)  // skip this layer
-                .map(l -> l.nameToModule)
-                .filter(map -> map.containsKey(name))
-                .map(map -> map.get(name))
-                .findAny();
-    }
-
-
-    /**
-     * Returns the {@code ClassLoader} for the module with the given name. If
-     * a module of the given name is not in this layer then the {@link #parents
-     * parent} layers are searched in the manner specified by {@link
-     * #findModule(String) findModule}.
-     *
-     * <p> If there is a security manager then its {@code checkPermission}
-     * method is called with a {@code RuntimePermission("getClassLoader")}
-     * permission to check that the caller is allowed to get access to the
-     * class loader. </p>
-     *
-     * @apiNote This method does not return an {@code Optional<ClassLoader>}
-     * because `null` must be used to represent the bootstrap class loader.
-     *
-     * @param  name
-     *         The name of the module to find
-     *
-     * @return The ClassLoader that the module is defined to
-     *
-     * @throws IllegalArgumentException if a module of the given name is not
-     *         defined in this layer or any parent of this layer
-     *
-     * @throws SecurityException if denied by the security manager
-     */
-    public ClassLoader findLoader(String name) {
-        Optional<Module> om = findModule(name);
-
-        // can't use map(Module::getClassLoader) as class loader can be null
-        if (om.isPresent()) {
-            return om.get().getClassLoader();
-        } else {
-            throw new IllegalArgumentException("Module " + name
-                                               + " not known to this layer");
-        }
-    }
-
-    /**
-     * Returns a string describing this layer.
-     *
-     * @return A possibly empty string describing this layer
-     */
-    @Override
-    public String toString() {
-        return modules().stream()
-                .map(Module::getName)
-                .collect(Collectors.joining(", "));
-    }
-
-    /**
-     * Returns the <em>empty</em> layer. There are no modules in the empty
-     * layer. It has no parents.
-     *
-     * @return The empty layer
-     */
-    public static Layer empty() {
-        return EMPTY_LAYER;
-    }
-
-
-    /**
-     * Returns the boot layer. The boot layer contains at least one module,
-     * {@code java.base}. Its parent is the {@link #empty() empty} layer.
-     *
-     * @apiNote This method returns {@code null} during startup and before
-     *          the boot layer is fully initialized.
-     *
-     * @return The boot layer
-     */
-    public static Layer boot() {
-        return SharedSecrets.getJavaLangAccess().getBootLayer();
-    }
-
-
-    /**
-     * Returns the ServicesCatalog for this Layer, creating it if not
-     * already created.
-     */
-    ServicesCatalog getServicesCatalog() {
-        ServicesCatalog servicesCatalog = this.servicesCatalog;
-        if (servicesCatalog != null)
-            return servicesCatalog;
-
-        synchronized (this) {
-            servicesCatalog = this.servicesCatalog;
-            if (servicesCatalog == null) {
-                servicesCatalog = ServicesCatalog.create();
-                nameToModule.values().forEach(servicesCatalog::register);
-                this.servicesCatalog = servicesCatalog;
-            }
-        }
-
-        return servicesCatalog;
-    }
-
-    private volatile ServicesCatalog servicesCatalog;
-
-
-    /**
-     * Record that this layer has at least one module defined to the given
-     * class loader.
-     */
-    void bindToLoader(ClassLoader loader) {
-        // CLV.computeIfAbsent(loader, (cl, clv) -> new CopyOnWriteArrayList<>())
-        List<Layer> list = CLV.get(loader);
-        if (list == null) {
-            list = new CopyOnWriteArrayList<>();
-            List<Layer> previous = CLV.putIfAbsent(loader, list);
-            if (previous != null) list = previous;
-        }
-        list.add(this);
-    }
-
-    /**
-     * Returns a stream of the layers that have at least one module defined to
-     * the given class loader.
-     */
-    static Stream<Layer> layers(ClassLoader loader) {
-        List<Layer> list = CLV.get(loader);
-        if (list != null) {
-            return list.stream();
-        } else {
-            return Stream.empty();
-        }
-    }
-
-    // the list of layers with modules defined to a class loader
-    private static final ClassLoaderValue<List<Layer>> CLV = new ClassLoaderValue<>();
-}
--- a/src/java.base/share/classes/java/lang/reflect/LayerInstantiationException.java	Mon Apr 10 16:20:40 2017 +0530
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.lang.reflect;
-
-/**
- * Thrown when creating a Layer fails.
- *
- * @see Layer
- *
- * @since 9
- * @spec JPMS
- */
-public class LayerInstantiationException extends RuntimeException {
-    private static final long serialVersionUID = -906239691613568347L;
-
-    /**
-     * Constructs a {@code LayerInstantiationException} with no detail message.
-     */
-    public LayerInstantiationException() {
-    }
-
-    /**
-     * Constructs a {@code LayerInstantiationException} with the given detail
-     * message.
-     *
-     * @param msg
-     *        The detail message; can be {@code null}
-     */
-    public LayerInstantiationException(String msg) {
-        super(msg);
-    }
-
-    /**
-     * Constructs a {@code LayerInstantiationException} with the given cause.
-     *
-     * @param cause
-     *        The cause; can be {@code null}
-     */
-    public LayerInstantiationException(Throwable cause) {
-        super(cause);
-    }
-
-    /**
-     * Constructs a {@code FindException} with the given detail message
-     * and cause.
-     *
-     * @param msg
-     *        The detail message; can be {@code null}
-     * @param cause
-     *        The cause; can be {@code null}
-     */
-    public LayerInstantiationException(String msg, Throwable cause) {
-        super(msg, cause);
-    }
-
-}
-
--- a/src/java.base/share/classes/java/lang/reflect/Module.java	Mon Apr 10 16:20:40 2017 +0530
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1591 +0,0 @@
-/*
- * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package java.lang.reflect;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.module.Configuration;
-import java.lang.module.ModuleReference;
-import java.lang.module.ModuleDescriptor;
-import java.lang.module.ModuleDescriptor.Exports;
-import java.lang.module.ModuleDescriptor.Opens;
-import java.lang.module.ModuleDescriptor.Version;
-import java.lang.module.ResolvedModule;
-import java.net.URI;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Function;
-import java.util.stream.Stream;
-
-import jdk.internal.loader.BuiltinClassLoader;
-import jdk.internal.loader.BootLoader;
-import jdk.internal.misc.JavaLangAccess;
-import jdk.internal.misc.JavaLangReflectModuleAccess;
-import jdk.internal.misc.SharedSecrets;
-import jdk.internal.module.ServicesCatalog;
-import jdk.internal.module.Resources;
-import jdk.internal.org.objectweb.asm.AnnotationVisitor;
-import jdk.internal.org.objectweb.asm.Attribute;
-import jdk.internal.org.objectweb.asm.ClassReader;
-import jdk.internal.org.objectweb.asm.ClassVisitor;
-import jdk.internal.org.objectweb.asm.ClassWriter;
-import jdk.internal.org.objectweb.asm.Opcodes;
-import jdk.internal.reflect.CallerSensitive;
-import jdk.internal.reflect.Reflection;
-import sun.security.util.SecurityConstants;
-
-/**
- * Represents a run-time module, either {@link #isNamed() named} or unnamed.
- *
- * <p> Named modules have a {@link #getName() name} and are constructed by the
- * Java Virtual Machine when a graph of modules is defined to the Java virtual
- * machine to create a module {@link Layer Layer}. </p>
- *
- * <p> An unnamed module does not have a name. There is an unnamed module for
- * each {@link ClassLoader ClassLoader}, obtained by invoking its {@link
- * ClassLoader#getUnnamedModule() getUnnamedModule} method. All types that are
- * not in a named module are members of their defining class loader's unnamed
- * module. </p>
- *
- * <p> The package names that are parameters or returned by methods defined in
- * this class are the fully-qualified names of the packages as defined in
- * section 6.5.3 of <cite>The Java&trade; Language Specification</cite>, for
- * example, {@code "java.lang"}. </p>
- *
- * <p> Unless otherwise specified, passing a {@code null} argument to a method
- * in this class causes a {@link NullPointerException NullPointerException} to
- * be thrown. </p>
- *
- * @since 9
- * @spec JPMS
- * @see java.lang.Class#getModule
- */
-
-public final class Module implements AnnotatedElement {
-
-    // the layer that contains this module, can be null
-    private final Layer layer;
-
-    // module name and loader, these fields are read by VM
-    private final String name;
-    private final ClassLoader loader;
-
-    // the module descriptor
-    private final ModuleDescriptor descriptor;
-
-
-    /**
-     * Creates a new named Module. The resulting Module will be defined to the
-     * VM but will not read any other modules, will not have any exports setup
-     * and will not be registered in the service catalog.
-     */
-    private Module(Layer layer,
-                   ClassLoader loader,
-                   ModuleDescriptor descriptor,
-                   URI uri)
-    {
-        this.layer = layer;
-        this.name = descriptor.name();
-        this.loader = loader;
-        this.descriptor = descriptor;
-
-        // define module to VM
-
-        boolean isOpen = descriptor.isOpen();
-        Version version = descriptor.version().orElse(null);
-        String vs = Objects.toString(version, null);
-        String loc = Objects.toString(uri, null);
-        String[] packages = descriptor.packages().toArray(new String[0]);
-        defineModule0(this, isOpen, vs, loc, packages);
-    }
-
-
-    /**
-     * Create the unnamed Module for the given ClassLoader.
-     *
-     * @see ClassLoader#getUnnamedModule
-     */
-    private Module(ClassLoader loader) {
-        this.layer = null;
-        this.name = null;
-        this.loader = loader;
-        this.descriptor = null;
-    }
-
-
-    /**
-     * Creates a named module but without defining the module to the VM.
-     *
-     * @apiNote This constructor is for VM white-box testing.
-     */
-    Module(ClassLoader loader, ModuleDescriptor descriptor) {
-        this.layer = null;
-        this.name = descriptor.name();
-        this.loader = loader;
-        this.descriptor = descriptor;
-    }
-
-
-
-    /**
-     * Returns {@code true} if this module is a named module.
-     *
-     * @return {@code true} if this is a named module
-     *
-     * @see ClassLoader#getUnnamedModule()
-     */
-    public boolean isNamed() {
-        return name != null;
-    }
-
-    /**
-     * Returns the module name or {@code null} if this module is an unnamed
-     * module.
-     *
-     * @return The module name
-     */
-    public String getName() {
-        return name;
-    }
-
-    /**
-     * Returns the {@code ClassLoader} for this module.
-     *
-     * <p> If there is a security manager then its {@code checkPermission}
-     * method if first called with a {@code RuntimePermission("getClassLoader")}
-     * permission to check that the caller is allowed to get access to the
-     * class loader. </p>
-     *
-     * @return The class loader for this module
-     *
-     * @throws SecurityException
-     *         If denied by the security manager
-     */
-    public ClassLoader getClassLoader() {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
-        }
-        return loader;
-    }
-
-    /**
-     * Returns the module descriptor for this module or {@code null} if this
-     * module is an unnamed module.
-     *
-     * @return The module descriptor for this module
-     */
-    public ModuleDescriptor getDescriptor() {
-        return descriptor;
-    }
-
-    /**
-     * Returns the layer that contains this module or {@code null} if this
-     * module is not in a layer.
-     *
-     * A module {@code Layer} contains named modules and therefore this
-     * method always returns {@code null} when invoked on an unnamed module.
-     *
-     * <p> <a href="Proxy.html#dynamicmodule">Dynamic modules</a> are named
-     * modules that are generated at runtime. A dynamic module may or may
-     * not be in a module Layer. </p>
-     *
-     * @return The layer that contains this module
-     *
-     * @see Proxy
-     */
-    public Layer getLayer() {
-        if (isNamed()) {
-            Layer layer = this.layer;
-            if (layer != null)
-                return layer;
-
-            // special-case java.base as it is created before the boot Layer
-            if (loader == null && name.equals("java.base")) {
-                return SharedSecrets.getJavaLangAccess().getBootLayer();
-            }
-        }
-
-        return null;
-    }
-
-
-    // --
-
-    // special Module to mean "all unnamed modules"
-    private static final Module ALL_UNNAMED_MODULE = new Module(null);
-
-    // special Module to mean "everyone"
-    private static final Module EVERYONE_MODULE = new Module(null);
-
-    // set contains EVERYONE_MODULE, used when a package is opened or
-    // exported unconditionally
-    private static final Set<Module> EVERYONE_SET = Set.of(EVERYONE_MODULE);
-
-
-    // -- readability --
-
-    // the modules that this module reads
-    private volatile Set<Module> reads;
-
-    // additional module (2nd key) that some module (1st key) reflectively reads
-    private static final WeakPairMap<Module, Module, Boolean> reflectivelyReads
-        = new WeakPairMap<>();
-
-
-    /**
-     * Indicates if this module reads the given module. This method returns
-     * {@code true} if invoked to test if this module reads itself. It also
-     * returns {@code true} if invoked on an unnamed module (as unnamed
-     * modules read all modules).
-     *
-     * @param  other
-     *         The other module
-     *
-     * @return {@code true} if this module reads {@code other}
-     *
-     * @see #addReads(Module)
-     */
-    public boolean canRead(Module other) {
-        Objects.requireNonNull(other);
-
-        // an unnamed module reads all modules
-        if (!this.isNamed())
-            return true;
-
-        // all modules read themselves
-        if (other == this)
-            return true;
-
-        // check if this module reads other
-        if (other.isNamed()) {
-            Set<Module> reads = this.reads; // volatile read
-            if (reads != null && reads.contains(other))
-                return true;
-        }
-
-        // check if this module reads the other module reflectively
-        if (reflectivelyReads.containsKeyPair(this, other))
-            return true;
-
-        // if other is an unnamed module then check if this module reads
-        // all unnamed modules
-        if (!other.isNamed()
-            && reflectivelyReads.containsKeyPair(this, ALL_UNNAMED_MODULE))
-            return true;
-
-        return false;
-    }