1 /*
   2  * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.io.BufferedReader;
  29 import java.io.IOException;
  30 import java.io.InputStream;
  31 import java.io.InputStreamReader;
  32 import java.lang.module.ModuleDescriptor;
  33 import java.lang.module.ModuleDescriptor.Provides;
  34 import java.lang.reflect.Constructor;
  35 import java.lang.reflect.InvocationTargetException;
  36 import java.lang.reflect.Layer;
  37 import java.lang.reflect.Modifier;
  38 import java.lang.reflect.Module;
  39 import java.net.URL;
  40 import java.net.URLConnection;
  41 import java.security.AccessController;
  42 import java.security.AccessControlContext;
  43 import java.security.PrivilegedAction;
  44 
  45 import jdk.internal.loader.BootLoader;
  46 import jdk.internal.loader.Loader;
  47 import jdk.internal.loader.LoaderPool;
  48 import jdk.internal.misc.JavaLangAccess;
  49 import jdk.internal.misc.SharedSecrets;
  50 import jdk.internal.misc.VM;
  51 import jdk.internal.module.ServicesCatalog;
  52 import jdk.internal.module.ServicesCatalog.ServiceProvider;
  53 
  54 import jdk.internal.reflect.CallerSensitive;
  55 import jdk.internal.reflect.Reflection;
  56 
  57 
  58 /**
  59  * A simple service-provider loading facility.
  60  *
  61  * <p> A <i>service</i> is a well-known set of interfaces and (usually
  62  * abstract) classes.  A <i>service provider</i> is a specific implementation
  63  * of a service.  The classes in a provider typically implement the interfaces
  64  * and subclass the classes defined in the service itself.
  65  * Providers may be developed and deployed as modules and made available using
  66  * the application module path. Providers may alternatively be packaged as JAR
  67  * files and made available by adding them to the application class path. The
  68  * advantage of developing a provider as a module is that the provider can be
  69  * fully encapsulated to hide all details of its implementation.
  70  *
  71  * <p> For the purpose of loading, a service is represented by a single type,
  72  * that is, a single interface or abstract class.  (A concrete class can be
  73  * used, but this is not recommended.)  A provider of a given service contains
  74  * one or more concrete classes that extend this <i>service type</i> with data
  75  * and code specific to the provider.  The <i>provider class</i> is typically
  76  * not the entire provider itself but rather a proxy which contains enough
  77  * information to decide whether the provider is able to satisfy a particular
  78  * request together with code that can create the actual provider on demand.
  79  * The details of provider classes tend to be highly service-specific; no
  80  * single class or interface could possibly unify them, so no such type is
  81  * defined here. A requirement enforced by this facility is that each provider
  82  * class must have a {@code public} zero-argument constructor.
  83  *
  84  * <p> An application or library using this loading facility and developed
  85  * and deployed as a named module must have an appropriate <i>uses</i> clause
  86  * in its <i>module descriptor</i> to declare that the module uses
  87  * implementations of the service. A corresponding requirement is that a
  88  * provider deployed as a named modules must have an appropriate
  89  * <i>provides</i> clause in its module descriptor to declare that the module
  90  * provides an implementation of the service. The <i>uses</i> and
  91  * <i>provides</i> allow consumers of a service to be <i>linked</i> to
  92  * providers of the service. In the case of {@code load} methods that locate
  93  * service providers using a class loader, then provider modules defined to
  94  * that class loader, or a class loader <i>reachable</i> using {@link
  95  * ClassLoader#getParent() parent} delegation, will be located.
  96  *
  97  * <p> A service provider that is packaged as a JAR file for the class path is
  98  * identified by placing a <i>provider-configuration file</i> in the resource
  99  * directory <tt>META-INF/services</tt>. The file's name is the fully-qualified
 100  * <a href="../lang/ClassLoader.html#name">binary name</a> of the service's
 101  * type. The file contains a list of fully-qualified binary names of concrete
 102  * provider classes, one per line.  Space and tab characters surrounding each
 103  * name, as well as blank lines, are ignored.  The comment character is
 104  * <tt>'#'</tt> (<tt>'\u0023'</tt>,
 105  * <font style="font-size:smaller;">NUMBER SIGN</font>); on
 106  * each line all characters following the first comment character are ignored.
 107  * The file must be encoded in UTF-8.
 108  * If a particular concrete provider class is named in more than one
 109  * configuration file, or is named in the same configuration file more than
 110  * once, then the duplicates are ignored.  The configuration file naming a
 111  * particular provider need not be in the same JAR file or other distribution
 112  * unit as the provider itself. The provider must be visible from the same
 113  * class loader that was initially queried to locate the configuration file;
 114  * note that this is not necessarily the class loader from which the file was
 115  * actually loaded.
 116  *
 117  * <p> Providers are located and instantiated lazily, that is, on demand.  A
 118  * service loader maintains a cache of the providers that have been loaded so
 119  * far.  Each invocation of the {@link #iterator iterator} method returns an
 120  * iterator that first yields all of the elements of the cache, in
 121  * instantiation order, and then lazily locates and instantiates any remaining
 122  * providers, adding each one to the cache in turn.  The cache can be cleared
 123  * via the {@link #reload reload} method.
 124  *
 125  * <p> Service loaders always execute in the security context of the caller
 126  * of the iterator methods and may also be restricted by the security
 127  * context of the caller that created the service loader.
 128  * Trusted system code should typically invoke the methods in this class, and
 129  * the methods of the iterators which they return, from within a privileged
 130  * security context.
 131  *
 132  * <p> Instances of this class are not safe for use by multiple concurrent
 133  * threads.
 134  *
 135  * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any
 136  * method in this class will cause a {@link NullPointerException} to be thrown.
 137  *
 138  * <p><span style="font-weight: bold; padding-right: 1em">Example</span>
 139  * Suppose we have a service type <tt>com.example.CodecSet</tt> which is
 140  * intended to represent sets of encoder/decoder pairs for some protocol.  In
 141  * this case it is an abstract class with two abstract methods:
 142  *
 143  * <blockquote><pre>
 144  * public abstract Encoder getEncoder(String encodingName);
 145  * public abstract Decoder getDecoder(String encodingName);</pre></blockquote>
 146  *
 147  * Each method returns an appropriate object or <tt>null</tt> if the provider
 148  * does not support the given encoding.  Typical providers support more than
 149  * one encoding.
 150  *
 151  * <p> The <tt>CodecSet</tt> class creates and saves a single service instance
 152  * at initialization:
 153  *
 154  * <pre>{@code
 155  * private static ServiceLoader<CodecSet> codecSetLoader
 156  *     = ServiceLoader.load(CodecSet.class);
 157  * }</pre>
 158  *
 159  * <p> To locate an encoder for a given encoding name it defines a static
 160  * factory method which iterates through the known and available providers,
 161  * returning only when it has located a suitable encoder or has run out of
 162  * providers.
 163  *
 164  * <pre>{@code
 165  * public static Encoder getEncoder(String encodingName) {
 166  *     for (CodecSet cp : codecSetLoader) {
 167  *         Encoder enc = cp.getEncoder(encodingName);
 168  *         if (enc != null)
 169  *             return enc;
 170  *     }
 171  *     return null;
 172  * }}</pre>
 173  *
 174  * <p> A {@code getDecoder} method is defined similarly.
 175  *
 176  * <p> If the code creating and using the service loader is developed as
 177  * a module then its module descriptor will declare the usage with:
 178  * <pre>{@code uses com.example.CodecSet;}</pre>
 179  *
 180  * <p> Now suppose that {@code com.example.impl.StandardCodecs} is an
 181  * implementation of the {@code CodecSet} service and developed as a module.
 182  * In that case then the module with the service provider module will declare
 183  * this in its module descriptor:
 184  * <pre>{@code provides com.example.CodecSet with com.example.impl.StandardCodecs;
 185  * }</pre>
 186  *
 187  * <p> On the other hand, suppose {@code com.example.impl.StandardCodecs} is
 188  * packaged in a JAR file for the class path then the JAR file will contain a
 189  * file named:
 190  * <pre>{@code META-INF/services/com.example.CodecSet}</pre>
 191  * that contains the single line:
 192  * <pre>{@code com.example.impl.StandardCodecs    # Standard codecs}</pre>
 193  *
 194  * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If
 195  * the class path of a class loader that is used for provider loading includes
 196  * remote network URLs then those URLs will be dereferenced in the process of
 197  * searching for provider-configuration files.
 198  *
 199  * <p> This activity is normal, although it may cause puzzling entries to be
 200  * created in web-server logs.  If a web server is not configured correctly,
 201  * however, then this activity may cause the provider-loading algorithm to fail
 202  * spuriously.
 203  *
 204  * <p> A web server should return an HTTP 404 (Not Found) response when a
 205  * requested resource does not exist.  Sometimes, however, web servers are
 206  * erroneously configured to return an HTTP 200 (OK) response along with a
 207  * helpful HTML error page in such cases.  This will cause a {@link
 208  * ServiceConfigurationError} to be thrown when this class attempts to parse
 209  * the HTML page as a provider-configuration file.  The best solution to this
 210  * problem is to fix the misconfigured web server to return the correct
 211  * response code (HTTP 404) along with the HTML error page.
 212  *
 213  * @param  <S>
 214  *         The type of the service to be loaded by this loader
 215  *
 216  * @author Mark Reinhold
 217  * @since 1.6
 218  */
 219 
 220 public final class ServiceLoader<S>
 221     implements Iterable<S>
 222 {
 223     private static final String PREFIX = "META-INF/services/";
 224 
 225     // The class or interface representing the service being loaded
 226     private final Class<S> service;
 227 
 228     // The module Layer used to locate providers; null when locating
 229     // providers using a class loader
 230     private final Layer layer;
 231 
 232     // The class loader used to locate, load, and instantiate providers;
 233     // null when locating provider using a module Layer
 234     private final ClassLoader loader;
 235 
 236     // The access control context taken when the ServiceLoader is created
 237     private final AccessControlContext acc;
 238 
 239     // Cached providers, in instantiation order
 240     private List<S> providers = new ArrayList<>();
 241 
 242     // The class names of the cached providers, only used when locating
 243     // service providers via a class loader
 244     private Set<String> providerNames = new HashSet<>();
 245 
 246     // Incremented when reload is called
 247     private int reloadCount;
 248 
 249     // the service iterator when locating services via a module layer
 250     private LayerLookupIterator layerLookupIterator;
 251 
 252     // The module services iterator when locating services in modules
 253     // defined to a class loader
 254     private ModuleServicesIterator moduleServicesIterator;
 255 
 256     // The current lazy-lookup iterator for locating legacy provider on the
 257     // class path via a class loader
 258     private LazyClassPathIterator lazyClassPathIterator;
 259 
 260 
 261     /**
 262      * Clear this loader's provider cache so that all providers will be
 263      * reloaded.
 264      *
 265      * <p> After invoking this method, subsequent invocations of the {@link
 266      * #iterator() iterator} method will lazily look up and instantiate
 267      * providers from scratch, just as is done by a newly-created loader.
 268      *
 269      * <p> This method is intended for use in situations in which new providers
 270      * can be installed into a running Java virtual machine.
 271      */
 272     public void reload() {
 273         providers.clear();
 274 
 275         assert layer == null || loader == null;
 276         if (layer != null) {
 277             layerLookupIterator = new LayerLookupIterator();
 278         } else {
 279             providerNames.clear();
 280             moduleServicesIterator = new ModuleServicesIterator();
 281             lazyClassPathIterator = new LazyClassPathIterator();
 282         }
 283 
 284         reloadCount++;
 285     }
 286 
 287 
 288     /**
 289      * Initializes a new instance of this class for locating service providers
 290      * in a module Layer.
 291      *
 292      * @throws ServiceConfigurationError
 293      *         If {@code svc} is not accessible to {@code caller} or that the
 294      *         caller's module does not declare that it uses the service type.
 295      */
 296     private ServiceLoader(Class<?> caller, Layer layer, Class<S> svc) {
 297 
 298         checkModule(caller.getModule(), svc);
 299 
 300         this.service = svc;
 301         this.layer = layer;
 302         this.loader = null;
 303         this.acc = (System.getSecurityManager() != null)
 304                 ? AccessController.getContext()
 305                 : null;
 306 
 307         reload();
 308     }
 309 
 310     /**
 311      * Initializes a new instance of this class for locating service providers
 312      * via a class loader.
 313      *
 314      * @throws ServiceConfigurationError
 315      *         If {@code svc} is not accessible to {@code caller} or that the
 316      *         caller's module does not declare that it uses the service type.
 317      */
 318     private ServiceLoader(Module callerModule, Class<S> svc, ClassLoader cl) {
 319         if (VM.isBooted()) {
 320 
 321             checkModule(callerModule, svc);
 322 
 323             if (cl == null) {
 324                 cl = ClassLoader.getSystemClassLoader();
 325             }
 326 
 327         } else {
 328 
 329             // if we get here then it means that ServiceLoader is being used
 330             // before the VM initialization has completed. At this point then
 331             // only code in the java.base should be executing.
 332             Module base = Object.class.getModule();
 333             Module svcModule = svc.getModule();
 334             if (callerModule != base || svcModule != base) {
 335                 fail(svc, "not accessible to " + callerModule + " during VM init");
 336             }
 337 
 338             // restricted to boot loader during startup
 339             cl = null;
 340         }
 341 
 342         this.service = svc;
 343         this.layer = null;
 344         this.loader = cl;
 345         this.acc = (System.getSecurityManager() != null)
 346                 ? AccessController.getContext()
 347                 : null;
 348 
 349         reload();
 350     }
 351 
 352     private ServiceLoader(Class<?> caller, Class<S> svc, ClassLoader cl) {
 353         this(caller.getModule(), svc, cl);
 354     }
 355 
 356 
 357 
 358     /**
 359      * Checks that the given service type is accessible to types in the given
 360      * module, and check that the module declare that it uses the service type.
 361      */
 362     private static void checkModule(Module module, Class<?> svc) {
 363 
 364         // Check that the service type is in a package that is
 365         // exported to the caller.
 366         if (!Reflection.verifyModuleAccess(module, svc)) {
 367             fail(svc, "not accessible to " + module);
 368         }
 369 
 370         // If the caller is in a named module then it should "uses" the
 371         // service type
 372         if (!module.canUse(svc)) {
 373             fail(svc, "use not declared in " + module);
 374         }
 375 
 376     }
 377 
 378     private static void fail(Class<?> service, String msg, Throwable cause)
 379         throws ServiceConfigurationError
 380     {
 381         throw new ServiceConfigurationError(service.getName() + ": " + msg,
 382                                             cause);
 383     }
 384 
 385     private static void fail(Class<?> service, String msg)
 386         throws ServiceConfigurationError
 387     {
 388         throw new ServiceConfigurationError(service.getName() + ": " + msg);
 389     }
 390 
 391     private static void fail(Class<?> service, URL u, int line, String msg)
 392         throws ServiceConfigurationError
 393     {
 394         fail(service, u + ":" + line + ": " + msg);
 395     }
 396 
 397     // Parse a single line from the given configuration file, adding the name
 398     // on the line to the names list.
 399     //
 400     private int parseLine(Class<?> service, URL u, BufferedReader r, int lc,
 401                           List<String> names)
 402         throws IOException, ServiceConfigurationError
 403     {
 404         String ln = r.readLine();
 405         if (ln == null) {
 406             return -1;
 407         }
 408         int ci = ln.indexOf('#');
 409         if (ci >= 0) ln = ln.substring(0, ci);
 410         ln = ln.trim();
 411         int n = ln.length();
 412         if (n != 0) {
 413             if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
 414                 fail(service, u, lc, "Illegal configuration-file syntax");
 415             int cp = ln.codePointAt(0);
 416             if (!Character.isJavaIdentifierStart(cp))
 417                 fail(service, u, lc, "Illegal provider-class name: " + ln);
 418             for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
 419                 cp = ln.codePointAt(i);
 420                 if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
 421                     fail(service, u, lc, "Illegal provider-class name: " + ln);
 422             }
 423             if (!providerNames.contains(ln) && !names.contains(ln))
 424                 names.add(ln);
 425         }
 426         return lc + 1;
 427     }
 428 
 429     /**
 430      * Parse the content of the given URL as a provider-configuration file.
 431      *
 432      * @param  service
 433      *         The service type for which providers are being sought;
 434      *         used to construct error detail strings
 435      *
 436      * @param  u
 437      *         The URL naming the configuration file to be parsed
 438      *
 439      * @return A (possibly empty) iterator that will yield the provider-class
 440      *         names in the given configuration file that are not yet members
 441      *         of the returned set
 442      *
 443      * @throws ServiceConfigurationError
 444      *         If an I/O error occurs while reading from the given URL, or
 445      *         if a configuration-file format error is detected
 446      *
 447      */
 448     private Iterator<String> parse(Class<?> service, URL u)
 449         throws ServiceConfigurationError
 450     {
 451         ArrayList<String> names = new ArrayList<>();
 452         try {
 453             URLConnection uc = u.openConnection();
 454             uc.setUseCaches(false);
 455             try (InputStream in = uc.getInputStream();
 456                  BufferedReader r
 457                      = new BufferedReader(new InputStreamReader(in, "utf-8")))
 458             {
 459                 int lc = 1;
 460                 while ((lc = parseLine(service, u, r, lc, names)) >= 0);
 461             }
 462         } catch (IOException x) {
 463             fail(service, "Error accessing configuration file", x);
 464         }
 465         return names.iterator();
 466     }
 467 
 468     /**
 469      * Returns the {@code Constructor} to instantiate the service provider.
 470      * The constructor has its accessible flag set so that the access check
 471      * is suppressed when instantiating the provider. This is necessary
 472      * because newInstance is a caller sensitive method and ServiceLoader
 473      * is instantiating the service provider on behalf of the service
 474      * consumer.
 475      */
 476     private static Constructor<?> checkAndGetConstructor(Class<?> c)
 477         throws NoSuchMethodException, IllegalAccessException
 478     {
 479         Constructor<?> ctor = c.getConstructor();
 480 
 481         // check class and no-arg constructor are public
 482         int modifiers = ctor.getModifiers();
 483         if (!Modifier.isPublic(Reflection.getClassAccessFlags(c) & modifiers)) {
 484             String cn = c.getName();
 485             throw new IllegalAccessException(cn + " is not public");
 486         }
 487 
 488         // return Constructor to create the service implementation
 489         PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
 490             public Void run() { ctor.setAccessible(true); return null; }
 491         };
 492         AccessController.doPrivileged(action);
 493         return ctor;
 494     }
 495 
 496     /**
 497      * Uses Class.forName to load a class in a module.
 498      */
 499     private static Class<?> loadClassInModule(Module module, String cn) {
 500         SecurityManager sm = System.getSecurityManager();
 501         if (sm == null) {
 502             return Class.forName(module, cn);
 503         } else {
 504             PrivilegedAction<Class<?>> pa = () -> Class.forName(module, cn);
 505             return AccessController.doPrivileged(pa);
 506         }
 507     }
 508 
 509     /**
 510      * An Iterator that runs the next and hasNext methods with permissions
 511      * restricted by the {@code AccessControlContext} obtained when the
 512      * ServiceLoader was created.
 513      */
 514     private abstract class RestrictedIterator<S>
 515         implements Iterator<S>
 516     {
 517         /**
 518          * Returns {@code true} if the iteration has more elements.
 519          */
 520         abstract boolean hasNextService();
 521 
 522         /**
 523          * Returns the next element in the iteration
 524          */
 525         abstract S nextService();
 526 
 527         public final boolean hasNext() {
 528             if (acc == null) {
 529                 return hasNextService();
 530             } else {
 531                 PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
 532                     public Boolean run() { return hasNextService(); }
 533                 };
 534                 return AccessController.doPrivileged(action, acc);
 535             }
 536         }
 537 
 538         public final S next() {
 539             if (acc == null) {
 540                 return nextService();
 541             } else {
 542                 PrivilegedAction<S> action = new PrivilegedAction<S>() {
 543                     public S run() { return nextService(); }
 544                 };
 545                 return AccessController.doPrivileged(action, acc);
 546             }
 547         }
 548     }
 549 
 550     /**
 551      * Implements lazy service provider lookup of service providers that
 552      * are provided by modules in a module Layer.
 553      *
 554      * For now, this iterator examines all modules in each Layer. This will
 555      * be replaced once we decide on how the service-use graph is exposed
 556      * in the module API.
 557      */
 558     private class LayerLookupIterator
 559         extends RestrictedIterator<S>
 560     {
 561         final String serviceName;
 562         Layer currentLayer;
 563         Iterator<ModuleDescriptor> descriptorIterator;
 564         Iterator<String> providersIterator;
 565 
 566         Module nextModule;
 567         String nextProvider;
 568 
 569         LayerLookupIterator() {
 570             serviceName = service.getName();
 571             currentLayer = layer;
 572 
 573             // need to get us started
 574             descriptorIterator = descriptors(layer, serviceName);
 575         }
 576 
 577         Iterator<ModuleDescriptor> descriptors(Layer layer, String service) {
 578             return layer.modules().stream()
 579                     .map(Module::getDescriptor)
 580                     .filter(d -> d.provides().get(service) != null)
 581                     .iterator();
 582         }
 583 
 584         @Override
 585         boolean hasNextService() {
 586 
 587             // already have the next provider cached
 588             if (nextProvider != null)
 589                 return true;
 590 
 591             while (true) {
 592 
 593                 // next provider
 594                 if (providersIterator != null && providersIterator.hasNext()) {
 595                     nextProvider = providersIterator.next();
 596                     return true;
 597                 }
 598 
 599                 // next descriptor
 600                 if (descriptorIterator.hasNext()) {
 601                     ModuleDescriptor descriptor = descriptorIterator.next();
 602 
 603                     nextModule = currentLayer.findModule(descriptor.name()).getWhenPresent();
 604 
 605                     Provides provides = descriptor.provides().get(serviceName);
 606                     providersIterator = provides.providers().iterator();
 607 
 608                     continue;
 609                 }
 610 
 611                 // next layer
 612                 Layer parent = currentLayer.parent().orElse(null);
 613                 if (parent == null)
 614                     return false;
 615 
 616                 currentLayer = parent;
 617                 descriptorIterator = descriptors(currentLayer, serviceName);
 618             }
 619         }
 620 
 621         @Override
 622         S nextService() {
 623             if (!hasNextService())
 624                 throw new NoSuchElementException();
 625 
 626             assert nextModule != null && nextProvider != null;
 627 
 628             String cn = nextProvider;
 629             nextProvider = null;
 630 
 631             // attempt to load the provider
 632             Class<?> c = loadClassInModule(nextModule, cn);
 633             if (c == null)
 634                 fail(service, "Provider " + cn  + " not found");
 635             if (!service.isAssignableFrom(c))
 636                 fail(service, "Provider " + cn  + " not a subtype");
 637 
 638             // instantiate the provider
 639             S p = null;
 640             try {
 641                 Constructor<?> ctor = checkAndGetConstructor(c);
 642                 p = service.cast(ctor.newInstance());
 643             } catch (Throwable x) {
 644                 if (x instanceof InvocationTargetException)
 645                     x = x.getCause();
 646                 fail(service,
 647                         "Provider " + cn + " could not be instantiated", x);
 648             }
 649 
 650             // add to cached provider list
 651             providers.add(p);
 652 
 653             return p;
 654         }
 655     }
 656 
 657     /**
 658      * Implements lazy service provider lookup of service providers that
 659      * are provided by modules defined to a class loader.
 660      */
 661     private class ModuleServicesIterator
 662         extends RestrictedIterator<S>
 663     {
 664         final JavaLangAccess langAccess = SharedSecrets.getJavaLangAccess();
 665 
 666         ClassLoader currentLoader;
 667         Iterator<ServiceProvider> iterator;
 668         ServiceProvider nextProvider;
 669 
 670         ModuleServicesIterator() {
 671             this.currentLoader = loader;
 672             this.iterator = iteratorFor(loader);
 673         }
 674 
 675         /**
 676          * Returns an iterator to iterate over the implementations of {@code
 677          * service} in modules defined to the given class loader.
 678          */
 679         private Iterator<ServiceProvider> iteratorFor(ClassLoader loader) {
 680 
 681             // if the class loader is in a loader pool then return an Iterator
 682             // that iterates over all service providers in the pool that provide
 683             // an implementation of the service
 684             if (currentLoader instanceof Loader) {
 685                 LoaderPool pool = ((Loader) loader).pool();
 686                 if (pool != null) {
 687                     return pool.loaders()
 688                             .map(l -> langAccess.getServicesCatalog(l))
 689                             .filter(sc -> sc != null)
 690                             .map(sc -> sc.findServices(service.getName()))
 691                             .flatMap(Set::stream)
 692                             .iterator();
 693                 }
 694             }
 695 
 696             ServicesCatalog catalog;
 697             if (currentLoader == null) {
 698                 catalog = BootLoader.getServicesCatalog();
 699             } else {
 700                 catalog = langAccess.getServicesCatalog(currentLoader);
 701             }
 702             if (catalog == null) {
 703                 return Collections.emptyIterator();
 704             } else {
 705                 return catalog.findServices(service.getName()).iterator();
 706             }
 707         }
 708 
 709         @Override
 710         boolean hasNextService() {
 711             // already have the next provider cached
 712             if (nextProvider != null)
 713                 return true;
 714 
 715             while (true) {
 716                 if (iterator.hasNext()) {
 717                     nextProvider = iterator.next();
 718                     return true;
 719                 }
 720 
 721                 // move to the next class loader if possible
 722                 if (currentLoader == null) {
 723                     return false;
 724                 } else {
 725                     currentLoader = currentLoader.getParent();
 726                     iterator = iteratorFor(currentLoader);
 727                 }
 728             }
 729         }
 730 
 731         @Override
 732         S nextService() {
 733             if (!hasNextService())
 734                 throw new NoSuchElementException();
 735 
 736             ServiceProvider provider = nextProvider;
 737             nextProvider = null;
 738 
 739             // attempt to load the provider
 740             Module module = provider.module();
 741             String cn = provider.providerName();
 742 
 743             Class<?> c = loadClassInModule(module, cn);
 744             if (c == null) {
 745                 fail(service,
 746                     "Provider " + cn + " not found in " + module.getName());
 747             }
 748             if (!service.isAssignableFrom(c)) {
 749                 fail(service, "Provider " + cn  + " not a subtype");
 750             }
 751 
 752             // instantiate the provider
 753             S p = null;
 754             try {
 755                 Constructor<?> ctor = checkAndGetConstructor(c);
 756                 p = service.cast(ctor.newInstance());
 757             } catch (Throwable x) {
 758                 if (x instanceof InvocationTargetException)
 759                     x = x.getCause();
 760                 fail(service,
 761                     "Provider " + cn + " could not be instantiated", x);
 762             }
 763 
 764             // add to provider list
 765             providers.add(p);
 766 
 767             // record the class name of the service provider, this is
 768             // needed for cases where there a module has both a "uses"
 769             // and a services configuration file listing the same
 770             // provider
 771             providerNames.add(cn);
 772 
 773             return p;
 774         }
 775     }
 776 
 777     /**
 778      * Implements lazy service provider lookup where the service providers
 779      * are configured via service configuration files.
 780      */
 781     private class LazyClassPathIterator
 782         extends RestrictedIterator<S>
 783     {
 784         Enumeration<URL> configs;
 785         Iterator<String> pending;
 786         String nextName;
 787 
 788         @Override
 789         boolean hasNextService() {
 790             if (nextName != null) {
 791                 return true;
 792             }
 793             if (configs == null) {
 794                 try {
 795                     String fullName = PREFIX + service.getName();
 796                     if (loader == null)
 797                         configs = ClassLoader.getSystemResources(fullName);
 798                     else
 799                         configs = loader.getResources(fullName);
 800                 } catch (IOException x) {
 801                     fail(service, "Error locating configuration files", x);
 802                 }
 803             }
 804             while ((pending == null) || !pending.hasNext()) {
 805                 if (!configs.hasMoreElements()) {
 806                     return false;
 807                 }
 808                 pending = parse(service, configs.nextElement());
 809             }
 810             nextName = pending.next();
 811             return true;
 812         }
 813 
 814         @Override
 815         S nextService() {
 816             if (!hasNextService())
 817                 throw new NoSuchElementException();
 818             String cn = nextName;
 819             nextName = null;
 820             Class<?> c = null;
 821             try {
 822                 c = Class.forName(cn, false, loader);
 823             } catch (ClassNotFoundException x) {
 824                 fail(service,
 825                      "Provider " + cn + " not found");
 826             }
 827             if (!service.isAssignableFrom(c)) {
 828                 fail(service,
 829                      "Provider " + cn  + " not a subtype");
 830             }
 831             S p = null;
 832             try {
 833                 p = service.cast(c.newInstance());
 834             } catch (Throwable x) {
 835                 fail(service,
 836                      "Provider " + cn + " could not be instantiated",
 837                      x);
 838             }
 839             providers.add(p);
 840             providerNames.add(cn);
 841             return p;
 842         }
 843     }
 844 
 845     /**
 846      * Lazily loads the available providers of this loader's service.
 847      *
 848      * <p> The iterator returned by this method first yields all of the
 849      * elements of the provider cache, in instantiation order.  It then lazily
 850      * loads and instantiates any remaining providers, adding each one to the
 851      * cache in turn.
 852      *
 853      * <p> To achieve laziness the actual work of locating and instantiating
 854      * providers must be done by the iterator itself. Its {@link
 855      * java.util.Iterator#hasNext hasNext} and {@link java.util.Iterator#next
 856      * next} methods can therefore throw a {@link ServiceConfigurationError}
 857      * if a provider class cannot be loaded, doesn't have the appropriate
 858      * constructor, can't be assigned to the service type or if any other kind
 859      * of exception or error is thrown as the next provider is located and
 860      * instantiated. To write robust code it is only necessary to catch {@link
 861      * ServiceConfigurationError} when using a service iterator.
 862      *
 863      * <p> If such an error is thrown then subsequent invocations of the
 864      * iterator will make a best effort to locate and instantiate the next
 865      * available provider, but in general such recovery cannot be guaranteed.
 866      *
 867      * <blockquote style="font-size: smaller; line-height: 1.2"><span
 868      * style="padding-right: 1em; font-weight: bold">Design Note</span>
 869      * Throwing an error in these cases may seem extreme.  The rationale for
 870      * this behavior is that a malformed provider-configuration file, like a
 871      * malformed class file, indicates a serious problem with the way the Java
 872      * virtual machine is configured or is being used.  As such it is
 873      * preferable to throw an error rather than try to recover or, even worse,
 874      * fail silently.</blockquote>
 875      *
 876      * <p> If this loader's provider cache is cleared by invoking the {@link
 877      * #reload() reload} method then existing iterators for this service
 878      * loader should be discarded.
 879      * The {@link java.util.Iterator#hasNext() hasNext} and {@link
 880      * java.util.Iterator#next() next} methods of the iterator throw {@link
 881      * java.util.ConcurrentModificationException ConcurrentModificationException}
 882      * if used after the provider cache has been cleared.
 883      *
 884      * <p> The iterator returned by this method does not support removal.
 885      * Invoking its {@link java.util.Iterator#remove() remove} method will
 886      * cause an {@link UnsupportedOperationException} to be thrown.
 887      *
 888      * @implNote When adding providers to the cache, the {@link #iterator
 889      * Iterator} processes resources in the order that the {@link
 890      * java.lang.ClassLoader#getResources(java.lang.String)
 891      * ClassLoader.getResources(String)} method finds the service configuration
 892      * files.
 893      *
 894      * @return  An iterator that lazily loads providers for this loader's
 895      *          service
 896      */
 897     public Iterator<S> iterator() {
 898         return new Iterator<S>() {
 899 
 900             // record reload count
 901             final int expectedReloadCount = ServiceLoader.this.reloadCount;
 902 
 903             // index into the cached providers list
 904             int index;
 905 
 906             /**
 907              * Throws ConcurrentModificationException if the list of cached
 908              * providers has been cleared by reload.
 909              */
 910             private void checkReloadCount() {
 911                 if (ServiceLoader.this.reloadCount != expectedReloadCount)
 912                     throw new ConcurrentModificationException();
 913             }
 914 
 915             public boolean hasNext() {
 916                 checkReloadCount();
 917                 if (index < providers.size())
 918                     return true;
 919 
 920                 if (layerLookupIterator != null) {
 921                     return layerLookupIterator.hasNext();
 922                 } else {
 923                     return moduleServicesIterator.hasNext() ||
 924                             lazyClassPathIterator.hasNext();
 925                 }
 926             }
 927 
 928             public S next() {
 929                 checkReloadCount();
 930                 S next;
 931                 if (index < providers.size()) {
 932                     next = providers.get(index);
 933                 } else {
 934                     if (layerLookupIterator != null) {
 935                         next = layerLookupIterator.next();
 936                     } else {
 937                         if (moduleServicesIterator.hasNext()) {
 938                             next = moduleServicesIterator.next();
 939                         } else {
 940                             next = lazyClassPathIterator.next();
 941                         }
 942                     }
 943                 }
 944                 index++;
 945                 return next;
 946             }
 947 
 948         };
 949     }
 950 
 951     /**
 952      * Creates a new service loader for the given service type, class
 953      * loader, and caller.
 954      *
 955      * @param  <S> the class of the service type
 956      *
 957      * @param  service
 958      *         The interface or abstract class representing the service
 959      *
 960      * @param  loader
 961      *         The class loader to be used to load provider-configuration files
 962      *         and provider classes, or <tt>null</tt> if the system class
 963      *         loader (or, failing that, the bootstrap class loader) is to be
 964      *         used
 965      *
 966      * @param  callerModule
 967      *         The caller's module for which a new service loader is created
 968      *
 969      * @return A new service loader
 970      */
 971     static <S> ServiceLoader<S> load(Class<S> service,
 972                                      ClassLoader loader,
 973                                      Module callerModule)
 974     {
 975         return new ServiceLoader<>(callerModule, service, loader);
 976     }
 977 
 978     /**
 979      * Creates a new service loader for the given service type and class
 980      * loader.
 981      *
 982      * @param  <S> the class of the service type
 983      *
 984      * @param  service
 985      *         The interface or abstract class representing the service
 986      *
 987      * @param  loader
 988      *         The class loader to be used to load provider-configuration files
 989      *         and provider classes, or {@code null} if the system class
 990      *         loader (or, failing that, the bootstrap class loader) is to be
 991      *         used
 992      *
 993      * @return A new service loader
 994      *
 995      * @throws ServiceConfigurationError
 996      *         if the service type is not accessible to the caller or the
 997      *         caller is in a named module and its module descriptor does
 998      *         not declare that it uses {@code service}
 999      */
