1 /*
2 * Copyright 2014 - 2020 Rafael Winterhalter
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.bytebuddy.implementation.bind.annotation;
17
18 import net.bytebuddy.build.HashCodeAndEqualsPlugin;
19 import net.bytebuddy.description.annotation.AnnotationDescription;
20 import net.bytebuddy.description.method.MethodDescription;
21 import net.bytebuddy.description.method.MethodList;
22 import net.bytebuddy.description.method.ParameterDescription;
23 import net.bytebuddy.description.type.TypeDescription;
24 import net.bytebuddy.dynamic.TargetType;
25 import net.bytebuddy.implementation.Implementation;
26 import net.bytebuddy.implementation.MethodAccessorFactory;
27 import net.bytebuddy.implementation.bind.MethodDelegationBinder;
28 import net.bytebuddy.implementation.bytecode.StackManipulation;
29 import net.bytebuddy.implementation.bytecode.assign.Assigner;
30 import net.bytebuddy.implementation.bytecode.constant.MethodConstant;
31 import net.bytebuddy.implementation.bytecode.constant.NullConstant;
32 import net.bytebuddy.implementation.bytecode.member.FieldAccess;
33 import net.bytebuddy.jar.asm.MethodVisitor;
34
35 import java.lang.annotation.*;
36 import java.lang.reflect.Method;
37
38 import static net.bytebuddy.matcher.ElementMatchers.named;
39
40 /**
41 * A parameter with this annotation is assigned an instance of {@link Method} which invokes a default method implementation of this method.
42 * If such a method is not available, this annotation causes that this delegation target cannot be bound unless {@link DefaultMethod#nullIfImpossible()}
43 * is set to {@code true}. The method is declared as {@code public} and is invokable unless the instrumented type itself is not visible. Note that
44 * requesting such a method exposes the super method to reflection.
45 *
46 * @see net.bytebuddy.implementation.MethodDelegation
47 * @see net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder
48 */
49 @Documented
50 @Retention(RetentionPolicy.RUNTIME)
51 @Target(ElementType.PARAMETER)
52 public @interface DefaultMethod {
53
54 /**
55 * Indicates if the instance assigned to this parameter should be stored in a static field for reuse.
56 *
57 * @return {@code true} if this method instance should be cached.
58 */
59 boolean cached() default true;
60
61 /**
62 * Indicates if the instance assigned to this parameter should be looked up using an {@link java.security.AccessController}.
63 *
64 * @return {@code true} if this method should be looked up using an {@link java.security.AccessController}.
65 */
66 boolean privileged() default false;
67
68 /**
69 * Specifies an explicit type that declares the default method to invoke.
70 *
71 * @return The type declaring the method to invoke or {@link TargetType} to indicate that the instrumented method declared the method.
72 */
73 Class<?> targetType() default void.class;
74
75 /**
76 * Indicates that {@code null} should be assigned to this parameter if no default method is invokable.
77 *
78 * @return {@code true} if {@code null} should be assigned if no valid method can be assigned.
79 */
80 boolean nullIfImpossible() default false;
81
82 /**
83 * A binder for the {@link DefaultMethod} annotation.
84 */
85 enum Binder implements TargetMethodAnnotationDrivenBinder.ParameterBinder<DefaultMethod> {
86
87 /**
88 * The singleton instance.
89 */
90 INSTANCE;
91
92 /**
93 * The {@link DefaultMethod#cached()} property.
94 */
95 private static final MethodDescription.InDefinedShape CACHED;
96
97 /**
98 * The {@link DefaultMethod#privileged()} property.
99 */
100 private static final MethodDescription.InDefinedShape PRIVILEGED;
101
102 /**
103 * The {@link DefaultMethod#targetType()} property.
104 */
105 private static final MethodDescription.InDefinedShape TARGET_TYPE;
106
107 /**
108 * The {@link DefaultMethod#nullIfImpossible()} property.
109 */
110 private static final MethodDescription.InDefinedShape NULL_IF_IMPOSSIBLE;
111
112 /*
113 * Locates method constants for properties of the default method annotation.
114 */
115 static {
116 MethodList<MethodDescription.InDefinedShape> methodList = TypeDescription.ForLoadedType.of(DefaultMethod.class).getDeclaredMethods();
117 CACHED = methodList.filter(named("cached")).getOnly();
118 PRIVILEGED = methodList.filter(named("privileged")).getOnly();
119 TARGET_TYPE = methodList.filter(named("targetType")).getOnly();
120 NULL_IF_IMPOSSIBLE = methodList.filter(named("nullIfImpossible")).getOnly();
121 }
122
123 /**
124 * {@inheritDoc}
125 */
126 public Class<DefaultMethod> getHandledType() {
127 return DefaultMethod.class;
128 }
129
130 /**
131 * {@inheritDoc}
132 */
133 public MethodDelegationBinder.ParameterBinding<?> bind(final AnnotationDescription.Loadable<DefaultMethod> annotation,
134 MethodDescription source,
135 ParameterDescription target,
136 Implementation.Target implementationTarget,
137 Assigner assigner,
138 Assigner.Typing typing) {
139 if (!target.getType().asErasure().isAssignableFrom(Method.class)) {
140 throw new IllegalStateException("Cannot assign Method type to " + target);
141 } else if (source.isMethod()) {
142 TypeDescription typeDescription = annotation.getValue(TARGET_TYPE).resolve(TypeDescription.class);
143 Implementation.SpecialMethodInvocation specialMethodInvocation = (typeDescription.represents(void.class)
144 ? MethodLocator.ForImplicitType.INSTANCE
145 : new MethodLocator.ForExplicitType(typeDescription)).resolve(implementationTarget, source).withCheckedCompatibilityTo(source.asTypeToken());
146 if (specialMethodInvocation.isValid()) {
147 return new MethodDelegationBinder.ParameterBinding.Anonymous(new DelegationMethod(specialMethodInvocation,
148 annotation.getValue(CACHED).resolve(Boolean.class),
149 annotation.getValue(PRIVILEGED).resolve(Boolean.class)));
150 } else if (annotation.getValue(NULL_IF_IMPOSSIBLE).resolve(Boolean.class)) {
151 return new MethodDelegationBinder.ParameterBinding.Anonymous(NullConstant.INSTANCE);
152 } else {
153 return MethodDelegationBinder.ParameterBinding.Illegal.INSTANCE;
154 }
155 } else if (annotation.getValue(NULL_IF_IMPOSSIBLE).resolve(Boolean.class)) {
156 return new MethodDelegationBinder.ParameterBinding.Anonymous(NullConstant.INSTANCE);
157 } else {
158 return MethodDelegationBinder.ParameterBinding.Illegal.INSTANCE;
159 }
160 }
161
162 /**
163 * A method locator is responsible for creating the super method call.
164 */
165 protected interface MethodLocator {
166
167 /**
168 * Resolves the special method invocation to this target.
169 *
170 * @param implementationTarget The implementation target.
171 * @param source The method being instrumented.
172 * @return A special method invocation that represents the super call of this binding.
173 */
174 Implementation.SpecialMethodInvocation resolve(Implementation.Target implementationTarget, MethodDescription source);
175
176 /**
177 * A method locator for an implicit target type.
178 */
179 enum ForImplicitType implements MethodLocator {
180
181 /**
182 * The singleton instance.
183 */
184 INSTANCE;
185
186 /**
187 * {@inheritDoc}
188 */
189 public Implementation.SpecialMethodInvocation resolve(Implementation.Target implementationTarget, MethodDescription source) {
190 return implementationTarget.invokeDefault(source.asSignatureToken());
191 }
192 }
193
194 /**
195 * A method locator for an explicit target type.
196 */
197 @HashCodeAndEqualsPlugin.Enhance
198 class ForExplicitType implements MethodLocator {
199
200 /**
201 * The explicit target type.
202 */
203 private final TypeDescription typeDescription;
204
205 /**
206 * Creates a method locator for an explicit target.
207 *
208 * @param typeDescription The explicit target type.
209 */
210 protected ForExplicitType(TypeDescription typeDescription) {
211 this.typeDescription = typeDescription;
212 }
213
214 /**
215 * {@inheritDoc}
216 */
217 public Implementation.SpecialMethodInvocation resolve(Implementation.Target implementationTarget, MethodDescription source) {
218 if (!typeDescription.isInterface()) {
219 throw new IllegalStateException(source + " method carries default method call parameter on non-interface type");
220 }
221 return implementationTarget.invokeDefault(source.asSignatureToken(), TargetType.resolve(typeDescription, implementationTarget.getInstrumentedType()));
222 }
223 }
224 }
225
226 /**
227 * Loads the delegation method constant onto the stack.
228 */
229 @HashCodeAndEqualsPlugin.Enhance
230 protected static class DelegationMethod implements StackManipulation {
231
232 /**
233 * The special method invocation that represents the super method call.
234 */
235 private final Implementation.SpecialMethodInvocation specialMethodInvocation;
236
237 /**
238 * {@code true} if the method constant should be cached.
239 */
240 private final boolean cached;
241
242 /**
243 * {@code true} if the method should be looked up using an {@link java.security.AccessController}.
244 */
245 private final boolean privileged;
246
247 /**
248 * Creates a new delegation method.
249 *
250 * @param specialMethodInvocation The special method invocation that represents the super method call.
251 * @param cached {@code true} if the method constant should be cached.
252 * @param privileged {@code true} if the method should be looked up using an {@link java.security.AccessController}.
253 */
254 protected DelegationMethod(Implementation.SpecialMethodInvocation specialMethodInvocation, boolean cached, boolean privileged) {
255 this.specialMethodInvocation = specialMethodInvocation;
256 this.cached = cached;
257 this.privileged = privileged;
258 }
259
260 /**
261 * {@inheritDoc}
262 */
263 public boolean isValid() {
264 return specialMethodInvocation.isValid();
265 }
266
267 /**
268 * {@inheritDoc}
269 */
270 public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
271 StackManipulation methodConstant = privileged
272 ? MethodConstant.ofPrivileged(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC))
273 : MethodConstant.of(implementationContext.registerAccessorFor(specialMethodInvocation, MethodAccessorFactory.AccessType.PUBLIC));
274 return (cached
275 ? FieldAccess.forField(implementationContext.cache(methodConstant, TypeDescription.ForLoadedType.of(Method.class))).read()
276 : methodConstant).apply(methodVisitor, implementationContext);
277 }
278 }
279 }
280 }
281