jdk.nashorn.internal.runtime.Context Java Examples

The following examples show how to use jdk.nashorn.internal.runtime.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ScriptObjectMirror.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void putAll(final Map<? extends String, ? extends Object> map) {
    Objects.requireNonNull(map);
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    inGlobal(new Callable<Object>() {
        @Override public Object call() {
            for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
                final Object value = entry.getValue();
                final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
                final String key = entry.getKey();
                checkKey(key);
                sobj.set(key, unwrap(modValue, global), getCallSiteFlags());
            }
            return null;
        }
    });
}
 
Example #2
Source File: NashornScriptEngine.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #3
Source File: Compiler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a compiler for an on-demand compilation job.
 *
 * @param installer                code installer
 * @param source                   source to compile
 * @param isStrict                 is this a strict compilation
 * @param compiledFunction         compiled function, if any
 * @param types                    parameter and return value type information, if any is known
 * @param invalidatedProgramPoints invalidated program points for recompilation
 * @param typeInformationFile      descriptor of the location where type information is persisted
 * @param continuationEntryPoints  continuation entry points for restof method
 * @param runtimeScope             runtime scope for recompilation type lookup in {@code TypeEvaluator}
 * @return a new compiler
 */
public static Compiler forOnDemandCompilation(
        final CodeInstaller installer,
        final Source source,
        final boolean isStrict,
        final RecompilableScriptFunctionData compiledFunction,
        final TypeMap types,
        final Map<Integer, Type> invalidatedProgramPoints,
        final Object typeInformationFile,
        final int[] continuationEntryPoints,
        final ScriptObject runtimeScope) {
    final Context context = installer.getContext();
    return new Compiler(context, installer, source, context.getErrorManager(), isStrict, true,
            compiledFunction, types, invalidatedProgramPoints, typeInformationFile,
            continuationEntryPoints, runtimeScope);
}
 
Example #4
Source File: Shell.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run method logic.
 *
 * @param in input stream for Shell
 * @param out output stream for Shell
 * @param err error stream for Shell
 * @param args arguments to Shell
 *
 * @return exit code
 *
 * @throws IOException if there's a problem setting up the streams
 */
