Class Context.Builder
- Enclosing class:
Context
Context
instances. A builder instance is not thread-safe
and must not be used from multiple threads at the same time.- Since:
- 19.0
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionallowAllAccess
(boolean enabled) Sets the default value for all privileges.allowCreateProcess
(boolean enabled) Iftrue
, allows guest language to execute external processes.allowCreateThread
(boolean enabled) Iftrue
, allows guest languages to create new threads.allowEnvironmentAccess
(EnvironmentAccess accessPolicy) Allow environment access using the provided policy.allowExperimentalOptions
(boolean enabled) Allow experimental options to be used for language options.allowHostAccess
(boolean enabled) Deprecated.allowHostAccess
(HostAccess config) Configures which public constructors, methods or fields of public classes are accessible by guest applications.allowHostClassLoading
(boolean enabled) If host class loading is enabled, then the guest language is allowed to load new host classes via jar or class files.allowHostClassLookup
(Predicate<String> classFilter) Sets a filter that specifies the Java host classes that can be looked up by the guest application.allowInnerContextOptions
(boolean enabled) Allows this context to spawn inner contexts that may change option values set for the outer context.allowIO
(boolean enabled) Deprecated.Configures guest language access to host IO.allowNativeAccess
(boolean enabled) Allows guest languages to access the native interface.allowPolyglotAccess
(PolyglotAccess accessPolicy) Allow polyglot access using the provided policy.allowValueSharing
(boolean enabled) Enables or disables sharing of anyvalue
between contexts.Sets the guest language application arguments for a languagecontext
.build()
Creates a new context instance from the configuration provided in the builder.currentWorkingDirectory
(Path workingDirectory) Sets the current working directory used by the guest application to resolve relative paths.Explicitly sets the underlying engine to use.environment
(String name, String value) Sets an environment variable.environment
(Map<String, String> env) Shortcut for setting multipleenvironment variables
using a map.err
(OutputStream err) Sets the error output stream to be used for the context.fileSystem
(FileSystem fileSystem) Deprecated.If a file system was previously set useallowIO(IOAccess.newBuilder().fileSystem(fileSystem).build())
.hostClassFilter
(Predicate<String> classFilter) Deprecated.useallowHostClassLookup(Predicate)
instead.hostClassLoader
(ClassLoader classLoader) Sets a host class loader.in
(InputStream in) Sets the input stream to be used for the context.logHandler
(OutputStream logOut) Installs a new loggingHandler
using givenOutputStream
.logHandler
(Handler logHandler) Installs a new loggingHandler
.Sets an option for thiscontext
.Shortcut for setting multipleoptions
using a map.out
(OutputStream out) Sets the standard output stream to be used for the context.processHandler
(ProcessHandler handler) Installs aProcessHandler
responsible for external process creation.resourceLimits
(ResourceLimits limits) Assigns resource limit configuration to a context.sandbox
(SandboxPolicy policy) Sets a code sandbox policy to a context.serverTransport
(MessageTransport serverTransport) Take over the transport of messages communication with a server peer.Sets the default time zone to be used for this context.useSystemExit
(boolean enabled) Specifies whetherSystem.exit(int)
may be used to improve efficiency of stack unwinding for context exit requested by the guest application.
-
Method Details
-
engine
Explicitly sets the underlying engine to use. By default, every context has its own isolated engine. If multiple contexts are created from one engine, then they may share/cache certain system resources like ASTs or optimized code by specifying a single underlying engine. SeeEngine
for more details about system resource sharing.- Since:
- 19.0
-
out
Sets the standard output stream to be used for the context. If not set, then the standard output stream configured for theengine
or standard error stream is used.- Since:
- 19.0
-
err
Sets the error output stream to be used for the context. If not set, then either the error stream configured for theengine
or standard error stream is used.- Since:
- 19.0
-
in
Sets the input stream to be used for the context. If not set, then either the input stream configured for theengine
or standard in stream is used.- Since:
- 19.0
-
allowHostAccess
Deprecated.useallowHostAccess(HostAccess)
orallowHostClassLookup(Predicate)
instead.Allows guest languages to access the host language by loading new classes. Default isfalse
. Ifall access
is set totrue
, then host access is enabled if not disallowed explicitly.- Since:
- 19.0
-
allowHostAccess
Configures which public constructors, methods or fields of public classes are accessible by guest applications. By default ifallowAllAccess(boolean)
isfalse
theHostAccess.EXPLICIT
policy will be used, otherwiseHostAccess.ALL
.- Since:
- 19.0
- See Also:
-
allowNativeAccess
Allows guest languages to access the native interface.- Since:
- 19.0
-
allowCreateThread
Iftrue
, allows guest languages to create new threads. Default isfalse
. Ifall access
is set totrue
, then the creation of threads is enabled if not allowed explicitly. Threads created by guest languages are closed, when the context isclosed
.- Since:
- 19.0
-
allowAllAccess
Sets the default value for all privileges. If not explicitly specified, then all access isfalse
. If all access is enabled then certain privileges may still be disabled by configuring it explicitly using the builder (either before or after the call toallowAllAccess()
). Allowing all access should only be set if the guest application is fully trusted.If
true
, grants the context the same access privileges as the host virtual machine. If the host VM runs without asecurity manager
enabled, then enabling all access gives the guest languages full control over the host process. Otherwise, Javasecurity manager
is in control of restricting the privileges of the polyglot context. If new privilege restrictions are added to the polyglot API, then they will default to full access.Grants full access to the following privileges by default:
- The
creation
and use of new threads. - The access to public
host classes
. - The loading of new
host classes
by adding entries to the class path. - Exporting new members into the polyglot
bindings
. - Unrestricted
IO operations
on host system. - Passing
experimental options
. - The
creation
and use of new sub-processes. - The
access
to process environment variables. - The
changing
of options for of inner contexts spawned by the language.
- Parameters:
enabled
-true
for all access by default.- Since:
- 19.0
- The
-
allowHostClassLoading
If host class loading is enabled, then the guest language is allowed to load new host classes via jar or class files. Ifall access
is set totrue
, then the host class loading is enabled if it is not disallowed explicitly. For host class loading to be useful,IO
operationshost class lookup
, and thehost access policy
needs to be configured as well.- Since:
- 19.0
- See Also:
-
allowHostClassLookup
Sets a filter that specifies the Java host classes that can be looked up by the guest application. If set tonull
then no class lookup is allowed and relevant language builtins are not available (e.g.Java.type
in JavaScript). If theclassFilter
parameter is set to a filter predicate, then language builtins are available and classes can be looked up if the filter predicate returnstrue
for the fully qualified class name. If the filter returnsfalse
, then the class cannot be looked up and as a result throws a guest language error when accessed. By default and ifall access
isfalse
, host class lookup is disabled. By default and ifall access
istrue
, then all classes may be looked up by the guest application.In order to access class members looked up by the guest application a
host access policy
needs to be set orall access
needs to be set totrue
.To load new classes the context uses the
hostClassLoader
if specified or thecontext class loader
that will be captured when the context isbuilt
. If an explicitengine
was specified, then the context class loader at enginebuild-time
will be used instead. When the Java module system is available (>= JDK 9) then only classes are accessible that are exported to the unnamed module of the captured class loader.Example usage with JavaScript:
public class MyClass { @HostAccess.Export public int accessibleMethod() { return 42; } public static void main(String[] args) { try (Context context = Context.newBuilder() // .allowHostClassLookup(c -> c.equals("myPackage.MyClass")) // .build()) { int result = context.eval("js", "" + "var MyClass = Java.type('myPackage.MyClass');" + "new MyClass().accessibleMethod()").asInt(); assert result == 42; } } }
In this example:
- We create a new context with the
permission
to look up the classmyPackage.MyClass
in the guest language application. - We evaluate a JavaScript code snippet that accesses the Java class
myPackage.MyClass
using theJava.type
builtin provided by the JavaScript language implementation. Other classes can only be looked up if the provided class filter returnstrue
for their name. - We create a new instance of the Java class
MyClass
by using the JavaScriptnew
keyword. - We call the method
accessibleMethod
which returns42
. The method is accessible to the guest language because because the enclosing class and the declared method are public, as well as annotated with the@HostAccess.Export
annotation. Which Java members of classes are accessible can be configured using thehost access policy
.
- Parameters:
classFilter
- a predicate that returnstrue
orfalse
for a qualified Java class name ornull
to disable host class lookup.- Since:
- 19.0
- See Also:
- We create a new context with the
-
allowExperimentalOptions
Allow experimental options to be used for language options. Do not use experimental options in production environments. If set tofalse
(the default), then passing an experimental option results in anIllegalArgumentException
when the context is built.Alternatively
Engine.Builder.allowExperimentalOptions(boolean)
may be used when constructing the context using anexplicit engine
.- Since:
- 19.0
-
allowPolyglotAccess
Allow polyglot access using the provided policy. Ifall access
istrue
then the default polyglot access policy isPolyglotAccess.ALL
, otherwisePolyglotAccess.NONE
. The provided access policy must not benull
.- Since:
- 19.0
-
allowValueSharing
Enables or disables sharing of anyvalue
between contexts. Value sharing is enabled by default and is not affected byallowAllAccess(boolean)
.If this option is set to
true
(default) then any value that is associated with one context will be automatically migrated when passed to another context. Primitive,host
andproxy
values can be migrated without limitation. When guest language values are migrated, they capture and remember their original context. Guest language objects need to be accessed when their respective context isentered
, therefore before any access their original context is entered and subsequently left. Entering the original context may fail, for example when the context of a original context value only allows single threaded access to values or if it wasclosed
in the mean time.If this option is set to
false
then any value passed from one context to another will fail with an error indicating that sharing is disallowed. Turning sharing off can be useful when strict safety is required and it would be considered an error if a value of one context is passed to another.Values of a guest language that are passed from one context to another are restricted to using the interoperability protocol only. In practice this often leads to slight changes and incompatibilities in behavior. For example, the prototype of a JavaScript object passed from one context to another is not writable, as the interoperability protocol does not allow such an operation (yet). A typical use-case is passing big immutable data structures that are infrequently accessed from one context to another, without copying them. In practice, passing values from one context to another should be avoided if possible, as their access is slower and their language compatibility reduced. This feature was introduced in 21.3. Older versions fail when guest values are passed from one context to another.
- Since:
- 21.3
-
allowInnerContextOptions
Allows this context to spawn inner contexts that may change option values set for the outer context. If this privilege is set tofalse
then inner contexts are only allowed to use the same option values as its outer context. If this privilege is set totrue
then the context may modify option values for inner contexts it creates. This privilege should not be enabled for security sensitive use-cases. The default value for this privilege is inherited fromallowAllAccess(boolean)
.Inner contexts are spawned by language implementations to implement language embeddings of their own. For example, some languages provide dedicated APIs to spawn language virtual machines. Such APIs are often implemented using the inner context mechanism.
- Since:
- 22.3
- See Also:
-
hostClassFilter
Deprecated.useallowHostClassLookup(Predicate)
instead.Sets a class filter that allows to limit the classes that are allowed to be loaded by guest languages. If the filter returnstrue
, then the class is accessible, otherwise it is not accessible and throws a guest language error when accessed. In order to have an effect,allowHostAccess(org.graalvm.polyglot.HostAccess)
orallowAllAccess(boolean)
needs to be set totrue
.- Parameters:
classFilter
- a predicate that returnstrue
orfalse
for a java qualified class name.- Since:
- 19.0
-
option
Sets an option for thiscontext
. By default, any options for theengine
,language
orinstrument
can be set for a context. If anexplicit engine
is set for the context, then only language options can be set. Instrument and engine options can be set exclusively on the explicit engine instance. If a language option is set for the context and the engine, then the option of the context is going to take precedence.If one of the set option keys or values is invalid, then an
IllegalArgumentException
is thrown when the context isbuilt
. The given key and value must not benull
.- Since:
- 19.0
- See Also:
-
options
Shortcut for setting multipleoptions
using a map. All values of the provided map must be non-null.- Parameters:
options
- a map options.- Since:
- 19.0
- See Also:
-
arguments
Sets the guest language application arguments for a languagecontext
. Application arguments are typically made available to guest language implementations. It depends on the language if and how they are accessible within theevaluated
guest language scripts. Passing no arguments to a language is equivalent to providing an empty arguments array.- Parameters:
language
- the language id of the primary language.args
- an array of arguments passed to the guest language program.- Throws:
IllegalArgumentException
- if an invalid language id was specified.- Since:
- 19.0
-
allowIO
Configures guest language access to host IO. Default isIOAccess.NONE
. Ifall access
is set totrue
, thenIOAccess.ALL
is used unless explicitly set. This method can be used to virtualize file system access in the guest language by using anIOAccess
with a custom filesystem.- Parameters:
ioAccess
- the IO configuration- Returns:
- the
Context.Builder
- Since:
- 23.0
- See Also:
-
allowIO
Deprecated.Iftrue
, allows guest language to perform unrestricted IO operations on host system. Default isfalse
. Ifall access
is set totrue
, then IO is enabled if not allowed explicitly.- Parameters:
enabled
-true
to enable Input/Output- Returns:
- the
Context.Builder
- Since:
- 19.0
-
fileSystem
Deprecated.If a file system was previously set useallowIO(IOAccess.newBuilder().fileSystem(fileSystem).build())
.Installs a newFileSystem
.- Parameters:
fileSystem
- the file system to be installed- Returns:
- the
Context.Builder
- Since:
- 19.0
-
serverTransport
Take over the transport of messages communication with a server peer. Provide an implementation ofMessageTransport
to virtualize a transport of messages to a server endpoint.MessageTransport.open(java.net.URI, org.graalvm.polyglot.io.MessageEndpoint)
corresponds to accept of a server socket.- Parameters:
serverTransport
- an implementation of message transport interceptor- Since:
- 19.0
- See Also:
-
logHandler
Installs a new loggingHandler
. The logger'sLevel
configuration is done using theContext's options
. The level option key has the following format:log.languageId.loggerName.level
orlog.instrumentId.loggerName.level
. The value is either the name of a pre-definedLevel
constant or a numericLevel
value. If not explicitly set in options, the level is inherited from the parent logger.Examples of setting log level options:
builder.option("log.level","FINE");
sets theFINE level
to allTruffleLogger
s.
builder.option("log.js.level","FINE");
sets theFINE level
to JavaScriptTruffleLogger
s.
builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");
sets theFINE level
toTruffleLogger
for theJavaScriptLanguage
class.
If the
logHandler
is not set onEngine
nor onContext
, the log messages are printed toContext's error output stream
.- Parameters:
logHandler
- theHandler
to use for logging in builtContext
. The passedlogHandler
is closed when the context isclosed
.- Returns:
- the
Context.Builder
- Since:
- 19.0
-
timeZone
Sets the default time zone to be used for this context. If not set, or explicitly set tonull
then thesystem default
zone will be used.- Returns:
- the
Context.Builder
- Since:
- 19.2.0
- See Also:
-
logHandler
Installs a new loggingHandler
using givenOutputStream
. The logger'sLevel
configuration is done using theContext's options
. The level option key has the following format:log.languageId.loggerName.level
orlog.instrumentId.loggerName.level
. The value is either the name of pre-definedLevel
constant or a numericLevel
value. If not explicitly set in options the level is inherited from the parent logger.Examples of setting log level options:
builder.option("log.level","FINE");
sets theFINE level
to allTruffleLogger
s.
builder.option("log.js.level","FINE");
sets theFINE level
to JavaScriptTruffleLogger
s.
builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");
sets theFINE level
toTruffleLogger
for theJavaScriptLanguage
class.
If the
logHandler
is not set onEngine
nor onContext
the log messages are printed toContext's standard output stream
.- Parameters:
logOut
- theOutputStream
to use for logging in builtContext
. The passedlogOut
stream is closed when the context isclosed
.- Returns:
- the
Context.Builder
- Since:
- 19.0
-
allowCreateProcess
Iftrue
, allows guest language to execute external processes. Default isfalse
. Ifall access
is set totrue
, then process creation is enabled if not denied explicitly.- Parameters:
enabled
-true
to enable external process creation- Since:
- 19.1.0
-
processHandler
Installs aProcessHandler
responsible for external process creation.- Parameters:
handler
- the handler to be installed- Since:
- 19.1.0
-
resourceLimits
Assigns resource limit configuration to a context. By default no resource limits are assigned. The limits will be enabled for all contexts created using this builder. Assigning a limit may have performance impact of all contexts that run with the same engine.- Since:
- 19.3.0
- See Also:
-
sandbox
Sets a code sandbox policy to a context. By default, the context's sandbox policy isSandboxPolicy.TRUSTED
, there are no restrictions to the context configuration.- Since:
- 23.0
- See Also:
-
allowEnvironmentAccess
Allow environment access using the provided policy. Ifall access
istrue
then the default environment access policy isEnvironmentAccess.INHERIT
, otherwiseEnvironmentAccess.NONE
. The provided access policy must not benull
.- Parameters:
accessPolicy
- theenvironment access policy
- Since:
- 19.1.0
-
environment
Sets an environment variable.- Parameters:
name
- the environment variable namevalue
- the environment variable value- Since:
- 19.1.0
-
environment
Shortcut for setting multipleenvironment variables
using a map. All values of the provided map must be non-null.- Parameters:
env
- environment variables- Since:
- 19.1.0
- See Also:
-
currentWorkingDirectory
Sets the current working directory used by the guest application to resolve relative paths. When the Context is built, the given directory is set as the current working directory on the Context's file system using theFileSystem.setCurrentWorkingDirectory
method.- Parameters:
workingDirectory
- the new current working directory- Throws:
NullPointerException
- whenworkingDirectory
isnull
IllegalArgumentException
- whenworkingDirectory
is a relative path- Since:
- 20.0.0
-
hostClassLoader
Sets a host class loader. If set the givenclassLoader
is used to load host classes and it's also set as acontext ClassLoader
during code execution. Otherwise the ClassLoader that was captured when the context wasbuilt
is used to to load host classes and thecontext ClassLoader
is not set during code execution. Setting the hostClassLoader has a negative effect on enter and leave performance.- Parameters:
classLoader
- the host class loader- Since:
- 20.1.0
-
useSystemExit
Specifies whetherSystem.exit(int)
may be used to improve efficiency of stack unwinding for context exit requested by the guest application.- Since:
- 22.0
- See Also:
-
build
Creates a new context instance from the configuration provided in the builder. The same context builder can be used to create multiple context instances.- Since:
- 19.0
-
allowHostAccess(HostAccess)
orallowHostClassLookup(Predicate)
instead.