/
ProxyFactory.java
1027 lines (935 loc) · 45.2 KB
/
ProxyFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.bean.proxy;
import static org.jboss.classfilewriter.util.DescriptorUtils.isPrimitive;
import static org.jboss.classfilewriter.util.DescriptorUtils.isWide;
import static org.jboss.weld.util.reflection.Reflections.cast;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import jakarta.enterprise.inject.spi.Bean;
import org.jboss.classfilewriter.AccessFlag;
import org.jboss.classfilewriter.ClassFile;
import org.jboss.classfilewriter.ClassMethod;
import org.jboss.classfilewriter.DuplicateMemberException;
import org.jboss.classfilewriter.code.BranchEnd;
import org.jboss.classfilewriter.code.CodeAttribute;
import org.jboss.classfilewriter.util.Boxing;
import org.jboss.classfilewriter.util.DescriptorUtils;
import org.jboss.weld.Container;
import org.jboss.weld.annotated.enhanced.MethodSignature;
import org.jboss.weld.annotated.enhanced.jlr.MethodSignatureImpl;
import org.jboss.weld.bean.AbstractProducerBean;
import org.jboss.weld.bean.builtin.AbstractBuiltInBean;
import org.jboss.weld.config.WeldConfiguration;
import org.jboss.weld.exceptions.DefinitionException;
import org.jboss.weld.exceptions.WeldException;
import org.jboss.weld.interceptor.proxy.LifecycleMixin;
import org.jboss.weld.interceptor.util.proxy.TargetInstanceProxy;
import org.jboss.weld.logging.BeanLogger;
import org.jboss.weld.proxy.WeldConstruct;
import org.jboss.weld.security.GetDeclaredConstructorsAction;
import org.jboss.weld.security.GetDeclaredMethodsAction;
import org.jboss.weld.security.GetProtectionDomainAction;
import org.jboss.weld.serialization.spi.BeanIdentifier;
import org.jboss.weld.serialization.spi.ContextualStore;
import org.jboss.weld.serialization.spi.ProxyServices;
import org.jboss.weld.util.Proxies;
import org.jboss.weld.util.Proxies.TypeInfo;
import org.jboss.weld.util.bytecode.BytecodeUtils;
import org.jboss.weld.util.bytecode.ConstructorUtils;
import org.jboss.weld.util.bytecode.DeferredBytecode;
import org.jboss.weld.util.bytecode.MethodInformation;
import org.jboss.weld.util.bytecode.RuntimeMethodInformation;
import org.jboss.weld.util.collections.ImmutableSet;
import org.jboss.weld.util.collections.Sets;
import org.jboss.weld.util.reflection.Reflections;
/**
* Main factory to produce proxy classes and instances for Weld beans. This
* implementation creates proxies which forward non-static method invocations to
* a {@link BeanInstance}. All proxies implement the {@link Proxy} interface.
*
* @author David Allen
* @author Stuart Douglas
* @author Marius Bogoevici
* @author Ales Justin
*/
public class ProxyFactory<T> implements PrivilegedAction<T> {
// Default proxy class name suffix
public static final String PROXY_SUFFIX = "$Proxy$";
// choose different package from what we have in tests to distinguish it clearly
public static final String WELD_PROXY_PREFIX = "org.jboss.weld.generated.proxies";
public static final String DEFAULT_PROXY_PACKAGE = WELD_PROXY_PREFIX + ".default";
public static final String CONSTRUCTED_FLAG_NAME = "constructed";
protected static final BytecodeMethodResolver DEFAULT_METHOD_RESOLVER = new DefaultBytecodeMethodResolver();
protected static final String LJAVA_LANG_REFLECT_METHOD = "Ljava/lang/reflect/Method;";
protected static final String LJAVA_LANG_BYTE = "Ljava/lang/Byte;";
protected static final String LJAVA_LANG_CLASS = "Ljava/lang/Class;";
protected static final String LJAVA_LANG_OBJECT = "Ljava/lang/Object;";
protected static final String LBEAN_IDENTIFIER = "Lorg/jboss/weld/serialization/spi/BeanIdentifier;";
protected static final String LJAVA_LANG_STRING = "Ljava/lang/String;";
protected static final String LJAVA_LANG_THREAD_LOCAL = "Ljava/lang/ThreadLocal;";
protected static final String INIT_METHOD_NAME = "<init>";
protected static final String INVOKE_METHOD_NAME = "invoke";
protected static final String METHOD_HANDLER_FIELD_NAME = "methodHandler";
static final String JAVA = "java";
static final String JAKARTA = "jakarta";
static final String NO_PACKAGE = "the class package is null or empty";
static final String SIGNED = "the class is signed";
private static final Set<ProxiedMethodFilter> METHOD_FILTERS;
static {
Set<ProxiedMethodFilter> filters = new HashSet<>();
filters.add(CommonProxiedMethodFilters.NON_STATIC);
filters.add(CommonProxiedMethodFilters.NON_FINAL);
filters.add(CommonProxiedMethodFilters.OBJECT_TO_STRING);
filters.add(CommonProxiedMethodFilters.NON_JDK_PACKAGE_PRIVATE);
GroovyMethodFilter groovy = new GroovyMethodFilter();
if (groovy.isEnabled()) {
filters.add(groovy);
}
METHOD_FILTERS = ImmutableSet.copyOf(filters);
}
private final Class<?> beanType;
private final Set<Class<?>> additionalInterfaces = new LinkedHashSet<Class<?>>();
private final String baseProxyName;
private final Bean<?> bean;
private final Class<?> proxiedBeanType;
private final String contextId;
private final ProxyServices proxyServices;
private final WeldConfiguration configuration;
private final ProxyInstantiator proxyInstantiator;
/**
* created a new proxy factory from a bean instance. The proxy name is
* generated from the bean id
*/
public ProxyFactory(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, Bean<?> bean) {
this(contextId, proxiedBeanType, typeClosure, bean, false);
}
public ProxyFactory(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, Bean<?> bean,
boolean forceSuperClass) {
this(contextId, proxiedBeanType, typeClosure, getProxyName(contextId, proxiedBeanType, typeClosure, bean), bean,
forceSuperClass);
}
/**
* Creates a new proxy factory when the name of the proxy class is already
* known, such as during de-serialization
*
* @param proxiedBeanType the super-class for this proxy class
* @param typeClosure the bean types of the bean
* @param proxyName the name of the proxy class
*/
public ProxyFactory(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, String proxyName,
Bean<?> bean) {
this(contextId, proxiedBeanType, typeClosure, proxyName, bean, false);
}
public ProxyFactory(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, String proxyName,
Bean<?> bean, boolean forceSuperClass) {
this.bean = bean;
this.contextId = contextId;
this.proxiedBeanType = proxiedBeanType;
this.configuration = Container.instance(contextId).deploymentManager().getServices().get(WeldConfiguration.class);
addInterfacesFromTypeClosure(typeClosure, proxiedBeanType);
TypeInfo typeInfo = TypeInfo.of(typeClosure);
Class<?> superClass = typeInfo.getSuperClass();
superClass = superClass == null ? Object.class : superClass;
if (forceSuperClass || (superClass.equals(Object.class) && additionalInterfaces.isEmpty())) {
// No interface beans, must use the bean impl as superclass
superClass = proxiedBeanType;
}
this.beanType = superClass;
addDefaultAdditionalInterfaces();
baseProxyName = proxyName;
proxyServices = Container.instance(contextId).services().get(ProxyServices.class);
// hierarchy order
if (additionalInterfaces.size() > 1) {
LinkedHashSet<Class<?>> sorted = Proxies.sortInterfacesHierarchy(additionalInterfaces);
additionalInterfaces.clear();
additionalInterfaces.addAll(sorted);
}
this.proxyInstantiator = Container.instance(contextId).services().get(ProxyInstantiator.class);
}
static String getProxyName(String contextId, Class<?> proxiedBeanType, Set<? extends Type> typeClosure, Bean<?> bean) {
TypeInfo typeInfo = TypeInfo.of(typeClosure);
final String className;
ProxyNameHolder holder;
if (typeInfo.getSuperClass() == Object.class) {
final StringBuilder name = new StringBuilder();
//interface only bean.
holder = createCompoundProxyName(contextId, bean, typeInfo, name);
} else {
boolean typeModified = false;
for (Class<?> iface : typeInfo.getInterfaces()) {
if (!iface.isAssignableFrom(typeInfo.getSuperClass())) {
typeModified = true;
break;
}
}
if (typeModified) {
// This bean has interfaces that the base type is not assignable to.
// One example of this is an EJB bean using @Local and declaring an interface it doesn't implement.
// Another case is a CDI bean with type added via ProcessBeanAttributes which isn't directly implemented.
StringBuilder name = new StringBuilder(typeInfo.getSuperClass().getSimpleName() + "$");
holder = createCompoundProxyName(contextId, bean, typeInfo, name, bean.getBeanClass().getPackage().getName());
} else {
holder = new ProxyNameHolder(null, typeInfo.getSuperClass().getSimpleName(), bean);
}
}
className = holder.getClassName() + PROXY_SUFFIX;
String proxyPackage = holder.getPackageName();
if (proxiedBeanType.equals(Object.class)) {
Class<?> superInterface = typeInfo.getSuperInterface();
if (superInterface == null) {
throw new IllegalArgumentException("Proxied bean type cannot be java.lang.Object without an interface");
} else {
String reason = getDefaultPackageReason(superInterface);
if (reason != null) {
proxyPackage = DEFAULT_PROXY_PACKAGE;
BeanLogger.LOG.generatingProxyToDefaultPackage(superInterface, DEFAULT_PROXY_PACKAGE, reason);
}
}
} else {
String reason = getDefaultPackageReason(proxiedBeanType);
if (reason != null && reason.equals(NO_PACKAGE)) {
proxyPackage = DEFAULT_PROXY_PACKAGE;
BeanLogger.LOG.generatingProxyToDefaultPackage(proxiedBeanType, DEFAULT_PROXY_PACKAGE, reason);
} else {
if (proxyPackage == null) {
proxyPackage = proxiedBeanType.getPackage().getName();
}
}
}
return proxyPackage + '.' + getEnclosingPrefix(proxiedBeanType) + className;
}
private static ProxyNameHolder createCompoundProxyName(String contextId, Bean<?> bean, TypeInfo typeInfo,
StringBuilder name) {
return createCompoundProxyName(contextId, bean, typeInfo, name, null);
}
private static ProxyNameHolder createCompoundProxyName(String contextId, Bean<?> bean, TypeInfo typeInfo,
StringBuilder name, String knownProxyPackage) {
String className;
String proxyPackage = knownProxyPackage;
// we need a sorted collection without repetition, hence LinkedHashSet
final Set<String> interfaces = new LinkedHashSet<>();
// for producers, try to determine the most specific class and make sure the proxy starts with the same package and class
if (bean != null && bean instanceof AbstractProducerBean) {
Class<?> mostSpecificClass = ((AbstractProducerBean) bean).getType();
// for producers, always override the proxy package
proxyPackage = mostSpecificClass.getPackage().getName();
if (mostSpecificClass.getDeclaringClass() != null) {
interfaces.add(mostSpecificClass.getDeclaringClass().getSimpleName());
}
interfaces.add(mostSpecificClass.getSimpleName());
}
// if the bean class is a non-public one (i.e. pack private), we prioritize placing proxy in the same package
// we skip built-in beans are those are often for jakarta.* classes and end up in Weld's default package anyway
if (proxyPackage == null && bean != null
&& !Modifier.isPublic(bean.getBeanClass().getModifiers())
&& !(bean instanceof AbstractBuiltInBean)) {
proxyPackage = bean.getBeanClass().getPackage().getName();
}
final Set<String> declaringClasses = new HashSet<>();
for (Class<?> type : typeInfo.getInterfaces()) {
Class<?> declaringClass = type.getDeclaringClass();
if (declaringClass != null && declaringClasses.add(declaringClass.getSimpleName())) {
interfaces.add(declaringClass.getSimpleName());
}
interfaces.add(type.getSimpleName());
if (proxyPackage == null) {
proxyPackage = typeInfo.getPackageNameForClass(type);
}
}
// no need to sort the set, because we copied already sorted set
Iterator<String> iterator = interfaces.iterator();
while (iterator.hasNext()) {
name.append(iterator.next());
if (iterator.hasNext()) {
name.append("$");
}
}
//there is a remote chance that this could generate the same
//proxy name for two interfaces with the same simple name.
//append the hash code of the bean id to be sure
// However, it is safe to share a proxy class for built-in beans of the same type (e.g. Event)
if (bean != null && !(bean instanceof AbstractBuiltInBean)) {
final BeanIdentifier id = Container.instance(contextId).services().get(ContextualStore.class).putIfAbsent(bean);
int idHash = id.hashCode();
// add a separator so that WeldDefaultProxyServices can determine the correct full class name by first occurrence of "$"
name.append("$");
name.append(Math.abs(idHash == Integer.MIN_VALUE ? 0 : idHash));
}
className = name.toString();
return new ProxyNameHolder(proxyPackage, className, bean);
}
private static String getEnclosingPrefix(Class<?> clazz) {
Class<?> encl = clazz.getEnclosingClass();
return encl == null ? "" : getEnclosingPrefix(encl) + encl.getSimpleName() + '$';
}
/**
* Convenience method to set the underlying bean instance for a proxy.
*
* @param proxy the proxy instance
* @param beanInstance the instance of the bean
*/
public static <T> void setBeanInstance(String contextId, T proxy, BeanInstance beanInstance, Bean<?> bean) {
if (proxy instanceof ProxyObject) {
ProxyObject proxyView = (ProxyObject) proxy;
proxyView.weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean));
}
}
private static String getDefaultPackageReason(Class<?> clazz) {
if (clazz.getPackage() == null || clazz.getPackage().getName().isEmpty()) {
return NO_PACKAGE;
}
if (clazz.getSigners() != null) {
return SIGNED;
}
return null;
}
public void addInterfacesFromTypeClosure(Set<? extends Type> typeClosure, Class<?> proxiedBeanType) {
for (Type type : typeClosure) {
Class<?> c = Reflections.getRawType(type);
// Ignore no-interface views, they are dealt with proxiedBeanType
// (pending redesign)
if (c.isInterface()) {
addInterface(c);
}
}
}
/**
* Adds an additional interface that the proxy should implement. The default
* implementation will be to forward invocations to the bean instance.
*
* @param newInterface an interface
*/
public void addInterface(Class<?> newInterface) {
if (!newInterface.isInterface()) {
throw new IllegalArgumentException(newInterface + " is not an interface");
}
additionalInterfaces.add(newInterface);
}
/**
* Method to create a new proxy that wraps the bean instance.
*
* @param beanInstance the bean instance
* @return a new proxy object
*/
public T create(BeanInstance beanInstance) {
final T proxy = (System.getSecurityManager() == null) ? run() : AccessController.doPrivileged(this);
((ProxyObject) proxy).weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean));
return proxy;
}
@Override
public T run() {
try {
Class<T> proxyClass = getProxyClass();
boolean hasConstrutedField = SecurityActions.hasDeclaredField(proxyClass, CONSTRUCTED_FLAG_NAME);
if (hasConstrutedField != useConstructedFlag()) {
// The proxy class was created with a different type of ProxyInstantiator
ProxyInstantiator newInstantiator = ProxyInstantiator.Factory.create(!hasConstrutedField);
BeanLogger.LOG.creatingProxyInstanceUsingDifferentInstantiator(proxyClass, newInstantiator, proxyInstantiator);
return newInstantiator.newInstance(proxyClass);
}
return proxyInstantiator.newInstance(proxyClass);
} catch (InstantiationException e) {
throw new DefinitionException(BeanLogger.LOG.proxyInstantiationFailed(this), e.getCause());
} catch (IllegalAccessException e) {
throw new DefinitionException(BeanLogger.LOG.proxyInstantiationBeanAccessFailed(this), e.getCause());
}
}
/**
* Produces or returns the existing proxy class. The operation is thread-safe.
*
* @return always the class of the proxy
*/
public Class<T> getProxyClass() {
String suffix = "_$$_Weld" + getProxyNameSuffix();
String proxyClassName = getBaseProxyName();
if (!proxyClassName.endsWith(suffix)) {
proxyClassName = proxyClassName + suffix;
}
if (proxyClassName.startsWith(JAVA)) {
proxyClassName = proxyClassName.replaceFirst(JAVA, WELD_PROXY_PREFIX);
} else if (proxyClassName.startsWith(JAKARTA)) {
proxyClassName = proxyClassName.replaceFirst(JAKARTA, WELD_PROXY_PREFIX);
}
Class<T> proxyClass = null;
Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType;
BeanLogger.LOG.generatingProxyClass(proxyClassName);
try {
// First check to see if we already have this proxy class
proxyClass = cast(proxyServices.loadClass(originalClass, proxyClassName));
} catch (ClassNotFoundException e) {
// Create the proxy class for this instance
try {
proxyClass = createProxyClass(originalClass, proxyClassName);
} catch (Throwable e1) {
//attempt to load the class again, just in case another thread
//defined it between the check and the create method
try {
proxyClass = cast(proxyServices.loadClass(originalClass, proxyClassName));
} catch (ClassNotFoundException e2) {
BeanLogger.LOG.catchingDebug(e1);
throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1);
}
}
}
return proxyClass;
}
/**
* Returns the package and base name for the proxy class.
*
* @return base name without suffixes
*/
protected String getBaseProxyName() {
return baseProxyName;
}
/**
* Returns a suffix to append to the name of the proxy class. The name
* already consists of <class-name>_$$_Weld, to which the suffix is added.
* This allows the creation of different types of proxies for the same class.
*
* @return a name suffix
*/
protected String getProxyNameSuffix() {
return PROXY_SUFFIX;
}
private void addDefaultAdditionalInterfaces() {
additionalInterfaces.add(Serializable.class);
// add a marker interface denoting that the resulting class uses weld internal contructs
additionalInterfaces.add(WeldConstruct.class);
}
/**
* Sub classes may override to specify additional interfaces the proxy should
* implement
*/
protected void addAdditionalInterfaces(Set<Class<?>> interfaces) {
}
private Class<T> createProxyClass(Class<?> originalClass, String proxyClassName) throws Exception {
Set<Class<?>> specialInterfaces = Sets.newHashSet(LifecycleMixin.class, TargetInstanceProxy.class, ProxyObject.class);
addAdditionalInterfaces(specialInterfaces);
// Remove special interfaces from main set (deserialization scenario)
additionalInterfaces.removeAll(specialInterfaces);
ClassFile proxyClassType = null;
final int accessFlags = AccessFlag.of(AccessFlag.PUBLIC, AccessFlag.SUPER, AccessFlag.SYNTHETIC);
if (getBeanType().isInterface()) {
proxyClassType = newClassFile(proxyClassName, accessFlags, Object.class.getName());
proxyClassType.addInterface(getBeanType().getName());
} else {
proxyClassType = newClassFile(proxyClassName, accessFlags, getBeanType().getName());
}
// Add interfaces which require method generation
for (Class<?> clazz : additionalInterfaces) {
proxyClassType.addInterface(clazz.getName());
}
List<DeferredBytecode> initialValueBytecode = new ArrayList<DeferredBytecode>();
// Workaround for IBM JVM - the ACC_STATIC flag should only be required for class file with version number 51.0 or above
ClassMethod staticConstructor = proxyClassType.addMethod(AccessFlag.of(AccessFlag.PUBLIC, AccessFlag.STATIC),
"<clinit>", "V");
addFields(proxyClassType, initialValueBytecode);
addConstructors(proxyClassType, initialValueBytecode);
addMethods(proxyClassType, staticConstructor);
staticConstructor.getCodeAttribute().returnInstruction();
// Additional interfaces whose methods require special handling
for (Class<?> specialInterface : specialInterfaces) {
proxyClassType.addInterface(specialInterface.getName());
}
// Dump proxy type bytecode if necessary
dumpToFile(proxyClassName, proxyClassType.toBytecode());
ProtectionDomain domain = AccessController.doPrivileged(new GetProtectionDomainAction(proxiedBeanType));
if (proxiedBeanType.getPackage() == null || proxiedBeanType.getPackage().getName().isEmpty()
|| proxiedBeanType.equals(Object.class)) {
domain = ProxyFactory.class.getProtectionDomain();
} else if (System.getSecurityManager() != null) {
ProtectionDomainCache cache = Container.instance(contextId).services().get(ProtectionDomainCache.class);
domain = cache.getProtectionDomainForProxy(domain);
}
Class<T> proxyClass = cast(toClass(proxyClassType, originalClass, proxyServices, domain));
BeanLogger.LOG.createdProxyClass(proxyClass, Arrays.toString(proxyClass.getInterfaces()));
return proxyClass;
}
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) {
try {
// We need to use a (non-deprecated) method that avoids instantiating DefaultClassFactory.INSTANCE
// If that happens, we will have module accessibility issues and the need to use --add-opens clausules
// NOTE: the CL and ClassFactory are never really used to define the class, see WeldDefaultProxyServices
return new ClassFile(name, accessFlags, superclass, ProxyFactory.class.getClassLoader(),
DummyClassFactoryImpl.INSTANCE, interfaces);
} catch (Exception e) {
throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause());
}
}
private void dumpToFile(String fileName, byte[] data) {
File proxyDumpFilePath = configuration.getProxyDumpFilePath();
if (proxyDumpFilePath == null) {
return;
}
File dumpFile = new File(proxyDumpFilePath, fileName + ".class");
try {
Files.write(dumpFile.toPath(), data, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
BeanLogger.LOG.beanCannotBeDumped(fileName, e);
}
}
/**
* Adds a constructor for the proxy for each constructor declared by the base
* bean type.
*
* @param proxyClassType the Javassist class for the proxy
* @param initialValueBytecode
*/
protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {
try {
if (getBeanType().isInterface()) {
ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());
} else {
boolean constructorFound = false;
for (Constructor<?> constructor : AccessController
.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {
if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {
constructorFound = true;
String[] exceptions = new String[constructor.getExceptionTypes().length];
for (int i = 0; i < exceptions.length; ++i) {
exceptions[i] = constructor.getExceptionTypes()[i].getName();
}
ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR,
DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions,
proxyClassType, initialValueBytecode, !useConstructedFlag());
}
}
if (!constructorFound) {
// the bean only has private constructors, we need to generate
// two fake constructors that call each other
addConstructorsForBeanWithPrivateConstructors(proxyClassType);
}
}
} catch (Exception e) {
throw new WeldException(e);
}
}
protected void addFields(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {
// The field representing the underlying instance or special method
// handling
proxyClassType.addField(AccessFlag.PRIVATE, METHOD_HANDLER_FIELD_NAME, getMethodHandlerType());
if (useConstructedFlag()) {
// field used to indicate that super() has been called
proxyClassType.addField(AccessFlag.PRIVATE, CONSTRUCTED_FLAG_NAME, BytecodeUtils.BOOLEAN_CLASS_DESCRIPTOR);
}
}
protected Class<? extends MethodHandler> getMethodHandlerType() {
return MethodHandler.class;
}
protected void addMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {
// Add all class methods for interception
addMethodsFromClass(proxyClassType, staticConstructor);
// Add special proxy methods
addSpecialMethods(proxyClassType, staticConstructor);
// Add serialization support methods
addSerializationSupport(proxyClassType);
}
/**
* Adds special serialization code. By default this is a nop
*
* @param proxyClassType the Javassist class for the proxy class
*/
protected void addSerializationSupport(ClassFile proxyClassType) {
//noop
}
protected void addMethodsFromClass(ClassFile proxyClassType, ClassMethod staticConstructor) {
try {
// Add all methods from the class hierarchy
Class<?> cls = getBeanType();
// First add equals/hashCode methods if required
generateEqualsMethod(proxyClassType);
generateHashCodeMethod(proxyClassType);
// In rare cases, the bean class may be abstract - in this case we have to add methods from all interfaces implemented by any abstract class
// from the hierarchy
boolean isBeanClassAbstract = Modifier.isAbstract(cls.getModifiers());
// a final method might have a non-final declaration in abstract superclass
// hence we need to remember which we saw and skip those in superclasses
Set<MethodSignature> foundFinalMethods = new HashSet<>();
while (cls != null) {
addMethods(cls, proxyClassType, staticConstructor, foundFinalMethods);
if (isBeanClassAbstract && Modifier.isAbstract(cls.getModifiers())) {
for (Class<?> implementedInterface : Reflections.getInterfaceClosure(cls)) {
if (!additionalInterfaces.contains(implementedInterface)) {
addMethods(implementedInterface, proxyClassType, staticConstructor, foundFinalMethods);
}
}
}
cls = cls.getSuperclass();
}
for (Class<?> c : additionalInterfaces) {
for (Method method : c.getMethods()) {
if (isMethodAccepted(method, getProxySuperclass())) {
try {
MethodInformation methodInfo = new RuntimeMethodInformation(method);
ClassMethod classMethod = proxyClassType.addMethod(method);
if (Reflections.isDefault(method)) {
addConstructedGuardToMethodBody(classMethod);
createForwardingMethodBody(classMethod, methodInfo, staticConstructor);
} else {
createSpecialMethodBody(classMethod, methodInfo, staticConstructor);
}
BeanLogger.LOG.addingMethodToProxy(method);
} catch (DuplicateMemberException e) {
}
}
}
}
} catch (Exception e) {
throw new WeldException(e);
}
}
private void addMethods(Class<?> cls, ClassFile proxyClassType, ClassMethod staticConstructor,
Set<MethodSignature> foundFinalmethods) {
for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(cls))) {
MethodSignature methodSignature = new MethodSignatureImpl(method);
if (Modifier.isFinal(method.getModifiers())) {
foundFinalmethods.add(methodSignature);
}
if (isMethodAccepted(method, getProxySuperclass()) && !foundFinalmethods.contains(methodSignature)) {
try {
MethodInformation methodInfo = new RuntimeMethodInformation(method);
ClassMethod classMethod = proxyClassType.addMethod(method);
addConstructedGuardToMethodBody(classMethod);
createForwardingMethodBody(classMethod, methodInfo, staticConstructor);
BeanLogger.LOG.addingMethodToProxy(method);
} catch (DuplicateMemberException e) {
// do nothing. This will happen if superclass methods
// have been overridden
}
}
}
}
protected boolean isMethodAccepted(Method method, Class<?> proxySuperclass) {
for (ProxiedMethodFilter filter : METHOD_FILTERS) {
if (!filter.accept(method, proxySuperclass)) {
return false;
}
}
return true;
}
/**
* Generate the body of the proxies hashCode method.
* <p/>
* If this method returns null, the method will not be added, and the
* hashCode on the superclass will be used as per normal virtual method
* resolution rules
*/
protected void generateHashCodeMethod(ClassFile proxyClassType) {
}
/**
* Generate the body of the proxies equals method.
* <p/>
* If this method returns null, the method will not be added, and the
* hashCode on the superclass will be used as per normal virtual method
* resolution rules
*
* @param proxyClassType The class file
*/
protected void generateEqualsMethod(ClassFile proxyClassType) {
}
protected void createSpecialMethodBody(ClassMethod proxyClassType, MethodInformation method,
ClassMethod staticConstructor) {
createInterceptorBody(proxyClassType, method, staticConstructor);
}
protected void addConstructedGuardToMethodBody(final ClassMethod classMethod) {
addConstructedGuardToMethodBody(classMethod, classMethod.getClassFile().getSuperclass());
}
/**
* Adds the following code to a delegating method:
* <p/>
* <code>
* if(!this.constructed) return super.thisMethod()
* </code>
* <p/>
* This means that the proxy will not start to delegate to the underlying
* bean instance until after the constructor has finished.
*/
protected void addConstructedGuardToMethodBody(final ClassMethod classMethod, String className) {
if (!useConstructedFlag()) {
return;
}
// now create the conditional
final CodeAttribute cond = classMethod.getCodeAttribute();
cond.aload(0);
cond.getfield(classMethod.getClassFile().getName(), CONSTRUCTED_FLAG_NAME, BytecodeUtils.BOOLEAN_CLASS_DESCRIPTOR);
// jump if the proxy constructor has finished
BranchEnd jumpMarker = cond.ifne();
// generate the invokespecial call to the super class method
// this is run when the proxy is being constructed
cond.aload(0);
cond.loadMethodParameters();
cond.invokespecial(className, classMethod.getName(), classMethod.getDescriptor());
cond.returnInstruction();
cond.branchEnd(jumpMarker);
}
protected void createForwardingMethodBody(ClassMethod classMethod, MethodInformation method,
ClassMethod staticConstructor) {
createInterceptorBody(classMethod, method, staticConstructor);
}
/**
* Creates the given method on the proxy class where the implementation
* forwards the call directly to the method handler.
* <p/>
* the generated bytecode is equivalent to:
* <p/>
* return (RetType) methodHandler.invoke(this,param1,param2);
*
* @param classMethod the class method
* @param method any JLR method
* @return the method byte code
*/
protected void createInterceptorBody(ClassMethod classMethod, MethodInformation method, ClassMethod staticConstructor) {
invokeMethodHandler(classMethod, method, true, DEFAULT_METHOD_RESOLVER, staticConstructor);
}
/**
* calls methodHandler.invoke for a given method
*
* @param method The method information
* @param addReturnInstruction set to true you want to return the result of
* the method invocation
* @param bytecodeMethodResolver The resolver that returns the method to invoke
*/
protected void invokeMethodHandler(ClassMethod classMethod, MethodInformation method, boolean addReturnInstruction,
BytecodeMethodResolver bytecodeMethodResolver, ClassMethod staticConstructor) {
// now we need to build the bytecode. The order we do this in is as
// follows:
// load methodHandler
// load this
// load the method object
// load null
// create a new array the same size as the number of parameters
// push our parameter values into the array
// invokeinterface the invoke method
// add checkcast to cast the result to the return type, or unbox if
// primitive
// add an appropriate return instruction
final CodeAttribute b = classMethod.getCodeAttribute();
b.aload(0);
getMethodHandlerField(classMethod.getClassFile(), b);
b.aload(0);
bytecodeMethodResolver.getDeclaredMethod(classMethod, method.getDeclaringClass(), method.getName(),
method.getParameterTypes(), staticConstructor);
b.aconstNull();
b.iconst(method.getParameterTypes().length);
b.anewarray("java.lang.Object");
int localVariableCount = 1;
for (int i = 0; i < method.getParameterTypes().length; ++i) {
String typeString = method.getParameterTypes()[i];
b.dup(); // duplicate the array reference
b.iconst(i);
// load the parameter value
BytecodeUtils.addLoadInstruction(b, typeString, localVariableCount);
// box the parameter if necessary
Boxing.boxIfNessesary(b, typeString);
// and store it in the array
b.aastore();
if (isWide(typeString)) {
localVariableCount = localVariableCount + 2;
} else {
localVariableCount++;
}
}
// now we have all our arguments on the stack
// lets invoke the method
b.invokeinterface(MethodHandler.class.getName(), INVOKE_METHOD_NAME, LJAVA_LANG_OBJECT,
new String[] { LJAVA_LANG_OBJECT,
LJAVA_LANG_REFLECT_METHOD, LJAVA_LANG_REFLECT_METHOD, "[" + LJAVA_LANG_OBJECT });
if (addReturnInstruction) {
// now we need to return the appropriate type
if (method.getReturnType().equals(BytecodeUtils.VOID_CLASS_DESCRIPTOR)) {
b.returnInstruction();
} else if (isPrimitive(method.getReturnType())) {
Boxing.unbox(b, method.getReturnType());
b.returnInstruction();
} else {
b.checkcast(BytecodeUtils.getName(method.getReturnType()));
b.returnInstruction();
}
}
}
/**
* Adds methods requiring special implementations rather than just
* delegation.
*
* @param proxyClassType the Javassist class description for the proxy type
*/
protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) {
try {
// Add special methods for interceptors
for (Method method : LifecycleMixin.class.getMethods()) {
BeanLogger.LOG.addingMethodToProxy(method);
MethodInformation methodInfo = new RuntimeMethodInformation(method);
final ClassMethod classMethod = proxyClassType.addMethod(method);
createInterceptorBody(classMethod, methodInfo, staticConstructor);
}
Method getInstanceMethod = TargetInstanceProxy.class.getMethod("weld_getTargetInstance");
Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod("weld_getTargetClass");
MethodInformation getInstanceMethodInfo = new RuntimeMethodInformation(getInstanceMethod);
createInterceptorBody(proxyClassType.addMethod(getInstanceMethod), getInstanceMethodInfo, staticConstructor);
MethodInformation getInstanceClassMethodInfo = new RuntimeMethodInformation(getInstanceClassMethod);
createInterceptorBody(proxyClassType.addMethod(getInstanceClassMethod), getInstanceClassMethodInfo,
staticConstructor);
Method setMethodHandlerMethod = ProxyObject.class.getMethod("weld_setHandler", MethodHandler.class);
generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod));
Method getMethodHandlerMethod = ProxyObject.class.getMethod("weld_getHandler");
generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod));
} catch (Exception e) {
throw new WeldException(e);
}
}
protected void generateSetMethodHandlerBody(ClassMethod method) {
final CodeAttribute b = method.getCodeAttribute();
b.aload(0);
b.aload(1);
b.checkcast(getMethodHandlerType());
b.putfield(method.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME,
DescriptorUtils.makeDescriptor(getMethodHandlerType()));
b.returnInstruction();
}
protected void generateGetMethodHandlerBody(ClassMethod method) {
final CodeAttribute b = method.getCodeAttribute();
b.aload(0);
getMethodHandlerField(method.getClassFile(), b);
b.returnInstruction();
}
/**
* Adds two constructors to the class that call each other in order to bypass
* the JVM class file verifier.
* <p/>
* This would result in a stack overflow if they were actually called,
* however the proxy is directly created without calling the constructor
*/
private void addConstructorsForBeanWithPrivateConstructors(ClassFile proxyClassType) {
ClassMethod ctor = proxyClassType.addMethod(AccessFlag.PUBLIC, INIT_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR,
LJAVA_LANG_BYTE);
CodeAttribute b = ctor.getCodeAttribute();
b.aload(0);
b.aconstNull();
b.aconstNull();
b.invokespecial(proxyClassType.getName(), INIT_METHOD_NAME,
"(" + LJAVA_LANG_BYTE + LJAVA_LANG_BYTE + ")" + BytecodeUtils.VOID_CLASS_DESCRIPTOR);
b.returnInstruction();
ctor = proxyClassType.addMethod(AccessFlag.PUBLIC, INIT_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR,
LJAVA_LANG_BYTE, LJAVA_LANG_BYTE);
b = ctor.getCodeAttribute();
b.aload(0);
b.aconstNull();
b.invokespecial(proxyClassType.getName(), INIT_METHOD_NAME,
"(" + LJAVA_LANG_BYTE + ")" + BytecodeUtils.VOID_CLASS_DESCRIPTOR);
b.returnInstruction();
}
public Class<?> getBeanType() {
return beanType;
}
public Set<Class<?>> getAdditionalInterfaces() {
return additionalInterfaces;
}
public Bean<?> getBean() {
return bean;
}
public String getContextId() {
return contextId;
}
protected Class<?> getProxiedBeanType() {
return proxiedBeanType;
}
protected void getMethodHandlerField(ClassFile file, CodeAttribute b) {
b.getfield(file.getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(getMethodHandlerType()));
}
protected Class<?> getProxySuperclass() {
return getBeanType().isInterface() ? Object.class : getBeanType();
}
/**
* @return {@code true} if {@link ProxyInstantiator} is used to instantiate proxy instances
*/
protected boolean isUsingProxyInstantiator() {
return true;
}
/**
* @return {@code true} if {@link #CONSTRUCTED_FLAG_NAME} should be used
*/
private boolean useConstructedFlag() {
return !isUsingProxyInstantiator() || proxyInstantiator.isUsingConstructor();
}
/**
* Delegates proxy creation via {@link ProxyServices} to the integrator or to our own implementation.
*/
protected Class<?> toClass(ClassFile ct, Class<?> originalClass, ProxyServices proxyServices, ProtectionDomain domain) {
try {
byte[] bytecode = ct.toBytecode();
Class<?> result;
if (domain == null) {
result = proxyServices.defineClass(originalClass, ct.getName(), bytecode, 0, bytecode.length);
} else {
result = proxyServices.defineClass(originalClass, ct.getName(), bytecode, 0, bytecode.length, domain);
}
return result;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* When creating a proxy class name we can sometimes determine it's package as well.
*/
private static class ProxyNameHolder {
private String packageName;
private String className;