protected final int run(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException {
    final Context context = makeContext(in, out, err, args);
    if (context == null) {
        return COMMANDLINE_ERROR;
    }

    final Global global = context.createGlobal();
    final ScriptEnvironment env = context.getEnv();
    final List<String> files = env.getFiles();
    if (files.isEmpty()) {
        return readEvalPrint(context, global);
    }

    if (env._compile_only) {
        return compileScripts(context, global, files);
    }

    if (env._fx) {
        return runFXScripts(context, global, files);
    }

    return runScripts(context, global, files);
}
 
Example #5
Source File: NativeDebug.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dump all Nashorn debug mode counters. Calling this may be better if
 * you want to print all counters. This way you can avoid too many callsites
 * due to counter access itself!!
 * @param self self reference
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object dumpCounters(final Object self) {
    final PrintWriter out = Context.getCurrentErr();

    out.println("ScriptObject count " + ScriptObject.getCount());
    out.println("Scope count " + Scope.getScopeCount());
    out.println("ScriptObject listeners added " + PropertyListeners.getListenersAdded());
    out.println("ScriptObject listeners removed " + PropertyListeners.getListenersRemoved());
    out.println("ScriptFunction constructor calls " + ScriptFunction.getConstructorCount());
    out.println("ScriptFunction invokes " + ScriptFunction.getInvokes());
    out.println("ScriptFunction allocations " + ScriptFunction.getAllocations());
    out.println("PropertyMap count " + PropertyMap.getCount());
    out.println("PropertyMap cloned " + PropertyMap.getClonedCount());
    out.println("PropertyMap history hit " + PropertyMap.getHistoryHit());
    out.println("PropertyMap proto invalidations " + PropertyMap.getProtoInvalidations());
    out.println("PropertyMap proto history hit " + PropertyMap.getProtoHistoryHit());
    out.println("PropertyMap setProtoNewMapCount " + PropertyMap.getSetProtoNewMapCount());
    out.println("Callsite count " + LinkerCallSite.getCount());
    out.println("Callsite misses " + LinkerCallSite.getMissCount());
    out.println("Callsite misses by site at " + LinkerCallSite.getMissSamplingPercentage() + "%");

    LinkerCallSite.getMissCounts(out);

    return UNDEFINED;
}
 
Example #6
Source File: NativeJavaImporter.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
private Object createProperty(final String name) {
    final int len = args.length;

    for (int i = len - 1; i > -1; i--) {
        final Object obj = args[i];

        if (obj instanceof StaticClass) {
            if (((StaticClass)obj).getRepresentedClass().getSimpleName().equals(name)) {
                return obj;
            }
        } else if (obj instanceof NativeJavaPackage) {
            final String pkgName  = ((NativeJavaPackage)obj).getName();
            final String fullName = pkgName.isEmpty() ? name : (pkgName + "." + name);
            final Context context = Global.instance().getContext();
            try {
                return StaticClass.forClass(context.findClass(fullName));
            } catch (final ClassNotFoundException e) {
                // IGNORE
            }
        }
    }
    return null;
}
 
Example #7
Source File: NashornScriptEngine.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #8
Source File: Shell.java    From nashorn with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run method logic.
 *
 * @param in input stream for Shell
 * @param out output stream for Shell
 * @param err error stream for Shell
 * @param args arguments to Shell
 *
 * @return exit code
 *
 * @throws IOException if there's a problem setting up the streams
 */
protected final int run(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException {
    final Context context = makeContext(in, out, err, args);
    if (context == null) {
        return COMMANDLINE_ERROR;
    }

    final ScriptObject global = context.createGlobal();
    final ScriptEnvironment env = context.getEnv();
    final List<String> files = env.getFiles();
    if (files.isEmpty()) {
        return readEvalPrint(context, global);
    }

    if (env._compile_only) {
        return compileScripts(context, global, files);
    }

    if (env._fx) {
        return runFXScripts(context, global, files);
    }

    return runScripts(context, global, files);
}
 
Example #9
Source File: NashornScriptEngine.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #10
Source File: NashornScriptEngine.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        return nashornContext.compileScript(source, newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #11
Source File: NativeDebug.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dump all Nashorn debug mode counters. Calling this may be better if
 * you want to print all counters. This way you can avoid too many callsites
 * due to counter access itself!!
 * @param self self reference
 * @return undefined
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object dumpCounters(final Object self) {
    final PrintWriter out = Context.getCurrentErr();

    out.println("ScriptObject count " + ScriptObject.getCount());
    out.println("Scope count " + Scope.getScopeCount());
    out.println("ScriptObject listeners added " + PropertyListeners.getListenersAdded());
    out.println("ScriptObject listeners removed " + PropertyListeners.getListenersRemoved());
    out.println("ScriptFunction constructor calls " + ScriptFunction.getConstructorCount());
    out.println("ScriptFunction invokes " + ScriptFunction.getInvokes());
    out.println("ScriptFunction allocations " + ScriptFunction.getAllocations());
    out.println("PropertyMap count " + PropertyMap.getCount());
    out.println("PropertyMap cloned " + PropertyMap.getClonedCount());
    out.println("PropertyMap history hit " + PropertyMap.getHistoryHit());
    out.println("PropertyMap proto invalidations " + PropertyMap.getProtoInvalidations());
    out.println("PropertyMap proto history hit " + PropertyMap.getProtoHistoryHit());
    out.println("PropertyMap setProtoNewMapCount " + PropertyMap.getSetProtoNewMapCount());
    out.println("Callsite count " + LinkerCallSite.getCount());
    out.println("Callsite misses " + LinkerCallSite.getMissCount());
    out.println("Callsite misses by site at " + LinkerCallSite.getMissSamplingPercentage() + "%");

    LinkerCallSite.getMissCounts(out);

    return UNDEFINED;
}
 
Example #12
Source File: ContextTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalTest() {
    final Options options = new Options("");
    final ErrorManager errors = new ErrorManager();
    final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    final Global oldGlobal = Context.getGlobal();
    Context.setGlobal(cx.createGlobal());
    try {
        String code = "22 + 10";
        assertTrue(32.0 == ((Number)(eval(cx, "<evalTest>", code))).doubleValue());

        code = "obj = { js: 'nashorn' }; obj.js";
        assertEquals(eval(cx, "<evalTest2>", code), "nashorn");
    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example #13
Source File: NashornBeansLinker.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static Method findFunctionalInterfaceMethod(final Class<?> clazz) {
    if (clazz == null) {
        return null;
    }

    for (final Class<?> iface : clazz.getInterfaces()) {
        // check accessiblity up-front
        if (! Context.isAccessibleClass(iface)) {
            continue;
        }

        // check for @FunctionalInterface
        if (iface.isAnnotationPresent(FunctionalInterface.class)) {
            // return the first abstract method
            for (final Method m : iface.getMethods()) {
                if (Modifier.isAbstract(m.getModifiers())) {
                    return m;
                }
            }
        }
    }

    // did not find here, try super class
    return findFunctionalInterfaceMethod(clazz.getSuperclass());
}
 
Example #14
Source File: NativeArray.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.4.4.7 Array.prototype.push (args...)
 *
 * @param self self reference
 * @param args arguments to push
 * @return array length after pushes
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object push(final Object self, final Object... args) {
    try {
        final ScriptObject sobj   = (ScriptObject)self;

        if (bulkable(sobj) && sobj.getArray().length() + args.length <= JSType.MAX_UINT) {
            final ArrayData newData = sobj.getArray().push(true, args);
            sobj.setArray(newData);
            return JSType.toNarrowestNumber(newData.length());
        }

        long len = JSType.toUint32(sobj.getLength());
        for (final Object element : args) {
            sobj.set(len++, element, CALLSITE_STRICT);
        }
        sobj.set("length", len, CALLSITE_STRICT);

        return JSType.toNarrowestNumber(len);
    } catch (final ClassCastException | NullPointerException e) {
        throw typeError(Context.getGlobal(), e, "not.an.object", ScriptRuntime.safeToString(self));
    }
}
 
Example #15
Source File: NashornScriptEngineFactory.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ScriptEngine getScriptEngine() {
    try {
        return new NashornScriptEngine(this, DEFAULT_OPTIONS, getAppClassLoader(), null);
    } catch (final RuntimeException e) {
        if (Context.DEBUG) {
            e.printStackTrace();
        }
        throw e;
    }
}
 
Example #16
Source File: NashornScriptEngine.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
private ScriptObject createNashornGlobal(final ScriptContext ctxt) {
    final ScriptObject newGlobal = AccessController.doPrivileged(new PrivilegedAction<ScriptObject>() {
        @Override
        public ScriptObject run() {
            try {
                return nashornContext.newGlobal();
            } catch (final RuntimeException e) {
                if (Context.DEBUG) {
                    e.printStackTrace();
                }
                throw e;
            }
        }
    }, CREATE_GLOBAL_ACC_CTXT);

    nashornContext.initGlobal(newGlobal);

    final int NON_ENUMERABLE_CONSTANT = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE;
    // current ScriptContext exposed as "context"
    // "context" is non-writable from script - but script engine still
    // needs to set it and so save the context Property object
    contextProperty = newGlobal.addOwnProperty("context", NON_ENUMERABLE_CONSTANT, ctxt);
    // current ScriptEngine instance exposed as "engine". We added @SuppressWarnings("LeakingThisInConstructor") as
    // NetBeans identifies this assignment as such a leak - this is a false positive as we're setting this property
    // in the Global of a Context we just created - both the Context and the Global were just created and can not be
    // seen from another thread outside of this constructor.
    newGlobal.addOwnProperty("engine", NON_ENUMERABLE_CONSTANT, this);
    // global script arguments with undefined value
    newGlobal.addOwnProperty("arguments", Property.NOT_ENUMERABLE, UNDEFINED);
    // file name default is null
    newGlobal.addOwnProperty(ScriptEngine.FILENAME, Property.NOT_ENUMERABLE, null);
    // evaluate engine.js initialization script this new global object
    try {
        evalImpl(compileImpl(ENGINE_SCRIPT_SRC, newGlobal), ctxt, newGlobal);
    } catch (final ScriptException exp) {
        throw new RuntimeException(exp);
    }
    return newGlobal;
}
 
Example #17
Source File: Compiler.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public DebugLogger initLogger(final Context ctxt) {
    final boolean optimisticTypes = env._optimistic_types;
    final boolean lazyCompilation = env._lazy_compilation;

    return ctxt.getLogger(this.getClass(), new Consumer<DebugLogger>() {
        @Override
        public void accept(final DebugLogger newLogger) {
            if (!lazyCompilation) {
                newLogger.warning("WARNING: Running with lazy compilation switched off. This is not a default setting.");
            }
            newLogger.warning("Optimistic types are ", optimisticTypes ? "ENABLED." : "DISABLED.");
        }
    });
}
 
Example #18
Source File: Compiler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convenience constructor for non on-demand compiler instances.
 */
private Compiler(
        final Context context,
        final CodeInstaller installer,
        final Source source,
        final ErrorManager errors,
        final boolean isStrict) {
    this(context, installer, source, errors, isStrict, false, null, null, null, null, null, null);
}
 
Example #19
Source File: ScriptUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Make a script object mirror on given object if needed.
 *
 * @param obj object to be wrapped
 * @return wrapped object
 * @throws IllegalArgumentException if obj cannot be wrapped
 */
public static ScriptObjectMirror wrap(final Object obj) {
    if (obj instanceof ScriptObjectMirror) {
        return (ScriptObjectMirror)obj;
    }

    if (obj instanceof ScriptObject) {
        final ScriptObject sobj = (ScriptObject)obj;
        return (ScriptObjectMirror) ScriptObjectMirror.wrap(sobj, Context.getGlobal());
    }

    throw new IllegalArgumentException();
}
 
Example #20
Source File: ClassEmitter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor from the compiler.
 *
 * @param env           Script environment
 * @param sourceName    Source name
 * @param unitClassName Compile unit class name.
 * @param strictMode    Should we generate this method in strict mode
 */
ClassEmitter(final Context context, final String sourceName, final String unitClassName, final boolean strictMode) {
    this(context,
         new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
            private static final String OBJECT_CLASS  = "java/lang/Object";

            @Override
            protected String getCommonSuperClass(final String type1, final String type2) {
                try {
                    return super.getCommonSuperClass(type1, type2);
                } catch (final RuntimeException e) {
                    if (isScriptObject(Compiler.SCRIPTS_PACKAGE, type1) && isScriptObject(Compiler.SCRIPTS_PACKAGE, type2)) {
                        return className(ScriptObject.class);
                    }
                    return OBJECT_CLASS;
                }
            }
        });

    this.unitClassName        = unitClassName;
    this.constantMethodNeeded = new HashSet<>();

    cw.visit(V1_7, ACC_PUBLIC | ACC_SUPER, unitClassName, null, pathName(jdk.nashorn.internal.scripts.JS.class.getName()), null);
    cw.visitSource(sourceName, null);

    defineCommonStatics(strictMode);
}
 
Example #21
Source File: ParserTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public void setupTest() {
    final Options options = new Options("nashorn");
    options.set("anon.functions", true);
    options.set("parse.only", true);
    options.set("scripting", true);
    options.set("const.as.var", true);

    final ErrorManager errors = new ErrorManager();
    this.context = new Context(options, errors, Thread.currentThread().getContextClassLoader());
}
 
Example #22
Source File: NashornStaticClassLinker.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final LinkRequest request = linkRequest.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = request.getReceiver();
    if (self.getClass() != StaticClass.class) {
        return null;
    }
    final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();

    Bootstrap.checkReflectionAccess(receiverClass, true);
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    // We intercept "new" on StaticClass instances to provide additional capabilities
    if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        if (! Modifier.isPublic(receiverClass.getModifiers())) {
            throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
        }

        // make sure new is on accessible Class
        Context.checkPackageAccess(receiverClass);

        // Is the class abstract? (This includes interfaces.)
        if (NashornLinker.isAbstractClass(receiverClass)) {
            // Change this link request into a link request on the adapter class.
            final Object[] args = request.getArguments();
            args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
                    linkRequest.getCallSiteDescriptor().getLookup());
            final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
            final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
            // Finally, modify the guard to test for the original abstract class.
            return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
        }
        // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
        // additional check to ensure we have a constructor. We could just fall through to the next "return"
        // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
        // with a more intuitive message when no suitable constructor is found.
        return checkNullConstructor(delegate(linkerServices, request), receiverClass);
    }
    // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
    return delegate(linkerServices, request);
}
 
Example #23
Source File: SharedContextEvaluator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * SharedContextEvaluator constructor
 * @param args initial script arguments to create shared context
 */
public SharedContextEvaluator(final String[] args) {
    this.ctxOut = new DelegatingOutputStream(System.out);
    this.ctxErr = new DelegatingOutputStream(System.err);
    final PrintWriter wout = new PrintWriter(ctxOut, true);
    final PrintWriter werr = new PrintWriter(ctxErr, true);
    final Options options = new Options("nashorn", werr);
    options.process(args);
    final ErrorManager errors = new ErrorManager(werr);
    this.context = new Context(options, errors, wout, werr, Thread.currentThread().getContextClassLoader());
}
 
Example #24
Source File: Global.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static PropertyMap checkAndGetMap(final Context context) {
    // security check first
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new RuntimePermission(Context.NASHORN_CREATE_GLOBAL));
    }

    Objects.requireNonNull(context);

    return $nasgenmap$;
}
 
