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.RUN_SCRIPT;
  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.lookup.Lookup.MH;
  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.ref.ReferenceQueue;
  43 import java.lang.ref.SoftReference;
  44 import java.lang.reflect.Field;
  45 import java.lang.reflect.Modifier;
  46 import java.net.MalformedURLException;
  47 import java.net.URL;
  48 import java.security.AccessControlContext;
  49 import java.security.AccessController;
  50 import java.security.CodeSigner;
  51 import java.security.CodeSource;
  52 import java.security.Permissions;
  53 import java.security.PrivilegedAction;
  54 import java.security.PrivilegedActionException;
  55 import java.security.PrivilegedExceptionAction;
  56 import java.security.ProtectionDomain;
  57 import java.util.HashMap;
  58 import java.util.LinkedHashMap;
  59 import java.util.Map;
  60 import java.util.concurrent.atomic.AtomicLong;
  61 import jdk.internal.org.objectweb.asm.ClassReader;
  62 import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
  63 import jdk.nashorn.api.scripting.ScriptObjectMirror;
  64 import jdk.nashorn.internal.codegen.Compiler;
  65 import jdk.nashorn.internal.codegen.ObjectClassGenerator;
  66 import jdk.nashorn.internal.ir.FunctionNode;
  67 import jdk.nashorn.internal.ir.debug.ASTWriter;
  68 import jdk.nashorn.internal.ir.debug.PrintVisitor;
  69 import jdk.nashorn.internal.objects.Global;
  70 import jdk.nashorn.internal.parser.Parser;
  71 import jdk.nashorn.internal.runtime.options.Options;
  72 
  73 /**
  74  * This class manages the global state of execution. Context is immutable.
  75  */
  76 public final class Context {
  77     // nashorn specific security runtime access permission names
  78     /**
  79      * Permission needed to pass arbitrary nashorn command line options when creating Context.
  80      */
  81     public static final String NASHORN_SET_CONFIG      = "nashorn.setConfig";
  82 
  83     /**
  84      * Permission needed to create Nashorn Context instance.
  85      */
  86     public static final String NASHORN_CREATE_CONTEXT  = "nashorn.createContext";
  87 
  88     /**
  89      * Permission needed to create Nashorn Global instance.
  90      */
  91     public static final String NASHORN_CREATE_GLOBAL   = "nashorn.createGlobal";
  92 
  93     /**
  94      * Permission to get current Nashorn Context from thread local storage.
  95      */
  96     public static final String NASHORN_GET_CONTEXT     = "nashorn.getContext";
  97 
  98     /**
  99      * Permission to use Java reflection/jsr292 from script code.
 100      */
 101     public static final String NASHORN_JAVA_REFLECTION = "nashorn.JavaReflection";
 102 
 103     /**
 104      * Permission to enable nashorn debug mode.
 105      */
 106     public static final String NASHORN_DEBUG_MODE = "nashorn.debugMode";
 107 
 108     // nashorn load psuedo URL prefixes
 109     private static final String LOAD_CLASSPATH = "classpath:";
 110     private static final String LOAD_FX = "fx:";
 111     private static final String LOAD_NASHORN = "nashorn:";
 112 
 113     /* Force DebuggerSupport to be loaded. */
 114     static {
 115         DebuggerSupport.FORCELOAD = true;
 116     }
 117 
 118     /**
 119      * ContextCodeInstaller that has the privilege of installing classes in the Context.
 120      * Can only be instantiated from inside the context and is opaque to other classes
 121      */
 122     public static class ContextCodeInstaller implements CodeInstaller<ScriptEnvironment> {
 123         private final Context      context;
 124         private final ScriptLoader loader;
 125         private final CodeSource   codeSource;
 126 
 127         private ContextCodeInstaller(final Context context, final ScriptLoader loader, final CodeSource codeSource) {
 128             this.context    = context;
 129             this.loader     = loader;
 130             this.codeSource = codeSource;
 131         }
 132 
 133         /**
 134          * Return the context for this installer
 135          * @return ScriptEnvironment
 136          */
 137         @Override
 138         public ScriptEnvironment getOwner() {
 139             return context.env;
 140         }
 141 
 142         @Override
 143         public Class<?> install(final String className, final byte[] bytecode, final Source source, final Object[] constants) {
 144             Compiler.LOG.fine("Installing class ", className);
 145 
 146             final String   binaryName = Compiler.binaryName(className);
 147             final Class<?> clazz      = loader.installClass(binaryName, bytecode, codeSource);
 148 
 149             try {
 150                 // Need doPrivileged because these fields are private
 151                 AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
 152                     @Override
 153                     public Void run() throws Exception {
 154                         //use reflection to write source and constants table to installed classes
 155                         final Field sourceField    = clazz.getDeclaredField(SOURCE.symbolName());
 156                         final Field constantsField = clazz.getDeclaredField(CONSTANTS.symbolName());
 157                         sourceField.setAccessible(true);
 158                         constantsField.setAccessible(true);
 159                         sourceField.set(null, source);
 160                         constantsField.set(null, constants);
 161                         return null;
 162                     }
 163                 });
 164             } catch (final PrivilegedActionException e) {
 165                 throw new RuntimeException(e);
 166             }
 167 
 168             return clazz;
 169         }
 170 
 171         @Override
 172         public void verify(final byte[] code) {
 173             context.verify(code);
 174         }
 175 
 176         @Override
 177         public long getUniqueScriptId() {
 178             return context.getUniqueScriptId();
 179         }
 180 
 181         @Override
 182         public long getUniqueEvalId() {
 183             return context.getUniqueEvalId();
 184         }
 185 
 186         @Override
 187         public void storeCompiledScript(final Source source, final String mainClassName,
 188                                         final Map<String, byte[]> classBytes, final Object[] constants) {
 189             if (context.codeStore != null) {
 190                 try {
 191                     context.codeStore.putScript(source, mainClassName, classBytes, constants);
 192                 } catch (final IOException e) {
 193                     throw new RuntimeException(e);
 194                 }
 195             }
 196         }
 197     }
 198 
 199     /** Is Context global debug mode enabled ? */
 200     public static final boolean DEBUG = Options.getBooleanProperty("nashorn.debug");
 201 
 202     private static final ThreadLocal<Global> currentGlobal = new ThreadLocal<>();
 203 
 204     // in-memory cache for loaded classes
 205     private ClassCache classCache;
 206 
 207     // persistent code store
 208     private CodeStore codeStore;
 209 
 210     /**
 211      * Get the current global scope
 212      * @return the current global scope
 213      */
 214     public static Global getGlobal() {
 215         // This class in a package.access protected package.
 216         // Trusted code only can call this method.
 217         return currentGlobal.get();
 218     }
 219 
 220     /**
 221      * Set the current global scope
 222      * @param global the global scope
 223      */
 224     public static void setGlobal(final ScriptObject global) {
 225         if (global != null && !(global instanceof Global)) {
 226             throw new IllegalArgumentException("not a global!");
 227         }
 228         setGlobal((Global)global);
 229     }
 230 
 231     /**
 232      * Set the current global scope
 233      * @param global the global scope
 234      */
 235     public static void setGlobal(final Global global) {
 236         // This class in a package.access protected package.
 237         // Trusted code only can call this method.
 238         currentGlobal.set(global);
 239     }
 240 
 241     /**
 242      * Get context of the current global
 243      * @return current global scope's context.
 244      */
 245     public static Context getContext() {
 246         final SecurityManager sm = System.getSecurityManager();
 247         if (sm != null) {
 248             sm.checkPermission(new RuntimePermission(NASHORN_GET_CONTEXT));
 249         }
 250         return getContextTrusted();
 251     }
 252 
 253     /**
 254      * Get current context's error writer
 255      *
 256      * @return error writer of the current context
 257      */
 258     public static PrintWriter getCurrentErr() {
 259         final ScriptObject global = getGlobal();
 260         return (global != null)? global.getContext().getErr() : new PrintWriter(System.err);
 261     }
 262 
 263     /**
 264      * Output text to this Context's error stream
 265      * @param str text to write
 266      */
 267     public static void err(final String str) {
 268         err(str, true);
 269     }
 270 
 271     /**
 272      * Output text to this Context's error stream, optionally with
 273      * a newline afterwards
 274      *
 275      * @param str  text to write
 276      * @param crlf write a carriage return/new line after text
 277      */
 278     @SuppressWarnings("resource")
 279     public static void err(final String str, final boolean crlf) {
 280         final PrintWriter err = Context.getCurrentErr();
 281         if (err != null) {
 282             if (crlf) {
 283                 err.println(str);
 284             } else {
 285                 err.print(str);
 286             }
 287         }
 288     }
 289 
 290     /** Current environment. */
 291     private final ScriptEnvironment env;
 292 
 293     /** is this context in strict mode? Cached from env. as this is used heavily. */
 294     final boolean _strict;
 295 
 296     /** class loader to resolve classes from script. */
 297     private final ClassLoader  appLoader;
 298 
 299     /** Class loader to load classes from -classpath option, if set. */
 300     private final ClassLoader  classPathLoader;
 301 
 302     /** Class loader to load classes compiled from scripts. */
 303     private final ScriptLoader scriptLoader;
 304 
 305     /** Current error manager. */
 306     private final ErrorManager errors;
 307 
 308     /** Unique id for script. Used only when --loader-per-compile=false */
 309     private final AtomicLong uniqueScriptId;
 310 
 311     /** Unique id for 'eval' */
 312     private final AtomicLong uniqueEvalId;
 313 
 314     private static final ClassLoader myLoader = Context.class.getClassLoader();
 315     private static final StructureLoader sharedLoader;
 316 
 317     /*package-private*/ @SuppressWarnings("static-method")
 318     ClassLoader getSharedLoader() {
 319         return sharedLoader;
 320     }
 321 
 322     private static AccessControlContext createNoPermAccCtxt() {
 323         return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) });
 324     }
 325 
 326     private static AccessControlContext createPermAccCtxt(final String permName) {
 327         final Permissions perms = new Permissions();
 328         perms.add(new RuntimePermission(permName));
 329         return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
 330     }
 331 
 332     private static final AccessControlContext NO_PERMISSIONS_ACC_CTXT = createNoPermAccCtxt();
 333     private static final AccessControlContext CREATE_LOADER_ACC_CTXT  = createPermAccCtxt("createClassLoader");
 334     private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT  = createPermAccCtxt(NASHORN_CREATE_GLOBAL);
 335 
 336     static {
 337         sharedLoader = AccessController.doPrivileged(new PrivilegedAction<StructureLoader>() {
 338             @Override
 339             public StructureLoader run() {
 340                 return new StructureLoader(myLoader);
 341             }
 342         }, CREATE_LOADER_ACC_CTXT);
 343     }
 344 
 345     /**
 346      * ThrowErrorManager that throws ParserException upon error conditions.
 347      */
 348     public static class ThrowErrorManager extends ErrorManager {
 349         @Override
 350         public void error(final String message) {
 351             throw new ParserException(message);
 352         }
 353 
 354         @Override
 355         public void error(final ParserException e) {
 356             throw e;
 357         }
 358     }
 359 
 360     /**
 361      * Constructor
 362      *
 363      * @param options options from command line or Context creator
 364      * @param errors  error manger
 365      * @param appLoader application class loader
 366      */
 367     public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader) {
 368         this(options, errors, new PrintWriter(System.out, true), new PrintWriter(System.err, true), appLoader);
 369     }
 370 
 371     /**
 372      * Constructor
 373      *
 374      * @param options options from command line or Context creator
 375      * @param errors  error manger
 376      * @param out     output writer for this Context
 377      * @param err     error writer for this Context
 378      * @param appLoader application class loader
 379      */
 380     public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader) {
 381         final SecurityManager sm = System.getSecurityManager();
 382         if (sm != null) {
 383             sm.checkPermission(new RuntimePermission(NASHORN_CREATE_CONTEXT));
 384         }
 385 
 386         this.env       = new ScriptEnvironment(options, out, err);
 387         this._strict   = env._strict;
 388         this.appLoader = appLoader;
 389         if (env._loader_per_compile) {
 390             this.scriptLoader = null;
 391             this.uniqueScriptId = null;
 392         } else {
 393             this.scriptLoader = createNewLoader();
 394             this.uniqueScriptId = new AtomicLong();
 395         }
 396         this.errors    = errors;
 397         this.uniqueEvalId = new AtomicLong();
 398 
 399         // if user passed -classpath option, make a class loader with that and set it as
 400         // thread context class loader so that script can access classes from that path.
 401         final String classPath = options.getString("classpath");
 402         if (! env._compile_only && classPath != null && !classPath.isEmpty()) {
 403             // make sure that caller can create a class loader.
 404             if (sm != null) {
 405                 sm.checkPermission(new RuntimePermission("createClassLoader"));
 406             }
 407             this.classPathLoader = NashornLoader.createClassLoader(classPath);
 408         } else {
 409             this.classPathLoader = null;
 410         }
 411 
 412         final int cacheSize = env._class_cache_size;
 413         if (cacheSize > 0) {
 414             classCache = new ClassCache(cacheSize);
 415         }
 416 
 417         if (env._persistent_cache) {
 418             if (env._lazy_compilation || env._specialize_calls != null) {
 419                 getErr().println("Can not use persistent class caching with lazy compilation or call specialization.");
 420             } else {
 421                 try {
 422                     final String cacheDir = Options.getStringProperty("nashorn.persistent.code.cache", "nashorn_code_cache");
 423                     codeStore = new CodeStore(cacheDir);
 424                 } catch (IOException e) {
 425                     throw new RuntimeException("Error initializing code cache", e);
 426                 }
 427             }
 428         }
 429 
 430         // print version info if asked.
 431         if (env._version) {
 432             getErr().println("nashorn " + Version.version());
 433         }
 434 
 435         if (env._fullversion) {
 436             getErr().println("nashorn full version " + Version.fullVersion());
 437         }
 438     }
 439 
 440     /**
 441      * Get the error manager for this context
 442      * @return error manger
 443      */
 444     public ErrorManager getErrorManager() {
 445         return errors;
 446     }
 447 
 448     /**
 449      * Get the script environment for this context
 450      * @return script environment
 451      */
 452     public ScriptEnvironment getEnv() {
 453         return env;
 454     }
 455 
 456     /**
 457      * Get the output stream for this context
 458      * @return output print writer
 459      */
 460     public PrintWriter getOut() {
 461         return env.getOut();
 462     }
 463 
 464     /**
 465      * Get the error stream for this context
 466      * @return error print writer
 467      */
 468     public PrintWriter getErr() {
 469         return env.getErr();
 470     }
 471 
 472     /**
 473      * Get the PropertyMap of the current global scope
 474      * @return the property map of the current global scope
 475      */
 476     public static PropertyMap getGlobalMap() {
 477         return Context.getGlobal().getMap();
 478     }
 479 
 480     /**
 481      * Compile a top level script.
 482      *
 483      * @param source the source
 484      * @param scope  the scope
 485      *
 486      * @return top level function for script
 487      */
 488     public ScriptFunction compileScript(final Source source, final ScriptObject scope) {
 489         return compileScript(source, scope, this.errors);
 490     }
 491 
 492     /**
 493      * Entry point for {@code eval}
 494      *
 495      * @param initialScope The scope of this eval call
 496      * @param string       Evaluated code as a String
 497      * @param callThis     "this" to be passed to the evaluated code
 498      * @param location     location of the eval call
 499      * @param strict       is this {@code eval} call from a strict mode code?
 500      *
 501      * @return the return value of the {@code eval}
 502      */
 503     public Object eval(final ScriptObject initialScope, final String string, final Object callThis, final Object location, final boolean strict) {
 504         final String  file       = (location == UNDEFINED || location == null) ? "<eval>" : location.toString();
 505         final Source  source     = sourceFor(file, string);
 506         final boolean directEval = location != UNDEFINED; // is this direct 'eval' call or indirectly invoked eval?
 507         final Global  global = Context.getGlobal();
 508 
 509         ScriptObject scope = initialScope;
 510 
 511         // ECMA section 10.1.1 point 2 says eval code is strict if it begins
 512         // with "use strict" directive or eval direct call itself is made
 513         // from from strict mode code. We are passed with caller's strict mode.
 514         boolean strictFlag = directEval && strict;
 515 
 516         Class<?> clazz = null;
 517         try {
 518             clazz = compile(source, new ThrowErrorManager(), strictFlag);
 519         } catch (final ParserException e) {
 520             e.throwAsEcmaException(global);
 521             return null;
 522         }
 523 
 524         if (!strictFlag) {
 525             // We need to get strict mode flag from compiled class. This is
 526             // because eval code may start with "use strict" directive.
 527             try {
 528                 strictFlag = clazz.getField(STRICT_MODE.symbolName()).getBoolean(null);
 529             } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
 530                 //ignored
 531                 strictFlag = false;
 532             }
 533         }
 534 
 535         // In strict mode, eval does not instantiate variables and functions
 536         // in the caller's environment. A new environment is created!
 537         if (strictFlag) {
 538             // Create a new scope object
 539             final ScriptObject strictEvalScope = global.newObject();
 540 
 541             // bless it as a "scope"
 542             strictEvalScope.setIsScope();
 543 
 544             // set given scope to be it's proto so that eval can still
 545             // access caller environment vars in the new environment.
 546             strictEvalScope.setProto(scope);
 547             scope = strictEvalScope;
 548         }
 549 
 550         ScriptFunction func = getRunScriptFunction(clazz, scope);
 551         Object evalThis;
 552         if (directEval) {
 553             evalThis = (callThis instanceof ScriptObject || strictFlag) ? callThis : global;
 554         } else {
 555             evalThis = global;
 556         }
 557 
 558         return ScriptRuntime.apply(func, evalThis);
 559     }
 560 
 561     private static Source loadInternal(final String srcStr, final String prefix, final String resourcePath) {
 562         if (srcStr.startsWith(prefix)) {
 563             final String resource = resourcePath + srcStr.substring(prefix.length());
 564             // NOTE: even sandbox scripts should be able to load scripts in nashorn: scheme
 565             // These scripts are always available and are loaded from nashorn.jar's resources.
 566             return AccessController.doPrivileged(
 567                     new PrivilegedAction<Source>() {
 568                         @Override
 569                         public Source run() {
 570                             try {
 571                                 final URL resURL = Context.class.getResource(resource);
 572                                 return (resURL != null)? sourceFor(srcStr, resURL) : null;
 573                             } catch (final IOException exp) {
 574                                 return null;
 575                             }
 576                         }
 577                     });
 578         }
 579 
 580         return null;
 581     }
 582 
 583     /**
 584      * Implementation of {@code load} Nashorn extension. Load a script file from a source
 585      * expression
 586      *
 587      * @param scope  the scope
 588      * @param from   source expression for script
 589      *
 590      * @return return value for load call (undefined)
 591      *
 592      * @throws IOException if source cannot be found or loaded
 593      */
 594     public Object load(final ScriptObject scope, final Object from) throws IOException {
 595         final Object src = (from instanceof ConsString)?  from.toString() : from;
 596         Source source = null;
 597 
 598         // load accepts a String (which could be a URL or a file name), a File, a URL
 599         // or a ScriptObject that has "name" and "source" (string valued) properties.
 600         if (src instanceof String) {
 601             final String srcStr = (String)src;
 602             if (srcStr.startsWith(LOAD_CLASSPATH)) {
 603                 URL url = getResourceURL(srcStr.substring(LOAD_CLASSPATH.length()));
 604                 source = (url != null)? sourceFor(url.toString(), url) : null;
 605             } else {
 606                 final File file = new File(srcStr);
 607                 if (srcStr.indexOf(':') != -1) {
 608                     if ((source = loadInternal(srcStr, LOAD_NASHORN, "resources/")) == null &&
 609                         (source = loadInternal(srcStr, LOAD_FX, "resources/fx/")) == null) {
 610                         URL url;
 611                         try {
 612                             //check for malformed url. if malformed, it may still be a valid file
 613                             url = new URL(srcStr);
 614                         } catch (final MalformedURLException e) {
 615                             url = file.toURI().toURL();
 616                         }
 617                         source = sourceFor(url.toString(), url);
 618                     }
 619                 } else if (file.isFile()) {
 620                     source = sourceFor(srcStr, file);
 621                 }
 622             }
 623         } else if (src instanceof File && ((File)src).isFile()) {
 624             final File file = (File)src;
 625             source = sourceFor(file.getName(), file);
 626         } else if (src instanceof URL) {
 627             final URL url = (URL)src;
 628             source = sourceFor(url.toString(), url);
 629         } else if (src instanceof ScriptObject) {
 630             final ScriptObject sobj = (ScriptObject)src;
 631             if (sobj.has("script") && sobj.has("name")) {
 632                 final String script = JSType.toString(sobj.get("script"));
 633                 final String name   = JSType.toString(sobj.get("name"));
 634                 source = sourceFor(name, script);
 635             }
 636         } else if (src instanceof Map) {
 637             final Map<?,?> map = (Map<?,?>)src;
 638             if (map.containsKey("script") && map.containsKey("name")) {
 639                 final String script = JSType.toString(map.get("script"));
 640                 final String name   = JSType.toString(map.get("name"));
 641                 source = sourceFor(name, script);
 642             }
 643         }
 644 
 645         if (source != null) {
 646             return evaluateSource(source, scope, scope);
 647         }
 648 
 649         throw typeError("cant.load.script", ScriptRuntime.safeToString(from));
 650     }
 651 
 652     /**
 653      * Implementation of {@code loadWithNewGlobal} Nashorn extension. Load a script file from a source
 654      * expression, after creating a new global scope.
 655      *
 656      * @param from source expression for script
 657      * @param args (optional) arguments to be passed to the loaded script
 658      *
 659      * @return return value for load call (undefined)
 660      *
 661      * @throws IOException if source cannot be found or loaded
 662      */
 663     public Object loadWithNewGlobal(final Object from, final Object...args) throws IOException {
 664         final Global oldGlobal = getGlobal();
 665         final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
 666            @Override
 667            public Global run() {
 668                try {
 669                    return newGlobal();
 670                } catch (final RuntimeException e) {
 671                    if (Context.DEBUG) {
 672                        e.printStackTrace();
 673                    }
 674                    throw e;
 675                }
 676            }
 677         }, CREATE_GLOBAL_ACC_CTXT);
 678         // initialize newly created Global instance
 679         initGlobal(newGlobal);
 680         setGlobal(newGlobal);
 681 
 682         final Object[] wrapped = args == null? ScriptRuntime.EMPTY_ARRAY :  ScriptObjectMirror.wrapArray(args, oldGlobal);
 683         newGlobal.put("arguments", newGlobal.wrapAsObject(wrapped), env._strict);
 684 
 685         try {
 686             // wrap objects from newGlobal's world as mirrors - but if result
 687             // is from oldGlobal's world, unwrap it!
 688             return ScriptObjectMirror.unwrap(ScriptObjectMirror.wrap(load(newGlobal, from), newGlobal), oldGlobal);
 689         } finally {
 690             setGlobal(oldGlobal);
 691         }
 692     }
 693 
 694     /**
 695      * Load or get a structure class. Structure class names are based on the number of parameter fields
 696      * and {@link AccessorProperty} fields in them. Structure classes are used to represent ScriptObjects
 697      *
 698      * @see ObjectClassGenerator
 699      * @see AccessorProperty
 700      * @see ScriptObject
 701      *
 702      * @param fullName  full name of class, e.g. jdk.nashorn.internal.objects.JO2P1 contains 2 fields and 1 parameter.
 703      *
 704      * @return the {@code Class<?>} for this structure
 705      *
 706      * @throws ClassNotFoundException if structure class cannot be resolved
 707      */
 708     public static Class<?> forStructureClass(final String fullName) throws ClassNotFoundException {
 709         if (System.getSecurityManager() != null && !StructureLoader.isStructureClass(fullName)) {
 710             throw new ClassNotFoundException(fullName);
 711         }
 712         return Class.forName(fullName, true, sharedLoader);
 713     }
 714 
 715     /**
 716      * Checks that the given Class can be accessed from no permissions context.
 717      *
 718      * @param clazz Class object
 719      * @throws SecurityException if not accessible
 720      */
 721     public static void checkPackageAccess(final Class<?> clazz) {
 722         final SecurityManager sm = System.getSecurityManager();
 723         if (sm != null) {
 724             Class<?> bottomClazz = clazz;
 725             while (bottomClazz.isArray()) {
 726                 bottomClazz = bottomClazz.getComponentType();
 727             }
 728             checkPackageAccess(sm, bottomClazz.getName());
 729         }
 730     }
 731 
 732     /**
 733      * Checks that the given package name can be accessed from no permissions context.
 734      *
 735      * @param pkgName package name
 736      * @throws SecurityException if not accessible
 737      */
 738     public static void checkPackageAccess(final String pkgName) {
 739         final SecurityManager sm = System.getSecurityManager();
 740         if (sm != null) {
 741             checkPackageAccess(sm, pkgName.endsWith(".") ? pkgName : pkgName + ".");
 742         }
 743     }
 744 
 745     /**
 746      * Checks that the given package can be accessed from no permissions context.
 747      *
 748      * @param sm current security manager instance
 749      * @param fullName fully qualified package name
 750      * @throw SecurityException if not accessible
 751      */
 752     private static void checkPackageAccess(final SecurityManager sm, final String fullName) {
 753         sm.getClass(); // null check
 754         final int index = fullName.lastIndexOf('.');
 755         if (index != -1) {
 756             final String pkgName = fullName.substring(0, index);
 757             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 758                 @Override
 759                 public Void run() {
 760                     sm.checkPackageAccess(pkgName);
 761                     return null;
 762                 }
 763             }, NO_PERMISSIONS_ACC_CTXT);
 764         }
 765     }
 766 
 767     /**
 768      * Checks that the given Class can be accessed from no permissions context.
 769      *
 770      * @param clazz Class object
 771      * @return true if package is accessible, false otherwise
 772      */
 773     private static boolean isAccessiblePackage(final Class<?> clazz) {
 774         try {
 775             checkPackageAccess(clazz);
 776             return true;
 777         } catch (final SecurityException se) {
 778             return false;
 779         }
 780     }
 781 
 782     /**
 783      * Checks that the given Class is public and it can be accessed from no permissions context.
 784      *
 785      * @param clazz Class object to check
 786      * @return true if Class is accessible, false otherwise
 787      */
 788     public static boolean isAccessibleClass(final Class<?> clazz) {
 789         return Modifier.isPublic(clazz.getModifiers()) && Context.isAccessiblePackage(clazz);
 790     }
 791 
 792     /**
 793      * Lookup a Java class. This is used for JSR-223 stuff linking in from
 794      * {@code jdk.nashorn.internal.objects.NativeJava} and {@code jdk.nashorn.internal.runtime.NativeJavaPackage}
 795      *
 796      * @param fullName full name of class to load
 797      *
 798      * @return the {@code Class<?>} for the name
 799      *
 800      * @throws ClassNotFoundException if class cannot be resolved
 801      */
 802     public Class<?> findClass(final String fullName) throws ClassNotFoundException {
 803         if (fullName.indexOf('[') != -1 || fullName.indexOf('/') != -1) {
 804             // don't allow array class names or internal names.
 805             throw new ClassNotFoundException(fullName);
 806         }
 807 
 808         // check package access as soon as possible!
 809         final SecurityManager sm = System.getSecurityManager();
 810         if (sm != null) {
 811             checkPackageAccess(sm, fullName);
 812         }
 813 
 814         // try the script -classpath loader, if that is set
 815         if (classPathLoader != null) {
 816             try {
 817                 return Class.forName(fullName, true, classPathLoader);
 818             } catch (final ClassNotFoundException ignored) {
 819                 // ignore, continue search
 820             }
 821         }
 822 
 823         // Try finding using the "app" loader.
 824         return Class.forName(fullName, true, appLoader);
 825     }
 826 
 827     /**
 828      * Hook to print stack trace for a {@link Throwable} that occurred during
 829      * execution
 830      *
 831      * @param t throwable for which to dump stack
 832      */
 833     public static void printStackTrace(final Throwable t) {
 834         if (Context.DEBUG) {
 835             t.printStackTrace(Context.getCurrentErr());
 836         }
 837     }
 838 
 839     /**
 840      * Verify generated bytecode before emission. This is called back from the
 841      * {@link ObjectClassGenerator} or the {@link Compiler}. If the "--verify-code" parameter
 842      * hasn't been given, this is a nop
 843      *
 844      * Note that verification may load classes -- we don't want to do that unless
 845      * user specified verify option. We check it here even though caller
 846      * may have already checked that flag
 847      *
 848      * @param bytecode bytecode to verify
 849      */
 850     public void verify(final byte[] bytecode) {
 851         if (env._verify_code) {
 852             // No verification when security manager is around as verifier
 853             // may load further classes - which should be avoided.
 854             if (System.getSecurityManager() == null) {
 855                 CheckClassAdapter.verify(new ClassReader(bytecode), sharedLoader, false, new PrintWriter(System.err, true));
 856             }
 857         }
 858     }
 859 
 860     /**
 861      * Create and initialize a new global scope object.
 862      *
 863      * @return the initialized global scope object.
 864      */
 865     public Global createGlobal() {
 866         return initGlobal(newGlobal());
 867     }
 868 
 869     /**
 870      * Create a new uninitialized global scope object
 871      * @return the global script object
 872      */
 873     public Global newGlobal() {
 874         return new Global(this);
 875     }
 876 
 877     /**
 878      * Initialize given global scope object.
 879      *
 880      * @param global the global
 881      * @return the initialized global scope object.
 882      */
 883     public Global initGlobal(final Global global) {
 884         // Need only minimal global object, if we are just compiling.
 885         if (!env._compile_only) {
 886             final Global oldGlobal = Context.getGlobal();
 887             try {
 888                 Context.setGlobal(global);
 889                 // initialize global scope with builtin global objects
 890                 global.initBuiltinObjects();
 891             } finally {
 892                 Context.setGlobal(oldGlobal);
 893             }
 894         }
 895 
 896         return global;
 897     }
 898 
 899     /**
 900      * Trusted variant - package-private
 901      */
 902 
 903     /**
 904      * Return the current global's context
 905      * @return current global's context
 906      */
 907     static Context getContextTrusted() {
 908         return ((ScriptObject)Context.getGlobal()).getContext();
 909     }
 910 
 911     /**
 912      * Try to infer Context instance from the Class. If we cannot,
 913      * then get it from the thread local variable.
 914      *
 915      * @param clazz the class
 916      * @return context
 917      */
 918     static Context fromClass(final Class<?> clazz) {
 919         final ClassLoader loader = clazz.getClassLoader();
 920 
 921         if (loader instanceof ScriptLoader) {
 922             return ((ScriptLoader)loader).getContext();
 923         }
 924 
 925         return Context.getContextTrusted();
 926     }
 927 
 928     private URL getResourceURL(final String resName) {
 929         // try the classPathLoader if we have and then
 930         // try the appLoader if non-null.
 931         if (classPathLoader != null) {
 932             return classPathLoader.getResource(resName);
 933         } else if (appLoader != null) {
 934             return appLoader.getResource(resName);
 935         }
 936 
 937         return null;
 938     }
 939 
 940     private Object evaluateSource(final Source source, final ScriptObject scope, final ScriptObject thiz) {
 941         ScriptFunction script = null;
 942 
 943         try {
 944             script = compileScript(source, scope, new Context.ThrowErrorManager());
 945         } catch (final ParserException e) {
 946             e.throwAsEcmaException();
 947         }
 948 
 949         return ScriptRuntime.apply(script, thiz);
 950     }
 951 
 952     private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) {
 953         if (script == null) {
 954             return null;
 955         }
 956 
 957         // Get run method - the entry point to the script
 958         final MethodHandle runMethodHandle =
 959                 MH.findStatic(
 960                     MethodHandles.lookup(),
 961                     script,
 962                     RUN_SCRIPT.symbolName(),
 963                     MH.type(
 964                         Object.class,
 965                         ScriptFunction.class,
 966                         Object.class));
 967 
 968         boolean strict;
 969 
 970         try {
 971             strict = script.getField(STRICT_MODE.symbolName()).getBoolean(null);
 972         } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
 973             strict = false;
 974         }
 975 
 976         // Package as a JavaScript function and pass function back to shell.
 977         return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict);
 978     }
 979 
 980     private ScriptFunction compileScript(final Source source, final ScriptObject scope, final ErrorManager errMan) {
 981         return getRunScriptFunction(compile(source, errMan, this._strict), scope);
 982     }
 983 
 984     private synchronized Class<?> compile(final Source source, final ErrorManager errMan, final boolean strict) {
 985         // start with no errors, no warnings.
 986         errMan.reset();
 987 
 988         Class<?> script = findCachedClass(source);
 989         if (script != null) {
 990             Compiler.LOG.fine("Code cache hit for ", source, " avoiding recompile.");
 991             return script;
 992         }
 993 
 994         CompiledScript compiledScript = null;
 995         FunctionNode functionNode = null;
 996 
 997         if (!env._parse_only && codeStore != null) {
 998             try {
 999                 compiledScript = codeStore.getScript(source);
1000             } catch (IOException | ClassNotFoundException e) {
1001                 Compiler.LOG.warning("Error loading ", source, " from cache: ", e);
1002                 // Fall back to normal compilation
1003             }
1004         }
1005 
1006         if (compiledScript == null) {
1007             functionNode = new Parser(env, source, errMan, strict).parse();
1008 
1009             if (errors.hasErrors()) {
1010                 return null;
1011             }
1012 
1013             if (env._print_ast) {
1014                 getErr().println(new ASTWriter(functionNode));
1015             }
1016 
1017             if (env._print_parse) {
1018                 getErr().println(new PrintVisitor(functionNode));
1019             }
1020         }
1021 
1022         if (env._parse_only) {
1023             return null;
1024         }
1025 
1026         final URL          url    = source.getURL();
1027         final ScriptLoader loader = env._loader_per_compile ? createNewLoader() : scriptLoader;
1028         final CodeSource   cs     = new CodeSource(url, (CodeSigner[])null);
1029         final CodeInstaller<ScriptEnvironment> installer = new ContextCodeInstaller(this, loader, cs);
1030 
1031         if (functionNode != null) {
1032             final Compiler compiler = new Compiler(installer, strict);
1033             final FunctionNode newFunctionNode = compiler.compile(functionNode);
1034             script = compiler.install(newFunctionNode);
1035         } else {
1036             script = install(compiledScript, installer);
1037         }
1038 
1039         cacheClass(source, script);
1040         return script;
1041     }
1042 
1043     private ScriptLoader createNewLoader() {
1044         return AccessController.doPrivileged(
1045              new PrivilegedAction<ScriptLoader>() {
1046                 @Override
1047                 public ScriptLoader run() {
1048                     return new ScriptLoader(appLoader, Context.this);
1049                 }
1050              }, CREATE_LOADER_ACC_CTXT);
1051     }
1052 
1053     private long getUniqueEvalId() {
1054         return uniqueEvalId.getAndIncrement();
1055     }
1056 
1057     private long getUniqueScriptId() {
1058         return uniqueScriptId.getAndIncrement();
1059     }
1060 
1061 
1062     /**
1063      * Install a previously compiled class from the code cache.
1064      *
1065      * @param compiledScript cached script containing class bytes and constants
1066      * @return main script class
1067      */
1068     private Class<?> install(final CompiledScript compiledScript, final CodeInstaller<ScriptEnvironment> installer) {
1069 
1070         final Map<String, Class<?>> installedClasses = new HashMap<>();
1071         final Source   source        = compiledScript.getSource();
1072         final Object[] constants     = compiledScript.getConstants();
1073         final String   rootClassName = compiledScript.getMainClassName();
1074         final byte[]   rootByteCode  = compiledScript.getClassBytes().get(rootClassName);
1075         final Class<?> rootClass     = installer.install(rootClassName, rootByteCode, source, constants);
1076 
1077         installedClasses.put(rootClassName, rootClass);
1078 
1079         for (final Map.Entry<String, byte[]> entry : compiledScript.getClassBytes().entrySet()) {
1080             final String className = entry.getKey();
1081             if (className.equals(rootClassName)) {
1082                 continue;
1083             }
1084             final byte[] code = entry.getValue();
1085 
1086             installedClasses.put(className, installer.install(className, code, source, constants));
1087         }
1088         for (Object constant : constants) {
1089             if (constant instanceof RecompilableScriptFunctionData) {
1090                 ((RecompilableScriptFunctionData) constant).setCodeAndSource(installedClasses, source);
1091             }
1092         }
1093 
1094         return rootClass;
1095     }
1096 
1097     /**
1098      * Cache for compiled script classes.
1099      */
1100     @SuppressWarnings("serial")
1101     private static class ClassCache extends LinkedHashMap<Source, ClassReference> {
1102         private final int size;
1103         private final ReferenceQueue<Class<?>> queue;
1104 
1105         ClassCache(int size) {
1106             super(size, 0.75f, true);
1107             this.size = size;
1108             this.queue = new ReferenceQueue<>();
1109         }
1110 
1111         void cache(final Source source, final Class<?> clazz) {
1112             put(source, new ClassReference(clazz, queue, source));
1113         }
1114 
1115         @Override
1116         protected boolean removeEldestEntry(final Map.Entry<Source, ClassReference> eldest) {
1117             return size() > size;
1118         }
1119 
1120         @Override
1121         public ClassReference get(Object key) {
1122             for (ClassReference ref; (ref = (ClassReference)queue.poll()) != null; ) {
1123                 remove(ref.source);
1124             }
1125             return super.get(key);
1126         }
1127 
1128     }
1129 
1130     private static class ClassReference extends SoftReference<Class<?>> {
1131         private final Source source;
1132 
1133         ClassReference(final Class<?> clazz, final ReferenceQueue<Class<?>> queue, final Source source) {
1134             super(clazz, queue);
1135             this.source = source;
1136         }
1137     }
1138 
1139     // Class cache management
1140     private Class<?> findCachedClass(final Source source) {
1141         ClassReference ref = classCache == null ? null : classCache.get(source);
1142         return ref != null ? ref.get() : null;
1143     }
1144 
1145     private void cacheClass(final Source source, final Class<?> clazz) {
1146         if (classCache != null) {
1147             classCache.cache(source, clazz);
1148         }
1149     }
1150 
1151 
1152 }