1 /* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package jdk.nashorn.api.scripting; 27 28 import java.nio.ByteBuffer; 29 import java.security.AccessControlContext; 30 import java.security.AccessController; 31 import java.security.Permissions; 32 import java.security.PrivilegedAction; 33 import java.security.ProtectionDomain; 34 import java.util.AbstractMap; 35 import java.util.ArrayList; 36 import java.util.Collection; 37 import java.util.Collections; 38 import java.util.Iterator; 39 import java.util.LinkedHashSet; 40 import java.util.List; 41 import java.util.Map; 42 import java.util.Set; 43 import java.util.concurrent.Callable; 44 import javax.script.Bindings; 45 import jdk.nashorn.internal.objects.Global; 46 import jdk.nashorn.internal.runtime.ConsString; 47 import jdk.nashorn.internal.runtime.Context; 48 import jdk.nashorn.internal.runtime.JSType; 49 import jdk.nashorn.internal.runtime.ScriptFunction; 50 import jdk.nashorn.internal.runtime.ScriptObject; 51 import jdk.nashorn.internal.runtime.ScriptRuntime; 52 import jdk.nashorn.internal.runtime.arrays.ArrayData; 53 import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor; 54 55 /** 56 * Mirror object that wraps a given Nashorn Script object. 57 */ 58 public final class ScriptObjectMirror extends AbstractJSObject implements Bindings { 59 private static AccessControlContext getContextAccCtxt() { 60 final Permissions perms = new Permissions(); 61 perms.add(new RuntimePermission(Context.NASHORN_GET_CONTEXT)); 62 return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) }); 63 } 64 65 private static final AccessControlContext GET_CONTEXT_ACC_CTXT = getContextAccCtxt(); 66 67 private final ScriptObject sobj; 68 private final Global global; 69 private final boolean strict; 70 71 @Override 72 public boolean equals(final Object other) { 73 if (other instanceof ScriptObjectMirror) { 74 return sobj.equals(((ScriptObjectMirror)other).sobj); 75 } 76 77 return false; 78 } 79 80 @Override 81 public int hashCode() { 82 return sobj.hashCode(); 83 } 84 85 @Override 86 public String toString() { 87 return inGlobal(new Callable<String>() { 88 @Override 89 public String call() { 90 return ScriptRuntime.safeToString(sobj); 91 } 92 }); 93 } 94 95 // JSObject methods 96 97 @Override 98 public Object call(final Object thiz, final Object... args) { 99 final Global oldGlobal = Context.getGlobal(); 100 final boolean globalChanged = (oldGlobal != global); 101 102 try { 103 if (globalChanged) { 104 Context.setGlobal(global); 105 } 106 107 if (sobj instanceof ScriptFunction) { 108 final Object[] modArgs = globalChanged? wrapArray(args, oldGlobal) : args; 109 final Object self = globalChanged? wrap(thiz, oldGlobal) : thiz; 110 return wrap(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)), global); 111 } 112 113 throw new RuntimeException("not a function: " + toString()); 114 } catch (final NashornException ne) { 115 throw ne.initEcmaError(global); 116 } catch (final RuntimeException | Error e) { 117 throw e; 118 } catch (final Throwable t) { 119 throw new RuntimeException(t); 120 } finally { 121 if (globalChanged) { 122 Context.setGlobal(oldGlobal); 123 } 124 } 125 } 126 127 @Override 128 public Object newObject(final Object... args) { 129 final Global oldGlobal = Context.getGlobal(); 130 final boolean globalChanged = (oldGlobal != global); 131 132 try { 133 if (globalChanged) { 134 Context.setGlobal(global); 135 } 136 137 if (sobj instanceof ScriptFunction) { 138 final Object[] modArgs = globalChanged? wrapArray(args, oldGlobal) : args; 139 return wrap(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)), global); 140 } 141 142 throw new RuntimeException("not a constructor: " + toString()); 143 } catch (final NashornException ne) { 144 throw ne.initEcmaError(global); 145 } catch (final RuntimeException | Error e) { 146 throw e; 147 } catch (final Throwable t) { 148 throw new RuntimeException(t); 149 } finally { 150 if (globalChanged) { 151 Context.setGlobal(oldGlobal); 152 } 153 } 154 } 155 156 @Override 157 public Object eval(final String s) { 158 return inGlobal(new Callable<Object>() { 159 @Override 160 public Object call() { 161 final Context context = AccessController.doPrivileged( 162 new PrivilegedAction<Context>() { 163 @Override 164 public Context run() { 165 return Context.getContext(); 166 } 167 }, GET_CONTEXT_ACC_CTXT); 168 return wrap(context.eval(global, s, sobj, null, false), global); 169 } 170 }); 171 } 172 173 /** 174 * Call member function 175 * @param functionName function name 176 * @param args arguments 177 * @return return value of function 178 */ 179 public Object callMember(final String functionName, final Object... args) { 180 functionName.getClass(); // null check 181 final Global oldGlobal = Context.getGlobal(); 182 final boolean globalChanged = (oldGlobal != global); 183 184 try { 185 if (globalChanged) { 186 Context.setGlobal(global); 187 } 188 189 final Object val = sobj.get(functionName); 190 if (val instanceof ScriptFunction) { 191 final Object[] modArgs = globalChanged? wrapArray(args, oldGlobal) : args; 192 return wrap(ScriptRuntime.apply((ScriptFunction)val, sobj, unwrapArray(modArgs, global)), global); 193 } else if (val instanceof JSObject && ((JSObject)val).isFunction()) { 194 return ((JSObject)val).call(sobj, args); 195 } 196 197 throw new NoSuchMethodException("No such function " + functionName); 198 } catch (final NashornException ne) { 199 throw ne.initEcmaError(global); 200 } catch (final RuntimeException | Error e) { 201 throw e; 202 } catch (final Throwable t) { 203 throw new RuntimeException(t); 204 } finally { 205 if (globalChanged) { 206 Context.setGlobal(oldGlobal); 207 } 208 } 209 } 210 211 @Override 212 public Object getMember(final String name) { 213 name.getClass(); 214 return inGlobal(new Callable<Object>() { 215 @Override public Object call() { 216 return wrap(sobj.get(name), global); 217 } 218 }); 219 } 220 221 @Override 222 public Object getSlot(final int index) { 223 return inGlobal(new Callable<Object>() { 224 @Override public Object call() { 225 return wrap(sobj.get(index), global); 226 } 227 }); 228 } 229 230 @Override 231 public boolean hasMember(final String name) { 232 name.getClass(); 233 return inGlobal(new Callable<Boolean>() { 234 @Override public Boolean call() { 235 return sobj.has(name); 236 } 237 }); 238 } 239 240 @Override 241 public boolean hasSlot(final int slot) { 242 return inGlobal(new Callable<Boolean>() { 243 @Override public Boolean call() { 244 return sobj.has(slot); 245 } 246 }); 247 } 248 249 @Override 250 public void removeMember(final String name) { 251 name.getClass(); 252 remove(name); 253 } 254 255 @Override 256 public void setMember(final String name, final Object value) { 257 name.getClass(); 258 put(name, value); 259 } 260 261 @Override 262 public void setSlot(final int index, final Object value) { 263 inGlobal(new Callable<Void>() { 264 @Override public Void call() { 265 sobj.set(index, unwrap(value, global), getCallSiteFlags()); 266 return null; 267 } 268 }); 269 } 270 271 /** 272 * Nashorn extension: setIndexedPropertiesToExternalArrayData. 273 * set indexed properties be exposed from a given nio ByteBuffer. 274 * 275 * @param buf external buffer - should be a nio ByteBuffer 276 */ 277 public void setIndexedPropertiesToExternalArrayData(final ByteBuffer buf) { 278 inGlobal(new Callable<Void>() { 279 @Override public Void call() { 280 sobj.setArray(ArrayData.allocate(buf)); 281 return null; 282 } 283 }); 284 } 285 286 287 @Override 288 public boolean isInstance(final Object obj) { 289 if (! (obj instanceof ScriptObjectMirror)) { 290 return false; 291 } 292 293 final ScriptObjectMirror instance = (ScriptObjectMirror)obj; 294 // if not belongs to my global scope, return false 295 if (global != instance.global) { 296 return false; 297 } 298 299 return inGlobal(new Callable<Boolean>() { 300 @Override public Boolean call() { 301 return sobj.isInstance(instance.sobj); 302 } 303 }); 304 } 305 306 @Override 307 public String getClassName() { 308 return sobj.getClassName(); 309 } 310 311 @Override 312 public boolean isFunction() { 313 return sobj instanceof ScriptFunction; 314 } 315 316 @Override 317 public boolean isStrictFunction() { 318 return isFunction() && ((ScriptFunction)sobj).isStrict(); 319 } 320 321 @Override 322 public boolean isArray() { 323 return sobj.isArray(); 324 } 325 326 // javax.script.Bindings methods 327 328 @Override 329 public void clear() { 330 inGlobal(new Callable<Object>() { 331 @Override public Object call() { 332 sobj.clear(strict); 333 return null; 334 } 335 }); 336 } 337 338 @Override 339 public boolean containsKey(final Object key) { 340 return inGlobal(new Callable<Boolean>() { 341 @Override public Boolean call() { 342 return sobj.containsKey(unwrap(key, global)); 343 } 344 }); 345 } 346 347 @Override 348 public boolean containsValue(final Object value) { 349 return inGlobal(new Callable<Boolean>() { 350 @Override public Boolean call() { 351 return sobj.containsValue(unwrap(value, global)); 352 } 353 }); 354 } 355 356 @Override 357 public Set<Map.Entry<String, Object>> entrySet() { 358 return inGlobal(new Callable<Set<Map.Entry<String, Object>>>() { 359 @Override public Set<Map.Entry<String, Object>> call() { 360 final Iterator<String> iter = sobj.propertyIterator(); 361 final Set<Map.Entry<String, Object>> entries = new LinkedHashSet<>(); 362 363 while (iter.hasNext()) { 364 final String key = iter.next(); 365 final Object value = translateUndefined(wrap(sobj.get(key), global)); 366 entries.add(new AbstractMap.SimpleImmutableEntry<>(key, value)); 367 } 368 369 return Collections.unmodifiableSet(entries); 370 } 371 }); 372 } 373 374 @Override 375 public Object get(final Object key) { 376 return inGlobal(new Callable<Object>() { 377 @Override public Object call() { 378 return translateUndefined(wrap(sobj.get(key), global)); 379 } 380 }); 381 } 382 383 @Override 384 public boolean isEmpty() { 385 return inGlobal(new Callable<Boolean>() { 386 @Override public Boolean call() { 387 return sobj.isEmpty(); 388 } 389 }); 390 } 391 392 @Override 393 public Set<String> keySet() { 394 return inGlobal(new Callable<Set<String>>() { 395 @Override public Set<String> call() { 396 final Iterator<String> iter = sobj.propertyIterator(); 397 final Set<String> keySet = new LinkedHashSet<>(); 398 399 while (iter.hasNext()) { 400 keySet.add(iter.next()); 401 } 402 403 return Collections.unmodifiableSet(keySet); 404 } 405 }); 406 } 407 408 @Override 409 public Object put(final String key, final Object value) { 410 final ScriptObject oldGlobal = Context.getGlobal(); 411 final boolean globalChanged = (oldGlobal != global); 412 return inGlobal(new Callable<Object>() { 413 @Override public Object call() { 414 final Object modValue = globalChanged? wrap(value, oldGlobal) : value; 415 return translateUndefined(wrap(sobj.put(key, unwrap(modValue, global), strict), global)); 416 } 417 }); 418 } 419 420 @Override 421 public void putAll(final Map<? extends String, ? extends Object> map) { 422 final ScriptObject oldGlobal = Context.getGlobal(); 423 final boolean globalChanged = (oldGlobal != global); 424 inGlobal(new Callable<Object>() { 425 @Override public Object call() { 426 for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) { 427 final Object value = entry.getValue(); 428 final Object modValue = globalChanged? wrap(value, oldGlobal) : value; 429 sobj.set(entry.getKey(), unwrap(modValue, global), getCallSiteFlags()); 430 } 431 return null; 432 } 433 }); 434 } 435 436 @Override 437 public Object remove(final Object key) { 438 return inGlobal(new Callable<Object>() { 439 @Override public Object call() { 440 return wrap(sobj.remove(unwrap(key, global), strict), global); 441 } 442 }); 443 } 444 445 /** 446 * Delete a property from this object. 447 * 448 * @param key the property to be deleted 449 * 450 * @return if the delete was successful or not 451 */ 452 public boolean delete(final Object key) { 453 return inGlobal(new Callable<Boolean>() { 454 @Override public Boolean call() { 455 return sobj.delete(unwrap(key, global), strict); 456 } 457 }); 458 } 459 460 @Override 461 public int size() { 462 return inGlobal(new Callable<Integer>() { 463 @Override public Integer call() { 464 return sobj.size(); 465 } 466 }); 467 } 468 469 @Override 470 public Collection<Object> values() { 471 return inGlobal(new Callable<Collection<Object>>() { 472 @Override public Collection<Object> call() { 473 final List<Object> values = new ArrayList<>(size()); 474 final Iterator<Object> iter = sobj.valueIterator(); 475 476 while (iter.hasNext()) { 477 values.add(translateUndefined(wrap(iter.next(), global))); 478 } 479 480 return Collections.unmodifiableList(values); 481 } 482 }); 483 } 484 485 // Support for ECMAScript Object API on mirrors 486 487 /** 488 * Return the __proto__ of this object. 489 * @return __proto__ object. 490 */ 491 public Object getProto() { 492 return inGlobal(new Callable<Object>() { 493 @Override public Object call() { 494 return wrap(sobj.getProto(), global); 495 } 496 }); 497 } 498 499 /** 500 * Set the __proto__ of this object. 501 * @param proto new proto for this object 502 */ 503 public void setProto(final Object proto) { 504 inGlobal(new Callable<Void>() { 505 @Override public Void call() { 506 sobj.setPrototypeOf(unwrap(proto, global)); 507 return null; 508 } 509 }); 510 } 511 512 /** 513 * ECMA 8.12.1 [[GetOwnProperty]] (P) 514 * 515 * @param key property key 516 * 517 * @return Returns the Property Descriptor of the named own property of this 518 * object, or undefined if absent. 519 */ 520 public Object getOwnPropertyDescriptor(final String key) { 521 return inGlobal(new Callable<Object>() { 522 @Override public Object call() { 523 return wrap(sobj.getOwnPropertyDescriptor(key), global); 524 } 525 }); 526 } 527 528 /** 529 * return an array of own property keys associated with the object. 530 * 531 * @param all True if to include non-enumerable keys. 532 * @return Array of keys. 533 */ 534 public String[] getOwnKeys(final boolean all) { 535 return inGlobal(new Callable<String[]>() { 536 @Override public String[] call() { 537 return sobj.getOwnKeys(all); 538 } 539 }); 540 } 541 542 /** 543 * Flag this script object as non extensible 544 * 545 * @return the object after being made non extensible 546 */ 547 public ScriptObjectMirror preventExtensions() { 548 return inGlobal(new Callable<ScriptObjectMirror>() { 549 @Override public ScriptObjectMirror call() { 550 sobj.preventExtensions(); 551 return ScriptObjectMirror.this; 552 } 553 }); 554 } 555 556 /** 557 * Check if this script object is extensible 558 * @return true if extensible 559 */ 560 public boolean isExtensible() { 561 return inGlobal(new Callable<Boolean>() { 562 @Override public Boolean call() { 563 return sobj.isExtensible(); 564 } 565 }); 566 } 567 568 /** 569 * ECMAScript 15.2.3.8 - seal implementation 570 * @return the sealed script object 571 */ 572 public ScriptObjectMirror seal() { 573 return inGlobal(new Callable<ScriptObjectMirror>() { 574 @Override public ScriptObjectMirror call() { 575 sobj.seal(); 576 return ScriptObjectMirror.this; 577 } 578 }); 579 } 580 581 /** 582 * Check whether this script object is sealed 583 * @return true if sealed 584 */ 585 public boolean isSealed() { 586 return inGlobal(new Callable<Boolean>() { 587 @Override public Boolean call() { 588 return sobj.isSealed(); 589 } 590 }); 591 } 592 593 /** 594 * ECMA 15.2.39 - freeze implementation. Freeze this script object 595 * @return the frozen script object 596 */ 597 public ScriptObjectMirror freeze() { 598 return inGlobal(new Callable<ScriptObjectMirror>() { 599 @Override public ScriptObjectMirror call() { 600 sobj.freeze(); 601 return ScriptObjectMirror.this; 602 } 603 }); 604 } 605 606 /** 607 * Check whether this script object is frozen 608 * @return true if frozen 609 */ 610 public boolean isFrozen() { 611 return inGlobal(new Callable<Boolean>() { 612 @Override public Boolean call() { 613 return sobj.isFrozen(); 614 } 615 }); 616 } 617 618 /** 619 * Utility to check if given object is ECMAScript undefined value 620 * 621 * @param obj object to check 622 * @return true if 'obj' is ECMAScript undefined value 623 */ 624 public static boolean isUndefined(final Object obj) { 625 return obj == ScriptRuntime.UNDEFINED; 626 } 627 628 /** 629 * Utilitity to convert this script object to the given type. 630 * 631 * @param <T> destination type to convert to 632 * @param type destination type to convert to 633 * @return converted object 634 */ 635 public <T> T to(final Class<T> type) { 636 return inGlobal(new Callable<T>() { 637 @Override 638 public T call() { 639 return type.cast(ScriptUtils.convert(sobj, type)); 640 } 641 }); 642 } 643 644 /** 645 * Make a script object mirror on given object if needed. Also converts ConsString instances to Strings. 646 * 647 * @param obj object to be wrapped/converted 648 * @param homeGlobal global to which this object belongs. Not used for ConsStrings. 649 * @return wrapped/converted object 650 */ 651 public static Object wrap(final Object obj, final Object homeGlobal) { 652 if(obj instanceof ScriptObject) { 653 return homeGlobal instanceof Global ? new ScriptObjectMirror((ScriptObject)obj, (Global)homeGlobal) : obj; 654 } 655 if(obj instanceof ConsString) { 656 return obj.toString(); 657 } 658 return obj; 659 } 660 661 /** 662 * Unwrap a script object mirror if needed. 663 * 664 * @param obj object to be unwrapped 665 * @param homeGlobal global to which this object belongs 666 * @return unwrapped object 667 */ 668 public static Object unwrap(final Object obj, final Object homeGlobal) { 669 if (obj instanceof ScriptObjectMirror) { 670 final ScriptObjectMirror mirror = (ScriptObjectMirror)obj; 671 return (mirror.global == homeGlobal)? mirror.sobj : obj; 672 } 673 674 return obj; 675 } 676 677 /** 678 * Wrap an array of object to script object mirrors if needed. 679 * 680 * @param args array to be unwrapped 681 * @param homeGlobal global to which this object belongs 682 * @return wrapped array 683 */ 684 public static Object[] wrapArray(final Object[] args, final Object homeGlobal) { 685 if (args == null || args.length == 0) { 686 return args; 687 } 688 689 final Object[] newArgs = new Object[args.length]; 690 int index = 0; 691 for (final Object obj : args) { 692 newArgs[index] = wrap(obj, homeGlobal); 693 index++; 694 } 695 return newArgs; 696 } 697 698 /** 699 * Unwrap an array of script object mirrors if needed. 700 * 701 * @param args array to be unwrapped 702 * @param homeGlobal global to which this object belongs 703 * @return unwrapped array 704 */ 705 public static Object[] unwrapArray(final Object[] args, final Object homeGlobal) { 706 if (args == null || args.length == 0) { 707 return args; 708 } 709 710 final Object[] newArgs = new Object[args.length]; 711 int index = 0; 712 for (final Object obj : args) { 713 newArgs[index] = unwrap(obj, homeGlobal); 714 index++; 715 } 716 return newArgs; 717 } 718 719 /** 720 * Are the given objects mirrors to same underlying object? 721 * 722 * @param obj1 first object 723 * @param obj2 second object 724 * @return true if obj1 and obj2 are identical script objects or mirrors of it. 725 */ 726 public static boolean identical(final Object obj1, final Object obj2) { 727 final Object o1 = (obj1 instanceof ScriptObjectMirror)? 728 ((ScriptObjectMirror)obj1).sobj : obj1; 729 730 final Object o2 = (obj2 instanceof ScriptObjectMirror)? 731 ((ScriptObjectMirror)obj2).sobj : obj2; 732 733 return o1 == o2; 734 } 735 736 // package-privates below this. 737 738 ScriptObjectMirror(final ScriptObject sobj, final Global global) { 739 assert sobj != null : "ScriptObjectMirror on null!"; 740 assert global != null : "home Global is null"; 741 742 this.sobj = sobj; 743 this.global = global; 744 this.strict = global.isStrictContext(); 745 } 746 747 // accessors for script engine 748 ScriptObject getScriptObject() { 749 return sobj; 750 } 751 752 Global getHomeGlobal() { 753 return global; 754 } 755 756 static Object translateUndefined(final Object obj) { 757 return (obj == ScriptRuntime.UNDEFINED)? null : obj; 758 } 759 760 private int getCallSiteFlags() { 761 return strict ? NashornCallSiteDescriptor.CALLSITE_STRICT : 0; 762 } 763 764 // internals only below this. 765 private <V> V inGlobal(final Callable<V> callable) { 766 final Global oldGlobal = Context.getGlobal(); 767 final boolean globalChanged = (oldGlobal != global); 768 if (globalChanged) { 769 Context.setGlobal(global); 770 } 771 try { 772 return callable.call(); 773 } catch (final NashornException ne) { 774 throw ne.initEcmaError(global); 775 } catch (final RuntimeException e) { 776 throw e; 777 } catch (final Exception e) { 778 throw new AssertionError("Cannot happen", e); 779 } finally { 780 if (globalChanged) { 781 Context.setGlobal(oldGlobal); 782 } 783 } 784 } 785 786 @Override 787 public double toNumber() { 788 return inGlobal(new Callable<Double>() { 789 @Override public Double call() { 790 return JSType.toNumber(sobj); 791 } 792 }); 793 } 794 }