1000     @CallerSensitive
1001     public static <S> ServiceLoader<S> load(Class<S> service,
1002                                             ClassLoader loader)
1003     {
1004         return new ServiceLoader<>(Reflection.getCallerClass(), service, loader);
1005     }
1006 
1007     /**
1008      * Creates a new service loader for the given service type, using the
1009      * current thread's {@linkplain java.lang.Thread#getContextClassLoader
1010      * context class loader}.
1011      *
1012      * <p> An invocation of this convenience method of the form
1013      *
1014      * <blockquote><pre>
1015      * ServiceLoader.load(<i>service</i>)</pre></blockquote>
1016      *
1017      * is equivalent to
1018      *
1019      * <blockquote><pre>
1020      * ServiceLoader.load(<i>service</i>,
1021      *                    Thread.currentThread().getContextClassLoader())</pre></blockquote>
1022      *
1023      * @param  <S> the class of the service type
1024      *
1025      * @param  service
1026      *         The interface or abstract class representing the service
1027      *
1028      * @return A new service loader
1029      *
1030      * @throws ServiceConfigurationError
1031      *         if the service type is not accessible to the caller or the
1032      *         caller is in a named module and its module descriptor does
1033      *         not declare that it uses {@code service}
1034      */
1035     @CallerSensitive
1036     public static <S> ServiceLoader<S> load(Class<S> service) {
1037         ClassLoader cl = Thread.currentThread().getContextClassLoader();
1038         return new ServiceLoader<>(Reflection.getCallerClass(), service, cl);
1039     }
1040 
1041     /**
1042      * Creates a new service loader for the given service type, using the
1043      * {@linkplain ClassLoader#getPlatformClassLoader() platform class loader}.
1044      *
1045      * <p> This convenience method is equivalent to: </p>
1046      *
1047      * <blockquote><pre>
1048      * ServiceLoader.load(<i>service</i>, <i>ClassLoader.getPlatformClassLoader())</i>
1049      * </pre></blockquote>
1050      *
1051      * <p> This method is intended for use when only installed providers are
1052      * desired.  The resulting service will only find and load providers that
1053      * have been installed into the current Java virtual machine; providers on
1054      * the application's module path or class path will be ignored.
1055      *
1056      * @param  <S> the class of the service type
1057      *
1058      * @param  service
1059      *         The interface or abstract class representing the service
1060      *
1061      * @return A new service loader
1062      *
1063      * @throws ServiceConfigurationError
1064      *         if the service type is not accessible to the caller or the
1065      *         caller is in a named module and its module descriptor does
1066      *         not declare that it uses {@code service}
1067      */
1068     @CallerSensitive
1069     public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
1070         ClassLoader cl = ClassLoader.getSystemClassLoader();
1071         ClassLoader prev = null;
1072         while (cl != null) {
1073             prev = cl;
1074             cl = cl.getParent();
1075         }
1076         return new ServiceLoader<>(Reflection.getCallerClass(), service, prev);
1077     }
1078 
1079     /**
1080      * Creates a new service loader for the given service type that loads
1081      * service providers from modules in the given {@code Layer} and its
1082      * ancestors.
1083      *
1084      * @apiNote Unlike the other load methods defined here, the service type
1085      * is the second parameter. The reason for this is to avoid source
1086      * compatibility issues for code that uses {@code load(S, null)}.
1087      *
1088      * @param  <S> the class of the service type
1089      *
1090      * @param  layer
1091      *         The module Layer
1092      *
1093      * @param  service
1094      *         The interface or abstract class representing the service
1095      *
1096      * @return A new service loader
1097      *
1098      * @throws ServiceConfigurationError
1099      *         if the service type is not accessible to the caller or the
1100      *         caller is in a named module and its module descriptor does
1101      *         not declare that it uses {@code service}
1102      *
1103      * @since 9
1104      */
1105     @CallerSensitive
1106     public static <S> ServiceLoader<S> load(Layer layer, Class<S> service) {
1107         return new ServiceLoader<>(Reflection.getCallerClass(),
1108                                    Objects.requireNonNull(layer),
1109                                    Objects.requireNonNull(service));
1110     }
1111 
1112     /**
1113      * Returns a string describing this service.
1114      *
1115      * @return  A descriptive string
1116      */
1117     public String toString() {
1118         return "java.util.ServiceLoader[" + service.getName() + "]";
1119     }
1120 
1121 }