| 1 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- |
| 2 | * |
| 3 | * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 | |
| 7 | // API class |
| 8 | |
| 9 | package org.mozilla.javascript; |
| 10 | |
| 11 | import java.security.AccessController; |
| 12 | import java.security.PrivilegedAction; |
| 13 | |
| 14 | /** |
| 15 | * Factory class that Rhino runtime uses to create new {@link Context} |
| 16 | * instances. A <code>ContextFactory</code> can also notify listeners |
| 17 | * about context creation and release. |
| 18 | * <p> |
| 19 | * When the Rhino runtime needs to create new {@link Context} instance during |
| 20 | * execution of {@link Context#enter()} or {@link Context}, it will call |
| 21 | * {@link #makeContext()} of the current global ContextFactory. |
| 22 | * See {@link #getGlobal()} and {@link #initGlobal(ContextFactory)}. |
| 23 | * <p> |
| 24 | * It is also possible to use explicit ContextFactory instances for Context |
| 25 | * creation. This is useful to have a set of independent Rhino runtime |
| 26 | * instances under single JVM. See {@link #call(ContextAction)}. |
| 27 | * <p> |
| 28 | * The following example demonstrates Context customization to terminate |
| 29 | * scripts running more then 10 seconds and to provide better compatibility |
| 30 | * with JavaScript code using MSIE-specific features. |
| 31 | * <pre> |
| 32 | * import org.mozilla.javascript.*; |
| 33 | * |
| 34 | * class MyFactory extends ContextFactory |
| 35 | * { |
| 36 | * |
| 37 | * // Custom {@link Context} to store execution time. |
| 38 | * private static class MyContext extends Context |
| 39 | * { |
| 40 | * long startTime; |
| 41 | * } |
| 42 | * |
| 43 | * static { |
| 44 | * // Initialize GlobalFactory with custom factory |
| 45 | * ContextFactory.initGlobal(new MyFactory()); |
| 46 | * } |
| 47 | * |
| 48 | * // Override {@link #makeContext()} |
| 49 | * protected Context makeContext() |
| 50 | * { |
| 51 | * MyContext cx = new MyContext(); |
| 52 | * // Make Rhino runtime to call observeInstructionCount |
| 53 | * // each 10000 bytecode instructions |
| 54 | * cx.setInstructionObserverThreshold(10000); |
| 55 | * return cx; |
| 56 | * } |
| 57 | * |
| 58 | * // Override {@link #hasFeature(Context, int)} |
| 59 | * public boolean hasFeature(Context cx, int featureIndex) |
| 60 | * { |
| 61 | * // Turn on maximum compatibility with MSIE scripts |
| 62 | * switch (featureIndex) { |
| 63 | * case {@link Context#FEATURE_NON_ECMA_GET_YEAR}: |
| 64 | * return true; |
| 65 | * |
| 66 | * case {@link Context#FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME}: |
| 67 | * return true; |
| 68 | * |
| 69 | * case {@link Context#FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER}: |
| 70 | * return true; |
| 71 | * |
| 72 | * case {@link Context#FEATURE_PARENT_PROTO_PROPERTIES}: |
| 73 | * return false; |
| 74 | * } |
| 75 | * return super.hasFeature(cx, featureIndex); |
| 76 | * } |
| 77 | * |
| 78 | * // Override {@link #observeInstructionCount(Context, int)} |
| 79 | * protected void observeInstructionCount(Context cx, int instructionCount) |
| 80 | * { |
| 81 | * MyContext mcx = (MyContext)cx; |
| 82 | * long currentTime = System.currentTimeMillis(); |
| 83 | * if (currentTime - mcx.startTime > 10*1000) { |
| 84 | * // More then 10 seconds from Context creation time: |
| 85 | * // it is time to stop the script. |
| 86 | * // Throw Error instance to ensure that script will never |
| 87 | * // get control back through catch or finally. |
| 88 | * throw new Error(); |
| 89 | * } |
| 90 | * } |
| 91 | * |
| 92 | * // Override {@link #doTopCall(Callable, |
| 93 | Context, Scriptable, |
| 94 | Scriptable, Object[])} |
| 95 | * protected Object doTopCall(Callable callable, |
| 96 | * Context cx, Scriptable scope, |
| 97 | * Scriptable thisObj, Object[] args) |
| 98 | * { |
| 99 | * MyContext mcx = (MyContext)cx; |
| 100 | * mcx.startTime = System.currentTimeMillis(); |
| 101 | * |
| 102 | * return super.doTopCall(callable, cx, scope, thisObj, args); |
| 103 | * } |
| 104 | * |
| 105 | * } |
| 106 | * |
| 107 | * </pre> |
| 108 | */ |
| 109 | |
| 110 | public class ContextFactory |
| 111 | { |
| 112 | private static volatile boolean hasCustomGlobal; |
| 113 | private static ContextFactory global = new ContextFactory(); |
| 114 | |
| 115 | private volatile boolean sealed; |
| 116 | |
| 117 | private final Object listenersLock = new Object(); |
| 118 | private volatile Object listeners; |
| 119 | private boolean disabledListening; |
| 120 | private ClassLoader applicationClassLoader; |
| 121 | |
| 122 | /** |
| 123 | * Listener of {@link Context} creation and release events. |
| 124 | */ |
| 125 | public interface Listener |
| 126 | { |
| 127 | /** |
| 128 | * Notify about newly created {@link Context} object. |
| 129 | */ |
| 130 | public void contextCreated(Context cx); |
| 131 | |
| 132 | /** |
| 133 | * Notify that the specified {@link Context} instance is no longer |
| 134 | * associated with the current thread. |
| 135 | */ |
| 136 | public void contextReleased(Context cx); |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * Get global ContextFactory. |
| 141 | * |
| 142 | * @see #hasExplicitGlobal() |
| 143 | * @see #initGlobal(ContextFactory) |
| 144 | */ |
| 145 | public static ContextFactory getGlobal() |
| 146 | { |
| 147 | return global; |
| 148 | } |
| 149 | |
| 150 | /** |
| 151 | * Check if global factory was set. |
| 152 | * Return true to indicate that {@link #initGlobal(ContextFactory)} was |
| 153 | * already called and false to indicate that the global factory was not |
| 154 | * explicitly set. |
| 155 | * |
| 156 | * @see #getGlobal() |
| 157 | * @see #initGlobal(ContextFactory) |
| 158 | */ |
| 159 | public static boolean hasExplicitGlobal() |
| 160 | { |
| 161 | return hasCustomGlobal; |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Set global ContextFactory. |
| 166 | * The method can only be called once. |
| 167 | * |
| 168 | * @see #getGlobal() |
| 169 | * @see #hasExplicitGlobal() |
| 170 | */ |
| 171 | public synchronized static void initGlobal(ContextFactory factory) |
| 172 | { |
| 173 | if (factory == null) { |
| 174 | throw new IllegalArgumentException(); |
| 175 | } |
| 176 | if (hasCustomGlobal) { |
| 177 | throw new IllegalStateException(); |
| 178 | } |
| 179 | hasCustomGlobal = true; |
| 180 | global = factory; |
| 181 | } |
| 182 | |
| 183 | public interface GlobalSetter { |
| 184 | public void setContextFactoryGlobal(ContextFactory factory); |
| 185 | public ContextFactory getContextFactoryGlobal(); |
| 186 | } |
| 187 | |
| 188 | public synchronized static GlobalSetter getGlobalSetter() { |
| 189 | if (hasCustomGlobal) { |
| 190 | throw new IllegalStateException(); |
| 191 | } |
| 192 | hasCustomGlobal = true; |
| 193 | class GlobalSetterImpl implements GlobalSetter { |
| 194 | public void setContextFactoryGlobal(ContextFactory factory) { |
| 195 | global = factory == null ? new ContextFactory() : factory; |
| 196 | } |
| 197 | public ContextFactory getContextFactoryGlobal() { |
| 198 | return global; |
| 199 | } |
| 200 | } |
| 201 | return new GlobalSetterImpl(); |
| 202 | } |
| 203 | |
| 204 | /** |
| 205 | * Create new {@link Context} instance to be associated with the current |
| 206 | * thread. |
| 207 | * This is a callback method used by Rhino to create {@link Context} |
| 208 | * instance when it is necessary to associate one with the current |
| 209 | * execution thread. <tt>makeContext()</tt> is allowed to call |
| 210 | * {@link Context#seal(Object)} on the result to prevent |
| 211 | * {@link Context} changes by hostile scripts or applets. |
| 212 | */ |
| 213 | protected Context makeContext() |
| 214 | { |
| 215 | return new Context(this); |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * Implementation of {@link Context#hasFeature(int featureIndex)}. |
| 220 | * This can be used to customize {@link Context} without introducing |
| 221 | * additional subclasses. |
| 222 | */ |
| 223 | protected boolean hasFeature(Context cx, int featureIndex) |
| 224 | { |
| 225 | int version; |
| 226 | switch (featureIndex) { |
| 227 | case Context.FEATURE_NON_ECMA_GET_YEAR: |
| 228 | /* |
| 229 | * During the great date rewrite of 1.3, we tried to track the |
| 230 | * evolving ECMA standard, which then had a definition of |
| 231 | * getYear which always subtracted 1900. Which we |
| 232 | * implemented, not realizing that it was incompatible with |
| 233 | * the old behavior... now, rather than thrash the behavior |
| 234 | * yet again, we've decided to leave it with the - 1900 |
| 235 | * behavior and point people to the getFullYear method. But |
| 236 | * we try to protect existing scripts that have specified a |
| 237 | * version... |
| 238 | */ |
| 239 | version = cx.getLanguageVersion(); |
| 240 | return (version == Context.VERSION_1_0 |
| 241 | || version == Context.VERSION_1_1 |
| 242 | || version == Context.VERSION_1_2); |
| 243 | |
| 244 | case Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME: |
| 245 | return false; |
| 246 | |
| 247 | case Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER: |
| 248 | return true; |
| 249 | |
| 250 | case Context.FEATURE_TO_STRING_AS_SOURCE: |
| 251 | version = cx.getLanguageVersion(); |
| 252 | return version == Context.VERSION_1_2; |
| 253 | |
| 254 | case Context.FEATURE_PARENT_PROTO_PROPERTIES: |
| 255 | return true; |
| 256 | |
| 257 | case Context.FEATURE_E4X: |
| 258 | version = cx.getLanguageVersion(); |
| 259 | return (version == Context.VERSION_DEFAULT |
| 260 | || version >= Context.VERSION_1_6); |
| 261 | |
| 262 | case Context.FEATURE_DYNAMIC_SCOPE: |
| 263 | return false; |
| 264 | |
| 265 | case Context.FEATURE_STRICT_VARS: |
| 266 | return false; |
| 267 | |
| 268 | case Context.FEATURE_STRICT_EVAL: |
| 269 | return false; |
| 270 | |
| 271 | case Context.FEATURE_LOCATION_INFORMATION_IN_ERROR: |
| 272 | return false; |
| 273 | |
| 274 | case Context.FEATURE_STRICT_MODE: |
| 275 | return false; |
| 276 | |
| 277 | case Context.FEATURE_WARNING_AS_ERROR: |
| 278 | return false; |
| 279 | |
| 280 | case Context.FEATURE_ENHANCED_JAVA_ACCESS: |
| 281 | return false; |
| 282 | |
| 283 | case Context.FEATURE_V8_EXTENSIONS: |
| 284 | return true; |
| 285 | |
| 286 | case Context.FEATURE_OLD_UNDEF_NULL_THIS: |
| 287 | return cx.getLanguageVersion() <= Context.VERSION_1_7; |
| 288 | |
| 289 | case Context.FEATURE_ENUMERATE_IDS_FIRST: |
| 290 | return cx.getLanguageVersion() >= Context.VERSION_ES6; |
| 291 | } |
| 292 | // It is a bug to call the method with unknown featureIndex |
| 293 | throw new IllegalArgumentException(String.valueOf(featureIndex)); |
| 294 | } |
| 295 | |
| 296 | private boolean isDom3Present() { |
| 297 | Class<?> nodeClass = Kit.classOrNull("org.w3c.dom.Node"); |
| 298 | if (nodeClass == null) return false; |
| 299 | // Check to see whether DOM3 is present; use a new method defined in |
| 300 | // DOM3 that is vital to our implementation |
| 301 | try { |
| 302 | nodeClass.getMethod("getUserData", new Class<?>[] { String.class }); |
| 303 | return true; |
| 304 | } catch (NoSuchMethodException e) { |
| 305 | return false; |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * Provides a default |
| 311 | * {@link org.mozilla.javascript.xml.XMLLib.Factory XMLLib.Factory} |
| 312 | * to be used by the <code>Context</code> instances produced by this |
| 313 | * factory. See {@link Context#getE4xImplementationFactory} for details. |
| 314 | * |
| 315 | * May return null, in which case E4X functionality is not supported in |
| 316 | * Rhino. |
| 317 | * |
| 318 | * The default implementation now prefers the DOM3 E4X implementation. |
| 319 | */ |
| 320 | protected org.mozilla.javascript.xml.XMLLib.Factory |
| 321 | getE4xImplementationFactory() |
| 322 | { |
| 323 | // Must provide default implementation, rather than abstract method, |
| 324 | // so that past implementors of ContextFactory do not fail at runtime |
| 325 | // upon invocation of this method. |
| 326 | // Note that the default implementation returns null if we |
| 327 | // neither have XMLBeans nor a DOM3 implementation present. |
| 328 | |
| 329 | if (isDom3Present()) { |
| 330 | return org.mozilla.javascript.xml.XMLLib.Factory.create( |
| 331 | "org.mozilla.javascript.xmlimpl.XMLLibImpl" |
| 332 | ); |
| 333 | } else { |
| 334 | return null; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | |
| 339 | /** |
| 340 | * Create class loader for generated classes. |
| 341 | * This method creates an instance of the default implementation |
| 342 | * of {@link GeneratedClassLoader}. Rhino uses this interface to load |
| 343 | * generated JVM classes when no {@link SecurityController} |
| 344 | * is installed. |
| 345 | * Application can override the method to provide custom class loading. |
| 346 | */ |
| 347 | protected GeneratedClassLoader createClassLoader(final ClassLoader parent) |
| 348 | { |
| 349 | return AccessController.doPrivileged(new PrivilegedAction<DefiningClassLoader>() { |
| 350 | public DefiningClassLoader run(){ |
| 351 | return new DefiningClassLoader(parent); |
| 352 | } |
| 353 | }); |
| 354 | } |
| 355 | |
| 356 | /** |
| 357 | * Get ClassLoader to use when searching for Java classes. |
| 358 | * Unless it was explicitly initialized with |
| 359 | * {@link #initApplicationClassLoader(ClassLoader)} the method returns |
| 360 | * null to indicate that Thread.getContextClassLoader() should be used. |
| 361 | */ |
| 362 | public final ClassLoader getApplicationClassLoader() |
| 363 | { |
| 364 | return applicationClassLoader; |
| 365 | } |
| 366 | |
| 367 | /** |
| 368 | * Set explicit class loader to use when searching for Java classes. |
| 369 | * |
| 370 | * @see #getApplicationClassLoader() |
| 371 | */ |
| 372 | public final void initApplicationClassLoader(ClassLoader loader) |
| 373 | { |
| 374 | if (loader == null) |
| 375 | throw new IllegalArgumentException("loader is null"); |
| 376 | if (!Kit.testIfCanLoadRhinoClasses(loader)) |
| 377 | throw new IllegalArgumentException( |
| 378 | "Loader can not resolve Rhino classes"); |
| 379 | |
| 380 | if (this.applicationClassLoader != null) |
| 381 | throw new IllegalStateException( |
| 382 | "applicationClassLoader can only be set once"); |
| 383 | checkNotSealed(); |
| 384 | |
| 385 | this.applicationClassLoader = loader; |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Execute top call to script or function. |
| 390 | * When the runtime is about to execute a script or function that will |
| 391 | * create the first stack frame with scriptable code, it calls this method |
| 392 | * to perform the real call. In this way execution of any script |
| 393 | * happens inside this function. |
| 394 | */ |
| 395 | protected Object doTopCall(Callable callable, |
| 396 | Context cx, Scriptable scope, |
| 397 | Scriptable thisObj, Object[] args) |
| 398 | { |
| 399 | Object result = callable.call(cx, scope, thisObj, args); |
| 400 | return result instanceof ConsString ? result.toString() : result; |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Implementation of |
| 405 | * {@link Context#observeInstructionCount(int instructionCount)}. |
| 406 | * This can be used to customize {@link Context} without introducing |
| 407 | * additional subclasses. |
| 408 | */ |
| 409 | protected void observeInstructionCount(Context cx, int instructionCount) { |
| 410 | } |
| 411 | |
| 412 | protected void onContextCreated(Context cx) |
| 413 | { |
| 414 | Object listeners = this.listeners; |
| 415 | for (int i = 0; ; ++i) { |
| 416 | Listener l = (Listener)Kit.getListener(listeners, i); |
| 417 | if (l == null) |
| 418 | break; |
| 419 | l.contextCreated(cx); |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | protected void onContextReleased(Context cx) |
| 424 | { |
| 425 | Object listeners = this.listeners; |
| 426 | for (int i = 0; ; ++i) { |
| 427 | Listener l = (Listener)Kit.getListener(listeners, i); |
| 428 | if (l == null) |
| 429 | break; |
| 430 | l.contextReleased(cx); |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | public final void addListener(Listener listener) |
| 435 | { |
| 436 | checkNotSealed(); |
| 437 | synchronized (listenersLock) { |
| 438 | if (disabledListening) { |
| 439 | throw new IllegalStateException(); |
| 440 | } |
| 441 | listeners = Kit.addListener(listeners, listener); |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | public final void removeListener(Listener listener) |
| 446 | { |
| 447 | checkNotSealed(); |
| 448 | synchronized (listenersLock) { |
| 449 | if (disabledListening) { |
| 450 | throw new IllegalStateException(); |
| 451 | } |
| 452 | listeners = Kit.removeListener(listeners, listener); |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | /** |
| 457 | * The method is used only to implement |
| 458 | * Context.disableStaticContextListening() |
| 459 | */ |
| 460 | final void disableContextListening() |
| 461 | { |
| 462 | checkNotSealed(); |
| 463 | synchronized (listenersLock) { |
| 464 | disabledListening = true; |
| 465 | listeners = null; |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /** |
| 470 | * Checks if this is a sealed ContextFactory. |
| 471 | * @see #seal() |
| 472 | */ |
| 473 | public final boolean isSealed() |
| 474 | { |
| 475 | return sealed; |
| 476 | } |
| 477 | |
| 478 | /** |
| 479 | * Seal this ContextFactory so any attempt to modify it like to add or |
| 480 | * remove its listeners will throw an exception. |
| 481 | * @see #isSealed() |
| 482 | */ |
| 483 | public final void seal() |
| 484 | { |
| 485 | checkNotSealed(); |
| 486 | sealed = true; |
| 487 | } |
| 488 | |
| 489 | protected final void checkNotSealed() |
| 490 | { |
| 491 | if (sealed) throw new IllegalStateException(); |
| 492 | } |
| 493 | |
| 494 | /** |
| 495 | * Call {@link ContextAction#run(Context cx)} |
| 496 | * using the {@link Context} instance associated with the current thread. |
| 497 | * If no Context is associated with the thread, then |
| 498 | * {@link #makeContext()} will be called to construct |
| 499 | * new Context instance. The instance will be temporary associated |
| 500 | * with the thread during call to {@link ContextAction#run(Context)}. |
| 501 | * |
| 502 | * @see ContextFactory#call(ContextAction) |
| 503 | * @see Context#call(ContextFactory factory, Callable callable, |
| 504 | * Scriptable scope, Scriptable thisObj, |
| 505 | * Object[] args) |
| 506 | */ |
| 507 | public final Object call(ContextAction action) |
| 508 | { |
| 509 | return Context.call(this, action); |
| 510 | } |
| 511 | |
| 512 | /** |
| 513 | * Get a context associated with the current thread, creating one if need |
| 514 | * be. The Context stores the execution state of the JavaScript engine, so |
| 515 | * it is required that the context be entered before execution may begin. |
| 516 | * Once a thread has entered a Context, then getCurrentContext() may be |
| 517 | * called to find the context that is associated with the current thread. |
| 518 | * <p> |
| 519 | * Calling <code>enterContext()</code> will return either the Context |
| 520 | * currently associated with the thread, or will create a new context and |
| 521 | * associate it with the current thread. Each call to |
| 522 | * <code>enterContext()</code> must have a matching call to |
| 523 | * {@link Context#exit()}. |
| 524 | * <pre> |
| 525 | * Context cx = contextFactory.enterContext(); |
| 526 | * try { |
| 527 | * ... |
| 528 | * cx.evaluateString(...); |
| 529 | * } finally { |
| 530 | * Context.exit(); |
| 531 | * } |
| 532 | * </pre> |
| 533 | * Instead of using <tt>enterContext()</tt>, <tt>exit()</tt> pair consider |
| 534 | * using {@link #call(ContextAction)} which guarantees proper association |
| 535 | * of Context instances with the current thread. |
| 536 | * With this method the above example becomes: |
| 537 | * <pre> |
| 538 | * ContextFactory.call(new ContextAction() { |
| 539 | * public Object run(Context cx) { |
| 540 | * ... |
| 541 | * cx.evaluateString(...); |
| 542 | * return null; |
| 543 | * } |
| 544 | * }); |
| 545 | * </pre> |
| 546 | * @return a Context associated with the current thread |
| 547 | * @see Context#getCurrentContext() |
| 548 | * @see Context#exit() |
| 549 | * @see #call(ContextAction) |
| 550 | */ |
| 551 | public Context enterContext() |
| 552 | { |
| 553 | return enterContext(null); |
| 554 | } |
| 555 | |
| 556 | /** |
| 557 | * @deprecated use {@link #enterContext()} instead |
| 558 | * @return a Context associated with the current thread |
| 559 | */ |
| 560 | @Deprecated |
| 561 | public final Context enter() |
| 562 | { |
| 563 | return enterContext(null); |
| 564 | } |
| 565 | |
| 566 | /** |
| 567 | * @deprecated Use {@link Context#exit()} instead. |
| 568 | */ |
| 569 | @Deprecated |
| 570 | public final void exit() |
| 571 | { |
| 572 | Context.exit(); |
| 573 | } |
| 574 | |
| 575 | /** |
| 576 | * Get a Context associated with the current thread, using the given |
| 577 | * Context if need be. |
| 578 | * <p> |
| 579 | * The same as <code>enterContext()</code> except that <code>cx</code> |
| 580 | * is associated with the current thread and returned if the current thread |
| 581 | * has no associated context and <code>cx</code> is not associated with any |
| 582 | * other thread. |
| 583 | * @param cx a Context to associate with the thread if possible |
| 584 | * @return a Context associated with the current thread |
| 585 | * @see #enterContext() |
| 586 | * @see #call(ContextAction) |
| 587 | * @throws IllegalStateException if <code>cx</code> is already associated |
| 588 | * with a different thread |
| 589 | */ |
| 590 | public final Context enterContext(Context cx) |
| 591 | { |
| 592 | return Context.enter(cx, this); |
| 593 | } |
| 594 | } |