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 26package jdk.nashorn.internal.runtime.linker; 27 28import static jdk.nashorn.internal.lookup.Lookup.MH; 29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 30import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 31 32import java.lang.invoke.MethodHandle; 33import java.lang.invoke.MethodHandles; 34import java.lang.invoke.MethodType; 35import java.util.HashMap; 36import java.util.Map; 37import java.util.function.Supplier; 38import jdk.dynalink.CallSiteDescriptor; 39import jdk.dynalink.NamedOperation; 40import jdk.dynalink.Operation; 41import jdk.dynalink.beans.BeansLinker; 42import jdk.dynalink.linker.GuardedInvocation; 43import jdk.dynalink.linker.GuardingDynamicLinker; 44import jdk.dynalink.linker.GuardingTypeConverterFactory; 45import jdk.dynalink.linker.LinkRequest; 46import jdk.dynalink.linker.LinkerServices; 47import jdk.dynalink.linker.support.Lookup; 48import jdk.nashorn.internal.codegen.types.Type; 49import jdk.nashorn.internal.runtime.ECMAException; 50import jdk.nashorn.internal.runtime.JSType; 51import jdk.nashorn.internal.runtime.ScriptRuntime; 52import jdk.nashorn.internal.runtime.UnwarrantedOptimismException; 53 54/** 55 * Nashorn bottom linker; used as a last-resort catch-all linker for all linking requests that fall through all other 56 * linkers (see how {@link Bootstrap} class configures the dynamic linker in its static initializer). It will throw 57 * appropriate ECMAScript errors for attempts to invoke operations on {@code null}, link no-op property getters and 58 * setters for Java objects that couldn't be linked by any other linker, and throw appropriate ECMAScript errors for 59 * attempts to invoke arbitrary Java objects as functions or constructors. 60 */ 61final class NashornBottomLinker implements GuardingDynamicLinker, GuardingTypeConverterFactory { 62 63 @Override 64 public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) 65 throws Exception { 66 final Object self = linkRequest.getReceiver(); 67 68 if (self == null) { 69 return linkNull(linkRequest); 70 } 71 72 // None of the objects that can be linked by NashornLinker should ever reach here. Basically, anything below 73 // this point is a generic Java bean. Therefore, reaching here with a ScriptObject is a Nashorn bug. 74 assert isExpectedObject(self) : "Couldn't link " + linkRequest.getCallSiteDescriptor() + " for " + self.getClass().getName(); 75 76 return linkBean(linkRequest); 77 } 78 79 private static final MethodHandle EMPTY_PROP_GETTER = 80 MH.dropArguments(MH.constant(Object.class, UNDEFINED), 0, Object.class); 81 private static final MethodHandle EMPTY_ELEM_GETTER = 82 MH.dropArguments(EMPTY_PROP_GETTER, 0, Object.class); 83 private static final MethodHandle EMPTY_PROP_SETTER = 84 MH.asType(EMPTY_ELEM_GETTER, EMPTY_ELEM_GETTER.type().changeReturnType(void.class)); 85 private static final MethodHandle EMPTY_ELEM_SETTER = 86 MH.dropArguments(EMPTY_PROP_SETTER, 0, Object.class); 87 88 private static final MethodHandle THROW_STRICT_PROPERTY_SETTER; 89 private static final MethodHandle THROW_OPTIMISTIC_UNDEFINED; 90 91 static { 92 final Lookup lookup = new Lookup(MethodHandles.lookup()); 93 THROW_STRICT_PROPERTY_SETTER = lookup.findOwnStatic("throwStrictPropertySetter", void.class, Object.class, Object.class); 94 THROW_OPTIMISTIC_UNDEFINED = lookup.findOwnStatic("throwOptimisticUndefined", Object.class, int.class); 95 } 96 97 private static GuardedInvocation linkBean(final LinkRequest linkRequest) throws Exception { 98 final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); 99 final Object self = linkRequest.getReceiver(); 100 switch (NashornCallSiteDescriptor.getStandardOperation(desc)) { 101 case NEW: 102 if(BeansLinker.isDynamicConstructor(self)) { 103 throw typeError("no.constructor.matches.args", ScriptRuntime.safeToString(self)); 104 } 105 if(BeansLinker.isDynamicMethod(self)) { 106 throw typeError("method.not.constructor", ScriptRuntime.safeToString(self)); 107 } 108 throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self)); 109 case CALL: 110 if(BeansLinker.isDynamicConstructor(self)) { 111 throw typeError("constructor.requires.new", ScriptRuntime.safeToString(self)); 112 } 113 if(BeansLinker.isDynamicMethod(self)) { 114 throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self)); 115 } 116 throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self)); 117 default: 118 // Everything else is supposed to have been already handled by Bootstrap.beansLinker 119 // delegating to linkNoSuchBeanMember 120 throw new AssertionError("unknown call type " + desc); 121 } 122 } 123 124 static MethodHandle linkMissingBeanMember(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception { 125 final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); 126 final String operand = NashornCallSiteDescriptor.getOperand(desc); 127 switch (NashornCallSiteDescriptor.getStandardOperation(desc)) { 128 case GET: 129 if (NashornCallSiteDescriptor.isOptimistic(desc)) { 130 return adaptThrower(MethodHandles.insertArguments(THROW_OPTIMISTIC_UNDEFINED, 0, NashornCallSiteDescriptor.getProgramPoint(desc)), desc); 131 } else if (operand != null) { 132 return getInvocation(EMPTY_PROP_GETTER, linkerServices, desc); 133 } 134 return getInvocation(EMPTY_ELEM_GETTER, linkerServices, desc); 135 case SET: 136 final boolean strict = NashornCallSiteDescriptor.isStrict(desc); 137 if (strict) { 138 return adaptThrower(bindOperand(THROW_STRICT_PROPERTY_SETTER, operand), desc); 139 } else if (operand != null) { 140 return getInvocation(EMPTY_PROP_SETTER, linkerServices, desc); 141 } 142 return getInvocation(EMPTY_ELEM_SETTER, linkerServices, desc); 143 default: 144 throw new AssertionError("unknown call type " + desc); 145 } 146 } 147 148 private static MethodHandle bindOperand(final MethodHandle handle, final String operand) { 149 return operand == null ? handle : MethodHandles.insertArguments(handle, 1, operand); 150 } 151 152 private static MethodHandle adaptThrower(final MethodHandle handle, final CallSiteDescriptor desc) { 153 final MethodType targetType = desc.getMethodType(); 154 final int paramCount = handle.type().parameterCount(); 155 return MethodHandles 156 .dropArguments(handle, paramCount, targetType.parameterList().subList(paramCount, targetType.parameterCount())) 157 .asType(targetType); 158 } 159 160 @SuppressWarnings("unused") 161 private static void throwStrictPropertySetter(final Object self, final Object name) { 162 throw createTypeError(self, name, "cant.set.property"); 163 } 164 165 private static ECMAException createTypeError(final Object self, final Object name, final String msg) { 166 return typeError(msg, String.valueOf(name), ScriptRuntime.safeToString(self)); 167 } 168 169 @SuppressWarnings("unused") 170 private static Object throwOptimisticUndefined(final int programPoint) { 171 throw new UnwarrantedOptimismException(UNDEFINED, programPoint, Type.OBJECT); 172 } 173 174 @Override 175 public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception { 176 final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType); 177 return gi == null ? null : gi.asType(MH.type(targetType, sourceType)); 178 } 179 180 /** 181 * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType} that doesn't 182 * care about adapting the method signature; that's done by the invoking method. Returns conversion 183 * from Object to String/number/boolean (JS primitive types). 184 * @param sourceType the source type 185 * @param targetType the target type 186 * @return a guarded invocation that converts from the source type to the target type. 187 * @throws Exception if something goes wrong 188 */ 189 private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception { 190 final MethodHandle mh = CONVERTERS.get(targetType); 191 if (mh != null) { 192 return new GuardedInvocation(mh); 193 } 194 195 return null; 196 } 197 198 private static MethodHandle getInvocation(final MethodHandle handle, final LinkerServices linkerServices, final CallSiteDescriptor desc) { 199 return linkerServices.asTypeLosslessReturn(handle, desc.getMethodType()); 200 } 201 202 // Used solely in an assertion to figure out if the object we get here is something we in fact expect. Objects 203 // linked by NashornLinker should never reach here. 204 private static boolean isExpectedObject(final Object obj) { 205 return !(NashornLinker.canLinkTypeStatic(obj.getClass())); 206 } 207 208 private static GuardedInvocation linkNull(final LinkRequest linkRequest) { 209 final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); 210 switch (NashornCallSiteDescriptor.getStandardOperation(desc)) { 211 case NEW: 212 case CALL: 213 throw typeError("not.a.function", "null"); 214 case GET: 215 throw typeError(NashornCallSiteDescriptor.isMethodFirstOperation(desc) ? "no.such.function" : "cant.get.property", getArgument(linkRequest), "null"); 216 case SET: 217 throw typeError("cant.set.property", getArgument(linkRequest), "null"); 218 default: 219 throw new AssertionError("unknown call type " + desc); 220 } 221 } 222 223 private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>(); 224 static { 225 CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle()); 226 CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle()); 227 CONVERTERS.put(int.class, JSType.TO_INTEGER.methodHandle()); 228 CONVERTERS.put(long.class, JSType.TO_LONG.methodHandle()); 229 CONVERTERS.put(String.class, JSType.TO_STRING.methodHandle()); 230 } 231 232 private static String getArgument(final LinkRequest linkRequest) { 233 final Operation op = linkRequest.getCallSiteDescriptor().getOperation(); 234 if (op instanceof NamedOperation) { 235 return ((NamedOperation)op).getName().toString(); 236 } 237 return ScriptRuntime.safeToString(linkRequest.getArguments()[1]); 238 } 239} 240