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