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.internal.runtime.linker;
  27 
  28 import java.lang.invoke.MethodHandles;
  29 import java.lang.reflect.Modifier;
  30 import jdk.dynalink.CallSiteDescriptor;
  31 import jdk.dynalink.NamedOperation;
  32 import jdk.dynalink.StandardOperation;
  33 import jdk.dynalink.beans.BeansLinker;
  34 import jdk.dynalink.beans.StaticClass;
  35 import jdk.dynalink.linker.GuardedInvocation;
  36 import jdk.dynalink.linker.GuardingDynamicLinker;
  37 import jdk.dynalink.linker.LinkRequest;
  38 import jdk.dynalink.linker.LinkerServices;
  39 import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
  40 import jdk.dynalink.linker.support.Guards;
  41 import jdk.nashorn.internal.runtime.Context;
  42 import jdk.nashorn.internal.runtime.ECMAErrors;
  43 
  44 /**
  45  * Internal linker for {@link StaticClass} objects, only ever used by Nashorn engine and not exposed to other engines.
  46  * It is used for extending the "new" operator on StaticClass in order to be able to instantiate interfaces and abstract
  47  * classes by passing a ScriptObject or ScriptFunction as their implementation, e.g.:
  48  * <pre>
  49  *   var r = new Runnable() { run: function() { print("Hello World" } }
  50  * </pre>
  51  * or for SAM types, even just passing a function:
  52  * <pre>
  53  *   var r = new Runnable(function() { print("Hello World" })
  54  * </pre>
  55  */
  56 final class NashornStaticClassLinker implements TypeBasedGuardingDynamicLinker {
  57     private final GuardingDynamicLinker staticClassLinker;
  58 
  59     NashornStaticClassLinker(final BeansLinker beansLinker) {
  60         this.staticClassLinker = beansLinker.getLinkerForClass(StaticClass.class);
  61     }
  62 
  63     @Override
  64     public boolean canLinkType(final Class<?> type) {
  65         return type == StaticClass.class;
  66     }
  67 
  68     @Override
  69     public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
  70         final Object self = request.getReceiver();
  71         if (self == null || self.getClass() != StaticClass.class) {
  72             return null;
  73         }
  74         final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();
  75 
  76         Bootstrap.checkReflectionAccess(receiverClass, true);
  77         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
  78         // We intercept "new" on StaticClass instances to provide additional capabilities
  79         if (NamedOperation.getBaseOperation(desc.getOperation()) == StandardOperation.NEW) {
  80             if (! Modifier.isPublic(receiverClass.getModifiers())) {
  81                 throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
  82             }
  83 
  84             // make sure new is on accessible Class
  85             Context.checkPackageAccess(receiverClass);
  86 
  87             // Is the class abstract? (This includes interfaces.)
  88             if (NashornLinker.isAbstractClass(receiverClass)) {
  89                 // Change this link request into a link request on the adapter class.
  90                 final Object[] args = request.getArguments();
  91                 final MethodHandles.Lookup lookup =
  92                         NashornCallSiteDescriptor.getLookupInternal(request.getCallSiteDescriptor());
  93 
  94                 args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null, lookup);
  95                 final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
  96                 final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
  97                 // Finally, modify the guard to test for the original abstract class.
  98                 return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
  99             }
 100             // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
 101             // additional check to ensure we have a constructor. We could just fall through to the next "return"
 102             // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
 103             // with a more intuitive message when no suitable constructor is found.
 104             return checkNullConstructor(delegate(linkerServices, request), receiverClass);
 105         }
 106         // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
 107         return delegate(linkerServices, request);
 108     }
 109 
 110     private GuardedInvocation delegate(final LinkerServices linkerServices, final LinkRequest request) throws Exception {
 111         return NashornBeansLinker.getGuardedInvocation(staticClassLinker, request, linkerServices);
 112     }
 113 
 114     private static GuardedInvocation checkNullConstructor(final GuardedInvocation ctorInvocation, final Class<?> receiverClass) {
 115         if(ctorInvocation == null) {
 116             throw ECMAErrors.typeError("no.constructor.matches.args", receiverClass.getName());
 117         }
 118         return ctorInvocation;
 119     }
 120 }