1 /*
   2  * Copyright (c) 2010, 2013, 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 jdk.nashorn.internal.runtime;
  27 
  28 import static jdk.internal.org.objectweb.asm.Opcodes.V1_7;
  29 import static jdk.nashorn.internal.codegen.CompilerConstants.CONSTANTS;
  30 import static jdk.nashorn.internal.codegen.CompilerConstants.CREATE_PROGRAM_FUNCTION;
  31 import static jdk.nashorn.internal.codegen.CompilerConstants.SOURCE;
  32 import static jdk.nashorn.internal.codegen.CompilerConstants.STRICT_MODE;
  33 import static jdk.nashorn.internal.runtime.CodeStore.newCodeStore;
  34 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
  35 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
  36 import static jdk.nashorn.internal.runtime.Source.sourceFor;
  37 
  38 import java.io.File;
  39 import java.io.IOException;
  40 import java.io.PrintWriter;
  41 import java.lang.invoke.MethodHandle;
  42 import java.lang.invoke.MethodHandles;
  43 import java.lang.invoke.MethodType;
  44 import java.lang.invoke.SwitchPoint;
  45 import java.lang.ref.Reference;
  46 import java.lang.ref.ReferenceQueue;
  47 import java.lang.ref.SoftReference;
  48 import java.lang.ref.WeakReference;
  49 import java.lang.reflect.Field;
  50 import java.lang.reflect.Modifier;
  51 import java.net.MalformedURLException;
  52 import java.net.URL;
  53 import java.security.AccessControlContext;
  54 import java.security.AccessController;
  55 import java.security.CodeSigner;
  56 import java.security.CodeSource;
  57 import java.security.Permissions;
  58 import java.security.PrivilegedAction;
  59 import java.security.PrivilegedActionException;
  60 import java.security.PrivilegedExceptionAction;
  61 import java.security.ProtectionDomain;
  62 import java.util.Collection;
  63 import java.util.HashMap;
  64 import java.util.LinkedHashMap;
  65 import java.util.Map;
  66 import java.util.Objects;
  67 import java.util.concurrent.atomic.AtomicLong;
  68 import java.util.concurrent.atomic.AtomicReference;
  69 import java.util.concurrent.atomic.LongAdder;
  70 import java.util.function.Consumer;
  71 import java.util.function.Supplier;
  72 import java.util.logging.Level;
  73 import javax.script.ScriptContext;
  74 import javax.script.ScriptEngine;
  75 import jdk.internal.org.objectweb.asm.ClassReader;
  76 import jdk.internal.org.objectweb.asm.ClassWriter;
  77 import jdk.internal.org.objectweb.asm.Opcodes;
  78 import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
  79 import jdk.nashorn.api.scripting.ClassFilter;
  80 import jdk.nashorn.api.scripting.ScriptObjectMirror;
  81 import jdk.nashorn.internal.codegen.Compiler;
  82 import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
  83 import jdk.nashorn.internal.codegen.ObjectClassGenerator;
  84 import jdk.nashorn.internal.ir.FunctionNode;
  85 import jdk.nashorn.internal.ir.debug.ASTWriter;
  86 import jdk.nashorn.internal.ir.debug.PrintVisitor;
  87 import jdk.nashorn.internal.lookup.MethodHandleFactory;
  88 import jdk.nashorn.internal.objects.Global;
  89 import jdk.nashorn.internal.parser.Parser;
  90 import jdk.nashorn.internal.runtime.events.RuntimeEvent;
  91 import jdk.nashorn.internal.runtime.logging.DebugLogger;
  92 import jdk.nashorn.internal.runtime.logging.Loggable;
  93 import jdk.nashorn.internal.runtime.logging.Logger;
  94 import jdk.nashorn.internal.runtime.options.LoggingOption.LoggerInfo;
  95 import jdk.nashorn.internal.runtime.options.Options;
  96 import sun.misc.Unsafe;
  97 
  98 /**
  99  * This class manages the global state of execution. Context is immutable.
 100  */
 101 public final class Context {
 102     // nashorn specific security runtime access permission names
 103     /**
 104      * Permission needed to pass arbitrary nashorn command line options when creating Context.
 105      */
 106     public static final String NASHORN_SET_CONFIG      = "nashorn.setConfig";
 107 
 108     /**
 109      * Permission needed to create Nashorn Context instance.
 110      */
 111     public static final String NASHORN_CREATE_CONTEXT  = "nashorn.createContext";
 112 
 113     /**
 114      * Permission needed to create Nashorn Global instance.
 115      */
 116     public static final String NASHORN_CREATE_GLOBAL   = "nashorn.createGlobal";
 117 
 118     /**
 119      * Permission to get current Nashorn Context from thread local storage.
 120      */
 121     public static final String NASHORN_GET_CONTEXT     = "nashorn.getContext";
 122 
 123     /**
 124      * Permission to use Java reflection/jsr292 from script code.
 125      */
 126     public static final String NASHORN_JAVA_REFLECTION = "nashorn.JavaReflection";
 127 
 128     /**
 129      * Permission to enable nashorn debug mode.
 130      */
 131     public static final String NASHORN_DEBUG_MODE = "nashorn.debugMode";
 132 
 133     // nashorn load psuedo URL prefixes
 134     private static final String LOAD_CLASSPATH = "classpath:";
 135     private static final String LOAD_FX = "fx:";
 136     private static final String LOAD_NASHORN = "nashorn:";
 137 
 138     private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
 139     private static final MethodType CREATE_PROGRAM_FUNCTION_TYPE = MethodType.methodType(ScriptFunction.class, ScriptObject.class);
 140 
 141     private static final LongAdder NAMED_INSTALLED_SCRIPT_COUNT = new LongAdder();
 142     private static final LongAdder ANONYMOUS_INSTALLED_SCRIPT_COUNT = new LongAdder();
 143 
 144     /**
 145      * Should scripts use only object slots for fields, or dual long/object slots? The default
 146      * behaviour is to couple this to optimistic types, using dual representation if optimistic types are enabled
 147      * and single field representation otherwise. This can be overridden by setting either the "nashorn.fields.objects"
 148      * or "nashorn.fields.dual" system property.
 149      */
 150     private final FieldMode fieldMode;
 151 
 152     private static enum FieldMode {
 153         /** Value for automatic field representation depending on optimistic types setting */
 154         AUTO,
 155         /** Value for object field representation regardless of optimistic types setting */
 156         OBJECTS,
 157         /** Value for dual primitive/object field representation regardless of optimistic types setting */
 158         DUAL
 159     }
 160 
 161     /**
 162      * Keeps track of which builtin prototypes and properties have been relinked
 163      * Currently we are conservative and associate the name of a builtin class with all
 164      * its properties, so it's enough to invalidate a property to break all assumptions
 165      * about a prototype. This can be changed to a more fine grained approach, but no one
 166      * ever needs this, given the very rare occurrence of swapping out only parts of
 167      * a builtin v.s. the entire builtin object
 168      */
 169     private final Map<String, SwitchPoint> builtinSwitchPoints = new HashMap<>();
 170 
 171     /* Force DebuggerSupport to be loaded. */
 172     static {
 173         DebuggerSupport.FORCELOAD = true;
 174     }
 175 
 176     static long getNamedInstalledScriptCount() {
 177         return NAMED_INSTALLED_SCRIPT_COUNT.sum();
 178     }
 179 
 180     static long getAnonymousInstalledScriptCount() {
 181         return ANONYMOUS_INSTALLED_SCRIPT_COUNT.sum();
 182     }
 183 
 184     /**
 185      * ContextCodeInstaller that has the privilege of installing classes in the Context.
 186      * Can only be instantiated from inside the context and is opaque to other classes
 187      */
 188     private abstract static class ContextCodeInstaller implements CodeInstaller {
 189         final Context context;
 190         final CodeSource codeSource;
 191 
 192         ContextCodeInstaller(final Context context, final CodeSource codeSource) {
 193             this.context = context;
 194             this.codeSource = codeSource;
 195         }
 196 
 197         @Override
 198         public Context getContext() {
 199             return context;
 200         }
 201 
 202         @Override
 203         public void initialize(final Collection<Class<?>> classes, final Source source, final Object[] constants) {
 204             try {
 205                 AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
 206                     @Override
 207                     public Void run() throws Exception {
 208                         for (final Class<?> clazz : classes) {
 209                             //use reflection to write source and constants table to installed classes
 210                             final Field sourceField = clazz.getDeclaredField(SOURCE.symbolName());
 211                             sourceField.setAccessible(true);
 212                             sourceField.set(null, source);
 213 
 214                             final Field constantsField = clazz.getDeclaredField(CONSTANTS.symbolName());
 215                             constantsField.setAccessible(true);
 216                             constantsField.set(null, constants);
 217                         }
 218                         return null;
 219                     }
 220                 });
 221             } catch (final PrivilegedActionException e) {
 222                 throw new RuntimeException(e);
 223             }
 224         }
 225 
 226         @Override
 227         public void verify(final byte[] code) {
 228             context.verify(code);
 229         }
 230 
 231         @Override
 232         public long getUniqueScriptId() {
 233             return context.getUniqueScriptId();
 234         }
 235 
 236         @Override
 237         public void storeScript(final String cacheKey, final Source source, final String mainClassName,
 238                                 final Map<String,byte[]> classBytes, final Map<Integer, FunctionInitializer> initializers,
 239                                 final Object[] constants, final int compilationId) {
 240             if (context.codeStore != null) {
 241                 context.codeStore.store(cacheKey, source, mainClassName, classBytes, initializers, constants, compilationId);
 242             }
 243         }
 244 
 245         @Override
 246         public StoredScript loadScript(final Source source, final String functionKey) {
 247             if (context.codeStore != null) {
 248                 return context.codeStore.load(source, functionKey);
 249             }
 250             return null;
 251         }
 252 
 253         @Override
 254         public boolean isCompatibleWith(final CodeInstaller other) {
 255             if (other instanceof ContextCodeInstaller) {
 256                 final ContextCodeInstaller cci = (ContextCodeInstaller)other;
 257                 return cci.context == context && cci.codeSource == codeSource;
 258             }
 259             return false;
 260         }
 261     }
 262 
 263     private static class NamedContextCodeInstaller extends ContextCodeInstaller {
 264         private final ScriptLoader loader;
 265         private int usageCount = 0;
 266         private int bytesDefined = 0;
 267 
 268         // We reuse this installer for 10 compilations or 200000 defined bytes. Usually the first condition
 269         // will occur much earlier, the second is a safety measure for very large scripts/functions.
 270         private final static int MAX_USAGES = 10;
 271         private final static int MAX_BYTES_DEFINED = 200_000;
 272 
 273         private NamedContextCodeInstaller(final Context context, final CodeSource codeSource, final ScriptLoader loader) {
 274             super(context, codeSource);
 275             this.loader = loader;
 276         }
 277 
 278         @Override
 279         public Class<?> install(final String className, final byte[] bytecode) {
 280             usageCount++;
 281             bytesDefined += bytecode.length;
 282             NAMED_INSTALLED_SCRIPT_COUNT.increment();
 283             return loader.installClass(Compiler.binaryName(className), bytecode, codeSource);
 284         }
 285 
 286         @Override
 287         public CodeInstaller getOnDemandCompilationInstaller() {
 288             // Reuse this installer if we're within our limits.
 289             if (usageCount < MAX_USAGES && bytesDefined < MAX_BYTES_DEFINED) {
 290                 return this;
 291             }
 292             return new NamedContextCodeInstaller(context, codeSource, context.createNewLoader());
 293         }
 294 
 295         @Override
 296         public CodeInstaller getMultiClassCodeInstaller() {
 297             // This installer is perfectly suitable for installing multiple classes that reference each other
 298             // as it produces classes with resolvable names, all defined in a single class loader.
 299             return this;
 300         }
 301     }
 302 
 303     private final Map<CodeSource, HostClassReference> anonymousHostClasses = new HashMap<>();
 304     private final ReferenceQueue<Class<?>> anonymousHostClassesRefQueue = new ReferenceQueue<>();
 305 
 306     private static class HostClassReference extends WeakReference<Class<?>> {
 307         final CodeSource codeSource;
 308 
 309         HostClassReference(final CodeSource codeSource, final Class<?> clazz, final ReferenceQueue<Class<?>> refQueue) {
 310             super(clazz, refQueue);
 311             this.codeSource = codeSource;
 312         }
 313     }
 314 
 315     private synchronized Class<?> getAnonymousHostClass(final CodeSource codeSource) {
 316         // Remove cleared entries
 317         for(;;) {
 318             final HostClassReference clearedRef = (HostClassReference)anonymousHostClassesRefQueue.poll();
 319             if (clearedRef == null) {
 320                 break;
 321             }
 322             anonymousHostClasses.remove(clearedRef.codeSource, clearedRef);
 323         }
 324 
 325         // Try to find an existing host class
 326         final Reference<Class<?>> ref = anonymousHostClasses.get(codeSource);
 327         if (ref != null) {
 328             final Class<?> existingHostClass = ref.get();
 329             if (existingHostClass != null) {
 330                 return existingHostClass;
 331             }
 332         }
 333 
 334         // Define a new host class if existing is not found
 335         final Class<?> newHostClass = createNewLoader().installClass(
 336                 // NOTE: we're defining these constants in AnonymousContextCodeInstaller so they are not
 337                 // initialized if we don't use AnonymousContextCodeInstaller. As this method is only ever
 338                 // invoked from AnonymousContextCodeInstaller, this is okay.
 339                 AnonymousContextCodeInstaller.ANONYMOUS_HOST_CLASS_NAME,
 340                 AnonymousContextCodeInstaller.ANONYMOUS_HOST_CLASS_BYTES, codeSource);
 341         anonymousHostClasses.put(codeSource, new HostClassReference(codeSource, newHostClass, anonymousHostClassesRefQueue));
 342         return newHostClass;
 343     }
 344 
 345     private static final class AnonymousContextCodeInstaller extends ContextCodeInstaller {
 346         private static final Unsafe UNSAFE = getUnsafe();
 347         private static final String ANONYMOUS_HOST_CLASS_NAME = Compiler.SCRIPTS_PACKAGE.replace('/', '.') + ".AnonymousHost";
 348         private static final byte[] ANONYMOUS_HOST_CLASS_BYTES = getAnonymousHostClassBytes();
 349 
 350         private final Class<?> hostClass;
 351 
 352         private AnonymousContextCodeInstaller(final Context context, final CodeSource codeSource, final Class<?> hostClass) {
 353             super(context, codeSource);
 354             this.hostClass = hostClass;
 355         }
 356 
 357         @Override
 358         public Class<?> install(final String className, final byte[] bytecode) {
 359             ANONYMOUS_INSTALLED_SCRIPT_COUNT.increment();
 360             return UNSAFE.defineAnonymousClass(hostClass, bytecode, null);
 361         }
 362 
 363         @Override
 364         public CodeInstaller getOnDemandCompilationInstaller() {
 365             // This code loader can be indefinitely reused for on-demand recompilations for the same code source.
 366             return this;
 367         }
 368 
 369         @Override
 370         public CodeInstaller getMultiClassCodeInstaller() {
 371             // This code loader can not be used to install multiple classes that reference each other, as they
 372             // would have no resolvable names. Therefore, in such situation we must revert to an installer that
 373             // produces named classes.
 374             return new NamedContextCodeInstaller(context, codeSource, context.createNewLoader());
 375         }
 376 
 377         private static final byte[] getAnonymousHostClassBytes() {
 378             final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
 379             cw.visit(V1_7, Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT, ANONYMOUS_HOST_CLASS_NAME.replace('.', '/'), null, "java/lang/Object", null);
 380             cw.visitEnd();
 381             return cw.toByteArray();
 382         }
 383 
 384         private static Unsafe getUnsafe() {
 385             return AccessController.doPrivileged(new PrivilegedAction<Unsafe>() {
 386                 @Override
 387                 public Unsafe run() {
 388                     try {
 389                         final Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
 390                         theUnsafeField.setAccessible(true);
 391                         return (Unsafe)theUnsafeField.get(null);
 392                     } catch (final ReflectiveOperationException e) {
 393                         throw new RuntimeException(e);
 394                     }
 395                 }
 396             });
 397         }
 398     }
 399 
 400     /** Is Context global debug mode enabled ? */
 401     public static final boolean DEBUG = Options.getBooleanProperty("nashorn.debug");
 402 
 403     private static final ThreadLocal<Global> currentGlobal = new ThreadLocal<>();
 404 
 405     // in-memory cache for loaded classes
 406     private ClassCache classCache;
 407 
 408     // persistent code store
 409     private CodeStore codeStore;
 410 
 411     // A factory for linking global properties as constant method handles. It is created when the first Global
 412     // is created, and invalidated forever once the second global is created.
 413     private final AtomicReference<GlobalConstants> globalConstantsRef = new AtomicReference<>();
 414 
 415     /**
 416      * Get the current global scope
 417      * @return the current global scope
 418      */
 419     public static Global getGlobal() {
 420         // This class in a package.access protected package.
 421         // Trusted code only can call this method.
 422         return currentGlobal.get();
 423     }
 424 
 425     /**
 426      * Set the current global scope
 427      * @param global the global scope
 428      */
 429     public static void setGlobal(final ScriptObject global) {
 430         if (global != null && !(global instanceof Global)) {
 431             throw new IllegalArgumentException("not a global!");
 432         }
 433         setGlobal((Global)global);
 434     }
 435 
 436     /**
 437      * Set the current global scope
 438      * @param global the global scope
 439      */
 440     public static void setGlobal(final Global global) {
 441         // This class in a package.access protected package.
 442         // Trusted code only can call this method.
 443         assert getGlobal() != global;
 444         //same code can be cached between globals, then we need to invalidate method handle constants
 445         if (global != null) {
 446             final GlobalConstants globalConstants = getContext(global).getGlobalConstants();
 447             if (globalConstants != null) {
 448                 globalConstants.invalidateAll();
 449             }
 450         }
 451         currentGlobal.set(global);
 452     }
 453 
 454     /**
 455      * Get context of the current global
 456      * @return current global scope's context.
 457      */
 458     public static Context getContext() {
 459         final SecurityManager sm = System.getSecurityManager();
 460         if (sm != null) {
 461             sm.checkPermission(new RuntimePermission(NASHORN_GET_CONTEXT));
 462         }
 463         return getContextTrusted();
 464     }
 465 
 466     /**
 467      * Get current context's error writer
 468      *
 469      * @return error writer of the current context
 470      */
 471     public static PrintWriter getCurrentErr() {
 472         final ScriptObject global = getGlobal();
 473         return (global != null)? global.getContext().getErr() : new PrintWriter(System.err);
 474     }
 475 
 476     /**
 477      * Output text to this Context's error stream
 478      * @param str text to write
 479      */
 480     public static void err(final String str) {
 481         err(str, true);
 482     }
 483 
 484     /**
 485      * Output text to this Context's error stream, optionally with
 486      * a newline afterwards
 487      *
 488      * @param str  text to write
 489      * @param crlf write a carriage return/new line after text
 490      */
 491     public static void err(final String str, final boolean crlf) {
 492         final PrintWriter err = Context.getCurrentErr();
 493         if (err != null) {
 494             if (crlf) {
 495                 err.println(str);
 496             } else {
 497                 err.print(str);
 498             }
 499         }
 500     }
 501 
 502     /** Current environment. */
 503     private final ScriptEnvironment env;
 504 
 505     /** is this context in strict mode? Cached from env. as this is used heavily. */
 506     final boolean _strict;
 507 
 508     /** class loader to resolve classes from script. */
 509     private final ClassLoader appLoader;
 510 
 511     /*package-private*/
 512     ClassLoader getAppLoader() {
 513         return appLoader;
 514     }
 515 
 516     /** Class loader to load classes compiled from scripts. */
 517     private final ScriptLoader scriptLoader;
 518 
 519     /** Current error manager. */
 520     private final ErrorManager errors;
 521 
 522     /** Unique id for script. Used only when --loader-per-compile=false */
 523     private final AtomicLong uniqueScriptId;
 524 
 525     /** Optional class filter to use for Java classes. Can be null. */
 526     private final ClassFilter classFilter;
 527 
 528     private static final ClassLoader myLoader = Context.class.getClassLoader();
 529     /** Process-wide singleton structure loader */
 530     private static final StructureLoader theStructLoader;
 531 
 532     /*package-private*/ @SuppressWarnings("static-method")
 533     ClassLoader getStructLoader() {
 534         return theStructLoader;
 535     }
 536 
 537     private static AccessControlContext createNoPermAccCtxt() {
 538         return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) });
 539     }
 540 
 541     private static AccessControlContext createPermAccCtxt(final String permName) {
 542         final Permissions perms = new Permissions();
 543         perms.add(new RuntimePermission(permName));
 544         return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
 545     }
 546 
 547     private static final AccessControlContext NO_PERMISSIONS_ACC_CTXT = createNoPermAccCtxt();
 548     private static final AccessControlContext CREATE_LOADER_ACC_CTXT  = createPermAccCtxt("createClassLoader");
 549     private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT  = createPermAccCtxt(NASHORN_CREATE_GLOBAL);
 550 
 551     static {
 552         theStructLoader = AccessController.doPrivileged(new PrivilegedAction<StructureLoader>() {
 553             @Override
 554             public StructureLoader run() {
 555                 return new StructureLoader(myLoader);
 556             }
 557         }, CREATE_LOADER_ACC_CTXT);
 558     }
 559 
 560     /**
 561      * ThrowErrorManager that throws ParserException upon error conditions.
 562      */
 563     public static class ThrowErrorManager extends ErrorManager {
 564         @Override
 565         public void error(final String message) {
 566             throw new ParserException(message);
 567         }
 568 
 569         @Override
 570         public void error(final ParserException e) {
 571             throw e;
 572         }
 573     }
 574 
 575     /**
 576      * Constructor
 577      *
 578      * @param options options from command line or Context creator
 579      * @param errors  error manger
 580      * @param appLoader application class loader
 581      */
 582     public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader) {
 583         this(options, errors, appLoader, null);
 584     }
 585 
 586     /**
 587      * Constructor
 588      *
 589      * @param options options from command line or Context creator
 590      * @param errors  error manger
 591      * @param appLoader application class loader
 592      * @param classFilter class filter to use
 593      */
 594     public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader, final ClassFilter classFilter) {
 595         this(options, errors, new PrintWriter(System.out, true), new PrintWriter(System.err, true), appLoader, classFilter);
 596     }
 597 
 598     /**
 599      * Constructor
 600      *
 601      * @param options options from command line or Context creator
 602      * @param errors  error manger
 603      * @param out     output writer for this Context
 604      * @param err     error writer for this Context
 605      * @param appLoader application class loader
 606      */
 607     public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader) {
 608         this(options, errors, out, err, appLoader, (ClassFilter)null);
 609     }
 610 
 611     /**
 612      * Constructor
 613      *
 614      * @param options options from command line or Context creator
 615      * @param errors  error manger
 616      * @param out     output writer for this Context
 617      * @param err     error writer for this Context
 618      * @param appLoader application class loader
 619      * @param classFilter class filter to use
 620      */
 621     public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader, final ClassFilter classFilter) {
 622         final SecurityManager sm = System.getSecurityManager();
 623         if (sm != null) {
 624             sm.checkPermission(new RuntimePermission(NASHORN_CREATE_CONTEXT));
 625         }
 626 
 627         this.classFilter = classFilter;
 628         this.env       = new ScriptEnvironment(options, out, err);
 629         this._strict   = env._strict;
 630         if (env._loader_per_compile) {
 631             this.scriptLoader = null;
 632             this.uniqueScriptId = null;
 633         } else {
 634             this.scriptLoader = createNewLoader();
 635             this.uniqueScriptId = new AtomicLong();
 636         }
 637         this.errors    = errors;
 638 
 639         // if user passed -classpath option, make a URLClassLoader with that and
 640         // the app loader as the parent.
 641         final String classPath = options.getString("classpath");
 642         if (!env._compile_only && classPath != null && !classPath.isEmpty()) {
 643             // make sure that caller can create a class loader.
 644             if (sm != null) {
 645                 sm.checkCreateClassLoader();
 646             }
 647             this.appLoader = NashornLoader.createClassLoader(classPath, appLoader);
 648         } else {
 649             this.appLoader = appLoader;
 650         }
 651 
 652         final int cacheSize = env._class_cache_size;
 653         if (cacheSize > 0) {
 654             classCache = new ClassCache(cacheSize);
 655         }
 656 
 657         if (env._persistent_cache) {
 658             codeStore = newCodeStore(this);
 659         }
 660 
 661         // print version info if asked.
 662         if (env._version) {
 663             getErr().println("nashorn " + Version.version());
 664         }
 665 
 666         if (env._fullversion) {
 667             getErr().println("nashorn full version " + Version.fullVersion());
 668         }
 669 
 670         if (Options.getBooleanProperty("nashorn.fields.dual")) {
 671             fieldMode = FieldMode.DUAL;
 672         } else if (Options.getBooleanProperty("nashorn.fields.objects")) {
 673             fieldMode = FieldMode.OBJECTS;
 674         } else {
 675             fieldMode = FieldMode.AUTO;
 676         }
 677 
 678         initLoggers();
 679     }
 680 
 681 
 682     /**
 683      * Get the class filter for this context
 684      * @return class filter
 685      */
 686     public ClassFilter getClassFilter() {
 687         return classFilter;
 688     }
 689 
 690     /**
 691      * Returns the factory for constant method handles for global properties. The returned factory can be
 692      * invalidated if this Context has more than one Global.
 693      * @return the factory for constant method handles for global properties.
 694      */
 695     GlobalConstants getGlobalConstants() {
 696         return globalConstantsRef.get();
 697     }
 698 
 699     /**
 700      * Get the error manager for this context
 701      * @return error manger
 702      */
 703     public ErrorManager getErrorManager() {
 704         return errors;
 705     }
 706 
 707     /**
 708      * Get the script environment for this context
 709      * @return script environment
 710      */
 711     public ScriptEnvironment getEnv() {
 712         return env;
 713     }
 714 
 715     /**
 716      * Get the output stream for this context
 717      * @return output print writer
 718      */
 719     public PrintWriter getOut() {
 720         return env.getOut();
 721     }
 722 
 723     /**
 724      * Get the error stream for this context
 725      * @return error print writer
 726      */
 727     public PrintWriter getErr() {
 728         return env.getErr();
 729     }
 730 
 731     /**
 732      * Should scripts compiled by this context use dual field representation?
 733      * @return true if using dual fields, false for object-only fields
 734      */
 735     public boolean useDualFields() {
 736         return fieldMode == FieldMode.DUAL || (fieldMode == FieldMode.AUTO && env._optimistic_types);
 737     }
 738 
 739     /**
 740      * Get the PropertyMap of the current global scope
 741      * @return the property map of the current global scope
 742      */
 743     public static PropertyMap getGlobalMap() {
 744         return Context.getGlobal().getMap();
 745     }
 746 
 747     /**
 748      * Compile a top level script.
 749      *
 750      * @param source the source
 751      * @param scope  the scope
 752      *
 753      * @return top level function for script
 754      */
 755     public ScriptFunction compileScript(final Source source, final ScriptObject scope) {
 756         return compileScript(source, scope, this.errors);
 757     }
 758 
 759     /**
 760      * Interface to represent compiled code that can be re-used across many
 761      * global scope instances
 762      */
 763     public static interface MultiGlobalCompiledScript {
 764         /**
 765          * Obtain script function object for a specific global scope object.
 766          *
 767          * @param newGlobal global scope for which function object is obtained
 768          * @return script function for script level expressions
 769          */
 770         public ScriptFunction getFunction(final Global newGlobal);
 771     }
 772 
 773     /**
 774      * Compile a top level script.
 775      *
 776      * @param source the script source
 777      * @return reusable compiled script across many global scopes.
 778      */
 779     public MultiGlobalCompiledScript compileScript(final Source source) {
 780         final Class<?> clazz = compile(source, this.errors, this._strict, false);
 781         final MethodHandle createProgramFunctionHandle = getCreateProgramFunctionHandle(clazz);
 782 
 783         return new MultiGlobalCompiledScript() {
 784             @Override
 785             public ScriptFunction getFunction(final Global newGlobal) {
 786                 return invokeCreateProgramFunctionHandle(createProgramFunctionHandle, newGlobal);
 787             }
 788         };
 789     }
 790 
 791     /**
 792      * Entry point for {@code eval}
 793      *
 794      * @param initialScope The scope of this eval call
 795      * @param string       Evaluated code as a String
 796      * @param callThis     "this" to be passed to the evaluated code
 797      * @param location     location of the eval call
 798      * @return the return value of the {@code eval}
 799      */
 800     public Object eval(final ScriptObject initialScope, final String string,
 801             final Object callThis, final Object location) {
 802         return eval(initialScope, string, callThis, location, false, false);
 803     }
 804 
 805     /**
 806      * Entry point for {@code eval}
 807      *
 808      * @param initialScope The scope of this eval call
 809      * @param string       Evaluated code as a String
 810      * @param callThis     "this" to be passed to the evaluated code
 811      * @param location     location of the eval call
 812      * @param strict       is this {@code eval} call from a strict mode code?
 813      * @param evalCall     is this called from "eval" builtin?
 814      *
 815      * @return the return value of the {@code eval}
 816      */
 817     public Object eval(final ScriptObject initialScope, final String string,
 818             final Object callThis, final Object location, final boolean strict, final boolean evalCall) {
 819         final String  file       = location == UNDEFINED || location == null ? "<eval>" : location.toString();
 820         final Source  source     = sourceFor(file, string, evalCall);
 821         // is this direct 'eval' builtin call?
 822         final boolean directEval = evalCall && (location != UNDEFINED);
 823         final Global  global = Context.getGlobal();
 824         ScriptObject scope = initialScope;
 825 
 826         // ECMA section 10.1.1 point 2 says eval code is strict if it begins
 827         // with "use strict" directive or eval direct call itself is made
 828         // from from strict mode code. We are passed with caller's strict mode.
 829         // Nashorn extension: any 'eval' is unconditionally strict when -strict is specified.
 830         boolean strictFlag = strict || this._strict;
 831 
 832         Class<?> clazz = null;
 833         try {
 834             clazz = compile(source, new ThrowErrorManager(), strictFlag, true);
 835         } catch (final ParserException e) {
 836             e.throwAsEcmaException(global);
 837             return null;
 838         }
 839 
 840         if (!strictFlag) {
 841             // We need to get strict mode flag from compiled class. This is
 842             // because eval code may start with "use strict" directive.
 843             try {
 844                 strictFlag = clazz.getField(STRICT_MODE.symbolName()).getBoolean(null);
 845             } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
 846                 //ignored
 847                 strictFlag = false;
 848             }
 849         }
 850 
 851         // In strict mode, eval does not instantiate variables and functions
 852         // in the caller's environment. A new environment is created!
 853         if (strictFlag) {
 854             // Create a new scope object with given scope as its prototype
 855             scope = newScope(scope);
 856         }
 857 
 858         final ScriptFunction func = getProgramFunction(clazz, scope);
 859         Object evalThis;
 860         if (directEval) {
 861             evalThis = (callThis != UNDEFINED && callThis != null) || strictFlag ? callThis : global;
 862         } else {
 863             // either indirect evalCall or non-eval (Function, engine.eval, ScriptObjectMirror.eval..)
 864             evalThis = callThis;
 865         }
 866 
 867         return ScriptRuntime.apply(func, evalThis);
 868     }
 869 
 870     private static ScriptObject newScope(final ScriptObject callerScope) {
 871         return new Scope(callerScope, PropertyMap.newMap(Scope.class));
 872     }
 873 
 874     private static Source loadInternal(final String srcStr, final String prefix, final String resourcePath) {
 875         if (srcStr.startsWith(prefix)) {
 876             final String resource = resourcePath + srcStr.substring(prefix.length());
 877             // NOTE: even sandbox scripts should be able to load scripts in nashorn: scheme
 878             // These scripts are always available and are loaded from nashorn.jar's resources.
 879             return AccessController.doPrivileged(
 880                     new PrivilegedAction<Source>() {
 881                         @Override
 882                         public Source run() {
 883                             try {
 884                                 final URL resURL = Context.class.getResource(resource);
 885                                 return resURL != null ? sourceFor(srcStr, resURL) : null;
 886                             } catch (final IOException exp) {
 887                                 return null;
 888                             }
 889                         }
 890                     });
 891         }
 892 
 893         return null;
 894     }
 895 
 896     /**
 897      * Implementation of {@code load} Nashorn extension. Load a script file from a source
 898      * expression
 899      *
 900      * @param scope  the scope
 901      * @param from   source expression for script
 902      *
 903      * @return return value for load call (undefined)
 904      *
 905      * @throws IOException if source cannot be found or loaded
 906      */
 907     public Object load(final Object scope, final Object from) throws IOException {
 908         final Object src = from instanceof ConsString ? from.toString() : from;
 909         Source source = null;
 910 
 911         // load accepts a String (which could be a URL or a file name), a File, a URL
 912         // or a ScriptObject that has "name" and "source" (string valued) properties.
 913         if (src instanceof String) {
 914             final String srcStr = (String)src;
 915             if (srcStr.startsWith(LOAD_CLASSPATH)) {
 916                 final URL url = getResourceURL(srcStr.substring(LOAD_CLASSPATH.length()));
 917                 source = url != null ? sourceFor(url.toString(), url) : null;
 918             } else {
 919                 final File file = new File(srcStr);
 920                 if (srcStr.indexOf(':') != -1) {
 921                     if ((source = loadInternal(srcStr, LOAD_NASHORN, "resources/")) == null &&
 922                         (source = loadInternal(srcStr, LOAD_FX, "resources/fx/")) == null) {
 923                         URL url;
 924                         try {
 925                             //check for malformed url. if malformed, it may still be a valid file
 926                             url = new URL(srcStr);
 927                         } catch (final MalformedURLException e) {
 928                             url = file.toURI().toURL();
 929                         }
 930                         source = sourceFor(url.toString(), url);
 931                     }
 932                 } else if (file.isFile()) {
 933                     source = sourceFor(srcStr, file);
 934                 }
 935             }
 936         } else if (src instanceof File && ((File)src).isFile()) {
 937             final File file = (File)src;
 938             source = sourceFor(file.getName(), file);
 939         } else if (src instanceof URL) {
 940             final URL url = (URL)src;
 941             source = sourceFor(url.toString(), url);
 942         } else if (src instanceof ScriptObject) {
 943             final ScriptObject sobj = (ScriptObject)src;
 944             if (sobj.has("script") && sobj.has("name")) {
 945                 final String script = JSType.toString(sobj.get("script"));
 946                 final String name   = JSType.toString(sobj.get("name"));
 947                 source = sourceFor(name, script);
 948             }
 949         } else if (src instanceof Map) {
 950             final Map<?,?> map = (Map<?,?>)src;
 951             if (map.containsKey("script") && map.containsKey("name")) {
 952                 final String script = JSType.toString(map.get("script"));
 953                 final String name   = JSType.toString(map.get("name"));
 954                 source = sourceFor(name, script);
 955             }
 956         }
 957 
 958         if (source != null) {
 959             if (scope instanceof ScriptObject && ((ScriptObject)scope).isScope()) {
 960                 final ScriptObject sobj = (ScriptObject)scope;
 961                 // passed object is a script object
 962                 // Global is the only user accessible scope ScriptObject
 963                 assert sobj.isGlobal() : "non-Global scope object!!";
 964                 return evaluateSource(source, sobj, sobj);
 965             } else if (scope == null || scope == UNDEFINED) {
 966                 // undefined or null scope. Use current global instance.
 967                 final Global global = getGlobal();
 968                 return evaluateSource(source, global, global);
 969             } else {
 970                 /*
 971                  * Arbitrary object passed for scope.
 972                  * Indirect load that is equivalent to:
 973                  *
 974                  *    (function(scope, source) {
 975                  *        with (scope) {
 976                  *            eval(<script_from_source>);
 977                  *        }
 978                  *    })(scope, source);
 979                  */
 980                 final Global global = getGlobal();
 981                 // Create a new object. This is where all declarations
 982                 // (var, function) from the evaluated code go.
 983                 // make global to be its __proto__ so that global
 984                 // definitions are accessible to the evaluated code.
 985                 final ScriptObject evalScope = newScope(global);
 986 
 987                 // finally, make a WithObject around user supplied scope object
 988                 // so that it's properties are accessible as variables.
 989                 final ScriptObject withObj = ScriptRuntime.openWith(evalScope, scope);
 990 
 991                 // evaluate given source with 'withObj' as scope
 992                 // but use global object as "this".
 993                 return evaluateSource(source, withObj, global);
 994             }
 995         }
 996 
 997         throw typeError("cant.load.script", ScriptRuntime.safeToString(from));
 998     }
 999 