Example #25
Source File: Global.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param context the context
 */
public Global(final Context context) {
    super(checkAndGetMap(context));
    this.context = context;
    this.setIsScope();

    final int cacheSize = context.getEnv()._class_cache_size;
    if (cacheSize > 0) {
        classCache = new ClassCache(cacheSize);
    }
}
 
Example #26
Source File: ReflectionCheckLinker.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void checkLinkRequest(final LinkRequest origRequest) {
    final Global global = Context.getGlobal();
    final ClassFilter cf = global.getClassFilter();
    if (cf != null) {
        throw typeError("no.reflection.with.classfilter");
    }

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        final LinkRequest requestWithoutContext = origRequest.withoutRuntimeContext(); // Nashorn has no runtime context
        final Object self = requestWithoutContext.getReceiver();
        // allow 'static' access on Class objects representing public classes of non-restricted packages
        if ((self instanceof Class) && Modifier.isPublic(((Class<?>)self).getModifiers())) {
            final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor();
            if(CallSiteDescriptorFactory.tokenizeOperators(desc).contains("getProp")) {
                if (desc.getNameTokenCount() > CallSiteDescriptor.NAME_OPERAND &&
                    "static".equals(desc.getNameToken(CallSiteDescriptor.NAME_OPERAND))) {
                    if (Context.isAccessibleClass((Class<?>)self) && !isReflectionClass((Class<?>)self)) {

                        // If "getProp:static" passes access checks, allow access.
                        return;
                    }
                }
            }
        }
        checkReflectionPermission(sm);
    }
}
 
