1 /*
   2  * Copyright (c) 1995, 2021, 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.lang;
  27 
  28 import java.lang.module.ModuleDescriptor;
  29 import java.lang.module.ModuleDescriptor.Exports;
  30 import java.lang.module.ModuleDescriptor.Opens;
  31 import java.lang.reflect.Member;
  32 import java.io.FileDescriptor;
  33 import java.io.File;
  34 import java.io.FilePermission;
  35 import java.net.InetAddress;
  36 import java.net.SocketPermission;
  37 import java.security.AccessControlContext;
  38 import java.security.AccessController;
  39 import java.security.Permission;
  40 import java.security.PrivilegedAction;
  41 import java.security.Security;
  42 import java.security.SecurityPermission;
  43 import java.util.HashSet;
  44 import java.util.Map;
  45 import java.util.Objects;
  46 import java.util.PropertyPermission;
  47 import java.util.Set;
  48 import java.util.concurrent.ConcurrentHashMap;
  49 
  50 import jdk.internal.module.ModuleLoaderMap;
  51 import jdk.internal.reflect.CallerSensitive;
  52 import sun.security.util.SecurityConstants;
  53 
  54 /**
  55  * The security manager is a class that allows
  56  * applications to implement a security policy. It allows an
  57  * application to determine, before performing a possibly unsafe or
  58  * sensitive operation, what the operation is and whether
  59  * it is being attempted in a security context that allows the
  60  * operation to be performed. The
  61  * application can allow or disallow the operation.
  62  * <p>
  63  * The {@code SecurityManager} class contains many methods with
  64  * names that begin with the word {@code check}. These methods
  65  * are called by various methods in the Java libraries before those
  66  * methods perform certain potentially sensitive operations. The
  67  * invocation of such a {@code check} method typically looks like this:
  68  * <blockquote><pre>
  69  *     SecurityManager security = System.getSecurityManager();
  70  *     if (security != null) {
  71  *         security.check<i>XXX</i>(argument, &nbsp;.&nbsp;.&nbsp;.&nbsp;);
  72  *     }
  73  * </pre></blockquote>
  74  * <p>
  75  * The security manager is thereby given an opportunity to prevent
  76  * completion of the operation by throwing an exception. A security
  77  * manager routine simply returns if the operation is permitted, but
  78  * throws a {@code SecurityException} if the operation is not
  79  * permitted.
  80  * <p>
  81  * Environments using a security manager will typically set the security
  82  * manager at startup. In the JDK implementation, this is done by setting the
  83  * system property {@systemProperty java.security.manager} on the command line
  84  * to the class name of the security manager. It can also be set to the empty
  85  * String ("") or the special token "{@code default}" to use the
  86  * default {@code java.lang.SecurityManager}. If a class name is specified,
  87  * it must be {@code java.lang.SecurityManager} or a public subclass and have
  88  * a public no-arg constructor. The class is loaded by the
  89  * {@linkplain ClassLoader#getSystemClassLoader() built-in system class loader}
  90  * if it is not {@code java.lang.SecurityManager}. If the
  91  * {@code java.security.manager} system property is not set, the default value
  92  * is {@code null}, which means a security manager will not be set at startup.
  93  * <p>
  94  * The Java run-time may also allow, but is not required to allow, the security
  95  * manager to be set dynamically by invoking the
  96  * {@link System#setSecurityManager(SecurityManager) setSecurityManager} method.
  97  * In the JDK implementation, if the Java virtual machine is started with
  98  * the {@code java.security.manager} system property set to the special token
  99  * "{@code disallow}" then a security manager will not be set at startup and
 100  * cannot be set dynamically (the
 101  * {@link System#setSecurityManager(SecurityManager) setSecurityManager}
 102  * method will throw an {@code UnsupportedOperationException}). If the
 103  * {@code java.security.manager} system property is not set or is set to the
 104  * special token "{@code allow}", then a security manager will not be set at
 105  * startup but can be set dynamically. Finally, if the
 106  * {@code java.security.manager} system property is set to the class name of
 107  * the security manager, or to the empty String ("") or the special token
 108  * "{@code default}", then a security manager is set at startup (as described
 109  * previously) and can also be subsequently replaced (or disabled) dynamically
 110  * (subject to the policy of the currently installed security manager). The
 111  * following table illustrates the behavior of the JDK implementation for the
 112  * different settings of the {@code java.security.manager} system property:
 113  * <table class="striped">
 114  * <caption style="display:none">property value,
 115  *  the SecurityManager set at startup,
 116  *  can dynamically set a SecurityManager
 117  * </caption>
 118  * <thead>
 119  * <tr>
 120  * <th scope="col">Property Value</th>
 121  * <th scope="col">The SecurityManager set at startup</th>
 122  * <th scope="col">System.setSecurityManager run-time behavior</th>
 123  * </tr>
 124  * </thead>
 125  * <tbody>
 126  *
 127  * <tr>
 128  *   <th scope="row">null</th>
 129  *   <td>None</td>
 130  *   <td>Success or throws {@code SecurityException} if not permitted by
 131  * the currently installed security manager</td>
 132  * </tr>
 133  *
 134  * <tr>
 135  *   <th scope="row">empty String ("")</th>
 136  *   <td>{@code java.lang.SecurityManager}</td>
 137  *   <td>Success or throws {@code SecurityException} if not permitted by
 138  * the currently installed security manager</td>
 139  * </tr>
 140  *
 141  * <tr>
 142  *   <th scope="row">"default"</th>
 143  *   <td>{@code java.lang.SecurityManager}</td>
 144  *   <td>Success or throws {@code SecurityException} if not permitted by
 145  * the currently installed security manager</td>
 146  * </tr>
 147  *
 148  * <tr>
 149  *   <th scope="row">"disallow"</th>
 150  *   <td>None</td>
 151  *   <td>Always throws {@code UnsupportedOperationException}</td>
 152  * </tr>
 153  *
 154  * <tr>
 155  *   <th scope="row">"allow"</th>
 156  *   <td>None</td>
 157  *   <td>Success or throws {@code SecurityException} if not permitted by
 158  * the currently installed security manager</td>
 159  * </tr>
 160  *
 161  * <tr>
 162  *   <th scope="row">a class name</th>
 163  *   <td>the named class</td>
 164  *   <td>Success or throws {@code SecurityException} if not permitted by
 165  * the currently installed security manager</td>
 166  * </tr>
 167  *
 168  * </tbody>
 169  * </table>
 170  * <p> A future release of the JDK may change the default value of the
 171  * {@code java.security.manager} system property to "{@code disallow}".
 172  * <p>
 173  * The current security manager is returned by the
 174  * {@link System#getSecurityManager() getSecurityManager} method.
 175  * <p>
 176  * The special method
 177  * {@link SecurityManager#checkPermission(java.security.Permission)}
 178  * determines whether an access request indicated by a specified
 179  * permission should be granted or denied. The
 180  * default implementation calls
 181  *
 182  * <pre>
 183  *   AccessController.checkPermission(perm);
 184  * </pre>
 185  *
 186  * <p>
 187  * If a requested access is allowed,
 188  * {@code checkPermission} returns quietly. If denied, a
 189  * {@code SecurityException} is thrown.
 190  * <p>
 191  * The default implementation of each of the other
 192  * {@code check} methods in {@code SecurityManager} is to
 193  * call the {@code SecurityManager checkPermission} method
 194  * to determine if the calling thread has permission to perform the requested
 195  * operation.
 196  * <p>
 197  * Note that the {@code checkPermission} method with
 198  * just a single permission argument always performs security checks
 199  * within the context of the currently executing thread.
 200  * Sometimes a security check that should be made within a given context
 201  * will actually need to be done from within a
 202  * <i>different</i> context (for example, from within a worker thread).
 203  * The {@link SecurityManager#getSecurityContext getSecurityContext} method
 204  * and the {@link SecurityManager#checkPermission(java.security.Permission,
 205  * java.lang.Object) checkPermission}
 206  * method that includes a context argument are provided
 207  * for this situation. The
 208  * {@code getSecurityContext} method returns a "snapshot"
 209  * of the current calling context. (The default implementation
 210  * returns an AccessControlContext object.) A sample call is
 211  * the following:
 212  *
 213  * <pre>
 214  *   Object context = null;
 215  *   SecurityManager sm = System.getSecurityManager();
 216  *   if (sm != null) context = sm.getSecurityContext();
 217  * </pre>
 218  *
 219  * <p>
 220  * The {@code checkPermission} method
 221  * that takes a context object in addition to a permission
 222  * makes access decisions based on that context,
 223  * rather than on that of the current execution thread.
 224  * Code within a different context can thus call that method,
 225  * passing the permission and the
 226  * previously-saved context object. A sample call, using the
 227  * SecurityManager {@code sm} obtained as in the previous example,
 228  * is the following:
 229  *
 230  * <pre>
 231  *   if (sm != null) sm.checkPermission(permission, context);
 232  * </pre>
 233  *
 234  * <p>Permissions fall into these categories: File, Socket, Net,
 235  * Security, Runtime, Property, AWT, Reflect, and Serializable.
 236  * The classes managing these various
 237  * permission categories are {@code java.io.FilePermission},
 238  * {@code java.net.SocketPermission},
 239  * {@code java.net.NetPermission},
 240  * {@code java.security.SecurityPermission},
 241  * {@code java.lang.RuntimePermission},
 242  * {@code java.util.PropertyPermission},
 243  * {@code java.awt.AWTPermission},
 244  * {@code java.lang.reflect.ReflectPermission}, and
 245  * {@code java.io.SerializablePermission}.
 246  *
 247  * <p>All but the first two (FilePermission and SocketPermission) are
 248  * subclasses of {@code java.security.BasicPermission}, which itself
 249  * is an abstract subclass of the
 250  * top-level class for permissions, which is
 251  * {@code java.security.Permission}. BasicPermission defines the
 252  * functionality needed for all permissions that contain a name
 253  * that follows the hierarchical property naming convention
 254  * (for example, "exitVM", "setFactory", "queuePrintJob", etc).
 255  * An asterisk
 256  * may appear at the end of the name, following a ".", or by itself, to
 257  * signify a wildcard match. For example: "a.*" or "*" is valid,
 258  * "*a" or "a*b" is not valid.
 259  *
 260  * <p>FilePermission and SocketPermission are subclasses of the
 261  * top-level class for permissions
 262  * ({@code java.security.Permission}). Classes like these
 263  * that have a more complicated name syntax than that used by
 264  * BasicPermission subclass directly from Permission rather than from
 265  * BasicPermission. For example,
 266  * for a {@code java.io.FilePermission} object, the permission name is
 267  * the path name of a file (or directory).
 268  *
 269  * <p>Some of the permission classes have an "actions" list that tells
 270  * the actions that are permitted for the object.  For example,
 271  * for a {@code java.io.FilePermission} object, the actions list
 272  * (such as "read, write") specifies which actions are granted for the
 273  * specified file (or for files in the specified directory).
 274  *
 275  * <p>Other permission classes are for "named" permissions -
 276  * ones that contain a name but no actions list; you either have the
 277  * named permission or you don't.
 278  *
 279  * <p>Note: There is also a {@code java.security.AllPermission}
 280  * permission that implies all permissions. It exists to simplify the work
 281  * of system administrators who might need to perform multiple
 282  * tasks that require all (or numerous) permissions.
 283  * <p>
 284  * See {@extLink security_guide_permissions
 285  * Permissions in the Java Development Kit (JDK)}
 286  * for permission-related information.
 287  * This document includes a table listing the various SecurityManager
 288  * {@code check} methods and the permission(s) the default
 289  * implementation of each such method requires.
 290  * It also contains a table of the methods
 291  * that require permissions, and for each such method tells
 292  * which permission it requires.
 293  *
 294  * @author  Arthur van Hoff
 295  * @author  Roland Schemers
 296  *
 297  * @see     java.lang.ClassLoader
 298  * @see     java.lang.SecurityException
 299  * @see     java.lang.System#getSecurityManager() getSecurityManager
 300  * @see     java.lang.System#setSecurityManager(java.lang.SecurityManager)
 301  *  setSecurityManager
 302  * @see     java.security.AccessController AccessController
 303  * @see     java.security.AccessControlContext AccessControlContext
 304  * @see     java.security.AccessControlException AccessControlException
 305  * @see     java.security.Permission
 306  * @see     java.security.BasicPermission
 307  * @see     java.io.FilePermission
 308  * @see     java.net.SocketPermission
 309  * @see     java.util.PropertyPermission
 310  * @see     java.lang.RuntimePermission
 311  * @see     java.security.Policy Policy
 312  * @see     java.security.SecurityPermission SecurityPermission
 313  * @see     java.security.ProtectionDomain
 314  *
 315  * @since   1.0
 316  * @deprecated The Security Manager is deprecated and subject to removal in a
 317  *       future release. There is no replacement for the Security Manager.
 318  *       See <a href="https://openjdk.java.net/jeps/411">JEP 411</a> for
 319  *       discussion and alternatives.
 320  */
 321 @Deprecated(since="17", forRemoval=true)
 322 public class SecurityManager {
 323 
 324     /*
 325      * Have we been initialized. Effective against finalizer attacks.
 326      */
 327     private boolean initialized = false;
 328 
 329     /**
 330      * Constructs a new {@code SecurityManager}.
 331      *
 332      * <p> If there is a security manager already installed, this method first
 333      * calls the security manager's {@code checkPermission} method
 334      * with the {@code RuntimePermission("createSecurityManager")}
 335      * permission to ensure the calling thread has permission to create a new
 336      * security manager.
 337      * This may result in throwing a {@code SecurityException}.
 338      *
 339      * @throws     java.lang.SecurityException if a security manager already
 340      *             exists and its {@code checkPermission} method
 341      *             doesn't allow creation of a new security manager.
 342      * @see        java.lang.System#getSecurityManager()
 343      * @see        #checkPermission(java.security.Permission) checkPermission
 344      * @see java.lang.RuntimePermission
 345      */
 346     public SecurityManager() {
 347         synchronized(SecurityManager.class) {
 348             @SuppressWarnings("removal")
 349             SecurityManager sm = System.getSecurityManager();
 350             if (sm != null) {
 351                 // ask the currently installed security manager if we
 352                 // can create a new one.
 353                 sm.checkPermission(new RuntimePermission
 354                                    ("createSecurityManager"));
 355             }
 356             initialized = true;
 357         }
 358     }
 359 
 360     /**
 361      * Returns the current execution stack as an array of classes.
 362      * <p>
 363      * The length of the array is the number of methods on the execution
 364      * stack. The element at index {@code 0} is the class of the
 365      * currently executing method, the element at index {@code 1} is
 366      * the class of that method's caller, and so on.
 367      *
 368      * @return  the execution stack.
 369      */
 370     protected native Class<?>[] getClassContext();
 371 
 372     /**
 373      * Creates an object that encapsulates the current execution
 374      * environment. The result of this method is used, for example, by the
 375      * three-argument {@code checkConnect} method and by the
 376      * two-argument {@code checkRead} method.
 377      * These methods are needed because a trusted method may be called
 378      * on to read a file or open a socket on behalf of another method.
 379      * The trusted method needs to determine if the other (possibly
 380      * untrusted) method would be allowed to perform the operation on its
 381      * own.
 382      * <p> The default implementation of this method is to return
 383      * an {@code AccessControlContext} object.
 384      *
 385      * @return  an implementation-dependent object that encapsulates
 386      *          sufficient information about the current execution environment
 387      *          to perform some security checks later.
 388      * @see     java.lang.SecurityManager#checkConnect(java.lang.String, int,
 389      *   java.lang.Object) checkConnect
 390      * @see     java.lang.SecurityManager#checkRead(java.lang.String,
 391      *   java.lang.Object) checkRead
 392      * @see     java.security.AccessControlContext AccessControlContext
 393      */
 394     @SuppressWarnings("removal")
 395     public Object getSecurityContext() {
 396         return AccessController.getContext();
 397     }
 398 
 399     /**
 400      * Throws a {@code SecurityException} if the requested
 401      * access, specified by the given permission, is not permitted based
 402      * on the security policy currently in effect.
 403      * <p>
 404      * This method calls {@code AccessController.checkPermission}
 405      * with the given permission.
 406      *
 407      * @param     perm   the requested permission.
 408      * @throws    SecurityException if access is not permitted based on
 409      *            the current security policy.
 410      * @throws    NullPointerException if the permission argument is
 411      *            {@code null}.
 412      * @since     1.2
 413      */
 414     @SuppressWarnings("removal")
 415     public void checkPermission(Permission perm) {
 416         java.security.AccessController.checkPermission(perm);
 417     }
 418 
 419     /**
 420      * Throws a {@code SecurityException} if the
 421      * specified security context is denied access to the resource
 422      * specified by the given permission.
 423      * The context must be a security
 424      * context returned by a previous call to
 425      * {@code getSecurityContext} and the access control
 426      * decision is based upon the configured security policy for
 427      * that security context.
 428      * <p>
 429      * If {@code context} is an instance of
 430      * {@code AccessControlContext} then the
 431      * {@code AccessControlContext.checkPermission} method is
 432      * invoked with the specified permission.
 433      * <p>
 434      * If {@code context} is not an instance of
 435      * {@code AccessControlContext} then a
 436      * {@code SecurityException} is thrown.
 437      *
 438      * @param      perm      the specified permission
 439      * @param      context   a system-dependent security context.
 440      * @throws     SecurityException  if the specified security context
 441      *             is not an instance of {@code AccessControlContext}
 442      *             (e.g., is {@code null}), or is denied access to the
 443      *             resource specified by the given permission.
 444      * @throws     NullPointerException if the permission argument is
 445      *             {@code null}.
 446      * @see        java.lang.SecurityManager#getSecurityContext()
 447      * @see java.security.AccessControlContext#checkPermission(java.security.Permission)
 448      * @since      1.2
 449      */
 450     @SuppressWarnings("removal")
 451     public void checkPermission(Permission perm, Object context) {
 452         if (context instanceof AccessControlContext) {
 453             ((AccessControlContext)context).checkPermission(perm);
 454         } else {
 455             throw new SecurityException();
 456         }
 457     }
 458 
 459     /**
 460      * Throws a {@code SecurityException} if the
 461      * calling thread is not allowed to create a new class loader.
 462      * <p>
 463      * This method calls {@code checkPermission} with the
 464      * {@code RuntimePermission("createClassLoader")}
 465      * permission.
 466      * <p>
 467      * If you override this method, then you should make a call to
 468      * {@code super.checkCreateClassLoader}
 469      * at the point the overridden method would normally throw an
 470      * exception.
 471      *
 472      * @throws    SecurityException if the calling thread does not
 473      *             have permission
 474      *             to create a new class loader.
 475      * @see        java.lang.ClassLoader#ClassLoader()
 476      * @see        #checkPermission(java.security.Permission) checkPermission
 477      */
 478     public void checkCreateClassLoader() {
 479         checkPermission(SecurityConstants.CREATE_CLASSLOADER_PERMISSION);
 480     }
 481 
 482     /**
 483      * reference to the root thread group, used for the checkAccess
 484      * methods.
 485      */
 486 
 487     private static ThreadGroup rootGroup = getRootGroup();
 488 
 489     private static ThreadGroup getRootGroup() {
 490         ThreadGroup root =  Thread.currentThread().getThreadGroup();
 491         while (root.getParent() != null) {
 492             root = root.getParent();
 493         }
 494         return root;
 495     }
 496 
 497     /**
 498      * Throws a {@code SecurityException} if the
 499      * calling thread is not allowed to modify the thread argument.
 500      * <p>
 501      * This method is invoked for the current security manager by the
 502      * {@code stop}, {@code suspend}, {@code resume},
 503      * {@code setPriority}, {@code setName}, and
 504      * {@code setDaemon} methods of class {@code Thread}.
 505      * <p>
 506      * If the thread argument is a system thread (belongs to
 507      * the thread group with a {@code null} parent) then
 508      * this method calls {@code checkPermission} with the
 509      * {@code RuntimePermission("modifyThread")} permission.
 510      * If the thread argument is <i>not</i> a system thread,
 511      * this method just returns silently.
 512      * <p>
 513      * Applications that want a stricter policy should override this
 514      * method. If this method is overridden, the method that overrides
 515      * it should additionally check to see if the calling thread has the
 516      * {@code RuntimePermission("modifyThread")} permission, and
 517      * if so, return silently. This is to ensure that code granted
 518      * that permission (such as the JDK itself) is allowed to
 519      * manipulate any thread.
 520      * <p>
 521      * If this method is overridden, then
 522      * {@code super.checkAccess} should
 523      * be called by the first statement in the overridden method, or the
 524      * equivalent security check should be placed in the overridden method.
 525      *
 526      * @param      t   the thread to be checked.
 527      * @throws     SecurityException  if the calling thread does not have
 528      *             permission to modify the thread.
 529      * @throws     NullPointerException if the thread argument is
 530      *             {@code null}.
 531      * @see        java.lang.Thread#resume() resume
 532      * @see        java.lang.Thread#setDaemon(boolean) setDaemon
 533      * @see        java.lang.Thread#setName(java.lang.String) setName
 534      * @see        java.lang.Thread#setPriority(int) setPriority
 535      * @see        java.lang.Thread#stop() stop
 536      * @see        java.lang.Thread#suspend() suspend
 537      * @see        #checkPermission(java.security.Permission) checkPermission
 538      */
 539     public void checkAccess(Thread t) {
 540         if (t == null) {
 541             throw new NullPointerException("thread can't be null");
 542         }
 543         if (t.getThreadGroup() == rootGroup) {
 544             checkPermission(SecurityConstants.MODIFY_THREAD_PERMISSION);
 545         } else {
 546             // just return
 547         }
 548     }
 549     /**
 550      * Throws a {@code SecurityException} if the
 551      * calling thread is not allowed to modify the thread group argument.
 552      * <p>
 553      * This method is invoked for the current security manager when a
 554      * new child thread or child thread group is created, and by the
 555      * {@code setDaemon}, {@code setMaxPriority},
 556      * {@code stop}, {@code suspend}, {@code resume}, and
 557      * {@code destroy} methods of class {@code ThreadGroup}.
 558      * <p>
 559      * If the thread group argument is the system thread group (
 560      * has a {@code null} parent) then
 561      * this method calls {@code checkPermission} with the
 562      * {@code RuntimePermission("modifyThreadGroup")} permission.
 563      * If the thread group argument is <i>not</i> the system thread group,
 564      * this method just returns silently.
 565      * <p>
 566      * Applications that want a stricter policy should override this
 567      * method. If this method is overridden, the method that overrides
 568      * it should additionally check to see if the calling thread has the
 569      * {@code RuntimePermission("modifyThreadGroup")} permission, and
 570      * if so, return silently. This is to ensure that code granted
 571      * that permission (such as the JDK itself) is allowed to
 572      * manipulate any thread.
 573      * <p>
 574      * If this method is overridden, then
 575      * {@code super.checkAccess} should
 576      * be called by the first statement in the overridden method, or the
 577      * equivalent security check should be placed in the overridden method.
 578      *
 579      * @param      g   the thread group to be checked.
 580      * @throws     SecurityException  if the calling thread does not have
 581      *             permission to modify the thread group.
 582      * @throws     NullPointerException if the thread group argument is
 583      *             {@code null}.
 584      * @see        java.lang.ThreadGroup#destroy() destroy
 585      * @see        java.lang.ThreadGroup#resume() resume
 586      * @see        java.lang.ThreadGroup#setDaemon(boolean) setDaemon
 587      * @see        java.lang.ThreadGroup#setMaxPriority(int) setMaxPriority
 588      * @see        java.lang.ThreadGroup#stop() stop
 589      * @see        java.lang.ThreadGroup#suspend() suspend
 590      * @see        #checkPermission(java.security.Permission) checkPermission
 591      */
 592     public void checkAccess(ThreadGroup g) {
 593         if (g == null) {
 594             throw new NullPointerException("thread group can't be null");
 595         }
 596         if (g == rootGroup) {
 597             checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION);
 598         } else {
 599             // just return
 600         }
 601     }
 602 
 603     /**
 604      * Throws a {@code SecurityException} if the
 605      * calling thread is not allowed to cause the Java Virtual Machine to
 606      * halt with the specified status code.
 607      * <p>
 608      * This method is invoked for the current security manager by the
 609      * {@code exit} method of class {@code Runtime}. A status
 610      * of {@code 0} indicates success; other values indicate various
 611      * errors.
 612      * <p>
 613      * This method calls {@code checkPermission} with the
 614      * {@code RuntimePermission("exitVM."+status)} permission.
 615      * <p>
 616      * If you override this method, then you should make a call to
 617      * {@code super.checkExit}
 618      * at the point the overridden method would normally throw an
 619      * exception.
 620      *
 621      * @param      status   the exit status.
 622      * @throws    SecurityException if the calling thread does not have
 623      *              permission to halt the Java Virtual Machine with
 624      *              the specified status.
 625      * @see        java.lang.Runtime#exit(int) exit
 626      * @see        #checkPermission(java.security.Permission) checkPermission
 627      */
 628     public void checkExit(int status) {
 629         checkPermission(new RuntimePermission("exitVM."+status));
 630     }
 631 
 632     /**
 633      * Throws a {@code SecurityException} if the
 634      * calling thread is not allowed to create a subprocess.
 635      * <p>
 636      * This method is invoked for the current security manager by the
 637      * {@code exec} methods of class {@code Runtime}.
 638      * <p>
 639      * This method calls {@code checkPermission} with the
 640      * {@code FilePermission(cmd,"execute")} permission
 641      * if cmd is an absolute path, otherwise it calls
 642      * {@code checkPermission} with
 643      * <code>FilePermission("&lt;&lt;ALL FILES&gt;&gt;","execute")</code>.
 644      * <p>
 645      * If you override this method, then you should make a call to
 646      * {@code super.checkExec}
 647      * at the point the overridden method would normally throw an
 648      * exception.
 649      *
 650      * @param      cmd   the specified system command.
 651      * @throws     SecurityException if the calling thread does not have
 652      *             permission to create a subprocess.
 653      * @throws     NullPointerException if the {@code cmd} argument is
 654      *             {@code null}.
 655      * @see     java.lang.Runtime#exec(java.lang.String)
 656      * @see     java.lang.Runtime#exec(java.lang.String, java.lang.String[])
 657      * @see     java.lang.Runtime#exec(java.lang.String[])
 658      * @see     java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
 659      * @see     #checkPermission(java.security.Permission) checkPermission
 660      */
 661     public void checkExec(String cmd) {
 662         File f = new File(cmd);
 663         if (f.isAbsolute()) {
 664             checkPermission(new FilePermission(cmd,
 665                 SecurityConstants.FILE_EXECUTE_ACTION));
 666         } else {
 667             checkPermission(new FilePermission("<<ALL FILES>>",
 668                 SecurityConstants.FILE_EXECUTE_ACTION));
 669         }
 670     }
 671 
 672     /**
 673      * Throws a {@code SecurityException} if the
 674      * calling thread is not allowed to dynamic link the library code
 675      * specified by the string argument file. The argument is either a
 676      * simple library name or a complete filename.
 677      * <p>
 678      * This method is invoked for the current security manager by
 679      * methods {@code load} and {@code loadLibrary} of class
 680      * {@code Runtime}.
 681      * <p>
 682      * This method calls {@code checkPermission} with the
 683      * {@code RuntimePermission("loadLibrary."+lib)} permission.
 684      * <p>
 685      * If you override this method, then you should make a call to
 686      * {@code super.checkLink}
 687      * at the point the overridden method would normally throw an
 688      * exception.
 689      *
 690      * @param      lib   the name of the library.
 691      * @throws     SecurityException if the calling thread does not have
 692      *             permission to dynamically link the library.
 693      * @throws     NullPointerException if the {@code lib} argument is
 694      *             {@code null}.
 695      * @see        java.lang.Runtime#load(java.lang.String)
 696      * @see        java.lang.Runtime#loadLibrary(java.lang.String)
 697      * @see        #checkPermission(java.security.Permission) checkPermission
 698      */
 699     public void checkLink(String lib) {
 700         if (lib == null) {
 701             throw new NullPointerException("library can't be null");
 702         }
 703         checkPermission(new RuntimePermission("loadLibrary."+lib));
 704     }
 705 
 706     /**
 707      * Throws a {@code SecurityException} if the
 708      * calling thread is not allowed to read from the specified file
 709      * descriptor.
 710      * <p>
 711      * This method calls {@code checkPermission} with the
 712      * {@code RuntimePermission("readFileDescriptor")}
 713      * permission.
 714      * <p>
 715      * If you override this method, then you should make a call to
 716      * {@code super.checkRead}
 717      * at the point the overridden method would normally throw an
 718      * exception.
 719      *
 720      * @param      fd   the system-dependent file descriptor.
 721      * @throws     SecurityException  if the calling thread does not have
 722      *             permission to access the specified file descriptor.
 723      * @throws     NullPointerException if the file descriptor argument is
 724      *             {@code null}.
 725      * @see        java.io.FileDescriptor
 726      * @see        #checkPermission(java.security.Permission) checkPermission
 727      */
 728     public void checkRead(FileDescriptor fd) {
 729         if (fd == null) {
 730             throw new NullPointerException("file descriptor can't be null");
 731         }
 732         checkPermission(new RuntimePermission("readFileDescriptor"));
 733     }
 734 
 735     /**
 736      * Throws a {@code SecurityException} if the
 737      * calling thread is not allowed to read the file specified by the
 738      * string argument.
 739      * <p>
 740      * This method calls {@code checkPermission} with the
 741      * {@code FilePermission(file,"read")} permission.
 742      * <p>
 743      * If you override this method, then you should make a call to
 744      * {@code super.checkRead}
 745      * at the point the overridden method would normally throw an
 746      * exception.
 747      *
 748      * @param      file   the system-dependent file name.
 749      * @throws     SecurityException if the calling thread does not have
 750      *             permission to access the specified file.
 751      * @throws     NullPointerException if the {@code file} argument is
 752      *             {@code null}.
 753      * @see        #checkPermission(java.security.Permission) checkPermission
 754      */
 755     public void checkRead(String file) {
 756         checkPermission(new FilePermission(file,
 757             SecurityConstants.FILE_READ_ACTION));
 758     }
 759 
 760     /**
 761      * Throws a {@code SecurityException} if the
 762      * specified security context is not allowed to read the file
 763      * specified by the string argument. The context must be a security
 764      * context returned by a previous call to
 765      * {@code getSecurityContext}.
 766      * <p> If {@code context} is an instance of
 767      * {@code AccessControlContext} then the
 768      * {@code AccessControlContext.checkPermission} method will
 769      * be invoked with the {@code FilePermission(file,"read")} permission.
 770      * <p> If {@code context} is not an instance of
 771      * {@code AccessControlContext} then a
 772      * {@code SecurityException} is thrown.
 773      * <p>
 774      * If you override this method, then you should make a call to
 775      * {@code super.checkRead}
 776      * at the point the overridden method would normally throw an
 777      * exception.
 778      *
 779      * @param      file      the system-dependent filename.
 780      * @param      context   a system-dependent security context.
 781      * @throws     SecurityException  if the specified security context
 782      *             is not an instance of {@code AccessControlContext}
 783      *             (e.g., is {@code null}), or does not have permission
 784      *             to read the specified file.
 785      * @throws     NullPointerException if the {@code file} argument is
 786      *             {@code null}.
 787      * @see        java.lang.SecurityManager#getSecurityContext()
 788      * @see        java.security.AccessControlContext#checkPermission(java.security.Permission)
 789      */
 790     public void checkRead(String file, Object context) {
 791         checkPermission(
 792             new FilePermission(file, SecurityConstants.FILE_READ_ACTION),
 793             context);
 794     }
 795 
 796     /**
 797      * Throws a {@code SecurityException} if the
 798      * calling thread is not allowed to write to the specified file
 799      * descriptor.
 800      * <p>
 801      * This method calls {@code checkPermission} with the
 802      * {@code RuntimePermission("writeFileDescriptor")}
 803      * permission.
 804      * <p>
 805      * If you override this method, then you should make a call to
 806      * {@code super.checkWrite}
 807      * at the point the overridden method would normally throw an
 808      * exception.
 809      *
 810      * @param      fd   the system-dependent file descriptor.
 811      * @throws    SecurityException  if the calling thread does not have
 812      *             permission to access the specified file descriptor.
 813      * @throws     NullPointerException if the file descriptor argument is
 814      *             {@code null}.
 815      * @see        java.io.FileDescriptor
 816      * @see        #checkPermission(java.security.Permission) checkPermission
 817      */
 818     public void checkWrite(FileDescriptor fd) {
 819         if (fd == null) {
 820             throw new NullPointerException("file descriptor can't be null");
 821         }
 822         checkPermission(new RuntimePermission("writeFileDescriptor"));
 823 
 824     }
 825 
 826     /**
 827      * Throws a {@code SecurityException} if the
 828      * calling thread is not allowed to write to the file specified by
 829      * the string argument.
 830      * <p>
 831      * This method calls {@code checkPermission} with the
 832      * {@code FilePermission(file,"write")} permission.
 833      * <p>
 834      * If you override this method, then you should make a call to
 835      * {@code super.checkWrite}
 836      * at the point the overridden method would normally throw an
 837      * exception.
 838      *
 839      * @param      file   the system-dependent filename.
 840      * @throws     SecurityException  if the calling thread does not
 841      *             have permission to access the specified file.
 842      * @throws     NullPointerException if the {@code file} argument is
 843      *             {@code null}.
 844      * @see        #checkPermission(java.security.Permission) checkPermission
 845      */
 846     public void checkWrite(String file) {
 847         checkPermission(new FilePermission(file,
 848             SecurityConstants.FILE_WRITE_ACTION));
 849     }
 850 
 851     /**
 852      * Throws a {@code SecurityException} if the
 853      * calling thread is not allowed to delete the specified file.
 854      * <p>
 855      * This method is invoked for the current security manager by the
 856      * {@code delete} method of class {@code File}.
 857      * <p>
 858      * This method calls {@code checkPermission} with the
 859      * {@code FilePermission(file,"delete")} permission.
 860      * <p>
 861      * If you override this method, then you should make a call to
 862      * {@code super.checkDelete}
 863      * at the point the overridden method would normally throw an
 864      * exception.
 865      *
 866      * @param      file   the system-dependent filename.
 867      * @throws     SecurityException if the calling thread does not
 868      *             have permission to delete the file.
 869      * @throws     NullPointerException if the {@code file} argument is
 870      *             {@code null}.
 871      * @see        java.io.File#delete()
 872      * @see        #checkPermission(java.security.Permission) checkPermission
 873      */
 874     public void checkDelete(String file) {
 875         checkPermission(new FilePermission(file,
 876             SecurityConstants.FILE_DELETE_ACTION));
 877     }
 878 
 879     /**
 880      * Throws a {@code SecurityException} if the
 881      * calling thread is not allowed to open a socket connection to the
 882      * specified host and port number.
 883      * <p>
 884      * A port number of {@code -1} indicates that the calling
 885      * method is attempting to determine the IP address of the specified
 886      * host name.
 887      * <p>
 888      * This method calls {@code checkPermission} with the
 889      * {@code SocketPermission(host+":"+port,"connect")} permission if
 890      * the port is not equal to -1. If the port is equal to -1, then
 891      * it calls {@code checkPermission} with the
 892      * {@code SocketPermission(host,"resolve")} permission.
 893      * <p>
 894      * If you override this method, then you should make a call to
 895      * {@code super.checkConnect}
 896      * at the point the overridden method would normally throw an
 897      * exception.
 898      *
 899      * @param      host   the host name port to connect to.
 900      * @param      port   the protocol port to connect to.
 901      * @throws     SecurityException  if the calling thread does not have
 902      *             permission to open a socket connection to the specified
 903      *               {@code host} and {@code port}.
 904      * @throws     NullPointerException if the {@code host} argument is
 905      *             {@code null}.
 906      * @see        #checkPermission(java.security.Permission) checkPermission
 907      */
 908     public void checkConnect(String host, int port) {
 909         if (host == null) {
 910             throw new NullPointerException("host can't be null");
 911         }
 912         if (!host.startsWith("[") && host.indexOf(':') != -1) {
 913             host = "[" + host + "]";
 914         }
 915         if (port == -1) {
 916             checkPermission(new SocketPermission(host,
 917                 SecurityConstants.SOCKET_RESOLVE_ACTION));
 918         } else {
 919             checkPermission(new SocketPermission(host+":"+port,
 920                 SecurityConstants.SOCKET_CONNECT_ACTION));
 921         }
 922     }
 923 
 924     /**
 925      * Throws a {@code SecurityException} if the
 926      * specified security context is not allowed to open a socket
 927      * connection to the specified host and port number.
 928      * <p>
 929      * A port number of {@code -1} indicates that the calling
 930      * method is attempting to determine the IP address of the specified
 931      * host name.
 932      * <p> If {@code context} is not an instance of
 933      * {@code AccessControlContext} then a
 934      * {@code SecurityException} is thrown.
 935      * <p>
 936      * Otherwise, the port number is checked. If it is not equal
 937      * to -1, the {@code context}'s {@code checkPermission}
 938      * method is called with a
 939      * {@code SocketPermission(host+":"+port,"connect")} permission.
 940      * If the port is equal to -1, then
 941      * the {@code context}'s {@code checkPermission} method
 942      * is called with a
 943      * {@code SocketPermission(host,"resolve")} permission.
 944      * <p>
 945      * If you override this method, then you should make a call to
 946      * {@code super.checkConnect}
 947      * at the point the overridden method would normally throw an
 948      * exception.
 949      *
 950      * @param      host      the host name port to connect to.
 951      * @param      port      the protocol port to connect to.
 952      * @param      context   a system-dependent security context.
 953      * @throws     SecurityException if the specified security context
 954      *             is not an instance of {@code AccessControlContext}
 955      *             (e.g., is {@code null}), or does not have permission
 956      *             to open a socket connection to the specified
 957      *             {@code host} and {@code port}.
 958      * @throws     NullPointerException if the {@code host} argument is
 959      *             {@code null}.
 960      * @see        java.lang.SecurityManager#getSecurityContext()
 961      * @see        java.security.AccessControlContext#checkPermission(java.security.Permission)
 962      */
 963     public void checkConnect(String host, int port, Object context) {
 964         if (host == null) {
 965             throw new NullPointerException("host can't be null");
 966         }
 967         if (!host.startsWith("[") && host.indexOf(':') != -1) {
 968             host = "[" + host + "]";
 969         }
 970         if (port == -1)
 971             checkPermission(new SocketPermission(host,
 972                 SecurityConstants.SOCKET_RESOLVE_ACTION),
 973                 context);
 974         else
 975             checkPermission(new SocketPermission(host+":"+port,
 976                 SecurityConstants.SOCKET_CONNECT_ACTION),
 977                 context);
 978     }
 979 
 980     /**
 981      * Throws a {@code SecurityException} if the
 982      * calling thread is not allowed to wait for a connection request on
 983      * the specified local port number.
 984      * <p>
 985      * This method calls {@code checkPermission} with the
 986      * {@code SocketPermission("localhost:"+port,"listen")}.
 987      * <p>
 988      * If you override this method, then you should make a call to
 989      * {@code super.checkListen}
 990      * at the point the overridden method would normally throw an
 991      * exception.
 992      *
 993      * @param      port   the local port.
 994      * @throws     SecurityException  if the calling thread does not have
 995      *             permission to listen on the specified port.
 996      * @see        #checkPermission(java.security.Permission) checkPermission
 997      */
 998     public void checkListen(int port) {
 999         checkPermission(new SocketPermission("localhost:"+port,
1000             SecurityConstants.SOCKET_LISTEN_ACTION));
1001     }
1002 
1003     /**
1004      * Throws a {@code SecurityException} if the
1005      * calling thread is not permitted to accept a socket connection from
1006      * the specified host and port number.
1007      * <p>
1008      * This method is invoked for the current security manager by the
1009      * {@code accept} method of class {@code ServerSocket}.
1010      * <p>
1011      * This method calls {@code checkPermission} with the
1012      * {@code SocketPermission(host+":"+port,"accept")} permission.
1013      * <p>
1014      * If you override this method, then you should make a call to
1015      * {@code super.checkAccept}
1016      * at the point the overridden method would normally throw an
1017      * exception.
1018      *
1019      * @param      host   the host name of the socket connection.
1020      * @param      port   the port number of the socket connection.
1021      * @throws     SecurityException  if the calling thread does not have
1022      *             permission to accept the connection.
1023      * @throws     NullPointerException if the {@code host} argument is
1024      *             {@code null}.
1025      * @see        java.net.ServerSocket#accept()
1026      * @see        #checkPermission(java.security.Permission) checkPermission
1027      */
1028     public void checkAccept(String host, int port) {
1029         if (host == null) {
1030             throw new NullPointerException("host can't be null");
1031         }
1032         if (!host.startsWith("[") && host.indexOf(':') != -1) {
1033             host = "[" + host + "]";
1034         }
1035         checkPermission(new SocketPermission(host+":"+port,
1036             SecurityConstants.SOCKET_ACCEPT_ACTION));
1037     }
1038 
1039     /**
1040      * Throws a {@code SecurityException} if the
1041      * calling thread is not allowed to use
1042      * (join/leave/send/receive) IP multicast.
1043      * <p>
1044      * This method calls {@code checkPermission} with the
1045      * <code>java.net.SocketPermission(maddr.getHostAddress(),
1046      * "accept,connect")</code> permission.
1047      * <p>
1048      * If you override this method, then you should make a call to
1049      * {@code super.checkMulticast}
1050      * at the point the overridden method would normally throw an
1051      * exception.
1052      *
1053      * @param      maddr  Internet group address to be used.
1054      * @throws     SecurityException  if the calling thread is not allowed to
1055      *  use (join/leave/send/receive) IP multicast.
1056      * @throws     NullPointerException if the address argument is
1057      *             {@code null}.
1058      * @since      1.1
1059      * @see        #checkPermission(java.security.Permission) checkPermission
1060      */
1061     public void checkMulticast(InetAddress maddr) {
1062         String host = maddr.getHostAddress();
1063         if (!host.startsWith("[") && host.indexOf(':') != -1) {
1064             host = "[" + host + "]";
1065         }
1066         checkPermission(new SocketPermission(host,
1067             SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
1068     }
1069 
1070     /**
1071      * Throws a {@code SecurityException} if the
1072      * calling thread is not allowed to use
1073      * (join/leave/send/receive) IP multicast.
1074      * <p>
1075      * This method calls {@code checkPermission} with the
1076      * <code>java.net.SocketPermission(maddr.getHostAddress(),
1077      * "accept,connect")</code> permission.
1078      * <p>
1079      * If you override this method, then you should make a call to
1080      * {@code super.checkMulticast}
1081      * at the point the overridden method would normally throw an
1082      * exception.
1083      *
1084      * @param      maddr  Internet group address to be used.
1085      * @param      ttl        value in use, if it is multicast send.
1086      * Note: this particular implementation does not use the ttl
1087      * parameter.
1088      * @throws     SecurityException  if the calling thread is not allowed to
1089      *  use (join/leave/send/receive) IP multicast.
1090      * @throws     NullPointerException if the address argument is
1091      *             {@code null}.
1092      * @since      1.1
1093      * @see        #checkPermission(java.security.Permission) checkPermission
1094      */
1095     @Deprecated(since="1.4", forRemoval=true)
1096     public void checkMulticast(InetAddress maddr, byte ttl) {
1097         String host = maddr.getHostAddress();
1098         if (!host.startsWith("[") && host.indexOf(':') != -1) {
1099             host = "[" + host + "]";
1100         }
1101         checkPermission(new SocketPermission(host,
1102             SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
1103     }
1104 
1105     /**
1106      * Throws a {@code SecurityException} if the
1107      * calling thread is not allowed to access or modify the system
1108      * properties.
1109      * <p>
1110      * This method is used by the {@code getProperties} and
1111      * {@code setProperties} methods of class {@code System}.
1112      * <p>
1113      * This method calls {@code checkPermission} with the
1114      * {@code PropertyPermission("*", "read,write")} permission.
1115      * <p>
1116      * If you override this method, then you should make a call to
1117      * {@code super.checkPropertiesAccess}
1118      * at the point the overridden method would normally throw an
1119      * exception.
1120      *
1121      * @throws     SecurityException  if the calling thread does not have
1122      *             permission to access or modify the system properties.
1123      * @see        java.lang.System#getProperties()
1124      * @see        java.lang.System#setProperties(java.util.Properties)
1125      * @see        #checkPermission(java.security.Permission) checkPermission
1126      */
1127     public void checkPropertiesAccess() {
1128         checkPermission(new PropertyPermission("*",
1129             SecurityConstants.PROPERTY_RW_ACTION));
1130     }
1131 
1132     /**
1133      * Throws a {@code SecurityException} if the
1134      * calling thread is not allowed to access the system property with
1135      * the specified {@code key} name.
1136      * <p>
1137      * This method is used by the {@code getProperty} method of
1138      * class {@code System}.
1139      * <p>
1140      * This method calls {@code checkPermission} with the
1141      * {@code PropertyPermission(key, "read")} permission.
1142      * <p>
1143      * If you override this method, then you should make a call to
1144      * {@code super.checkPropertyAccess}
1145      * at the point the overridden method would normally throw an
1146      * exception.
1147      *
1148      * @param      key   a system property key.
1149      *
1150      * @throws     SecurityException  if the calling thread does not have
1151      *             permission to access the specified system property.
1152      * @throws     NullPointerException if the {@code key} argument is
1153      *             {@code null}.
1154      * @throws     IllegalArgumentException if {@code key} is empty.
1155      *
1156      * @see        java.lang.System#getProperty(java.lang.String)
1157      * @see        #checkPermission(java.security.Permission) checkPermission
1158      */
1159     public void checkPropertyAccess(String key) {
1160         checkPermission(new PropertyPermission(key,
1161             SecurityConstants.PROPERTY_READ_ACTION));
1162     }
1163 
1164     /**
1165      * Throws a {@code SecurityException} if the
1166      * calling thread is not allowed to initiate a print job request.
1167      * <p>
1168      * This method calls
1169      * {@code checkPermission} with the
1170      * {@code RuntimePermission("queuePrintJob")} permission.
1171      * <p>
1172      * If you override this method, then you should make a call to
1173      * {@code super.checkPrintJobAccess}
1174      * at the point the overridden method would normally throw an
1175      * exception.
1176      *
1177      * @throws     SecurityException  if the calling thread does not have
1178      *             permission to initiate a print job request.
1179      * @since   1.1
1180      * @see        #checkPermission(java.security.Permission) checkPermission
1181      */
1182     public void checkPrintJobAccess() {
1183         checkPermission(new RuntimePermission("queuePrintJob"));
1184     }
1185 
1186     /*
1187      * We have an initial invalid bit (initially false) for the class
1188      * variables which tell if the cache is valid.  If the underlying
1189      * java.security.Security property changes via setProperty(), the
1190      * Security class uses reflection to change the variable and thus
1191      * invalidate the cache.
1192      *
1193      * Locking is handled by synchronization to the
1194      * packageAccessLock/packageDefinitionLock objects.  They are only
1195      * used in this class.
1196      *
1197      * Note that cache invalidation as a result of the property change
1198      * happens without using these locks, so there may be a delay between
1199      * when a thread updates the property and when other threads updates
1200      * the cache.
1201      */
1202     private static boolean packageAccessValid = false;
1203     private static String[] packageAccess;
1204     private static final Object packageAccessLock = new Object();
1205 
1206     private static boolean packageDefinitionValid = false;
1207     private static String[] packageDefinition;
1208     private static final Object packageDefinitionLock = new Object();
1209 
1210     private static String[] getPackages(String p) {
1211         String packages[] = null;
1212         if (p != null && !p.isEmpty()) {
1213             java.util.StringTokenizer tok =
1214                 new java.util.StringTokenizer(p, ",");
1215             int n = tok.countTokens();
1216             if (n > 0) {
1217                 packages = new String[n];
1218                 int i = 0;
1219                 while (tok.hasMoreElements()) {
1220                     String s = tok.nextToken().trim();
1221                     packages[i++] = s;
1222                 }
1223             }
1224         }
1225 
1226         if (packages == null) {
1227             packages = new String[0];
1228         }
1229         return packages;
1230     }
1231 
1232     // The non-exported packages in modules defined to the boot or platform
1233     // class loaders. A non-exported package is a package that is not exported
1234     // or is only exported to specific modules.
1235     private static final Map<String, Boolean> nonExportedPkgs = new ConcurrentHashMap<>();
1236     static {
1237         addNonExportedPackages(ModuleLayer.boot());
1238     }
1239 
1240     /**
1241      * Record the non-exported packages of the modules in the given layer
1242      */
1243     static void addNonExportedPackages(ModuleLayer layer) {
1244         Set<String> bootModules = ModuleLoaderMap.bootModules();
1245         Set<String> platformModules = ModuleLoaderMap.platformModules();
1246         layer.modules().stream()
1247                 .map(Module::getDescriptor)
1248                 .filter(md -> bootModules.contains(md.name())
1249                         || platformModules.contains(md.name()))
1250                 .map(SecurityManager::nonExportedPkgs)
1251                 .flatMap(Set::stream)
1252                 .forEach(pn -> nonExportedPkgs.put(pn, Boolean.TRUE));
1253     }
1254 
1255 
1256     /**
1257      * Called by java.security.Security
1258      */
1259     static void invalidatePackageAccessCache() {
1260         synchronized (packageAccessLock) {
1261             packageAccessValid = false;
1262         }
1263         synchronized (packageDefinitionLock) {
1264             packageDefinitionValid = false;
1265         }
1266     }
1267 
1268     /**
1269      * Returns the non-exported packages of the specified module.
1270      */
1271     private static Set<String> nonExportedPkgs(ModuleDescriptor md) {
1272         // start with all packages in the module
1273         Set<String> pkgs = new HashSet<>(md.packages());
1274 
1275         // remove the non-qualified exported packages
1276         md.exports().stream()
1277                     .filter(p -> !p.isQualified())
1278                     .map(Exports::source)
1279                     .forEach(pkgs::remove);
1280 
1281         // remove the non-qualified open packages
1282         md.opens().stream()
1283                   .filter(p -> !p.isQualified())
1284                   .map(Opens::source)
1285                   .forEach(pkgs::remove);
1286 
1287         return pkgs;
1288     }
1289 
1290     /**
1291      * Throws a {@code SecurityException} if the calling thread is not allowed
1292      * to access the specified package.
1293      * <p>
1294      * During class loading, this method may be called by the {@code loadClass}
1295      * method of class loaders and by the Java Virtual Machine to ensure that
1296      * the caller is allowed to access the package of the class that is
1297      * being loaded.
1298      * <p>
1299      * This method checks if the specified package starts with or equals
1300      * any of the packages in the {@code package.access} Security Property.
1301      * An implementation may also check the package against an additional
1302      * list of restricted packages as noted below. If the package is restricted,
1303      * {@link #checkPermission(Permission)} is called with a
1304      * {@code RuntimePermission("accessClassInPackage."+pkg)} permission.
1305      * <p>
1306      * If this method is overridden, then {@code super.checkPackageAccess}
1307      * should be called as the first line in the overridden method.
1308      *
1309      * @implNote
1310      * This implementation also restricts all non-exported packages of modules
1311      * loaded by {@linkplain ClassLoader#getPlatformClassLoader
1312      * the platform class loader} or its ancestors. A "non-exported package"
1313      * refers to a package that is not exported to all modules. Specifically,
1314      * it refers to a package that either is not exported at all by its
1315      * containing module or is exported in a qualified fashion by its
1316      * containing module.
1317      *
1318      * @param      pkg   the package name.
1319      * @throws     SecurityException  if the calling thread does not have
1320      *             permission to access the specified package.
1321      * @throws     NullPointerException if the package name argument is
1322      *             {@code null}.
1323      * @see        java.lang.ClassLoader#loadClass(String, boolean) loadClass
1324      * @see        java.security.Security#getProperty getProperty
1325      * @see        #checkPermission(Permission) checkPermission
1326      */
1327     public void checkPackageAccess(String pkg) {
1328         Objects.requireNonNull(pkg, "package name can't be null");
1329 
1330         // check if pkg is not exported to all modules
1331         if (nonExportedPkgs.containsKey(pkg)) {
1332             checkPermission(
1333                 new RuntimePermission("accessClassInPackage." + pkg));
1334             return;
1335         }
1336 
1337         String[] restrictedPkgs;
1338         synchronized (packageAccessLock) {
1339             /*
1340              * Do we need to update our property array?
1341              */
1342             if (!packageAccessValid) {
1343                 @SuppressWarnings("removal")
1344                 String tmpPropertyStr =
1345                     AccessController.doPrivileged(
1346                         new PrivilegedAction<>() {
1347                             public String run() {
1348                                 return Security.getProperty("package.access");
1349                             }
1350                         }
1351                     );
1352                 packageAccess = getPackages(tmpPropertyStr);
1353                 packageAccessValid = true;
1354             }
1355 
1356             // Using a snapshot of packageAccess -- don't care if static field
1357             // changes afterwards; array contents won't change.
1358             restrictedPkgs = packageAccess;
1359         }
1360 
1361         /*
1362          * Traverse the list of packages, check for any matches.
1363          */
1364         final int plen = pkg.length();
1365         for (String restrictedPkg : restrictedPkgs) {
1366             final int rlast = restrictedPkg.length() - 1;
1367 
1368             // Optimizations:
1369             //
1370             // If rlast >= plen then restrictedPkg is longer than pkg by at
1371             // least one char. This means pkg cannot start with restrictedPkg,
1372             // since restrictedPkg will be longer than pkg.
1373             //
1374             // Similarly if rlast != plen, then pkg + "." cannot be the same
1375             // as restrictedPkg, since pkg + "." will have a different length
1376             // than restrictedPkg.
1377             //
1378             if (rlast < plen && pkg.startsWith(restrictedPkg) ||
1379                 // The following test is equivalent to
1380                 // restrictedPkg.equals(pkg + ".") but is noticeably more
1381                 // efficient:
1382                 rlast == plen && restrictedPkg.startsWith(pkg) &&
1383                 restrictedPkg.charAt(rlast) == '.')
1384             {
1385                 checkPermission(
1386                     new RuntimePermission("accessClassInPackage." + pkg));
1387                 break;  // No need to continue; only need to check this once
1388             }
1389         }
1390     }
1391 
1392     /**
1393      * Throws a {@code SecurityException} if the calling thread is not
1394      * allowed to define classes in the specified package.
1395      * <p>
1396      * This method is called by the {@code loadClass} method of some
1397      * class loaders.
1398      * <p>
1399      * This method checks if the specified package starts with or equals
1400      * any of the packages in the {@code package.definition} Security
1401      * Property. An implementation may also check the package against an
1402      * additional list of restricted packages as noted below. If the package
1403      * is restricted, {@link #checkPermission(Permission)} is called with a
1404      * {@code RuntimePermission("defineClassInPackage."+pkg)} permission.
1405      * <p>
1406      * If this method is overridden, then {@code super.checkPackageDefinition}
1407      * should be called as the first line in the overridden method.
1408      *
1409      * @implNote
1410      * This implementation also restricts all non-exported packages of modules
1411      * loaded by {@linkplain ClassLoader#getPlatformClassLoader
1412      * the platform class loader} or its ancestors. A "non-exported package"
1413      * refers to a package that is not exported to all modules. Specifically,
1414      * it refers to a package that either is not exported at all by its
1415      * containing module or is exported in a qualified fashion by its
1416      * containing module.
1417      *
1418      * @param      pkg   the package name.
1419      * @throws     SecurityException  if the calling thread does not have
1420      *             permission to define classes in the specified package.
1421      * @throws     NullPointerException if the package name argument is
1422      *             {@code null}.
1423      * @see        java.lang.ClassLoader#loadClass(String, boolean)
1424      * @see        java.security.Security#getProperty getProperty
1425      * @see        #checkPermission(Permission) checkPermission
1426      */
1427     public void checkPackageDefinition(String pkg) {
1428         Objects.requireNonNull(pkg, "package name can't be null");
1429 
1430         // check if pkg is not exported to all modules
1431         if (nonExportedPkgs.containsKey(pkg)) {
1432             checkPermission(
1433                 new RuntimePermission("defineClassInPackage." + pkg));
1434             return;
1435         }
1436 
1437         String[] pkgs;
1438         synchronized (packageDefinitionLock) {
1439             /*
1440              * Do we need to update our property array?
1441              */
1442             if (!packageDefinitionValid) {
1443                 @SuppressWarnings("removal")
1444                 String tmpPropertyStr =
1445                     AccessController.doPrivileged(
1446                         new PrivilegedAction<>() {
1447                             public String run() {
1448                                 return java.security.Security.getProperty(
1449                                     "package.definition");
1450                             }
1451                         }
1452                     );
1453                 packageDefinition = getPackages(tmpPropertyStr);
1454                 packageDefinitionValid = true;
1455             }
1456             // Using a snapshot of packageDefinition -- don't care if static
1457             // field changes afterwards; array contents won't change.
1458             pkgs = packageDefinition;
1459         }
1460 
1461         /*
1462          * Traverse the list of packages, check for any matches.
1463          */
1464         for (String restrictedPkg : pkgs) {
1465             if (pkg.startsWith(restrictedPkg) || restrictedPkg.equals(pkg + ".")) {
1466                 checkPermission(
1467                     new RuntimePermission("defineClassInPackage." + pkg));
1468                 break; // No need to continue; only need to check this once
1469             }
1470         }
1471     }
1472 
1473     /**
1474      * Throws a {@code SecurityException} if the
1475      * calling thread is not allowed to set the socket factory used by
1476      * {@code ServerSocket} or {@code Socket}, or the stream
1477      * handler factory used by {@code URL}.
1478      * <p>
1479      * This method calls {@code checkPermission} with the
1480      * {@code RuntimePermission("setFactory")} permission.
1481      * <p>
1482      * If you override this method, then you should make a call to
1483      * {@code super.checkSetFactory}
1484      * at the point the overridden method would normally throw an
1485      * exception.
1486      *
1487      * @throws     SecurityException  if the calling thread does not have
1488      *             permission to specify a socket factory or a stream
1489      *             handler factory.
1490      *
1491      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) setSocketFactory
1492      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory) setSocketImplFactory
1493      * @see        java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory) setURLStreamHandlerFactory
1494      * @see        #checkPermission(java.security.Permission) checkPermission
1495      */
1496     public void checkSetFactory() {
1497         checkPermission(new RuntimePermission("setFactory"));
1498     }
1499 
1500     /**
1501      * Determines whether the permission with the specified permission target
1502      * name should be granted or denied.
1503      *
1504      * <p> If the requested permission is allowed, this method returns
1505      * quietly. If denied, a SecurityException is raised.
1506      *
1507      * <p> This method creates a {@code SecurityPermission} object for
1508      * the given permission target name and calls {@code checkPermission}
1509      * with it.
1510      *
1511      * <p> See the documentation for
1512      * <code>{@link java.security.SecurityPermission}</code> for
1513      * a list of possible permission target names.
1514      *
1515      * <p> If you override this method, then you should make a call to
1516      * {@code super.checkSecurityAccess}
1517      * at the point the overridden method would normally throw an
1518      * exception.
1519      *
1520      * @param target the target name of the {@code SecurityPermission}.
1521      *
1522      * @throws    SecurityException if the calling thread does not have
1523      * permission for the requested access.
1524      * @throws    NullPointerException if {@code target} is null.
1525      * @throws    IllegalArgumentException if {@code target} is empty.
1526      *
1527      * @since   1.1
1528      * @see        #checkPermission(java.security.Permission) checkPermission
1529      */
1530     public void checkSecurityAccess(String target) {
1531         checkPermission(new SecurityPermission(target));
1532     }
1533 
1534     /**
1535      * Returns the thread group into which to instantiate any new
1536      * thread being created at the time this is being called.
1537      * By default, it returns the thread group of the current
1538      * thread. This should be overridden by a specific security
1539      * manager to return the appropriate thread group.
1540      *
1541      * @return  ThreadGroup that new threads are instantiated into
1542      * @since   1.1
1543      * @see     java.lang.ThreadGroup
1544      */
1545     public ThreadGroup getThreadGroup() {
1546         return Thread.getCurrentThreadGroup();
1547     }
1548 
1549 }