1 /*
   2  * Copyright (c) 1997, 2015, 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.security;
  27 
  28 import java.util.ArrayList;
  29 import java.util.List;
  30 
  31 import sun.security.util.Debug;
  32 import sun.security.util.FilePermCompat;
  33 import sun.security.util.SecurityConstants;
  34 
  35 
  36 /**
  37  * An AccessControlContext is used to make system resource access decisions
  38  * based on the context it encapsulates.
  39  *
  40  * <p>More specifically, it encapsulates a context and
  41  * has a single method, {@code checkPermission},
  42  * that is equivalent to the {@code checkPermission} method
  43  * in the AccessController class, with one difference: The AccessControlContext
  44  * {@code checkPermission} method makes access decisions based on the
  45  * context it encapsulates,
  46  * rather than that of the current execution thread.
  47  *
  48  * <p>Thus, the purpose of AccessControlContext is for those situations where
  49  * a security check that should be made within a given context
  50  * actually needs to be done from within a
  51  * <i>different</i> context (for example, from within a worker thread).
  52  *
  53  * <p> An AccessControlContext is created by calling the
  54  * {@code AccessController.getContext} method.
  55  * The {@code getContext} method takes a "snapshot"
  56  * of the current calling context, and places
  57  * it in an AccessControlContext object, which it returns. A sample call is
  58  * the following:
  59  *
  60  * <pre>
  61  *   AccessControlContext acc = AccessController.getContext()
  62  * </pre>
  63  *
  64  * <p>
  65  * Code within a different context can subsequently call the
  66  * {@code checkPermission} method on the
  67  * previously-saved AccessControlContext object. A sample call is the
  68  * following:
  69  *
  70  * <pre>
  71  *   acc.checkPermission(permission)
  72  * </pre>
  73  *
  74  * @see AccessController
  75  *
  76  * @author Roland Schemers
  77  */
  78 
  79 public final class AccessControlContext {
  80 
  81     private ProtectionDomain[] context;
  82     // isPrivileged and isAuthorized are referenced by the VM - do not remove
  83     // or change their names
  84     private boolean isPrivileged;
  85     private boolean isAuthorized = false;
  86 
  87     // Note: This field is directly used by the virtual machine
  88     // native codes. Don't touch it.
  89     private AccessControlContext privilegedContext;
  90 
  91     private DomainCombiner combiner = null;
  92 
  93     // limited privilege scope
  94     private Permission[] permissions;
  95     private AccessControlContext parent;
  96     private boolean isWrapped;
  97 
  98     // is constrained by limited privilege scope?
  99     private boolean isLimited;
 100     private ProtectionDomain[] limitedContext;
 101 
 102     private static boolean debugInit = false;
 103     private static Debug debug = null;
 104 
 105     static Debug getDebug()
 106     {
 107         if (debugInit)
 108             return debug;
 109         else {
 110             if (Policy.isSet()) {
 111                 debug = Debug.getInstance("access");
 112                 debugInit = true;
 113             }
 114             return debug;
 115         }
 116     }
 117 
 118     /**
 119      * Create an AccessControlContext with the given array of ProtectionDomains.
 120      * Context must not be null. Duplicate domains will be removed from the
 121      * context.
 122      *
 123      * @param context the ProtectionDomains associated with this context.
 124      * The non-duplicate domains are copied from the array. Subsequent
 125      * changes to the array will not affect this AccessControlContext.
 126      * @throws NullPointerException if {@code context} is {@code null}
 127      */
 128     public AccessControlContext(ProtectionDomain[] context)
 129     {
 130         if (context.length == 0) {
 131             this.context = null;
 132         } else if (context.length == 1) {
 133             if (context[0] != null) {
 134                 this.context = context.clone();
 135             } else {
 136                 this.context = null;
 137             }
 138         } else {
 139             List<ProtectionDomain> v = new ArrayList<>(context.length);
 140             for (int i =0; i< context.length; i++) {
 141                 if ((context[i] != null) &&  (!v.contains(context[i])))
 142                     v.add(context[i]);
 143             }
 144             if (!v.isEmpty()) {
 145                 this.context = new ProtectionDomain[v.size()];
 146                 this.context = v.toArray(this.context);
 147             }
 148         }
 149     }
 150 
 151     /**
 152      * Create a new {@code AccessControlContext} with the given
 153      * {@code AccessControlContext} and {@code DomainCombiner}.
 154      * This constructor associates the provided
 155      * {@code DomainCombiner} with the provided
 156      * {@code AccessControlContext}.
 157      *
 158      * @param acc the {@code AccessControlContext} associated
 159      *          with the provided {@code DomainCombiner}.
 160      *
 161      * @param combiner the {@code DomainCombiner} to be associated
 162      *          with the provided {@code AccessControlContext}.
 163      *
 164      * @exception NullPointerException if the provided
 165      *          {@code context} is {@code null}.
 166      *
 167      * @exception SecurityException if a security manager is installed and the
 168      *          caller does not have the "createAccessControlContext"
 169      *          {@link SecurityPermission}
 170      * @since 1.3
 171      */
 172     public AccessControlContext(AccessControlContext acc,
 173                                 DomainCombiner combiner) {
 174 
 175         this(acc, combiner, false);
 176     }
 177 
 178     /**
 179      * package private to allow calls from ProtectionDomain without performing
 180      * the security check for {@linkplain SecurityConstants#CREATE_ACC_PERMISSION}
 181      * permission
 182      */
 183     AccessControlContext(AccessControlContext acc,
 184                         DomainCombiner combiner,
 185                         boolean preauthorized) {
 186         if (!preauthorized) {
 187             SecurityManager sm = System.getSecurityManager();
 188             if (sm != null) {
 189                 sm.checkPermission(SecurityConstants.CREATE_ACC_PERMISSION);
 190                 this.isAuthorized = true;
 191             }
 192         } else {
 193             this.isAuthorized = true;
 194         }
 195 
 196         this.context = acc.context;
 197 
 198         // we do not need to run the combine method on the
 199         // provided ACC.  it was already "combined" when the
 200         // context was originally retrieved.
 201         //
 202         // at this point in time, we simply throw away the old
 203         // combiner and use the newly provided one.
 204         this.combiner = combiner;
 205     }
 206 
 207     /**
 208      * package private for AccessController
 209      *
 210      * This "argument wrapper" context will be passed as the actual context
 211      * parameter on an internal doPrivileged() call used in the implementation.
 212      */
 213     AccessControlContext(ProtectionDomain caller, DomainCombiner combiner,
 214         AccessControlContext parent, AccessControlContext context,
 215         Permission[] perms)
 216     {
 217         /*
 218          * Combine the domains from the doPrivileged() context into our
 219          * wrapper context, if necessary.
 220          */
 221         ProtectionDomain[] callerPDs = null;
 222         if (caller != null) {
 223              callerPDs = new ProtectionDomain[] { caller };
 224         }
 225         if (context != null) {
 226             if (combiner != null) {
 227                 this.context = combiner.combine(callerPDs, context.context);
 228             } else {
 229                 this.context = combine(callerPDs, context.context);
 230             }
 231         } else {
 232             /*
 233              * Call combiner even if there is seemingly nothing to combine.
 234              */
 235             if (combiner != null) {
 236                 this.context = combiner.combine(callerPDs, null);
 237             } else {
 238                 this.context = combine(callerPDs, null);
 239             }
 240         }
 241         this.combiner = combiner;
 242 
 243         Permission[] tmp = null;
 244         if (perms != null) {
 245             tmp = new Permission[perms.length];
 246             for (int i=0; i < perms.length; i++) {
 247                 if (perms[i] == null) {
 248                     throw new NullPointerException("permission can't be null");
 249                 }
 250 
 251                 /*
 252                  * An AllPermission argument is equivalent to calling
 253                  * doPrivileged() without any limit permissions.
 254                  */
 255                 if (perms[i].getClass() == AllPermission.class) {
 256                     parent = null;
 257                 }
 258                 // Add altPath into permission for compatibility.
 259                 tmp[i] = FilePermCompat.newPermPlusAltPath(perms[i]);
 260             }
 261         }
 262 
 263         /*
 264          * For a doPrivileged() with limited privilege scope, initialize
 265          * the relevant fields.
 266          *
 267          * The limitedContext field contains the union of all domains which
 268          * are enclosed by this limited privilege scope. In other words,
 269          * it contains all of the domains which could potentially be checked
 270          * if none of the limiting permissions implied a requested permission.
 271          */
 272         if (parent != null) {
 273             this.limitedContext = combine(parent.context, parent.limitedContext);
 274             this.isLimited = true;
 275             this.isWrapped = true;
 276             this.permissions = tmp;
 277             this.parent = parent;
 278             this.privilegedContext = context; // used in checkPermission2()
 279         }
 280         this.isAuthorized = true;
 281     }
 282 
 283 
 284     /**
 285      * package private constructor for AccessController.getContext()
 286      */
 287 
 288     AccessControlContext(ProtectionDomain[] context,
 289                          boolean isPrivileged)
 290     {
 291         this.context = context;
 292         this.isPrivileged = isPrivileged;
 293         this.isAuthorized = true;
 294     }
 295 
 296     /**
 297      * Constructor for JavaSecurityAccess.doIntersectionPrivilege()
 298      */
 299     AccessControlContext(ProtectionDomain[] context,
 300                          AccessControlContext privilegedContext)
 301     {
 302         this.context = context;
 303         this.privilegedContext = privilegedContext;
 304         this.isPrivileged = true;
 305     }
 306 
 307     /**
 308      * Returns this context's context.
 309      */
 310     ProtectionDomain[] getContext() {
 311         return context;
 312     }
 313 
 314     /**
 315      * Returns true if this context is privileged.
 316      */
 317     boolean isPrivileged()
 318     {
 319         return isPrivileged;
 320     }
 321 
 322     /**
 323      * get the assigned combiner from the privileged or inherited context
 324      */
 325     DomainCombiner getAssignedCombiner() {
 326         AccessControlContext acc;
 327         if (isPrivileged) {
 328             acc = privilegedContext;
 329         } else {
 330             acc = AccessController.getInheritedAccessControlContext();
 331         }
 332         if (acc != null) {
 333             return acc.combiner;
 334         }
 335         return null;
 336     }
 337 
 338     /**
 339      * Get the {@code DomainCombiner} associated with this
 340      * {@code AccessControlContext}.
 341      *
 342      * @return the {@code DomainCombiner} associated with this
 343      *          {@code AccessControlContext}, or {@code null}
 344      *          if there is none.
 345      *
 346      * @exception SecurityException if a security manager is installed and
 347      *          the caller does not have the "getDomainCombiner"
 348      *          {@link SecurityPermission}
 349      * @since 1.3
 350      */
 351     public DomainCombiner getDomainCombiner() {
 352 
 353         SecurityManager sm = System.getSecurityManager();
 354         if (sm != null) {
 355             sm.checkPermission(SecurityConstants.GET_COMBINER_PERMISSION);
 356         }
 357         return getCombiner();
 358     }
 359 
 360     /**
 361      * package private for AccessController
 362      */
 363     DomainCombiner getCombiner() {
 364         return combiner;
 365     }
 366 
 367     boolean isAuthorized() {
 368         return isAuthorized;
 369     }
 370 
 371     /**
 372      * Determines whether the access request indicated by the
 373      * specified permission should be allowed or denied, based on
 374      * the security policy currently in effect, and the context in
 375      * this object. The request is allowed only if every ProtectionDomain
 376      * in the context implies the permission. Otherwise the request is
 377      * denied.
 378      *
 379      * <p>
 380      * This method quietly returns if the access request
 381      * is permitted, or throws a suitable AccessControlException otherwise.
 382      *
 383      * @param perm the requested permission.
 384      *
 385      * @exception AccessControlException if the specified permission
 386      * is not permitted, based on the current security policy and the
 387      * context encapsulated by this object.
 388      * @exception NullPointerException if the permission to check for is null.
 389      */
 390     public void checkPermission(Permission perm)
 391         throws AccessControlException
 392     {
 393         boolean dumpDebug = false;
 394 
 395         if (perm == null) {
 396             throw new NullPointerException("permission can't be null");
 397         }
 398         if (getDebug() != null) {
 399             // If "codebase" is not specified, we dump the info by default.
 400             dumpDebug = !Debug.isOn("codebase=");
 401             if (!dumpDebug) {
 402                 // If "codebase" is specified, only dump if the specified code
 403                 // value is in the stack.
 404                 for (int i = 0; context != null && i < context.length; i++) {
 405                     if (context[i].getCodeSource() != null &&
 406                         context[i].getCodeSource().getLocation() != null &&
 407                         Debug.isOn("codebase=" + context[i].getCodeSource().getLocation().toString())) {
 408                         dumpDebug = true;
 409                         break;
 410                     }
 411                 }
 412             }
 413 
 414             dumpDebug &= !Debug.isOn("permission=") ||
 415                 Debug.isOn("permission=" + perm.getClass().getCanonicalName());
 416 
 417             if (dumpDebug && Debug.isOn("stack")) {
 418                 Thread.dumpStack();
 419             }
 420 
 421             if (dumpDebug && Debug.isOn("domain")) {
 422                 if (context == null) {
 423                     debug.println("domain (context is null)");
 424                 } else {
 425                     for (int i=0; i< context.length; i++) {
 426                         debug.println("domain "+i+" "+context[i]);
 427                     }
 428                 }
 429             }
 430         }
 431 
 432         /*
 433          * iterate through the ProtectionDomains in the context.
 434          * Stop at the first one that doesn't allow the
 435          * requested permission (throwing an exception).
 436          *
 437          */
 438 
 439         /* if ctxt is null, all we had on the stack were system domains,
 440            or the first domain was a Privileged system domain. This
 441            is to make the common case for system code very fast */
 442 
 443         if (context == null) {
 444             checkPermission2(perm);
 445             return;
 446         }
 447 
 448         for (int i=0; i< context.length; i++) {
 449             if (context[i] != null && !context[i].impliesWithAltFilePerm(perm)) {
 450                 if (dumpDebug) {
 451                     debug.println("access denied " + perm);
 452                 }
 453 
 454                 if (Debug.isOn("failure") && debug != null) {
 455                     // Want to make sure this is always displayed for failure,
 456                     // but do not want to display again if already displayed
 457                     // above.
 458                     if (!dumpDebug) {
 459                         debug.println("access denied " + perm);
 460                     }
 461                     Thread.dumpStack();
 462                     final ProtectionDomain pd = context[i];
 463                     final Debug db = debug;
 464                     AccessController.doPrivileged (new PrivilegedAction<>() {
 465                         public Void run() {
 466                             db.println("domain that failed "+pd);
 467                             return null;
 468                         }
 469                     });
 470                 }
 471                 throw new AccessControlException("access denied "+perm, perm);
 472             }
 473         }
 474 
 475         // allow if all of them allowed access
 476         if (dumpDebug) {
 477             debug.println("access allowed "+perm);
 478         }
 479 
 480         checkPermission2(perm);
 481     }
 482 
 483     /*
 484      * Check the domains associated with the limited privilege scope.
 485      */
 486     private void checkPermission2(Permission perm) {
 487         if (!isLimited) {
 488             return;
 489         }
 490 
 491         /*
 492          * Check the doPrivileged() context parameter, if present.
 493          */
 494         if (privilegedContext != null) {
 495             privilegedContext.checkPermission2(perm);
 496         }
 497 
 498         /*
 499          * Ignore the limited permissions and parent fields of a wrapper
 500          * context since they were already carried down into the unwrapped
 501          * context.
 502          */
 503         if (isWrapped) {
 504             return;
 505         }
 506 
 507         /*
 508          * Try to match any limited privilege scope.
 509          */
 510         if (permissions != null) {
 511             Class<?> permClass = perm.getClass();
 512             for (int i=0; i < permissions.length; i++) {
 513                 Permission limit = permissions[i];
 514                 if (limit.getClass().equals(permClass) && limit.implies(perm)) {
 515                     return;
 516                 }
 517             }
 518         }
 519 
 520         /*
 521          * Check the limited privilege scope up the call stack or the inherited
 522          * parent thread call stack of this ACC.
 523          */
 524         if (parent != null) {
 525             /*
 526              * As an optimization, if the parent context is the inherited call
 527              * stack context from a parent thread then checking the protection
 528              * domains of the parent context is redundant since they have
 529              * already been merged into the child thread's context by
 530              * optimize(). When parent is set to an inherited context this
 531              * context was not directly created by a limited scope
 532              * doPrivileged() and it does not have its own limited permissions.
 533              */
 534             if (permissions == null) {
 535                 parent.checkPermission2(perm);
 536             } else {
 537                 parent.checkPermission(perm);
 538             }
 539         }
 540     }
 541 
 542     /**
 543      * Take the stack-based context (this) and combine it with the
 544      * privileged or inherited context, if need be. Any limited
 545      * privilege scope is flagged regardless of whether the assigned
 546      * context comes from an immediately enclosing limited doPrivileged().
 547      * The limited privilege scope can indirectly flow from the inherited
 548      * parent thread or an assigned context previously captured by getContext().
 549      */
 550     AccessControlContext optimize() {
 551         // the assigned (privileged or inherited) context
 552         AccessControlContext acc;
 553         DomainCombiner combiner = null;
 554         AccessControlContext parent = null;
 555         Permission[] permissions = null;
 556 
 557         if (isPrivileged) {
 558             acc = privilegedContext;
 559             if (acc != null) {
 560                 /*
 561                  * If the context is from a limited scope doPrivileged() then
 562                  * copy the permissions and parent fields out of the wrapper
 563                  * context that was created to hold them.
 564                  */
 565                 if (acc.isWrapped) {
 566                     permissions = acc.permissions;
 567                     parent = acc.parent;
 568                 }
 569             }
 570         } else {
 571             acc = AccessController.getInheritedAccessControlContext();
 572             if (acc != null) {
 573                 /*
 574                  * If the inherited context is constrained by a limited scope
 575                  * doPrivileged() then set it as our parent so we will process
 576                  * the non-domain-related state.
 577                  */
 578                 if (acc.isLimited) {
 579                     parent = acc;
 580                 }
 581             }
 582         }
 583 
 584         // this.context could be null if only system code is on the stack;
 585         // in that case, ignore the stack context
 586         boolean skipStack = (context == null);
 587 
 588         // acc.context could be null if only system code was involved;
 589         // in that case, ignore the assigned context
 590         boolean skipAssigned = (acc == null || acc.context == null);
 591         ProtectionDomain[] assigned = (skipAssigned) ? null : acc.context;
 592         ProtectionDomain[] pd;
 593 
 594         // if there is no enclosing limited privilege scope on the stack or
 595         // inherited from a parent thread
 596         boolean skipLimited = ((acc == null || !acc.isWrapped) && parent == null);
 597 
 598         if (acc != null && acc.combiner != null) {
 599             // let the assigned acc's combiner do its thing
 600             if (getDebug() != null) {
 601                 debug.println("AccessControlContext invoking the Combiner");
 602             }
 603 
 604             // No need to clone current and assigned.context
 605             // combine() will not update them
 606             combiner = acc.combiner;
 607             pd = combiner.combine(context, assigned);
 608         } else {
 609             if (skipStack) {
 610                 if (skipAssigned) {
 611                     calculateFields(acc, parent, permissions);
 612                     return this;
 613                 } else if (skipLimited) {
 614                     return acc;
 615                 }
 616             } else if (assigned != null) {
 617                 if (skipLimited) {
 618                     // optimization: if there is a single stack domain and
 619                     // that domain is already in the assigned context; no
 620                     // need to combine
 621                     if (context.length == 1 && context[0] == assigned[0]) {
 622                         return acc;
 623                     }
 624                 }
 625             }
 626 
 627             pd = combine(context, assigned);
 628             if (skipLimited && !skipAssigned && pd == assigned) {
 629                 return acc;
 630             } else if (skipAssigned && pd == context) {
 631                 calculateFields(acc, parent, permissions);
 632                 return this;
 633             }
 634         }
 635 
 636         // Reuse existing ACC
 637         this.context = pd;
 638         this.combiner = combiner;
 639         this.isPrivileged = false;
 640 
 641         calculateFields(acc, parent, permissions);
 642         return this;
 643     }
 644 
 645 
 646     /*
 647      * Combine the current (stack) and assigned domains.
 648      */
 649     private static ProtectionDomain[] combine(ProtectionDomain[] current,
 650         ProtectionDomain[] assigned) {
 651 
 652         // current could be null if only system code is on the stack;
 653         // in that case, ignore the stack context
 654         boolean skipStack = (current == null);
 655 
 656         // assigned could be null if only system code was involved;
 657         // in that case, ignore the assigned context
 658         boolean skipAssigned = (assigned == null);
 659 
 660         int slen = (skipStack) ? 0 : current.length;
 661 
 662         // optimization: if there is no assigned context and the stack length
 663         // is less then or equal to two; there is no reason to compress the
 664         // stack context, it already is
 665         if (skipAssigned && slen <= 2) {
 666             return current;
 667         }
 668 
 669         int n = (skipAssigned) ? 0 : assigned.length;
 670 
 671         // now we combine both of them, and create a new context
 672         ProtectionDomain[] pd = new ProtectionDomain[slen + n];
 673 
 674         // first copy in the assigned context domains, no need to compress
 675         if (!skipAssigned) {
 676             System.arraycopy(assigned, 0, pd, 0, n);
 677         }
 678 
 679         // now add the stack context domains, discarding nulls and duplicates
 680     outer:
 681         for (int i = 0; i < slen; i++) {
 682             ProtectionDomain sd = current[i];
 683             if (sd != null) {
 684                 for (int j = 0; j < n; j++) {
 685                     if (sd == pd[j]) {
 686                         continue outer;
 687                     }
 688                 }
 689                 pd[n++] = sd;
 690             }
 691         }
 692 
 693         // if length isn't equal, we need to shorten the array
 694         if (n != pd.length) {
 695             // optimization: if we didn't really combine anything
 696             if (!skipAssigned && n == assigned.length) {
 697                 return assigned;
 698             } else if (skipAssigned && n == slen) {
 699                 return current;
 700             }
 701             ProtectionDomain[] tmp = new ProtectionDomain[n];
 702             System.arraycopy(pd, 0, tmp, 0, n);
 703             pd = tmp;
 704         }
 705 
 706         return pd;
 707     }
 708 
 709 
 710     /*
 711      * Calculate the additional domains that could potentially be reached via
 712      * limited privilege scope. Mark the context as being subject to limited
 713      * privilege scope unless the reachable domains (if any) are already
 714      * contained in this domain context (in which case any limited
 715      * privilege scope checking would be redundant).
 716      */
 717     private void calculateFields(AccessControlContext assigned,
 718         AccessControlContext parent, Permission[] permissions)
 719     {
 720         ProtectionDomain[] parentLimit = null;
 721         ProtectionDomain[] assignedLimit = null;
 722         ProtectionDomain[] newLimit;
 723 
 724         parentLimit = (parent != null)? parent.limitedContext: null;
 725         assignedLimit = (assigned != null)? assigned.limitedContext: null;
 726         newLimit = combine(parentLimit, assignedLimit);
 727         if (newLimit != null) {
 728             if (context == null || !containsAllPDs(newLimit, context)) {
 729                 this.limitedContext = newLimit;
 730                 this.permissions = permissions;
 731                 this.parent = parent;
 732                 this.isLimited = true;
 733             }
 734         }
 735     }
 736 
 737 
 738     /**
 739      * Checks two AccessControlContext objects for equality.
 740      * Checks that {@code obj} is
 741      * an AccessControlContext and has the same set of ProtectionDomains
 742      * as this context.
 743      *
 744      * @param obj the object we are testing for equality with this object.
 745      * @return true if {@code obj} is an AccessControlContext, and has the
 746      * same set of ProtectionDomains as this context, false otherwise.
 747      */
 748     public boolean equals(Object obj) {
 749         if (obj == this)
 750             return true;
 751 
 752         if (! (obj instanceof AccessControlContext))
 753             return false;
 754 
 755         AccessControlContext that = (AccessControlContext) obj;
 756 
 757         if (!equalContext(that))
 758             return false;
 759 
 760         if (!equalLimitedContext(that))
 761             return false;
 762 
 763         return true;
 764     }
 765 
 766     /*
 767      * Compare for equality based on state that is free of limited
 768      * privilege complications.
 769      */
 770     private boolean equalContext(AccessControlContext that) {
 771         if (!equalPDs(this.context, that.context))
 772             return false;
 773 
 774         if (this.combiner == null && that.combiner != null)
 775             return false;
 776 
 777         if (this.combiner != null && !this.combiner.equals(that.combiner))
 778             return false;
 779 
 780         return true;
 781     }
 782 
 783     private boolean equalPDs(ProtectionDomain[] a, ProtectionDomain[] b) {
 784         if (a == null) {
 785             return (b == null);
 786         }
 787 
 788         if (b == null)
 789             return false;
 790 
 791         if (!(containsAllPDs(a, b) && containsAllPDs(b, a)))
 792             return false;
 793 
 794         return true;
 795     }
 796 
 797     /*
 798      * Compare for equality based on state that is captured during a
 799      * call to AccessController.getContext() when a limited privilege
 800      * scope is in effect.
 801      */
 802     private boolean equalLimitedContext(AccessControlContext that) {
 803         if (that == null)
 804             return false;
 805 
 806         /*
 807          * If neither instance has limited privilege scope then we're done.
 808          */
 809         if (!this.isLimited && !that.isLimited)
 810             return true;
 811 
 812         /*
 813          * If only one instance has limited privilege scope then we're done.
 814          */
 815          if (!(this.isLimited && that.isLimited))
 816              return false;
 817 
 818         /*
 819          * Wrapped instances should never escape outside the implementation
 820          * this class and AccessController so this will probably never happen
 821          * but it only makes any sense to compare if they both have the same
 822          * isWrapped state.
 823          */
 824         if ((this.isWrapped && !that.isWrapped) ||
 825             (!this.isWrapped && that.isWrapped)) {
 826             return false;
 827         }
 828 
 829         if (this.permissions == null && that.permissions != null)
 830             return false;
 831 
 832         if (this.permissions != null && that.permissions == null)
 833             return false;
 834 
 835         if (!(this.containsAllLimits(that) && that.containsAllLimits(this)))
 836             return false;
 837 
 838         /*
 839          * Skip through any wrapped contexts.
 840          */
 841         AccessControlContext thisNextPC = getNextPC(this);
 842         AccessControlContext thatNextPC = getNextPC(that);
 843 
 844         /*
 845          * The protection domains and combiner of a privilegedContext are
 846          * not relevant because they have already been included in the context
 847          * of this instance by optimize() so we only care about any limited
 848          * privilege state they may have.
 849          */
 850         if (thisNextPC == null && thatNextPC != null && thatNextPC.isLimited)
 851             return false;
 852 
 853         if (thisNextPC != null && !thisNextPC.equalLimitedContext(thatNextPC))
 854             return false;
 855 
 856         if (this.parent == null && that.parent != null)
 857             return false;
 858 
 859         if (this.parent != null && !this.parent.equals(that.parent))
 860             return false;
 861 
 862         return true;
 863     }
 864 
 865     /*
 866      * Follow the privilegedContext link making our best effort to skip
 867      * through any wrapper contexts.
 868      */
 869     private static AccessControlContext getNextPC(AccessControlContext acc) {
 870         while (acc != null && acc.privilegedContext != null) {
 871             acc = acc.privilegedContext;
 872             if (!acc.isWrapped)
 873                 return acc;
 874         }
 875         return null;
 876     }
 877 
 878     private static boolean containsAllPDs(ProtectionDomain[] thisContext,
 879         ProtectionDomain[] thatContext) {
 880         boolean match = false;
 881 
 882         //
 883         // ProtectionDomains within an ACC currently cannot be null
 884         // and this is enforced by the constructor and the various
 885         // optimize methods. However, historically this logic made attempts
 886         // to support the notion of a null PD and therefore this logic continues
 887         // to support that notion.
 888         ProtectionDomain thisPd;
 889         for (int i = 0; i < thisContext.length; i++) {
 890             match = false;
 891             if ((thisPd = thisContext[i]) == null) {
 892                 for (int j = 0; (j < thatContext.length) && !match; j++) {
 893                     match = (thatContext[j] == null);
 894                 }
 895             } else {
 896                 Class<?> thisPdClass = thisPd.getClass();
 897                 ProtectionDomain thatPd;
 898                 for (int j = 0; (j < thatContext.length) && !match; j++) {
 899                     thatPd = thatContext[j];
 900 
 901                     // Class check required to avoid PD exposure (4285406)
 902                     match = (thatPd != null &&
 903                         thisPdClass == thatPd.getClass() && thisPd.equals(thatPd));
 904                 }
 905             }
 906             if (!match) return false;
 907         }
 908         return match;
 909     }
 910 
 911     private boolean containsAllLimits(AccessControlContext that) {
 912         boolean match = false;
 913         Permission thisPerm;
 914 
 915         if (this.permissions == null && that.permissions == null)
 916             return true;
 917 
 918         for (int i = 0; i < this.permissions.length; i++) {
 919             Permission limit = this.permissions[i];
 920             Class <?> limitClass = limit.getClass();
 921             match = false;
 922             for (int j = 0; (j < that.permissions.length) && !match; j++) {
 923                 Permission perm = that.permissions[j];
 924                 match = (limitClass.equals(perm.getClass()) &&
 925                     limit.equals(perm));
 926             }
 927             if (!match) return false;
 928         }
 929         return match;
 930     }
 931 
 932 
 933     /**
 934      * Returns the hash code value for this context. The hash code
 935      * is computed by exclusive or-ing the hash code of all the protection
 936      * domains in the context together.
 937      *
 938      * @return a hash code value for this context.
 939      */
 940 
 941     public int hashCode() {
 942         int hashCode = 0;
 943 
 944         if (context == null)
 945             return hashCode;
 946 
 947         for (int i =0; i < context.length; i++) {
 948             if (context[i] != null)
 949                 hashCode ^= context[i].hashCode();
 950         }
 951 
 952         return hashCode;
 953     }
 954 }