Example #27
Source File: ObjectClassGenerator.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param context a context
 * @param dualFields whether to use dual fields representation
 */
public ObjectClassGenerator(final Context context, final boolean dualFields) {
    this.context = context;
    this.dualFields = dualFields;
    assert context != null;
    this.log = initLogger(context);
    if (!initialized) {
        initialized = true;
        if (!dualFields) {
            log.warning("Running with object fields only - this is a deprecated configuration.");
        }
    }
}
 
Example #28
Source File: ScriptUtils.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unwrap an array of script object mirrors if needed.
 *
 * @param args array to be unwrapped
 * @return unwrapped array
 */
public static Object[] unwrapArray(final Object[] args) {
    if (args == null || args.length == 0) {
        return args;
    }

    return ScriptObjectMirror.unwrapArray(args, Context.getGlobal());
}
 
Example #29
Source File: Global.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the passed function is the built-in "Java.to".
 * @param fn the function in question
 * @return true if the function is built-in "Java.to"
 */
public static boolean isBuiltInJavaTo(final ScriptFunction fn) {
    if(!"to".equals(fn.getName())) {
        // Avoid hitting the thread local if the name doesn't match.
        return false;
    }
    return fn == Context.getGlobal().builtInJavaTo;
}
 
Example #30
Source File: ReflectionCheckLinker.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void checkReflectionAccess(final Class<?> clazz, final boolean isStatic) {
    final Global global = Context.getGlobal();
    final ClassFilter cf = global.getClassFilter();
    if (cf != null && isReflectiveCheckNeeded(clazz, isStatic)) {
        throw typeError("no.reflection.with.classfilter");
    }

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null && isReflectiveCheckNeeded(clazz, isStatic)) {
        checkReflectionPermission(sm);
    }
}