nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java
author hannesw
Fri, 19 Sep 2014 13:13:20 +0200
changeset 26764 c777787a937d
parent 26508 b40ef4386b01
child 26768 751b0f427090
permissions -rw-r--r--
8046202: Make persistent code store more flexible Reviewed-by: lagergren, sundar
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     1
/*
16151
97c1e756ae1e 8005663: Update copyright year to 2013
jlaskey
parents: 16147
diff changeset
     2
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     4
 *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     5
 * This code is free software; you can redistribute it and/or modify it
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     6
 * under the terms of the GNU General Public License version 2 only, as
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     7
 * published by the Free Software Foundation.  Oracle designates this
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     8
 * particular file as subject to the "Classpath" exception as provided
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
     9
 * by Oracle in the LICENSE file that accompanied this code.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    10
 *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    14
 * version 2 for more details (a copy is included in the LICENSE file that
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    15
 * accompanied this code).
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    16
 *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    17
 * You should have received a copy of the GNU General Public License version
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    20
 *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    22
 * or visit www.oracle.com if you need additional information or have any
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    23
 * questions.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    24
 */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    25
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    26
package jdk.nashorn.internal.runtime;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    27
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
    28
import static jdk.nashorn.internal.codegen.CompilerConstants.CONSTANTS;
24719
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
    29
import static jdk.nashorn.internal.codegen.CompilerConstants.CREATE_PROGRAM_FUNCTION;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
    30
import static jdk.nashorn.internal.codegen.CompilerConstants.SOURCE;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    31
import static jdk.nashorn.internal.codegen.CompilerConstants.STRICT_MODE;
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
    32
import static jdk.nashorn.internal.runtime.CodeStore.newCodeStore;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    33
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    34
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
    35
import static jdk.nashorn.internal.runtime.Source.sourceFor;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    36
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    37
import java.io.File;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    38
import java.io.IOException;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    39
import java.io.PrintWriter;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    40
import java.lang.invoke.MethodHandle;
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
    41
import java.lang.invoke.MethodHandles;
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
    42
import java.lang.invoke.MethodType;
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
    43
import java.lang.ref.ReferenceQueue;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
    44
import java.lang.ref.SoftReference;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
    45
import java.lang.reflect.Field;
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
    46
import java.lang.reflect.Modifier;
16254
2ed824fc93be 8008554: load was broken for URLs
lagergren
parents: 16251
diff changeset
    47
import java.net.MalformedURLException;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    48
import java.net.URL;
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
    49
import java.security.AccessControlContext;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    50
import java.security.AccessController;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    51
import java.security.CodeSigner;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    52
import java.security.CodeSource;
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
    53
import java.security.Permissions;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    54
import java.security.PrivilegedAction;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
    55
import java.security.PrivilegedActionException;
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
    56
import java.security.PrivilegedExceptionAction;
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
    57
import java.security.ProtectionDomain;
24769
attila
parents: 24759 24282
diff changeset
    58
import java.util.Collection;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
    59
import java.util.HashMap;
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
    60
import java.util.LinkedHashMap;
18334
47413e8d71b5 8016618: script mirror object access should be improved
sundar
parents: 18328
diff changeset
    61
import java.util.Map;
22669
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
    62
import java.util.concurrent.atomic.AtomicLong;
24769
attila
parents: 24759 24282
diff changeset
    63
import java.util.function.Consumer;
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
    64
import java.util.function.Supplier;
24731
ab0c8fc915ae 8038406: Testability: as a first step of moving loggers away from the process global space, the Debug object now supports logging POJOs from log entries as an event queue, which can be introspected from test scripts. This is way better than screen scraping brittle and subject-to-change log output.
lagergren
parents: 24727
diff changeset
    65
import java.util.logging.Level;
25422
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
    66
import javax.script.ScriptEngine;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    67
import jdk.internal.org.objectweb.asm.ClassReader;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    68
import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
    69
import jdk.nashorn.api.scripting.ClassFilter;
17979
adae4d39ee07 8015945: loadWithNewGlobal return value has to be properly wrapped
sundar
parents: 17976
diff changeset
    70
import jdk.nashorn.api.scripting.ScriptObjectMirror;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    71
import jdk.nashorn.internal.codegen.Compiler;
24759
31aed7d9c02a 8034206: Make parts of code pipeline reusable in order to facilitate faster warmup and faster lazy compilation.
lagergren
parents: 24745
diff changeset
    72
import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
16240
e1468b33e201 8008239: Unpublicized parts of the code generator package that were only package internal.
lagergren
parents: 16233
diff changeset
    73
import jdk.nashorn.internal.codegen.ObjectClassGenerator;
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
    74
import jdk.nashorn.internal.ir.FunctionNode;
16240
e1468b33e201 8008239: Unpublicized parts of the code generator package that were only package internal.
lagergren
parents: 16233
diff changeset
    75
import jdk.nashorn.internal.ir.debug.ASTWriter;
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
    76
import jdk.nashorn.internal.ir.debug.PrintVisitor;
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
    77
import jdk.nashorn.internal.lookup.MethodHandleFactory;
18851
bdb92c95f886 8019947: inherited property invalidation does not work with two globals in same context
sundar
parents: 18618
diff changeset
    78
import jdk.nashorn.internal.objects.Global;
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
    79
import jdk.nashorn.internal.parser.Parser;
24742
a9afb384e654 8040655: When processing a RewriteException debug object, the return value has already been reset to null. We need to catch this value before that.
lagergren
parents: 24733
diff changeset
    80
import jdk.nashorn.internal.runtime.events.RuntimeEvent;
24744
5290da85fc3d 8038426: Move all loggers from process wide scope into Global scope
lagergren
parents: 24742
diff changeset
    81
import jdk.nashorn.internal.runtime.logging.DebugLogger;
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
    82
import jdk.nashorn.internal.runtime.logging.Loggable;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
    83
import jdk.nashorn.internal.runtime.logging.Logger;
24769
attila
parents: 24759 24282
diff changeset
    84
import jdk.nashorn.internal.runtime.options.LoggingOption.LoggerInfo;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    85
import jdk.nashorn.internal.runtime.options.Options;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    86
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    87
/**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    88
 * This class manages the global state of execution. Context is immutable.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    89
 */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
    90
public final class Context {
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    91
    // nashorn specific security runtime access permission names
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    92
    /**
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    93
     * Permission needed to pass arbitrary nashorn command line options when creating Context.
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    94
     */
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    95
    public static final String NASHORN_SET_CONFIG      = "nashorn.setConfig";
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    96
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    97
    /**
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    98
     * Permission needed to create Nashorn Context instance.
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
    99
     */
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   100
    public static final String NASHORN_CREATE_CONTEXT  = "nashorn.createContext";
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   101
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   102
    /**
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   103
     * Permission needed to create Nashorn Global instance.
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   104
     */
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   105
    public static final String NASHORN_CREATE_GLOBAL   = "nashorn.createGlobal";
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   106
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   107
    /**
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   108
     * Permission to get current Nashorn Context from thread local storage.
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   109
     */
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   110
    public static final String NASHORN_GET_CONTEXT     = "nashorn.getContext";
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   111
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   112
    /**
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   113
     * Permission to use Java reflection/jsr292 from script code.
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   114
     */
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   115
    public static final String NASHORN_JAVA_REFLECTION = "nashorn.JavaReflection";
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   116
22389
ea3dda90768c 8032060: PropertyMap of Error objects is not stable
sundar
parents: 20933
diff changeset
   117
    /**
ea3dda90768c 8032060: PropertyMap of Error objects is not stable
sundar
parents: 20933
diff changeset
   118
     * Permission to enable nashorn debug mode.
ea3dda90768c 8032060: PropertyMap of Error objects is not stable
sundar
parents: 20933
diff changeset
   119
     */
ea3dda90768c 8032060: PropertyMap of Error objects is not stable
sundar
parents: 20933
diff changeset
   120
    public static final String NASHORN_DEBUG_MODE = "nashorn.debugMode";
ea3dda90768c 8032060: PropertyMap of Error objects is not stable
sundar
parents: 20933
diff changeset
   121
20564
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   122
    // nashorn load psuedo URL prefixes
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   123
    private static final String LOAD_CLASSPATH = "classpath:";
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   124
    private static final String LOAD_FX = "fx:";
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   125
    private static final String LOAD_NASHORN = "nashorn:";
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   126
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
   127
    private static MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
   128
    private static MethodType CREATE_PROGRAM_FUNCTION_TYPE = MethodType.methodType(ScriptFunction.class, ScriptObject.class);
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
   129
19622
b042dad0de96 8023228: Debugger information gather is too slow.
jlaskey
parents: 19472
diff changeset
   130
    /* Force DebuggerSupport to be loaded. */
b042dad0de96 8023228: Debugger information gather is too slow.
jlaskey
parents: 19472
diff changeset
   131
    static {
b042dad0de96 8023228: Debugger information gather is too slow.
jlaskey
parents: 19472
diff changeset
   132
        DebuggerSupport.FORCELOAD = true;
b042dad0de96 8023228: Debugger information gather is too slow.
jlaskey
parents: 19472
diff changeset
   133
    }
b042dad0de96 8023228: Debugger information gather is too slow.
jlaskey
parents: 19472
diff changeset
   134
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   135
    /**
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   136
     * ContextCodeInstaller that has the privilege of installing classes in the Context.
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   137
     * Can only be instantiated from inside the context and is opaque to other classes
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   138
     */
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   139
    public static class ContextCodeInstaller implements CodeInstaller<ScriptEnvironment> {
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   140
        private final Context      context;
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   141
        private final ScriptLoader loader;
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   142
        private final CodeSource   codeSource;
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   143
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   144
        private ContextCodeInstaller(final Context context, final ScriptLoader loader, final CodeSource codeSource) {
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   145
            this.context    = context;
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   146
            this.loader     = loader;
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   147
            this.codeSource = codeSource;
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   148
        }
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   149
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   150
        /**
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   151
         * Return the context for this installer
16523
af8b30edebce 8009718: Lazy execution architecture continued - ScriptFunctionData is either final or recompilable. Moved ScriptFunctionData creation logic away from runtime to compile time. Prepared for method generation/specialization. Got rid of ScriptFunctionImplTrampoline whose semantics could be done as part of the relinking anyway. Merge with the lookup package change.
lagergren
parents: 16522
diff changeset
   152
         * @return ScriptEnvironment
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   153
         */
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   154
        @Override
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   155
        public ScriptEnvironment getOwner() {
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   156
            return context.env;
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   157
        }
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   158
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   159
        @Override
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   160
        public Class<?> install(final String className, final byte[] bytecode) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   161
            final String   binaryName = Compiler.binaryName(className);
24769
attila
parents: 24759 24282
diff changeset
   162
            return loader.installClass(binaryName, bytecode, codeSource);
attila
parents: 24759 24282
diff changeset
   163
        }
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   164
24769
attila
parents: 24759 24282
diff changeset
   165
        @Override
attila
parents: 24759 24282
diff changeset
   166
        public void initialize(final Collection<Class<?>> classes, final Source source, final Object[] constants) {
26248
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   167
            try {
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   168
                AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   169
                    @Override
26248
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   170
                    public Void run() throws Exception {
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   171
                        for (final Class<?> clazz : classes) {
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   172
                            //use reflection to write source and constants table to installed classes
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   173
                            final Field sourceField = clazz.getDeclaredField(SOURCE.symbolName());
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   174
                            sourceField.setAccessible(true);
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   175
                            sourceField.set(null, source);
24769
attila
parents: 24759 24282
diff changeset
   176
26248
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   177
                            final Field constantsField = clazz.getDeclaredField(CONSTANTS.symbolName());
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   178
                            constantsField.setAccessible(true);
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   179
                            constantsField.set(null, constants);
24769
attila
parents: 24759 24282
diff changeset
   180
                        }
26248
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   181
                        return null;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   182
                    }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   183
                });
26248
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   184
            } catch (final PrivilegedActionException e) {
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   185
                throw new RuntimeException(e);
9e9455565f77 8055954: Do not parallelize class installation
attila
parents: 26071
diff changeset
   186
            }
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   187
        }
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   188
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   189
        @Override
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   190
        public void verify(final byte[] code) {
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   191
            context.verify(code);
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   192
        }