1000     /**
1001      * Implementation of {@code loadWithNewGlobal} Nashorn extension. Load a script file from a source
1002      * expression, after creating a new global scope.
1003      *
1004      * @param from source expression for script
1005      * @param args (optional) arguments to be passed to the loaded script
1006      *
1007      * @return return value for load call (undefined)
1008      *
1009      * @throws IOException if source cannot be found or loaded
1010      */
1011     public Object loadWithNewGlobal(final Object from, final Object...args) throws IOException {
1012         final Global oldGlobal = getGlobal();
1013         final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
1014            @Override
1015            public Global run() {
1016                try {
1017                    return newGlobal();
1018                } catch (final RuntimeException e) {
1019                    if (Context.DEBUG) {
1020                        e.printStackTrace();
1021                    }
1022                    throw e;
1023                }
1024            }
1025         }, CREATE_GLOBAL_ACC_CTXT);
1026         // initialize newly created Global instance
1027         initGlobal(newGlobal);
1028         setGlobal(newGlobal);
1029 
1030         final Object[] wrapped = args == null? ScriptRuntime.EMPTY_ARRAY :  ScriptObjectMirror.wrapArray(args, oldGlobal);
1031         newGlobal.put("arguments", newGlobal.wrapAsObject(wrapped), env._strict);
1032 
1033         try {
1034             // wrap objects from newGlobal's world as mirrors - but if result
1035             // is from oldGlobal's world, unwrap it!
1036             return ScriptObjectMirror.unwrap(ScriptObjectMirror.wrap(load(newGlobal, from), newGlobal), oldGlobal);
1037         } finally {
1038             setGlobal(oldGlobal);
1039         }
1040     }
1041 
1042     /**
1043      * Load or get a structure class. Structure class names are based on the number of parameter fields
1044      * and {@link AccessorProperty} fields in them. Structure classes are used to represent ScriptObjects
1045      *
1046      * @see ObjectClassGenerator
1047      * @see AccessorProperty
1048      * @see ScriptObject
1049      *
1050      * @param fullName  full name of class, e.g. jdk.nashorn.internal.objects.JO2P1 contains 2 fields and 1 parameter.
1051      *
1052      * @return the {@code Class<?>} for this structure
1053      *
1054      * @throws ClassNotFoundException if structure class cannot be resolved
1055      */
1056     @SuppressWarnings("unchecked")
1057     public static Class<? extends ScriptObject> forStructureClass(final String fullName) throws ClassNotFoundException {
1058         if (System.getSecurityManager() != null && !StructureLoader.isStructureClass(fullName)) {
1059             throw new ClassNotFoundException(fullName);
1060         }
1061         return (Class<? extends ScriptObject>)Class.forName(fullName, true, theStructLoader);
1062     }
1063 
1064     /**
1065      * Checks that the given Class can be accessed from no permissions context.
1066      *
1067      * @param clazz Class object
1068      * @throws SecurityException if not accessible
1069      */
1070     public static void checkPackageAccess(final Class<?> clazz) {
1071         final SecurityManager sm = System.getSecurityManager();
1072         if (sm != null) {
1073             Class<?> bottomClazz = clazz;
1074             while (bottomClazz.isArray()) {
1075                 bottomClazz = bottomClazz.getComponentType();
1076             }
1077             checkPackageAccess(sm, bottomClazz.getName());
1078         }
1079     }
1080 
1081     /**
1082      * Checks that the given package name can be accessed from no permissions context.
1083      *
1084      * @param pkgName package name
1085      * @throws SecurityException if not accessible
1086      */
1087     public static void checkPackageAccess(final String pkgName) {
1088         final SecurityManager sm = System.getSecurityManager();
1089         if (sm != null) {
1090             checkPackageAccess(sm, pkgName.endsWith(".") ? pkgName : pkgName + ".");
1091         }
1092     }
1093 
1094     /**
1095      * Checks that the given package can be accessed from no permissions context.
1096      *
1097      * @param sm current security manager instance
1098      * @param fullName fully qualified package name
1099      * @throw SecurityException if not accessible
1100      */
1101     private static void checkPackageAccess(final SecurityManager sm, final String fullName) {
1102         Objects.requireNonNull(sm);
1103         final int index = fullName.lastIndexOf('.');
1104         if (index != -1) {
1105             final String pkgName = fullName.substring(0, index);
1106             AccessController.doPrivileged(new PrivilegedAction<Void>() {
1107                 @Override
1108                 public Void run() {
1109                     sm.checkPackageAccess(pkgName);
1110                     return null;
1111                 }
1112             }, NO_PERMISSIONS_ACC_CTXT);
1113         }
1114     }
1115 
1116     /**
1117      * Is {@code className} the name of a structure class?
1118      *
1119      * @param className a class name
1120      * @return true if className is a structure class name
1121      */
1122     public static boolean isStructureClass(final String className) {
1123         return StructureLoader.isStructureClass(className);
1124     }
1125 
1126     /**
1127      * Checks that the given Class can be accessed from no permissions context.
1128      *
1129      * @param clazz Class object
1130      * @return true if package is accessible, false otherwise
1131      */
1132     private static boolean isAccessiblePackage(final Class<?> clazz) {
1133         try {
1134             checkPackageAccess(clazz);
1135             return true;
1136         } catch (final SecurityException se) {
1137             return false;
1138         }
1139     }
1140 
1141     /**
1142      * Checks that the given Class is public and it can be accessed from no permissions context.
1143      *
1144      * @param clazz Class object to check
1145      * @return true if Class is accessible, false otherwise
1146      */
1147     public static boolean isAccessibleClass(final Class<?> clazz) {
1148         return Modifier.isPublic(clazz.getModifiers()) && Context.isAccessiblePackage(clazz);
1149     }
1150 
1151     /**
1152      * Lookup a Java class. This is used for JSR-223 stuff linking in from
1153      * {@code jdk.nashorn.internal.objects.NativeJava} and {@code jdk.nashorn.internal.runtime.NativeJavaPackage}
1154      *
1155      * @param fullName full name of class to load
1156      *
1157      * @return the {@code Class<?>} for the name
1158      *
1159      * @throws ClassNotFoundException if class cannot be resolved
1160      */
1161     public Class<?> findClass(final String fullName) throws ClassNotFoundException {
1162         if (fullName.indexOf('[') != -1 || fullName.indexOf('/') != -1) {
1163             // don't allow array class names or internal names.
1164             throw new ClassNotFoundException(fullName);
1165         }
1166 
1167         // give chance to ClassFilter to filter out, if present
1168         if (classFilter != null && !classFilter.exposeToScripts(fullName)) {
1169             throw new ClassNotFoundException(fullName);
1170         }
1171 
1172         // check package access as soon as possible!
1173         final SecurityManager sm = System.getSecurityManager();
1174         if (sm != null) {
1175             checkPackageAccess(sm, fullName);
1176         }
1177 
1178         // Try finding using the "app" loader.
1179         if (appLoader != null) {
1180             return Class.forName(fullName, true, appLoader);
1181         } else {
1182             final Class<?> cl = Class.forName(fullName);
1183             // return the Class only if it was loaded by boot loader
1184             if (cl.getClassLoader() == null) {
1185                 return cl;
1186             } else {
1187                 throw new ClassNotFoundException(fullName);
1188             }
1189         }
1190     }
1191 
1192     /**
1193      * Hook to print stack trace for a {@link Throwable} that occurred during
1194      * execution
1195      *
1196      * @param t throwable for which to dump stack
1197      */
1198     public static void printStackTrace(final Throwable t) {
1199         if (Context.DEBUG) {
1200             t.printStackTrace(Context.getCurrentErr());
1201         }
1202     }
1203 
1204     /**
1205      * Verify generated bytecode before emission. This is called back from the
1206      * {@link ObjectClassGenerator} or the {@link Compiler}. If the "--verify-code" parameter
1207      * hasn't been given, this is a nop
1208      *
1209      * Note that verification may load classes -- we don't want to do that unless
1210      * user specified verify option. We check it here even though caller
1211      * may have already checked that flag
1212      *
1213      * @param bytecode bytecode to verify
1214      */
1215     public void verify(final byte[] bytecode) {
1216         if (env._verify_code) {
1217             // No verification when security manager is around as verifier
1218             // may load further classes - which should be avoided.
1219             if (System.getSecurityManager() == null) {
1220                 CheckClassAdapter.verify(new ClassReader(bytecode), theStructLoader, false, new PrintWriter(System.err, true));
1221             }
1222         }
1223     }
1224 
1225     /**
1226      * Create and initialize a new global scope object.
1227      *
1228      * @return the initialized global scope object.
1229      */
1230     public Global createGlobal() {
1231         return initGlobal(newGlobal());
1232     }
1233 
1234     /**
1235      * Create a new uninitialized global scope object
1236      * @return the global script object
1237      */
1238     public Global newGlobal() {
1239         createOrInvalidateGlobalConstants();
1240         return new Global(this);
1241     }
1242 
1243     private void createOrInvalidateGlobalConstants() {
1244         for (;;) {
1245             final GlobalConstants currentGlobalConstants = getGlobalConstants();
1246             if (currentGlobalConstants != null) {
1247                 // Subsequent invocation; we're creating our second or later Global. GlobalConstants is not safe to use
1248                 // with more than one Global, as the constant method handle linkages it creates create a coupling
1249                 // between the Global and the call sites in the compiled code.
1250                 currentGlobalConstants.invalidateForever();
1251                 return;
1252             }
1253             final GlobalConstants newGlobalConstants = new GlobalConstants(getLogger(GlobalConstants.class));
1254             if (globalConstantsRef.compareAndSet(null, newGlobalConstants)) {
1255                 // First invocation; we're creating the first Global in this Context. Create the GlobalConstants object
1256                 // for this Context.
1257                 return;
1258             }
1259 
1260             // If we reach here, then we started out as the first invocation, but another concurrent invocation won the
1261             // CAS race. We'll just let the loop repeat and invalidate the CAS race winner.
1262         }
1263     }
1264 
1265     /**
1266      * Initialize given global scope object.
1267      *
1268      * @param global the global
1269      * @param engine the associated ScriptEngine instance, can be null
1270      * @return the initialized global scope object.
1271      */
1272     public Global initGlobal(final Global global, final ScriptEngine engine) {
1273         // Need only minimal global object, if we are just compiling.
1274         if (!env._compile_only) {
1275             final Global oldGlobal = Context.getGlobal();
1276             try {
1277                 Context.setGlobal(global);
1278                 // initialize global scope with builtin global objects
1279                 global.initBuiltinObjects(engine);
1280             } finally {
1281                 Context.setGlobal(oldGlobal);
1282             }
1283         }
1284 
1285         return global;
1286     }
1287 
1288     /**
1289      * Initialize given global scope object.
1290      *
1291      * @param global the global
1292      * @return the initialized global scope object.
1293      */
1294     public Global initGlobal(final Global global) {
1295         return initGlobal(global, null);
1296     }
1297 
1298     /**
1299      * Return the current global's context
1300      * @return current global's context
1301      */
1302     static Context getContextTrusted() {
1303         return getContext(getGlobal());
1304     }
1305 
1306     static Context getContextTrustedOrNull() {
1307         final Global global = Context.getGlobal();
1308         return global == null ? null : getContext(global);
1309     }
1310 
1311     private static Context getContext(final Global global) {
1312         // We can't invoke Global.getContext() directly, as it's a protected override, and Global isn't in our package.
1313         // In order to access the method, we must cast it to ScriptObject first (which is in our package) and then let
1314         // virtual invocation do its thing.
1315         return ((ScriptObject)global).getContext();
1316     }
1317 
1318     /**
1319      * Try to infer Context instance from the Class. If we cannot,
1320      * then get it from the thread local variable.
1321      *
1322      * @param clazz the class
1323      * @return context
1324      */
1325     static Context fromClass(final Class<?> clazz) {
1326         final ClassLoader loader = clazz.getClassLoader();
1327 
1328         if (loader instanceof ScriptLoader) {
1329             return ((ScriptLoader)loader).getContext();
1330         }
1331 
1332         return Context.getContextTrusted();
1333     }
1334 
1335     private URL getResourceURL(final String resName) {
1336         if (appLoader != null) {
1337             return appLoader.getResource(resName);
1338         }
1339         return ClassLoader.getSystemResource(resName);
1340     }
1341 
1342     private Object evaluateSource(final Source source, final ScriptObject scope, final ScriptObject thiz) {
1343         ScriptFunction script = null;
1344 
1345         try {
1346             script = compileScript(source, scope, new Context.ThrowErrorManager());
1347         } catch (final ParserException e) {
1348             e.throwAsEcmaException();
1349         }
1350 
1351         return ScriptRuntime.apply(script, thiz);
1352     }
1353 
1354     private static ScriptFunction getProgramFunction(final Class<?> script, final ScriptObject scope) {
1355         if (script == null) {
1356             return null;
1357         }
1358         return invokeCreateProgramFunctionHandle(getCreateProgramFunctionHandle(script), scope);
1359     }
1360 
1361     private static MethodHandle getCreateProgramFunctionHandle(final Class<?> script) {
1362         try {
1363             return LOOKUP.findStatic(script, CREATE_PROGRAM_FUNCTION.symbolName(), CREATE_PROGRAM_FUNCTION_TYPE);
1364         } catch (NoSuchMethodException | IllegalAccessException e) {
1365             throw new AssertionError("Failed to retrieve a handle for the program function for " + script.getName(), e);
1366         }
1367     }
1368 
1369     private static ScriptFunction invokeCreateProgramFunctionHandle(final MethodHandle createProgramFunctionHandle, final ScriptObject scope) {
1370         try {
1371             return (ScriptFunction)createProgramFunctionHandle.invokeExact(scope);
1372         } catch (final RuntimeException|Error e) {
1373             throw e;
1374         } catch (final Throwable t) {
1375             throw new AssertionError("Failed to create a program function", t);
1376         }
1377     }
1378 
1379     private ScriptFunction compileScript(final Source source, final ScriptObject scope, final ErrorManager errMan) {
1380         return getProgramFunction(compile(source, errMan, this._strict, false), scope);
1381     }
1382 
1383     private synchronized Class<?> compile(final Source source, final ErrorManager errMan, final boolean strict, final boolean isEval) {
1384         // start with no errors, no warnings.
1385         errMan.reset();
1386 
1387         Class<?> script = findCachedClass(source);
1388         if (script != null) {
1389             final DebugLogger log = getLogger(Compiler.class);
1390             if (log.isEnabled()) {
1391                 log.fine(new RuntimeEvent<>(Level.INFO, source), "Code cache hit for ", source, " avoiding recompile.");
1392             }
1393             return script;
1394         }
1395 
1396         StoredScript storedScript = null;
1397         FunctionNode functionNode = null;
1398         // Don't use code store if optimistic types is enabled but lazy compilation is not.
1399         // This would store a full script compilation with many wrong optimistic assumptions that would
1400         // do more harm than good on later runs with both optimistic types and lazy compilation enabled.
1401         final boolean useCodeStore = codeStore != null && !env._parse_only && (!env._optimistic_types || env._lazy_compilation);
1402         final String cacheKey = useCodeStore ? CodeStore.getCacheKey("script", null) : null;
1403 
1404         if (useCodeStore) {
1405             storedScript = codeStore.load(source, cacheKey);
1406         }
1407 
1408         if (storedScript == null) {
1409             if (env._dest_dir != null) {
1410                 source.dump(env._dest_dir);
1411             }
1412 
1413             functionNode = new Parser(env, source, errMan, strict, getLogger(Parser.class)).parse();
1414 
1415             if (errMan.hasErrors()) {
1416                 return null;
1417             }
1418 
1419             if (env._print_ast || functionNode.getFlag(FunctionNode.IS_PRINT_AST)) {
1420                 getErr().println(new ASTWriter(functionNode));
1421             }
1422 
1423             if (env._print_parse || functionNode.getFlag(FunctionNode.IS_PRINT_PARSE)) {
1424                 getErr().println(new PrintVisitor(functionNode, true, false));
1425             }
1426         }
1427 
1428         if (env._parse_only) {
1429             return null;
1430         }
1431 
1432         final URL          url    = source.getURL();
1433         final CodeSource   cs     = new CodeSource(url, (CodeSigner[])null);
1434         final CodeInstaller installer;
1435         if (!env.useAnonymousClasses(source.getLength()) || env._persistent_cache || !env._lazy_compilation) {
1436             // Persistent code cache and eager compilation preclude use of VM anonymous classes
1437             final ScriptLoader loader = env._loader_per_compile ? createNewLoader() : scriptLoader;
1438             installer = new NamedContextCodeInstaller(this, cs, loader);
1439         } else {
1440             installer = new AnonymousContextCodeInstaller(this, cs, getAnonymousHostClass(cs));
1441         }
1442 
1443         if (storedScript == null) {
1444             final CompilationPhases phases = Compiler.CompilationPhases.COMPILE_ALL;
1445 
1446             final Compiler compiler = Compiler.forInitialCompilation(
1447                     installer,
1448                     source,
1449                     errMan,
1450                     strict | functionNode.isStrict());
1451 
1452             final FunctionNode compiledFunction = compiler.compile(functionNode, phases);
1453             if (errMan.hasErrors()) {
1454                 return null;
1455             }
1456             script = compiledFunction.getRootClass();
1457             compiler.persistClassInfo(cacheKey, compiledFunction);
1458         } else {
1459             Compiler.updateCompilationId(storedScript.getCompilationId());
1460             script = storedScript.installScript(source, installer);
1461         }
1462 
1463         cacheClass(source, script);
1464         return script;
1465     }
1466 
1467     private ScriptLoader createNewLoader() {
1468         return AccessController.doPrivileged(
1469              new PrivilegedAction<ScriptLoader>() {
1470                 @Override
1471                 public ScriptLoader run() {
1472                     return new ScriptLoader(Context.this);
1473                 }
1474              }, CREATE_LOADER_ACC_CTXT);
1475     }
1476 
1477     private long getUniqueScriptId() {
1478         return uniqueScriptId.getAndIncrement();
1479     }
1480 
1481     /**
1482      * Cache for compiled script classes.
1483      */
1484     @SuppressWarnings("serial")
1485     private static class ClassCache extends LinkedHashMap<Source, ClassReference> {
1486         private final int size;
1487         private final ReferenceQueue<Class<?>> queue;
1488 
1489         ClassCache(final int size) {
1490             super(size, 0.75f, true);
1491             this.size = size;
1492             this.queue = new ReferenceQueue<>();
1493         }
1494 
1495         void cache(final Source source, final Class<?> clazz) {
1496             put(source, new ClassReference(clazz, queue, source));
1497         }
1498 
1499         @Override
1500         protected boolean removeEldestEntry(final Map.Entry<Source, ClassReference> eldest) {
1501             return size() > size;
1502         }
1503 
1504         @Override
1505         public ClassReference get(final Object key) {
1506             for (ClassReference ref; (ref = (ClassReference)queue.poll()) != null; ) {
1507                 remove(ref.source);
1508             }
1509             return super.get(key);
1510         }
1511 
1512     }
1513 
1514     private static class ClassReference extends SoftReference<Class<?>> {
1515         private final Source source;
1516 
1517         ClassReference(final Class<?> clazz, final ReferenceQueue<Class<?>> queue, final Source source) {
1518             super(clazz, queue);
1519             this.source = source;
1520         }
1521     }
1522 
1523     // Class cache management
1524     private Class<?> findCachedClass(final Source source) {
1525         final ClassReference ref = classCache == null ? null : classCache.get(source);
1526         return ref != null ? ref.get() : null;
1527     }
1528 
1529     private void cacheClass(final Source source, final Class<?> clazz) {
1530         if (classCache != null) {
1531             classCache.cache(source, clazz);
1532         }
1533     }
1534 
1535     // logging
1536     private final Map<String, DebugLogger> loggers = new HashMap<>();
1537 
1538     private void initLoggers() {
1539         ((Loggable)MethodHandleFactory.getFunctionality()).initLogger(this);
1540     }
1541 
1542     /**
1543      * Get a logger, given a loggable class
1544      * @param clazz a Loggable class
1545      * @return debuglogger associated with that class
1546      */
1547     public DebugLogger getLogger(final Class<? extends Loggable> clazz) {
1548         return getLogger(clazz, null);
1549     }
1550 
1551     /**
1552      * Get a logger, given a loggable class
1553      * @param clazz a Loggable class
1554      * @param initHook an init hook - if this is the first time the logger is created in the context, run the init hook
1555      * @return debuglogger associated with that class
1556      */
1557     public DebugLogger getLogger(final Class<? extends Loggable> clazz, final Consumer<DebugLogger> initHook) {
1558         final String name = getLoggerName(clazz);
1559         DebugLogger logger = loggers.get(name);
1560         if (logger == null) {
1561             if (!env.hasLogger(name)) {
1562                 return DebugLogger.DISABLED_LOGGER;
1563             }
1564             final LoggerInfo info = env._loggers.get(name);
1565             logger = new DebugLogger(name, info.getLevel(), info.isQuiet());
1566             if (initHook != null) {
1567                 initHook.accept(logger);
1568             }
1569             loggers.put(name, logger);
1570         }
1571         return logger;
1572     }
1573 
1574     /**
1575      * Given a Loggable class, weave debug info info a method handle for that logger.
1576      * Level.INFO is used
1577      *
1578      * @param clazz loggable
1579      * @param mh    method handle
1580      * @param text  debug printout to add
1581      *
1582      * @return instrumented method handle, or null if logger not enabled
1583      */
1584     public MethodHandle addLoggingToHandle(final Class<? extends Loggable> clazz, final MethodHandle mh, final Supplier<String> text) {
1585         return addLoggingToHandle(clazz, Level.INFO, mh, Integer.MAX_VALUE, false, text);
1586     }
1587 
1588     /**
1589      * Given a Loggable class, weave debug info info a method handle for that logger.
1590      *
1591      * @param clazz            loggable
1592      * @param level            log level
1593      * @param mh               method handle
1594      * @param paramStart       first parameter to print
1595      * @param printReturnValue should we print the return value?
1596      * @param text             debug printout to add
1597      *
1598      * @return instrumented method handle, or null if logger not enabled
1599      */
1600     public MethodHandle addLoggingToHandle(final Class<? extends Loggable> clazz, final Level level, final MethodHandle mh, final int paramStart, final boolean printReturnValue, final Supplier<String> text) {
1601         final DebugLogger log = getLogger(clazz);
1602         if (log.isEnabled()) {
1603             return MethodHandleFactory.addDebugPrintout(log, level, mh, paramStart, printReturnValue, text.get());
1604         }
1605         return mh;
1606     }
1607 
1608     private static String getLoggerName(final Class<?> clazz) {
1609         Class<?> current = clazz;
1610         while (current != null) {
1611             final Logger log = current.getAnnotation(Logger.class);
1612             if (log != null) {
1613                 assert !"".equals(log.name());
1614                 return log.name();
1615             }
1616             current = current.getSuperclass();
1617         }
1618         assert false;
1619         return null;
1620     }
1621 
1622     /**
1623      * This is a special kind of switchpoint used to guard builtin
1624      * properties and prototypes. In the future it might contain
1625      * logic to e.g. multiple switchpoint classes.
1626      */
1627     public static final class BuiltinSwitchPoint extends SwitchPoint {
1628         //empty
1629     }
1630 
1631     /**
1632      * Create a new builtin switchpoint and return it
1633      * @param name key name
1634      * @return new builtin switchpoint
1635      */
1636     public SwitchPoint newBuiltinSwitchPoint(final String name) {
1637         assert builtinSwitchPoints.get(name) == null;
1638         final SwitchPoint sp = new BuiltinSwitchPoint();
1639         builtinSwitchPoints.put(name, sp);
1640         return sp;
1641     }
1642 
1643     /**
1644      * Return the builtin switchpoint for a particular key name
1645      * @param name key name
1646      * @return builtin switchpoint or null if none
1647      */
1648     public SwitchPoint getBuiltinSwitchPoint(final String name) {
1649         return builtinSwitchPoints.get(name);
1650     }
1651 
1652 }