18862
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   193
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   194
        @Override
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   195
        public long getUniqueScriptId() {
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   196
            return context.getUniqueScriptId();
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   197
        }
20929
f2bd18181940 8026167: Class cache/reuse of 'eval' scripts results in ClassCastException in some cases.
sundar
parents: 20928
diff changeset
   198
f2bd18181940 8026167: Class cache/reuse of 'eval' scripts results in ClassCastException in some cases.
sundar
parents: 20928
diff changeset
   199
        @Override
26508
b40ef4386b01 8057021: UserAccessorProperty guards fail with multiple globals
hannesw
parents: 26504
diff changeset
   200
        public void storeScript(final String cacheKey, final Source source, final String mainClassName,
26067
b32ccc3a76c9 8055199: Tidy up Nashorn codebase for code standards (August 2014)
attila
parents: 26065
diff changeset
   201
                                final Map<String,byte[]> classBytes, final Map<Integer, FunctionInitializer> initializers,
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   202
                                final Object[] constants, final int compilationId) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   203
            if (context.codeStore != null) {
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
   204
                context.codeStore.store(cacheKey, source, mainClassName, classBytes, initializers, constants, compilationId);
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   205
            }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   206
        }
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   207
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   208
        @Override
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   209
        public StoredScript loadScript(final Source source, final String functionKey) {
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   210
            if (context.codeStore != null) {
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
   211
                return context.codeStore.load(source, functionKey);
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   212
            }
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   213
            return null;
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
   214
        }
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   215
    }
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   216
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   217
    /** Is Context global debug mode enabled ? */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   218
    public static final boolean DEBUG = Options.getBooleanProperty("nashorn.debug");
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   219
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   220
    private static final ThreadLocal<Global> currentGlobal = new ThreadLocal<>();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   221
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   222
    // in-memory cache for loaded classes
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   223
    private ClassCache classCache;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   224
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   225
    // persistent code store
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   226
    private CodeStore codeStore;
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   227
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   228
    /**
16188
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   229
     * Get the current global scope
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   230
     * @return the current global scope
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   231
     */
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   232
    public static Global getGlobal() {
17231
734f61d5a097 8012612: Compile failed
sundar
parents: 16947
diff changeset
   233
        // This class in a package.access protected package.
734f61d5a097 8012612: Compile failed
sundar
parents: 16947
diff changeset
   234
        // Trusted code only can call this method.
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   235
        return currentGlobal.get();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   236
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   237
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   238
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   239
     * Set the current global scope
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   240
     * @param global the global scope
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   241
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   242
    public static void setGlobal(final ScriptObject global) {
18851
bdb92c95f886 8019947: inherited property invalidation does not work with two globals in same context
sundar
parents: 18618
diff changeset
   243
        if (global != null && !(global instanceof Global)) {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   244
            throw new IllegalArgumentException("not a global!");
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   245
        }
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   246
        setGlobal((Global)global);
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   247
    }
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   248
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   249
    /**
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   250
     * Set the current global scope
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   251
     * @param global the global scope
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   252
     */
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   253
    public static void setGlobal(final Global global) {
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   254
        // This class in a package.access protected package.
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   255
        // Trusted code only can call this method.
24733
1e825be55fd1 8027043: Turn global accesses into MethodHandle.constant, with one chance of reassignment, e.g. x = value occuring once in the global scope is ok, twice is not.
lagergren
parents: 24731
diff changeset
   256
        assert getGlobal() != global;
1e825be55fd1 8027043: Turn global accesses into MethodHandle.constant, with one chance of reassignment, e.g. x = value occuring once in the global scope is ok, twice is not.
lagergren
parents: 24731
diff changeset
   257
        //same code can be cached between globals, then we need to invalidate method handle constants
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
   258
        if (global != null) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
   259
            Global.getConstants().invalidateAll();
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
   260
        }
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   261
        currentGlobal.set(global);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   262
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   263
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   264
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   265
     * Get context of the current global
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   266
     * @return current global scope's context.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   267
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   268
    public static Context getContext() {
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   269
        final SecurityManager sm = System.getSecurityManager();
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   270
        if (sm != null) {
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   271
            sm.checkPermission(new RuntimePermission(NASHORN_GET_CONTEXT));
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   272
        }
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   273
        return getContextTrusted();
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   274
    }
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   275
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   276
    /**
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   277
     * Get current context's error writer
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   278
     *
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   279
     * @return error writer of the current context
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   280
     */
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   281
    public static PrintWriter getCurrentErr() {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   282
        final ScriptObject global = getGlobal();
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   283
        return (global != null)? global.getContext().getErr() : new PrintWriter(System.err);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   284
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   285
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   286
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   287
     * Output text to this Context's error stream
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   288
     * @param str text to write
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   289
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   290
    public static void err(final String str) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   291
        err(str, true);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   292
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   293
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   294
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   295
     * Output text to this Context's error stream, optionally with
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   296
     * a newline afterwards
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   297
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   298
     * @param str  text to write
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   299
     * @param crlf write a carriage return/new line after text
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   300
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   301
    public static void err(final String str, final boolean crlf) {
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   302
        final PrintWriter err = Context.getCurrentErr();
16155
a8ab83cbaa49 8005788: Loggers and their corresponding system properties not working correctly
lagergren
parents: 16151
diff changeset
   303
        if (err != null) {
a8ab83cbaa49 8005788: Loggers and their corresponding system properties not working correctly
lagergren
parents: 16151
diff changeset
   304
            if (crlf) {
a8ab83cbaa49 8005788: Loggers and their corresponding system properties not working correctly
lagergren
parents: 16151
diff changeset
   305
                err.println(str);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   306
            } else {
16155
a8ab83cbaa49 8005788: Loggers and their corresponding system properties not working correctly
lagergren
parents: 16151
diff changeset
   307
                err.print(str);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   308
            }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   309
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   310
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   311
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   312
    /** Current environment. */
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   313
    private final ScriptEnvironment env;
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   314
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   315
    /** is this context in strict mode? Cached from env. as this is used heavily. */
18328
ebd24057f163 8015355: Array.prototype functions don't honour non-writable length and / or index properties
sundar
parents: 18321
diff changeset
   316
    final boolean _strict;
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   317
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   318
    /** class loader to resolve classes from script. */
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   319
    private final ClassLoader  appLoader;
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   320
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   321
    /** Class loader to load classes from -classpath option, if set. */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   322
    private final ClassLoader  classPathLoader;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   323
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   324
    /** Class loader to load classes compiled from scripts. */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   325
    private final ScriptLoader scriptLoader;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   326
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   327
    /** Current error manager. */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   328
    private final ErrorManager errors;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   329
18862
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   330
    /** Unique id for script. Used only when --loader-per-compile=false */
18864
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   331
    private final AtomicLong uniqueScriptId;
18862
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
   332
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   333
    /** Optional class filter to use for Java classes. Can be null. */
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   334
    private final ClassFilter classFilter;
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   335
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   336
    private static final ClassLoader myLoader = Context.class.getClassLoader();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   337
    private static final StructureLoader sharedLoader;
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   338
20933
89748612fd1d 8026250: Logging nullpointer bugfix and javadoc warnings
lagergren
parents: 20929
diff changeset
   339
    /*package-private*/ @SuppressWarnings("static-method")
89748612fd1d 8026250: Logging nullpointer bugfix and javadoc warnings
lagergren
parents: 20929
diff changeset
   340
    ClassLoader getSharedLoader() {
19895
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
   341
        return sharedLoader;
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
   342
    }
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
   343
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   344
    private static AccessControlContext createNoPermAccCtxt() {
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   345
        return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) });
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   346
    }
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   347
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   348
    private static AccessControlContext createPermAccCtxt(final String permName) {
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   349
        final Permissions perms = new Permissions();
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   350
        perms.add(new RuntimePermission(permName));
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   351
        return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   352
    }
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   353
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   354
    private static final AccessControlContext NO_PERMISSIONS_ACC_CTXT = createNoPermAccCtxt();
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   355
    private static final AccessControlContext CREATE_LOADER_ACC_CTXT  = createPermAccCtxt("createClassLoader");
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   356
    private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT  = createPermAccCtxt(NASHORN_CREATE_GLOBAL);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   357
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   358
    static {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   359
        sharedLoader = AccessController.doPrivileged(new PrivilegedAction<StructureLoader>() {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   360
            @Override
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   361
            public StructureLoader run() {
19895
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
   362
                return new StructureLoader(myLoader);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   363
            }
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   364
        }, CREATE_LOADER_ACC_CTXT);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   365
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   366
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   367
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   368
     * ThrowErrorManager that throws ParserException upon error conditions.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   369
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   370
    public static class ThrowErrorManager extends ErrorManager {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   371
        @Override
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   372
        public void error(final String message) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   373
            throw new ParserException(message);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   374
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   375
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   376
        @Override
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   377
        public void error(final ParserException e) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   378
            throw e;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   379
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   380
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   381
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   382
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   383
     * Constructor
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   384
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   385
     * @param options options from command line or Context creator
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   386
     * @param errors  error manger
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   387
     * @param appLoader application class loader
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   388
     */
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   389
    public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader) {
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   390
        this(options, errors, appLoader, (ClassFilter)null);
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   391
    }
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   392
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   393
    /**
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   394
     * Constructor
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   395
     *
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   396
     * @param options options from command line or Context creator
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   397
     * @param errors  error manger
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   398
     * @param appLoader application class loader
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   399
     * @param classFilter class filter to use
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   400
     */
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   401
    public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader, final ClassFilter classFilter) {
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   402
        this(options, errors, new PrintWriter(System.out, true), new PrintWriter(System.err, true), appLoader, classFilter);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   403
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   404
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   405
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   406
     * Constructor
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   407
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   408
     * @param options options from command line or Context creator
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   409
     * @param errors  error manger
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   410
     * @param out     output writer for this Context
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   411
     * @param err     error writer for this Context
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   412
     * @param appLoader application class loader
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   413
     */
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   414
    public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader) {
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   415
        this(options, errors, out, err, appLoader, (ClassFilter)null);
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   416
    }
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   417
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   418
    /**
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   419
     * Constructor
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   420
     *
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   421
     * @param options options from command line or Context creator
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   422
     * @param errors  error manger
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   423
     * @param out     output writer for this Context
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   424
     * @param err     error writer for this Context
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   425
     * @param appLoader application class loader
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   426
     * @param classFilter class filter to use
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   427
     */
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   428
    public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader, final ClassFilter classFilter) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   429
        final SecurityManager sm = System.getSecurityManager();
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   430
        if (sm != null) {
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   431
            sm.checkPermission(new RuntimePermission(NASHORN_CREATE_CONTEXT));
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   432
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   433
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   434
        this.classFilter = classFilter;
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   435
        this.env       = new ScriptEnvironment(options, out, err);
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   436
        this._strict   = env._strict;
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   437
        this.appLoader = appLoader;
18864
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   438
        if (env._loader_per_compile) {
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   439
            this.scriptLoader = null;
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   440
            this.uniqueScriptId = null;
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   441
        } else {
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   442
            this.scriptLoader = createNewLoader();
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   443
            this.uniqueScriptId = new AtomicLong();
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
   444
        }
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   445
        this.errors    = errors;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   446
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   447
        // if user passed -classpath option, make a class loader with that and set it as
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   448
        // thread context class loader so that script can access classes from that path.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   449
        final String classPath = options.getString("classpath");
24719
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
   450
        if (!env._compile_only && classPath != null && !classPath.isEmpty()) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   451
            // make sure that caller can create a class loader.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   452
            if (sm != null) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   453
                sm.checkPermission(new RuntimePermission("createClassLoader"));
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   454
            }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   455
            this.classPathLoader = NashornLoader.createClassLoader(classPath);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   456
        } else {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   457
            this.classPathLoader = null;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   458
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   459
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   460
        final int cacheSize = env._class_cache_size;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   461
        if (cacheSize > 0) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   462
            classCache = new ClassCache(cacheSize);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   463
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   464
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   465
        if (env._persistent_cache) {
25243
7a1edca6ce94 8048079: Persistent code store is broken after optimistic types merge
hannesw
parents: 25240
diff changeset
   466
            try {
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
   467
                codeStore = newCodeStore(this);
25243
7a1edca6ce94 8048079: Persistent code store is broken after optimistic types merge
hannesw
parents: 25240
diff changeset
   468
            } catch (final IOException e) {
7a1edca6ce94 8048079: Persistent code store is broken after optimistic types merge
hannesw
parents: 25240
diff changeset
   469
                throw new RuntimeException("Error initializing code cache", e);
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   470
            }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   471
        }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
   472
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   473
        // print version info if asked.
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   474
        if (env._version) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   475
            getErr().println("nashorn " + Version.version());
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   476
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   477
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   478
        if (env._fullversion) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   479
            getErr().println("nashorn full version " + Version.fullVersion());
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   480
        }
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
   481
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
   482
        initLoggers();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   483
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   484
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   485
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   486
    /**
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   487
     * Get the class filter for this context
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   488
     * @return class filter
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   489
     */
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   490
    public ClassFilter getClassFilter() {
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   491
        return classFilter;
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   492
    }
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   493
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   494
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   495
     * Get the error manager for this context
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   496
     * @return error manger
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   497
     */
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   498
    public ErrorManager getErrorManager() {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   499
        return errors;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   500
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   501
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   502
    /**
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   503
     * Get the script environment for this context
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   504
     * @return script environment
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   505
     */
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   506
    public ScriptEnvironment getEnv() {
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   507
        return env;
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   508
    }
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   509
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   510
    /**
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   511
     * Get the output stream for this context
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   512
     * @return output print writer
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   513
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   514
    public PrintWriter getOut() {
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   515
        return env.getOut();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   516
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   517
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   518
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   519
     * Get the error stream for this context
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   520
     * @return error print writer
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   521
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   522
    public PrintWriter getErr() {
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   523
        return env.getErr();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   524
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   525
16201
889ddb179cdf 8007062: Split Lower up into Lower/Attr/FinalizeTypes. Integrate AccessSpecalizer into FinalizeTypes.
lagergren
parents: 16196
diff changeset
   526
    /**
16188
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   527
     * Get the PropertyMap of the current global scope
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   528
     * @return the property map of the current global scope
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   529
     */
16201
889ddb179cdf 8007062: Split Lower up into Lower/Attr/FinalizeTypes. Integrate AccessSpecalizer into FinalizeTypes.
lagergren
parents: 16196
diff changeset
   530
    public static PropertyMap getGlobalMap() {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   531
        return Context.getGlobal().getMap();
16188
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   532
    }
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
   533
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   534
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   535
     * Compile a top level script.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   536
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   537
     * @param source the source
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   538
     * @param scope  the scope
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   539
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   540
     * @return top level function for script
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   541
     */
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   542
    public ScriptFunction compileScript(final Source source, final ScriptObject scope) {
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   543
        return compileScript(source, scope, this.errors);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   544
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   545
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   546
    /**
24282
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   547
     * Interface to represent compiled code that can be re-used across many
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   548
     * global scope instances
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   549
     */
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   550
    public static interface MultiGlobalCompiledScript {
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   551
        /**
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   552
         * Obtain script function object for a specific global scope object.
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   553
         *
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   554
         * @param newGlobal global scope for which function object is obtained
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   555
         * @return script function for script level expressions
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   556
         */
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   557
        public ScriptFunction getFunction(final Global newGlobal);
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   558
    }
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   559
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   560
    /**
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   561
     * Compile a top level script.
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   562
     *
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   563
     * @param source the script source
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   564
     * @return reusable compiled script across many global scopes.
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   565
     */
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   566
    public MultiGlobalCompiledScript compileScript(final Source source) {
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   567
        final Class<?> clazz = compile(source, this.errors, this._strict);
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
   568
        final MethodHandle createProgramFunctionHandle = getCreateProgramFunctionHandle(clazz);
24282
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   569
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   570
        return new MultiGlobalCompiledScript() {
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   571
            @Override
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   572
            public ScriptFunction getFunction(final Global newGlobal) {
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
   573
                return invokeCreateProgramFunctionHandle(createProgramFunctionHandle, newGlobal);
24282
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   574
            }
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   575
        };
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   576
    }
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   577
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
   578
    /**
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   579
     * Entry point for {@code eval}
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   580
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   581
     * @param initialScope The scope of this eval call
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   582
     * @param string       Evaluated code as a String
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   583
     * @param callThis     "this" to be passed to the evaluated code
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   584
     * @param location     location of the eval call
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   585
     * @param strict       is this {@code eval} call from a strict mode code?
25240
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   586
     * @return the return value of the {@code eval}
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   587
     */
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   588
    public Object eval(final ScriptObject initialScope, final String string,
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   589
            final Object callThis, final Object location, final boolean strict) {
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   590
        return eval(initialScope, string, callThis, location, strict, false);
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   591
    }
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   592
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   593
    /**
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   594
     * Entry point for {@code eval}
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   595
     *
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   596
     * @param initialScope The scope of this eval call
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   597
     * @param string       Evaluated code as a String
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   598
     * @param callThis     "this" to be passed to the evaluated code
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   599
     * @param location     location of the eval call
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   600
     * @param strict       is this {@code eval} call from a strict mode code?
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   601
     * @param evalCall     is this called from "eval" builtin?
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   602
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   603
     * @return the return value of the {@code eval}
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   604
     */
25240
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   605
    public Object eval(final ScriptObject initialScope, final String string,
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   606
            final Object callThis, final Object location, final boolean strict, final boolean evalCall) {
24725
7bb1f687a852 8033334: Make sure that scope depth information is maintained in the RecompilableScriptFunctionDatas, to avoid unnecessary slow proto linkage when doing on demand compilation
lagergren
parents: 24719
diff changeset
   607
        final String  file       = location == UNDEFINED || location == null ? "<eval>" : location.toString();
25240
f92c14b1ca11 8047959: bindings created for declarations in eval code are not mutable
sundar
parents: 24993
diff changeset
   608
        final Source  source     = sourceFor(file, string, evalCall);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   609
        final boolean directEval = location != UNDEFINED; // is this direct 'eval' call or indirectly invoked eval?
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   610
        final Global  global = Context.getGlobal();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   611
        ScriptObject scope = initialScope;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   612
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   613
        // ECMA section 10.1.1 point 2 says eval code is strict if it begins
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   614
        // with "use strict" directive or eval direct call itself is made
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   615
        // from from strict mode code. We are passed with caller's strict mode.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   616
        boolean strictFlag = directEval && strict;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   617
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   618
        Class<?> clazz = null;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   619
        try {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   620
            clazz = compile(source, new ThrowErrorManager(), strictFlag);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   621
        } catch (final ParserException e) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   622
            e.throwAsEcmaException(global);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   623
            return null;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   624
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   625
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   626
        if (!strictFlag) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   627
            // We need to get strict mode flag from compiled class. This is
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   628
            // because eval code may start with "use strict" directive.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   629
            try {
17233
72ccf78a8216 8010701: Immutable nodes - final iteration
lagergren
parents: 17231
diff changeset
   630
                strictFlag = clazz.getField(STRICT_MODE.symbolName()).getBoolean(null);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   631
            } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   632
                //ignored
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   633
                strictFlag = false;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   634
            }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   635
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   636
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   637
        // In strict mode, eval does not instantiate variables and functions
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   638
        // in the caller's environment. A new environment is created!
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   639
        if (strictFlag) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   640
            // Create a new scope object
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   641
            final ScriptObject strictEvalScope = global.newObject();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   642
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   643
            // bless it as a "scope"
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   644
            strictEvalScope.setIsScope();
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   645
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   646
            // set given scope to be it's proto so that eval can still
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   647
            // access caller environment vars in the new environment.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   648
            strictEvalScope.setProto(scope);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   649
            scope = strictEvalScope;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   650
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   651
24725
7bb1f687a852 8033334: Make sure that scope depth information is maintained in the RecompilableScriptFunctionDatas, to avoid unnecessary slow proto linkage when doing on demand compilation
lagergren
parents: 24719
diff changeset
   652
        final ScriptFunction func = getProgramFunction(clazz, scope);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   653
        Object evalThis;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   654
        if (directEval) {
24725
7bb1f687a852 8033334: Make sure that scope depth information is maintained in the RecompilableScriptFunctionDatas, to avoid unnecessary slow proto linkage when doing on demand compilation
lagergren
parents: 24719
diff changeset
   655
            evalThis = callThis instanceof ScriptObject || strictFlag ? callThis : global;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   656
        } else {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   657
            evalThis = global;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   658
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   659
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   660
        return ScriptRuntime.apply(func, evalThis);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   661
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   662
17518
2225a4f929c0 8013477: Node.setSymbol needs to be copy on write - enable IR snapshots for recompilation based on callsite type specialization. [not enabled by default, hidden by a flag for now]
lagergren
parents: 17513
diff changeset
   663
    private static Source loadInternal(final String srcStr, final String prefix, final String resourcePath) {
17244
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   664
        if (srcStr.startsWith(prefix)) {
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   665
            final String resource = resourcePath + srcStr.substring(prefix.length());
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   666
            // NOTE: even sandbox scripts should be able to load scripts in nashorn: scheme
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   667
            // These scripts are always available and are loaded from nashorn.jar's resources.
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   668
            return AccessController.doPrivileged(
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   669
                    new PrivilegedAction<Source>() {
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   670
                        @Override
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   671
                        public Source run() {
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   672
                            try {
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   673
                                final URL resURL = Context.class.getResource(resource);
24769
attila
parents: 24759 24282
diff changeset
   674
                                return resURL != null ? sourceFor(srcStr, resURL) : null;
17244
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   675
                            } catch (final IOException exp) {
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   676
                                return null;
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   677
                            }
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   678
                        }
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   679
                    });
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   680
        }
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   681
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   682
        return null;
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   683
    }
041afba4cec5 8012251: jjs should support -fx option
jlaskey
parents: 17233
diff changeset
   684
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   685
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   686
     * Implementation of {@code load} Nashorn extension. Load a script file from a source
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   687
     * expression
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   688
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   689
     * @param scope  the scope
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   690
     * @param from   source expression for script
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   691
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   692
     * @return return value for load call (undefined)
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   693
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   694
     * @throws IOException if source cannot be found or loaded
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   695
     */
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   696
    public Object load(final ScriptObject scope, final Object from) throws IOException {
24725
7bb1f687a852 8033334: Make sure that scope depth information is maintained in the RecompilableScriptFunctionDatas, to avoid unnecessary slow proto linkage when doing on demand compilation
lagergren
parents: 24719
diff changeset
   697
        final Object src = from instanceof ConsString ? from.toString() : from;
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   698
        Source source = null;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   699
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   700
        // load accepts a String (which could be a URL or a file name), a File, a URL
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   701
        // or a ScriptObject that has "name" and "source" (string valued) properties.
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   702
        if (src instanceof String) {
16251
4a5d15b2f168 8008166: URL handling was broken on windows, causing "load" to malfunction
lagergren
parents: 16245
diff changeset
   703
            final String srcStr = (String)src;
20564
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   704
            if (srcStr.startsWith(LOAD_CLASSPATH)) {
24725
7bb1f687a852 8033334: Make sure that scope depth information is maintained in the RecompilableScriptFunctionDatas, to avoid unnecessary slow proto linkage when doing on demand compilation
lagergren
parents: 24719
diff changeset
   705
                final URL url = getResourceURL(srcStr.substring(LOAD_CLASSPATH.length()));
24769
attila
parents: 24759 24282
diff changeset
   706
                source = url != null ? sourceFor(url.toString(), url) : null;
20564
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   707
            } else {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   708
                final File file = new File(srcStr);
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   709
                if (srcStr.indexOf(':') != -1) {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   710
                    if ((source = loadInternal(srcStr, LOAD_NASHORN, "resources/")) == null &&
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   711
                        (source = loadInternal(srcStr, LOAD_FX, "resources/fx/")) == null) {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   712
                        URL url;
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   713
                        try {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   714
                            //check for malformed url. if malformed, it may still be a valid file
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   715
                            url = new URL(srcStr);
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   716
                        } catch (final MalformedURLException e) {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   717
                            url = file.toURI().toURL();
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   718
                        }
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
   719
                        source = sourceFor(url.toString(), url);
16254
2ed824fc93be 8008554: load was broken for URLs
lagergren
parents: 16251
diff changeset
   720
                    }
20564
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
   721
                } else if (file.isFile()) {
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
   722
                    source = sourceFor(srcStr, file);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   723
                }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   724
            }
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   725
        } else if (src instanceof File && ((File)src).isFile()) {
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   726
            final File file = (File)src;
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
   727
            source = sourceFor(file.getName(), file);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   728
        } else if (src instanceof URL) {
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   729
            final URL url = (URL)src;
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
   730
            source = sourceFor(url.toString(), url);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   731
        } else if (src instanceof ScriptObject) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   732
            final ScriptObject sobj = (ScriptObject)src;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   733
            if (sobj.has("script") && sobj.has("name")) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   734
                final String script = JSType.toString(sobj.get("script"));
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   735
                final String name   = JSType.toString(sobj.get("name"));
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
   736
                source = sourceFor(name, script);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   737
            }
18334
47413e8d71b5 8016618: script mirror object access should be improved
sundar
parents: 18328
diff changeset
   738
        } else if (src instanceof Map) {
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
   739
            final Map<?,?> map = (Map<?,?>)src;
18334
47413e8d71b5 8016618: script mirror object access should be improved
sundar
parents: 18328
diff changeset
   740
            if (map.containsKey("script") && map.containsKey("name")) {
47413e8d71b5 8016618: script mirror object access should be improved
sundar
parents: 18328
diff changeset
   741
                final String script = JSType.toString(map.get("script"));
47413e8d71b5 8016618: script mirror object access should be improved
sundar
parents: 18328
diff changeset
   742
                final String name   = JSType.toString(map.get("name"));
24206
40c6d45af73f 8040078: Avoid repeated reading of source for cached loads
hannesw
parents: 23767
diff changeset
   743
                source = sourceFor(name, script);
18334
47413e8d71b5 8016618: script mirror object access should be improved
sundar
parents: 18328
diff changeset
   744
            }
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   745
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   746
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   747
        if (source != null) {
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   748
            return evaluateSource(source, scope, scope);
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   749
        }
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
   750
16256
f2d9a0c49914 8007002: Replace implicit exception throwing methods with explicit throws - simplify control flow and remove useless code
lagergren
parents: 16254
diff changeset
   751
        throw typeError("cant.load.script", ScriptRuntime.safeToString(from));
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   752
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   753
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   754
    /**
17974
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   755
     * Implementation of {@code loadWithNewGlobal} Nashorn extension. Load a script file from a source
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   756
     * expression, after creating a new global scope.
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   757
     *
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   758
     * @param from source expression for script
18321
b2ceadf211cb 8016239: loadWithNewGlobal should support user supplied arguments from the caller
sundar
parents: 17982
diff changeset
   759
     * @param args (optional) arguments to be passed to the loaded script
17974
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   760
     *
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   761
     * @return return value for load call (undefined)
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   762
     *
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   763
     * @throws IOException if source cannot be found or loaded
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   764
     */
18321
b2ceadf211cb 8016239: loadWithNewGlobal should support user supplied arguments from the caller
sundar
parents: 17982
diff changeset
   765
    public Object loadWithNewGlobal(final Object from, final Object...args) throws IOException {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   766
        final Global oldGlobal = getGlobal();
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   767
        final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
17976
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   768
           @Override
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   769
           public Global run() {
17976
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   770
               try {
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   771
                   return newGlobal();
17976
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   772
               } catch (final RuntimeException e) {
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   773
                   if (Context.DEBUG) {
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   774
                       e.printStackTrace();
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   775
                   }
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   776
                   throw e;
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   777
               }
5615a31822a1 8015814: loadWithNewGlobal needs to wrap createGlobal in AccessController.doPrivileged
jlaskey
parents: 17974
diff changeset
   778
           }
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   779
        }, CREATE_GLOBAL_ACC_CTXT);
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   780
        // initialize newly created Global instance
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
   781
        initGlobal(newGlobal);
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   782
        setGlobal(newGlobal);
17974
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   783
18874
8ba96bd382d3 8020463: Input argument array wrapping in loadWithNewGlobal is wrong
sundar
parents: 18865
diff changeset
   784
        final Object[] wrapped = args == null? ScriptRuntime.EMPTY_ARRAY :  ScriptObjectMirror.wrapArray(args, oldGlobal);
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   785
        newGlobal.put("arguments", newGlobal.wrapAsObject(wrapped), env._strict);
18321
b2ceadf211cb 8016239: loadWithNewGlobal should support user supplied arguments from the caller
sundar
parents: 17982
diff changeset
   786
17974
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   787
        try {
18874
8ba96bd382d3 8020463: Input argument array wrapping in loadWithNewGlobal is wrong
sundar
parents: 18865
diff changeset
   788
            // wrap objects from newGlobal's world as mirrors - but if result
8ba96bd382d3 8020463: Input argument array wrapping in loadWithNewGlobal is wrong
sundar
parents: 18865
diff changeset
   789
            // is from oldGlobal's world, unwrap it!
8ba96bd382d3 8020463: Input argument array wrapping in loadWithNewGlobal is wrong
sundar
parents: 18865
diff changeset
   790
            return ScriptObjectMirror.unwrap(ScriptObjectMirror.wrap(load(newGlobal, from), newGlobal), oldGlobal);
17974
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   791
        } finally {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   792
            setGlobal(oldGlobal);
17974
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   793
        }
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   794
    }
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   795
a2818f17324e 8015741: Need a global.load function that starts with a new global scope.
jlaskey
parents: 17524
diff changeset
   796
    /**
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   797
     * Load or get a structure class. Structure class names are based on the number of parameter fields
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   798
     * and {@link AccessorProperty} fields in them. Structure classes are used to represent ScriptObjects
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   799
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   800
     * @see ObjectClassGenerator
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   801
     * @see AccessorProperty
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   802
     * @see ScriptObject
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   803
     *
16275
d5d430071b22 8009379: Remove $ from generated class names
jlaskey
parents: 16272
diff changeset
   804
     * @param fullName  full name of class, e.g. jdk.nashorn.internal.objects.JO2P1 contains 2 fields and 1 parameter.
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   805
     *
16272
675a0caf75bc 8009263: Fix all javadoc errors in nashorn code
sundar
parents: 16262
diff changeset
   806
     * @return the {@code Class<?>} for this structure
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   807
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   808
     * @throws ClassNotFoundException if structure class cannot be resolved
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   809
     */
24719
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
   810
    @SuppressWarnings("unchecked")
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
   811
    public static Class<? extends ScriptObject> forStructureClass(final String fullName) throws ClassNotFoundException {
19895
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
   812
        if (System.getSecurityManager() != null && !StructureLoader.isStructureClass(fullName)) {
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
   813
            throw new ClassNotFoundException(fullName);
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
   814
        }
24719
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
   815
        return (Class<? extends ScriptObject>)Class.forName(fullName, true, sharedLoader);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   816
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   817
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   818
    /**
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   819
     * Checks that the given Class can be accessed from no permissions context.
18865
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   820
     *
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   821
     * @param clazz Class object
23374
f470afc89c6c 8015958: DataView constructor is not defined
sundar
parents: 23372
diff changeset
   822
     * @throws SecurityException if not accessible
18865
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   823
     */
20928
3ff39d5c8c08 8026137: Fix Issues with Binary Evaluation Order
lagergren
parents: 20567
diff changeset
   824
    public static void checkPackageAccess(final Class<?> clazz) {
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   825
        final SecurityManager sm = System.getSecurityManager();
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   826
        if (sm != null) {
20928
3ff39d5c8c08 8026137: Fix Issues with Binary Evaluation Order
lagergren
parents: 20567
diff changeset
   827
            Class<?> bottomClazz = clazz;
3ff39d5c8c08 8026137: Fix Issues with Binary Evaluation Order
lagergren
parents: 20567
diff changeset
   828
            while (bottomClazz.isArray()) {
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   829
                bottomClazz = bottomClazz.getComponentType();
18865
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   830
            }
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   831
            checkPackageAccess(sm, bottomClazz.getName());
18865
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   832
        }
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   833
    }
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   834
8844964e5fc5 8020325: static property does not work on accessible, public classes
sundar
parents: 18864
diff changeset
   835
    /**
22669
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   836
     * Checks that the given package name can be accessed from no permissions context.
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   837
     *
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   838
     * @param pkgName package name
23374
f470afc89c6c 8015958: DataView constructor is not defined
sundar
parents: 23372
diff changeset
   839
     * @throws SecurityException if not accessible
22669
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   840
     */
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   841
    public static void checkPackageAccess(final String pkgName) {
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   842
        final SecurityManager sm = System.getSecurityManager();
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   843
        if (sm != null) {
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
   844
            checkPackageAccess(sm, pkgName.endsWith(".") ? pkgName : pkgName + ".");
22669
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   845
        }
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   846
    }
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   847
75563515567f 8032681: Issues with Nashorn
attila
parents: 22389
diff changeset
   848
    /**
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
   849
     * Checks that the given package can be accessed from no permissions context.
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   850
     *
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   851
     * @param sm current security manager instance
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   852
     * @param fullName fully qualified package name
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   853
     * @throw SecurityException if not accessible
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   854
     */
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   855
    private static void checkPackageAccess(final SecurityManager sm, final String fullName) {
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   856
        sm.getClass(); // null check
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   857
        final int index = fullName.lastIndexOf('.');
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   858
        if (index != -1) {
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   859
            final String pkgName = fullName.substring(0, index);
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   860
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   861
                @Override
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   862
                public Void run() {
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   863
                    sm.checkPackageAccess(pkgName);
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   864
                    return null;
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   865
                }
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   866
            }, NO_PERMISSIONS_ACC_CTXT);
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   867
        }
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   868
    }
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   869
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   870
    /**
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   871
     * Checks that the given Class can be accessed from no permissions context.
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   872
     *
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   873
     * @param clazz Class object
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   874
     * @return true if package is accessible, false otherwise
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   875
     */
20928
3ff39d5c8c08 8026137: Fix Issues with Binary Evaluation Order
lagergren
parents: 20567
diff changeset
   876
    private static boolean isAccessiblePackage(final Class<?> clazz) {
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   877
        try {
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   878
            checkPackageAccess(clazz);
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   879
            return true;
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   880
        } catch (final SecurityException se) {
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   881
            return false;
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   882
        }
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   883
    }
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   884
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   885
    /**
19097
f544a2ea40ef 8021262: Make nashorn access checks consistent with underlying dynalink
sundar
parents: 19088
diff changeset
   886
     * Checks that the given Class is public and it can be accessed from no permissions context.
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   887
     *
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   888
     * @param clazz Class object to check
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   889
     * @return true if Class is accessible, false otherwise
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   890
     */
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   891
    public static boolean isAccessibleClass(final Class<?> clazz) {
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   892
        return Modifier.isPublic(clazz.getModifiers()) && Context.isAccessiblePackage(clazz);
19088
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   893
    }
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   894
153f268bfa72 8021122: Not all callables are handled for toString and other function valued properties
sundar
parents: 19085
diff changeset
   895
    /**
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   896
     * Lookup a Java class. This is used for JSR-223 stuff linking in from
17524
703643aeb0d6 8013914: Removed explicit LineNumberNodes that were too brittle when code moves around, and also introduced unnecessary footprint. Introduced the Statement node and fixed dead code elimination issues that were discovered by the absense of labels for LineNumberNodes.
lagergren
parents: 17519
diff changeset
   897
     * {@code jdk.nashorn.internal.objects.NativeJava} and {@code jdk.nashorn.internal.runtime.NativeJavaPackage}
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   898
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   899
     * @param fullName full name of class to load
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   900
     *
16272
675a0caf75bc 8009263: Fix all javadoc errors in nashorn code
sundar
parents: 16262
diff changeset
   901
     * @return the {@code Class<?>} for the name
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   902
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   903
     * @throws ClassNotFoundException if class cannot be resolved
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   904
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   905
    public Class<?> findClass(final String fullName) throws ClassNotFoundException {
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   906
        if (fullName.indexOf('[') != -1 || fullName.indexOf('/') != -1) {
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   907
            // don't allow array class names or internal names.
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   908
            throw new ClassNotFoundException(fullName);
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   909
        }
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   910
26071
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   911
        // give chance to ClassFilter to filter out, if present
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   912
        if (classFilter != null && !classFilter.exposeToScripts(fullName)) {
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   913
            throw new ClassNotFoundException(fullName);
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   914
        }
430e39f6731f 8050078: Nashorn ClassFilter Support
sundar
parents: 26068
diff changeset
   915
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   916
        // check package access as soon as possible!
20567
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   917
        final SecurityManager sm = System.getSecurityManager();
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   918
        if (sm != null) {
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   919
            checkPackageAccess(sm, fullName);
5621fc356049 8025771: Enhance Nashorn Contexts
sundar
parents: 20564
diff changeset
   920
        }
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   921
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   922
        // try the script -classpath loader, if that is set
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   923
        if (classPathLoader != null) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   924
            try {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   925
                return Class.forName(fullName, true, classPathLoader);
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   926
            } catch (final ClassNotFoundException ignored) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   927
                // ignore, continue search
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   928
            }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   929
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   930
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   931
        // Try finding using the "app" loader.
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   932
        return Class.forName(fullName, true, appLoader);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   933
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   934
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   935
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   936
     * Hook to print stack trace for a {@link Throwable} that occurred during
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   937
     * execution
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   938
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   939
     * @param t throwable for which to dump stack
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   940
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   941
    public static void printStackTrace(final Throwable t) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   942
        if (Context.DEBUG) {
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   943
            t.printStackTrace(Context.getCurrentErr());
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   944
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   945
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   946
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   947
    /**
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   948
     * Verify generated bytecode before emission. This is called back from the
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   949
     * {@link ObjectClassGenerator} or the {@link Compiler}. If the "--verify-code" parameter
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   950
     * hasn't been given, this is a nop
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   951
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   952
     * Note that verification may load classes -- we don't want to do that unless
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   953
     * user specified verify option. We check it here even though caller
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   954
     * may have already checked that flag
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   955
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   956
     * @param bytecode bytecode to verify
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   957
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   958
    public void verify(final byte[] bytecode) {
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   959
        if (env._verify_code) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   960
            // No verification when security manager is around as verifier
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   961
            // may load further classes - which should be avoided.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   962
            if (System.getSecurityManager() == null) {
19098
473dfe87bb7b 8021294: --verify-code option results in AnalyzerException
sundar
parents: 19097
diff changeset
   963
                CheckClassAdapter.verify(new ClassReader(bytecode), sharedLoader, false, new PrintWriter(System.err, true));
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   964
            }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   965
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   966
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   967
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   968
    /**
16211
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   969
     * Create and initialize a new global scope object.
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   970
     *
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   971
     * @return the initialized global scope object.
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   972
     */
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   973
    public Global createGlobal() {
16211
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   974
        return initGlobal(newGlobal());
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   975
    }
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   976
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   977
    /**
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   978
     * Create a new uninitialized global scope object
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   979
     * @return the global script object
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   980
     */
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   981
    public Global newGlobal() {
19085
066c9e5afd79 8020731: Revisit checkPermission calls in Context class
sundar
parents: 18874
diff changeset
   982
        return new Global(this);
16211
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   983
    }
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   984
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   985
    /**
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   986
     * Initialize given global scope object.
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   987
     *
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
   988
     * @param global the global
25422
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
   989
     * @param engine the associated ScriptEngine instance, can be null
16211
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   990
     * @return the initialized global scope object.
41e031a45186 8006191: `cmd` -> exec("cmd") in script mode
jlaskey
parents: 16201
diff changeset
   991
     */
25422
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
   992
    public Global initGlobal(final Global global, final ScriptEngine engine) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
   993
        // Need only minimal global object, if we are just compiling.
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
   994
        if (!env._compile_only) {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   995
            final Global oldGlobal = Context.getGlobal();
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   996
            try {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
   997
                Context.setGlobal(global);
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
   998
                // initialize global scope with builtin global objects
25422
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
   999
                global.initBuiltinObjects(engine);
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1000
            } finally {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
  1001
                Context.setGlobal(oldGlobal);
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1002
            }
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1003
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1004
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1005
        return global;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1006
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1007
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1008
    /**
25422
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1009
     * Initialize given global scope object.
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1010
     *
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1011
     * @param global the global
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1012
     * @return the initialized global scope object.
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1013
     */
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1014
    public Global initGlobal(final Global global) {
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1015
        return initGlobal(global, null);
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1016
    }
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1017
199a23bee487 8049524: Global object initialization via javax.script API should be minimal
sundar
parents: 25243
diff changeset
  1018
    /**
16188
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
  1019
     * Return the current global's context
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
  1020
     * @return current global's context
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1021
     */
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1022
    static Context getContextTrusted() {
23375
a1110f2cbe75 8037400: Remove getInitialMap getters and GlobalObject interface
sundar
parents: 23374
diff changeset
  1023
        return ((ScriptObject)Context.getGlobal()).getContext();
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1024
    }
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1025
24769
attila
parents: 24759 24282
diff changeset
  1026
    static Context getContextTrustedOrNull() {
attila
parents: 24759 24282
diff changeset
  1027
        final Global global = Context.getGlobal();
attila
parents: 24759 24282
diff changeset
  1028
        return global == null ? null : ((ScriptObject)global).getContext();
attila
parents: 24759 24282
diff changeset
  1029
    }
attila
parents: 24759 24282
diff changeset
  1030
16185
893aabe8c800 8006635: Reduce access levels as much as possible
sundar
parents: 16155
diff changeset
  1031
    /**
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1032
     * Try to infer Context instance from the Class. If we cannot,
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1033
     * then get it from the thread local variable.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1034
     *
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1035
     * @param clazz the class
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1036
     * @return context
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1037
     */
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1038
    static Context fromClass(final Class<?> clazz) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1039
        final ClassLoader loader = clazz.getClassLoader();
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1040
19895
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
  1041
        if (loader instanceof ScriptLoader) {
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
  1042
            return ((ScriptLoader)loader).getContext();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1043
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1044
19895
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
  1045
        return Context.getContextTrusted();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1046
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1047
20928
3ff39d5c8c08 8026137: Fix Issues with Binary Evaluation Order
lagergren
parents: 20567
diff changeset
  1048
    private URL getResourceURL(final String resName) {
20564
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1049
        // try the classPathLoader if we have and then
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1050
        // try the appLoader if non-null.
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1051
        if (classPathLoader != null) {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1052
            return classPathLoader.getResource(resName);
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1053
        } else if (appLoader != null) {
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1054
            return appLoader.getResource(resName);
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1055
        }
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1056
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1057
        return null;
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1058
    }
f353da961684 8025629: load function should support a way to load scripts from classpath
sundar
parents: 19895
diff changeset
  1059
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1060
    private Object evaluateSource(final Source source, final ScriptObject scope, final ScriptObject thiz) {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1061
        ScriptFunction script = null;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1062
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1063
        try {
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
  1064
            script = compileScript(source, scope, new Context.ThrowErrorManager());
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1065
        } catch (final ParserException e) {
16188
d6390b0ea32a 8006678: Avoid too many Context.getGlobal() calls
sundar
parents: 16185
diff changeset
  1066
            e.throwAsEcmaException();
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1067
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1068
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1069
        return ScriptRuntime.apply(script, thiz);
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1070
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1071
24719
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
  1072
    private static ScriptFunction getProgramFunction(final Class<?> script, final ScriptObject scope) {
24879
d316854e4249 8046215: Running uncompilable scripts throws NullPointerException
hannesw
parents: 24783
diff changeset
  1073
        if (script == null) {
d316854e4249 8046215: Running uncompilable scripts throws NullPointerException
hannesw
parents: 24783
diff changeset
  1074
            return null;
d316854e4249 8046215: Running uncompilable scripts throws NullPointerException
hannesw
parents: 24783
diff changeset
  1075
        }
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1076
        return invokeCreateProgramFunctionHandle(getCreateProgramFunctionHandle(script), scope);
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1077
    }
24282
2e3bd98c5664 8041697: CompiledScript slower when eval with binding
sundar
parents: 24206
diff changeset
  1078
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1079
    private static MethodHandle getCreateProgramFunctionHandle(final Class<?> script) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1080
        try {
24783
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1081
            return LOOKUP.findStatic(script, CREATE_PROGRAM_FUNCTION.symbolName(), CREATE_PROGRAM_FUNCTION_TYPE);
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1082
        } catch (NoSuchMethodException | IllegalAccessException e) {
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1083
            throw new AssertionError("Failed to retrieve a handle for the program function for " + script.getName(), e);
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1084
        }
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1085
    }
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1086
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1087
    private static ScriptFunction invokeCreateProgramFunctionHandle(final MethodHandle createProgramFunctionHandle, final ScriptObject scope) {
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1088
        try {
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1089
            return (ScriptFunction)createProgramFunctionHandle.invokeExact(scope);
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1090
        } catch (final RuntimeException|Error e) {
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1091
            throw e;
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1092
        } catch (final Throwable t) {
b5c31bfe1496 8046014: MultiGlobalCompiledScript should cache :createProgramFunction handle
attila
parents: 24779
diff changeset
  1093
            throw new AssertionError("Failed to create a program function", t);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1094
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1095
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1096
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
  1097
    private ScriptFunction compileScript(final Source source, final ScriptObject scope, final ErrorManager errMan) {
24719
f726e9d67629 8035820: Optimistic recompilation
attila
parents: 23076
diff changeset
  1098
        return getProgramFunction(compile(source, errMan, this._strict), scope);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1099
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1100
16230
c38c724d82e7 8008103: Source object should maintain URL of the script source as a private field
sundar
parents: 16226
diff changeset
  1101
    private synchronized Class<?> compile(final Source source, final ErrorManager errMan, final boolean strict) {
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1102
        // start with no errors, no warnings.
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1103
        errMan.reset();
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1104
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1105
        Class<?> script = findCachedClass(source);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1106
        if (script != null) {
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1107
            final DebugLogger log = getLogger(Compiler.class);
24744
5290da85fc3d 8038426: Move all loggers from process wide scope into Global scope
lagergren
parents: 24742
diff changeset
  1108
            if (log.isEnabled()) {
5290da85fc3d 8038426: Move all loggers from process wide scope into Global scope
lagergren
parents: 24742
diff changeset
  1109
                log.fine(new RuntimeEvent<>(Level.INFO, source), "Code cache hit for ", source, " avoiding recompile.");
24731
ab0c8fc915ae 8038406: Testability: as a first step of moving loggers away from the process global space, the Debug object now supports logging POJOs from log entries as an event queue, which can be introspected from test scripts. This is way better than screen scraping brittle and subject-to-change log output.
lagergren
parents: 24727
diff changeset
  1110
            }
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1111
            return script;
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1112
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1113
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1114
        StoredScript storedScript = null;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1115
        FunctionNode functionNode = null;
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1116
        final boolean useCodeStore = env._persistent_cache && !env._parse_only && !env._optimistic_types;
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1117
        final String cacheKey = useCodeStore ? CodeStore.getCacheKey(0, null) : null;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1118
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1119
        if (useCodeStore) {
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
  1120
            storedScript = codeStore.load(source, cacheKey);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1121
        }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1122
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1123
        if (storedScript == null) {
24769
attila
parents: 24759 24282
diff changeset
  1124
            functionNode = new Parser(env, source, errMan, strict, getLogger(Parser.class)).parse();
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1125
26377
028dad61662f 8051889: Implement block scoping in symbol assignment and scope computation
hannesw
parents: 26248
diff changeset
  1126
            if (errMan.hasErrors()) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1127
                return null;
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1128
            }
16240
e1468b33e201 8008239: Unpublicized parts of the code generator package that were only package internal.
lagergren
parents: 16233
diff changeset
  1129
26065
d15adb218527 8055107: Extension directives to turn on callsite profiling, tracing, AST print and other debug features locally
sundar
parents: 26055
diff changeset
  1130
            if (env._print_ast || functionNode.getFlag(FunctionNode.IS_PRINT_AST)) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1131
                getErr().println(new ASTWriter(functionNode));
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1132
            }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1133
26065
d15adb218527 8055107: Extension directives to turn on callsite profiling, tracing, AST print and other debug features locally
sundar
parents: 26055
diff changeset
  1134
            if (env._print_parse || functionNode.getFlag(FunctionNode.IS_PRINT_PARSE)) {
24769
attila
parents: 24759 24282
diff changeset
  1135
                getErr().println(new PrintVisitor(functionNode, true, false));
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1136
            }
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
  1137
        }
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
  1138
17233
72ccf78a8216 8010701: Immutable nodes - final iteration
lagergren
parents: 17231
diff changeset
  1139
        if (env._parse_only) {
72ccf78a8216 8010701: Immutable nodes - final iteration
lagergren
parents: 17231
diff changeset
  1140
            return null;
72ccf78a8216 8010701: Immutable nodes - final iteration
lagergren
parents: 17231
diff changeset
  1141
        }
72ccf78a8216 8010701: Immutable nodes - final iteration
lagergren
parents: 17231
diff changeset
  1142
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
  1143
        final URL          url    = source.getURL();
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
  1144
        final ScriptLoader loader = env._loader_per_compile ? createNewLoader() : scriptLoader;
23076
8660ebaaa2f2 8033924: Default permissions are not given for eval code
sundar
parents: 22669
diff changeset
  1145
        final CodeSource   cs     = new CodeSource(url, (CodeSigner[])null);
16262
75513555e603 8008731: Separate configuration environment (options, error/output writer etc.) from Context
sundar
parents: 16256
diff changeset
  1146
        final CodeInstaller<ScriptEnvironment> installer = new ContextCodeInstaller(this, loader, cs);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1147
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1148
        if (storedScript == null) {
24769
attila
parents: 24759 24282
diff changeset
  1149
            final CompilationPhases phases = Compiler.CompilationPhases.COMPILE_ALL;
24759
31aed7d9c02a 8034206: Make parts of code pipeline reusable in order to facilitate faster warmup and faster lazy compilation.
lagergren
parents: 24745
diff changeset
  1150
24769
attila
parents: 24759 24282
diff changeset
  1151
            final Compiler compiler = new Compiler(
attila
parents: 24759 24282
diff changeset
  1152
                    this,
attila
parents: 24759 24282
diff changeset
  1153
                    env,
attila
parents: 24759 24282
diff changeset
  1154
                    installer,
attila
parents: 24759 24282
diff changeset
  1155
                    source,
26377
028dad61662f 8051889: Implement block scoping in symbol assignment and scope computation
hannesw
parents: 26248
diff changeset
  1156
                    errMan,
24769
attila
parents: 24759 24282
diff changeset
  1157
                    strict | functionNode.isStrict());
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
  1158
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1159
            final FunctionNode compiledFunction = compiler.compile(functionNode, phases);
26377
028dad61662f 8051889: Implement block scoping in symbol assignment and scope computation
hannesw
parents: 26248
diff changeset
  1160
            if (errMan.hasErrors()) {
028dad61662f 8051889: Implement block scoping in symbol assignment and scope computation
hannesw
parents: 26248
diff changeset
  1161
                return null;
028dad61662f 8051889: Implement block scoping in symbol assignment and scope computation
hannesw
parents: 26248
diff changeset
  1162
            }
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1163
            script = compiledFunction.getRootClass();
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1164
            compiler.persistClassInfo(cacheKey, compiledFunction);
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1165
        } else {
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1166
            Compiler.updateCompilationId(storedScript.getCompilationId());
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1167
            script = install(storedScript, source, installer);
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1168
        }
16233
95d3e01c04c3 8008199: Lazy compilation and trampoline implementation
lagergren
parents: 16230
diff changeset
  1169
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1170
        cacheClass(source, script);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1171
        return script;
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1172
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1173
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1174
    private ScriptLoader createNewLoader() {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1175
        return AccessController.doPrivileged(
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1176
             new PrivilegedAction<ScriptLoader>() {
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1177
                @Override
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1178
                public ScriptLoader run() {
19895
965b12eb322e 8024619: JDBC java.sql.DriverManager is not usable from JS script
sundar
parents: 19884
diff changeset
  1179
                    return new ScriptLoader(appLoader, Context.this);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1180
                }
19459
79e75274df99 8022707: Revisit all doPrivileged blocks
sundar
parents: 19098
diff changeset
  1181
             }, CREATE_LOADER_ACC_CTXT);
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1182
    }
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1183
18864
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
  1184
    private long getUniqueScriptId() {
c701b823ed9e 8020276: interface checks in Invocable.getInterface implementation
sundar
parents: 18862
diff changeset
  1185
        return uniqueScriptId.getAndIncrement();
18862
8b6a01b38cb8 8020224: LinkageError: attempted duplicate class definition when --loader-per-compiler=false
sundar
parents: 18860
diff changeset
  1186
    }
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1187
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1188
    /**
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1189
     * Install a previously compiled class from the code cache.
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1190
     *
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1191
     * @param storedScript cached script containing class bytes and constants
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1192
     * @return main script class
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1193
     */
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1194
    private static Class<?> install(final StoredScript storedScript, final Source source, final CodeInstaller<ScriptEnvironment> installer) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1195
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1196
        final Map<String, Class<?>> installedClasses = new HashMap<>();
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
  1197
        final Map<String, byte[]>   classBytes       = storedScript.getClassBytes();
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1198
        final Object[] constants       = storedScript.getConstants();
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1199
        final String   mainClassName   = storedScript.getMainClassName();
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
  1200
        final byte[]   mainClassBytes  = classBytes.get(mainClassName);
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1201
        final Class<?> mainClass       = installer.install(mainClassName, mainClassBytes);
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1202
        final Map<Integer, FunctionInitializer> initialzers = storedScript.getInitializers();
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1203
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1204
        installedClasses.put(mainClassName, mainClass);
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1205
26764
c777787a937d 8046202: Make persistent code store more flexible
hannesw
parents: 26508
diff changeset
  1206
        for (final Map.Entry<String, byte[]> entry : classBytes.entrySet()) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1207
            final String className = entry.getKey();
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1208
            if (className.equals(mainClassName)) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1209
                continue;
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1210
            }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1211
            final byte[] code = entry.getValue();
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1212
24769
attila
parents: 24759 24282
diff changeset
  1213
            installedClasses.put(className, installer.install(className, code));
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1214
        }
24769
attila
parents: 24759 24282
diff changeset
  1215
attila
parents: 24759 24282
diff changeset
  1216
        installer.initialize(installedClasses.values(), source, constants);
attila
parents: 24759 24282
diff changeset
  1217
24778
2ff5d7041566 8044638: Tidy up Nashorn codebase for code standards
attila
parents: 24769
diff changeset
  1218
        for (final Object constant : constants) {
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1219
            if (constant instanceof RecompilableScriptFunctionData) {
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1220
                final RecompilableScriptFunctionData data = (RecompilableScriptFunctionData) constant;
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1221
                data.initTransients(source, installer);
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1222
                if (initialzers != null) {
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1223
                    final FunctionInitializer initializer = initialzers.get(data.getFunctionNodeId());
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1224
                    initializer.setCode(installedClasses.get(initializer.getClassName()));
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1225
                    data.initializeCode(initializer);
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1226
                }
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1227
            }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1228
        }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1229
26055
fe8be844ba50 8043956: Make code caching work with optimistic typing and lazy compilation
hannesw
parents: 25422
diff changeset
  1230
        return mainClass;
23767
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1231
    }
7c0614b75e23 8038638: Persistent store for compiled scripts
hannesw
parents: 23375
diff changeset
  1232
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1233
    /**
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1234
     * Cache for compiled script classes.
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1235
     */
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1236
    @SuppressWarnings("serial")
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1237
    private static class ClassCache extends LinkedHashMap<Source, ClassReference> {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1238
        private final int size;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1239
        private final ReferenceQueue<Class<?>> queue;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1240
24731
ab0c8fc915ae 8038406: Testability: as a first step of moving loggers away from the process global space, the Debug object now supports logging POJOs from log entries as an event queue, which can be introspected from test scripts. This is way better than screen scraping brittle and subject-to-change log output.
lagergren
parents: 24727
diff changeset
  1241
        ClassCache(final int size) {
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1242
            super(size, 0.75f, true);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1243
            this.size = size;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1244
            this.queue = new ReferenceQueue<>();
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1245
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1246
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1247
        void cache(final Source source, final Class<?> clazz) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1248
            put(source, new ClassReference(clazz, queue, source));
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1249
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1250
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1251
        @Override
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1252
        protected boolean removeEldestEntry(final Map.Entry<Source, ClassReference> eldest) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1253
            return size() > size;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1254
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1255
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1256
        @Override
24731
ab0c8fc915ae 8038406: Testability: as a first step of moving loggers away from the process global space, the Debug object now supports logging POJOs from log entries as an event queue, which can be introspected from test scripts. This is way better than screen scraping brittle and subject-to-change log output.
lagergren
parents: 24727
diff changeset
  1257
        public ClassReference get(final Object key) {
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1258
            for (ClassReference ref; (ref = (ClassReference)queue.poll()) != null; ) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1259
                remove(ref.source);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1260
            }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1261
            return super.get(key);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1262
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1263
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1264
    }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1265
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1266
    private static class ClassReference extends SoftReference<Class<?>> {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1267
        private final Source source;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1268
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1269
        ClassReference(final Class<?> clazz, final ReferenceQueue<Class<?>> queue, final Source source) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1270
            super(clazz, queue);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1271
            this.source = source;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1272
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1273
    }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1274
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1275
    // Class cache management
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1276
    private Class<?> findCachedClass(final Source source) {
24731
ab0c8fc915ae 8038406: Testability: as a first step of moving loggers away from the process global space, the Debug object now supports logging POJOs from log entries as an event queue, which can be introspected from test scripts. This is way better than screen scraping brittle and subject-to-change log output.
lagergren
parents: 24727
diff changeset
  1277
        final ClassReference ref = classCache == null ? null : classCache.get(source);
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1278
        return ref != null ? ref.get() : null;
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1279
    }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1280
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1281
    private void cacheClass(final Source source, final Class<?> clazz) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1282
        if (classCache != null) {
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1283
            classCache.cache(source, clazz);
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1284
        }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1285
    }
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1286
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1287
    // logging
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1288
    private final Map<String, DebugLogger> loggers = new HashMap<>();
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1289
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1290
    private void initLoggers() {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1291
        ((Loggable)MethodHandleFactory.getFunctionality()).initLogger(this);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1292
    }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1293
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1294
    /**
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1295
     * Get a logger, given a loggable class
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1296
     * @param clazz a Loggable class
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1297
     * @return debuglogger associated with that class
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1298
     */
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1299
    public DebugLogger getLogger(final Class<? extends Loggable> clazz) {
24993
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1300
        return getLogger(clazz, null);
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1301
    }
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1302
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1303
    /**
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1304
     * Get a logger, given a loggable class
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1305
     * @param clazz a Loggable class
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1306
     * @param initHook an init hook - if this is the first time the logger is created in the context, run the init hook
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1307
     * @return debuglogger associated with that class
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1308
     */
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1309
    public DebugLogger getLogger(final Class<? extends Loggable> clazz, final Consumer<DebugLogger> initHook) {
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1310
        final String name = getLoggerName(clazz);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1311
        DebugLogger logger = loggers.get(name);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1312
        if (logger == null) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1313
            if (!env.hasLogger(name)) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1314
                return DebugLogger.DISABLED_LOGGER;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1315
            }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1316
            final LoggerInfo info = env._loggers.get(name);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1317
            logger = new DebugLogger(name, info.getLevel(), info.isQuiet());
24993
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1318
            if (initHook != null) {
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1319
                initHook.accept(logger);
b707d46bae40 8046898: Make sure that lazy compilation is the default, remove redundant "enable lazy compilation" flags, added warning message if compile logging is enabled and lazy is switched off. Verified existing test suite code coverage equivalence between lazy and eager.
lagergren
parents: 24879
diff changeset
  1320
            }
24745
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1321
            loggers.put(name, logger);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1322
        }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1323
        return logger;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1324
    }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1325
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1326
    /**
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1327
     * Given a Loggable class, weave debug info info a method handle for that logger.
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1328
     * Level.INFO is used
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1329
     *
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1330
     * @param clazz loggable
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1331
     * @param mh    method handle
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1332
     * @param text  debug printout to add
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1333
     *
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1334
     * @return instrumented method handle, or null if logger not enabled
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1335
     */
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1336
    public MethodHandle addLoggingToHandle(final Class<? extends Loggable> clazz, final MethodHandle mh, final Supplier<String> text) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1337
        return addLoggingToHandle(clazz, Level.INFO, mh, Integer.MAX_VALUE, false, text);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1338
    }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1339
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1340
    /**
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1341
     * Given a Loggable class, weave debug info info a method handle for that logger.
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1342
     *
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1343
     * @param clazz            loggable
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1344
     * @param level            log level
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1345
     * @param mh               method handle
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1346
     * @param paramStart       first parameter to print
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1347
     * @param printReturnValue should we print the return vaulue?
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1348
     * @param text             debug printout to add
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1349
     *
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1350
     * @return instrumented method handle, or null if logger not enabled
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1351
     */
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1352
    public MethodHandle addLoggingToHandle(final Class<? extends Loggable> clazz, final Level level, final MethodHandle mh, final int paramStart, final boolean printReturnValue, final Supplier<String> text) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1353
        final DebugLogger log = getLogger(clazz);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1354
        if (log.isEnabled()) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1355
            return MethodHandleFactory.addDebugPrintout(log, level, mh, paramStart, printReturnValue, text.get());
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1356
        }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1357
        return mh;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1358
    }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1359
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1360
    private static String getLoggerName(final Class<?> clazz) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1361
        Class<?> current = clazz;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1362
        while (current != null) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1363
            final Logger log = current.getAnnotation(Logger.class);
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1364
            if (log != null) {
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1365
                assert !"".equals(log.name());
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1366
                return log.name();
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1367
            }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1368
            current = current.getSuperclass();
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1369
        }
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1370
        assert false;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1371
        return null;
3a6e1477362b 8041434: Add synchronization to the common global constants structure
lagergren
parents: 24744
diff changeset
  1372
    }
23372
09707b3e5fb0 8021350: Share script classes between threads/globals within context
hannesw
parents: 23076
diff changeset
  1373
16147
e63b63819133 8005403: Open-source Nashorn
jlaskey
parents:
diff changeset
  1374
}