forked from raphw/byte-buddy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassInjector.java
2915 lines (2652 loc) · 137 KB
/
ClassInjector.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
/*
* Copyright 2014 - Present Rafael Winterhalter
*
* 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 net.bytebuddy.dynamic.loading;
import com.sun.jna.*;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.asm.MemberRemoval;
import net.bytebuddy.build.AccessControllerPlugin;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.PackageDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.utility.GraalImageCode;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.utility.JavaType;
import net.bytebuddy.utility.RandomString;
import net.bytebuddy.utility.dispatcher.JavaDispatcher;
import net.bytebuddy.utility.nullability.AlwaysNull;
import net.bytebuddy.utility.nullability.MaybeNull;
import net.bytebuddy.utility.nullability.UnknownNull;
import net.bytebuddy.utility.privilege.GetMethodAction;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.*;
import java.net.URL;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import static net.bytebuddy.matcher.ElementMatchers.any;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* <p>
* A class injector is capable of injecting classes into a {@link java.lang.ClassLoader} without
* requiring the class loader to being able to explicitly look up these classes.
* </p>
* <p>
* <b>Important</b>: Byte Buddy does not supply privileges when injecting code. When using a {@code java.lang.SecurityManager},
* the user of this injector is responsible for providing access to non-public properties.
* </p>
*/
public interface ClassInjector {
/**
* A permission for the {@code suppressAccessChecks} permission.
*/
Permission SUPPRESS_ACCESS_CHECKS = new ReflectPermission("suppressAccessChecks");
/**
* Determines the default behavior for type injections when a type is already loaded.
*/
boolean ALLOW_EXISTING_TYPES = false;
/**
* Indicates if this class injector is available on the current VM.
*
* @return {@code true} if this injector is available on the current VM.
*/
boolean isAlive();
/**
* Injects the given types into the represented class loader.
*
* @param types The types to load via injection.
* @return The loaded types that were passed as arguments.
*/
Map<TypeDescription, Class<?>> inject(Map<? extends TypeDescription, byte[]> types);
/**
* Injects the given types into the represented class loader using a mapping from name to binary representation.
*
* @param types The types to load via injection.
* @return The loaded types that were passed as arguments.
*/
Map<String, Class<?>> injectRaw(Map<? extends String, byte[]> types);
/**
* An abstract base implementation of a class injector.
*/
abstract class AbstractBase implements ClassInjector {
/**
* {@inheritDoc}
*/
public Map<TypeDescription, Class<?>> inject(Map<? extends TypeDescription, byte[]> types) {
Map<String, byte[]> binaryRepresentations = new LinkedHashMap<String, byte[]>();
for (Map.Entry<? extends TypeDescription, byte[]> entry : types.entrySet()) {
binaryRepresentations.put(entry.getKey().getName(), entry.getValue());
}
Map<String, Class<?>> loadedTypes = injectRaw(binaryRepresentations);
Map<TypeDescription, Class<?>> result = new LinkedHashMap<TypeDescription, Class<?>>();
for (TypeDescription typeDescription : types.keySet()) {
result.put(typeDescription, loadedTypes.get(typeDescription.getName()));
}
return result;
}
}
/**
* A class injector that uses reflective method calls.
*/
@HashCodeAndEqualsPlugin.Enhance
class UsingReflection extends AbstractBase {
/**
* The dispatcher to use for accessing a class loader via reflection.
*/
private static final Dispatcher.Initializable DISPATCHER = doPrivileged(Dispatcher.CreationAction.INSTANCE);
/**
* A proxy for {@code java.lang.System} to access the security manager if available.
*/
private static final System SYSTEM = doPrivileged(JavaDispatcher.of(System.class));
/**
* The {@code java.lang.SecurityManager#checkPermission} method or {@code null} if not available.
*/
private static final Method CHECK_PERMISSION = doPrivileged(new GetMethodAction("java.lang.SecurityManager",
"checkPermission",
Permission.class));
/**
* The class loader into which the classes are to be injected.
*/
private final ClassLoader classLoader;
/**
* The protection domain that is used when loading classes.
*/
@MaybeNull
@HashCodeAndEqualsPlugin.ValueHandling(HashCodeAndEqualsPlugin.ValueHandling.Sort.REVERSE_NULLABILITY)
private final ProtectionDomain protectionDomain;
/**
* The package definer to be queried for package definitions.
*/
private final PackageDefinitionStrategy packageDefinitionStrategy;
/**
* Determines if an exception should be thrown when attempting to load a type that already exists.
*/
private final boolean forbidExisting;
/**
* Creates a new injector for the given {@link java.lang.ClassLoader} and a default {@link java.security.ProtectionDomain} and a
* trivial {@link PackageDefinitionStrategy} which does not trigger an error when discovering existent classes.
*
* @param classLoader The {@link java.lang.ClassLoader} into which new class definitions are to be injected. Must not be the bootstrap loader.
*/
public UsingReflection(ClassLoader classLoader) {
this(classLoader, ClassLoadingStrategy.NO_PROTECTION_DOMAIN);
}
/**
* Creates a new injector for the given {@link java.lang.ClassLoader} and a default {@link PackageDefinitionStrategy} where the
* injection of existent classes does not trigger an error.
*
* @param classLoader The {@link java.lang.ClassLoader} into which new class definitions are to be injected. Must not be the bootstrap loader.
* @param protectionDomain The protection domain to apply during class definition.
*/
public UsingReflection(ClassLoader classLoader, @MaybeNull ProtectionDomain protectionDomain) {
this(classLoader,
protectionDomain,
PackageDefinitionStrategy.Trivial.INSTANCE,
ALLOW_EXISTING_TYPES);
}
/**
* Creates a new injector for the given {@link java.lang.ClassLoader} and {@link java.security.ProtectionDomain}.
*
* @param classLoader The {@link java.lang.ClassLoader} into which new class definitions are to be injected.Must not be the bootstrap loader.
* @param protectionDomain The protection domain to apply during class definition.
* @param packageDefinitionStrategy The package definer to be queried for package definitions.
* @param forbidExisting Determines if an exception should be thrown when attempting to load a type that already exists.
*/
public UsingReflection(ClassLoader classLoader,
@MaybeNull ProtectionDomain protectionDomain,
PackageDefinitionStrategy packageDefinitionStrategy,
boolean forbidExisting) {
if (classLoader == null) {
throw new IllegalArgumentException("Cannot inject classes into the bootstrap class loader");
}
this.classLoader = classLoader;
this.protectionDomain = protectionDomain;
this.packageDefinitionStrategy = packageDefinitionStrategy;
this.forbidExisting = forbidExisting;
}
/**
* A proxy for {@code java.security.AccessController#doPrivileged} that is activated if available.
*
* @param action The action to execute from a privileged context.
* @param <T> The type of the action's resolved value.
* @return The action's resolved value.
*/
@AccessControllerPlugin.Enhance
private static <T> T doPrivileged(PrivilegedAction<T> action) {
return action.run();
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return isAvailable();
}
/**
* {@inheritDoc}
*/
public Map<String, Class<?>> injectRaw(Map<? extends String, byte[]> types) {
Dispatcher dispatcher = DISPATCHER.initialize();
Map<String, Class<?>> result = new HashMap<String, Class<?>>();
for (Map.Entry<? extends String, byte[]> entry : types.entrySet()) {
synchronized (dispatcher.getClassLoadingLock(classLoader, entry.getKey())) {
Class<?> type = dispatcher.findClass(classLoader, entry.getKey());
if (type == null) {
int packageIndex = entry.getKey().lastIndexOf('.');
if (packageIndex != -1) {
String packageName = entry.getKey().substring(0, packageIndex);
PackageDefinitionStrategy.Definition definition = packageDefinitionStrategy.define(classLoader, packageName, entry.getKey());
if (definition.isDefined()) {
Package definedPackage = dispatcher.getDefinedPackage(classLoader, packageName);
if (definedPackage == null) {
try {
dispatcher.definePackage(classLoader,
packageName,
definition.getSpecificationTitle(),
definition.getSpecificationVersion(),
definition.getSpecificationVendor(),
definition.getImplementationTitle(),
definition.getImplementationVersion(),
definition.getImplementationVendor(),
definition.getSealBase());
} catch (IllegalStateException exception) {
// Custom classloaders may call getPackage (instead of getDefinedPackage) from
// within definePackage, which can cause the package to be defined in an
// ancestor classloader or find a previously defined one from an ancestor. In
// this case definePackage will also throw since it considers that package
// already loaded and will not allow to define it directly in this classloader.
// To make sure this is the case, call getPackage instead of getDefinedPackage
// here and verify that we actually have a compatible package defined in an
// ancestor classloader. This issue is known to happen on WLS14+JDK11.
definedPackage = dispatcher.getPackage(classLoader, packageName);
if (definedPackage == null) {
throw exception;
} else if (!definition.isCompatibleTo(definedPackage)) {
throw new SecurityException("Sealing violation for package " + packageName + " (getPackage fallback)");
}
}
} else if (!definition.isCompatibleTo(definedPackage)) {
throw new SecurityException("Sealing violation for package " + packageName);
}
}
}
type = dispatcher.defineClass(classLoader, entry.getKey(), entry.getValue(), protectionDomain);
} else if (forbidExisting) {
throw new IllegalStateException("Cannot inject already loaded type: " + type);
}
result.put(entry.getKey(), type);
}
}
return result;
}
/**
* Indicates if this class injection is available on the current VM.
*
* @return {@code true} if this class injection is available.
*/
public static boolean isAvailable() {
return DISPATCHER.isAvailable();
}
/**
* Creates a class injector for the system class loader.
*
* @return A class injector for the system class loader.
*/
public static ClassInjector ofSystemClassLoader() {
return new UsingReflection(ClassLoader.getSystemClassLoader());
}
/**
* A dispatcher for accessing a {@link ClassLoader} reflectively.
*/
protected interface Dispatcher {
/**
* Indicates a class that is currently not defined.
*/
@AlwaysNull
Class<?> UNDEFINED = null;
/**
* Returns the lock for loading the specified class.
*
* @param classLoader the class loader to inject the class into.
* @param name The name of the class.
* @return The lock for loading this class.
*/
Object getClassLoadingLock(ClassLoader classLoader, String name);
/**
* Looks up a class from the given class loader.
*
* @param classLoader The class loader for which a class should be located.
* @param name The binary name of the class that should be located.
* @return The class for the binary name or {@code null} if no such class is defined for the provided class loader.
*/
@MaybeNull
Class<?> findClass(ClassLoader classLoader, String name);
/**
* Defines a class for the given class loader.
*
* @param classLoader The class loader for which a new class should be defined.
* @param name The binary name of the class that should be defined.
* @param binaryRepresentation The binary representation of the class.
* @param protectionDomain The protection domain for the defined class.
* @return The defined, loaded class.
*/
Class<?> defineClass(ClassLoader classLoader, String name, byte[] binaryRepresentation, @MaybeNull ProtectionDomain protectionDomain);
/**
* Looks up a package from a class loader. If the operation is not supported, falls back to {@link #getPackage(ClassLoader, String)}
*
* @param classLoader The class loader to query.
* @param name The binary name of the package.
* @return The package for the given name as defined by the provided class loader or {@code null} if no such package exists.
*/
@MaybeNull
Package getDefinedPackage(ClassLoader classLoader, String name);
/**
* Looks up a package from a class loader or its ancestor.
*
* @param classLoader The class loader to query.
* @param name The binary name of the package.
* @return The package for the given name as defined by the provided class loader or its ancestor, or {@code null} if no such package exists.
*/
@MaybeNull
Package getPackage(ClassLoader classLoader, String name);
/**
* Defines a package for the given class loader.
*
* @param classLoader The class loader for which a package is to be defined.
* @param name The binary name of the package.
* @param specificationTitle The specification title of the package or {@code null} if no specification title exists.
* @param specificationVersion The specification version of the package or {@code null} if no specification version exists.
* @param specificationVendor The specification vendor of the package or {@code null} if no specification vendor exists.
* @param implementationTitle The implementation title of the package or {@code null} if no implementation title exists.
* @param implementationVersion The implementation version of the package or {@code null} if no implementation version exists.
* @param implementationVendor The implementation vendor of the package or {@code null} if no implementation vendor exists.
* @param sealBase The seal base URL or {@code null} if the package should not be sealed.
* @return The defined package.
*/
Package definePackage(ClassLoader classLoader,
String name,
@MaybeNull String specificationTitle,
@MaybeNull String specificationVersion,
@MaybeNull String specificationVendor,
@MaybeNull String implementationTitle,
@MaybeNull String implementationVersion,
@MaybeNull String implementationVendor,
@MaybeNull URL sealBase);
/**
* Initializes a dispatcher to make non-accessible APIs accessible.
*/
interface Initializable {
/**
* Indicates if this dispatcher is available.
*
* @return {@code true} if this dispatcher is available.
*/
boolean isAvailable();
/**
* Initializes this dispatcher.
*
* @return The initialized dispatcher.
*/
Dispatcher initialize();
/**
* Represents an unsuccessfully loaded method lookup.
*/
@HashCodeAndEqualsPlugin.Enhance
class Unavailable implements Dispatcher, Initializable {
/**
* The reason why this dispatcher is not available.
*/
private final String message;
/**
* Creates a new faulty reflection store.
*
* @param message The reason why this dispatcher is not available.
*/
protected Unavailable(String message) {
this.message = message;
}
/**
* {@inheritDoc}
*/
public boolean isAvailable() {
return false;
}
/**
* {@inheritDoc}
*/
public Dispatcher initialize() {
return this;
}
/**
* {@inheritDoc}
*/
public Object getClassLoadingLock(ClassLoader classLoader, String name) {
return classLoader;
}
/**
* {@inheritDoc}
*/
public Class<?> findClass(ClassLoader classLoader, String name) {
try {
return classLoader.loadClass(name);
} catch (ClassNotFoundException ignored) {
return UNDEFINED;
}
}
/**
* {@inheritDoc}
*/
public Class<?> defineClass(ClassLoader classLoader, String name, byte[] binaryRepresentation, @MaybeNull ProtectionDomain protectionDomain) {
throw new UnsupportedOperationException("Cannot define class using reflection: " + message);
}
/**
* {@inheritDoc}
*/
public Package getDefinedPackage(ClassLoader classLoader, String name) {
throw new UnsupportedOperationException("Cannot get defined package using reflection: " + message);
}
/**
* {@inheritDoc}
*/
public Package getPackage(ClassLoader classLoader, String name) {
throw new UnsupportedOperationException("Cannot get package using reflection: " + message);
}
/**
* {@inheritDoc}
*/
public Package definePackage(ClassLoader classLoader,
String name,
@MaybeNull String specificationTitle,
@MaybeNull String specificationVersion,
@MaybeNull String specificationVendor,
@MaybeNull String implementationTitle,
@MaybeNull String implementationVersion,
@MaybeNull String implementationVendor,
@MaybeNull URL sealBase) {
throw new UnsupportedOperationException("Cannot define package using injection: " + message);
}
}
}
/**
* A creation action for a dispatcher.
*/
enum CreationAction implements PrivilegedAction<Initializable> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback.")
public Initializable run() {
try {
if (JavaModule.isSupported()) {
return UsingUnsafe.isAvailable()
? UsingUnsafeInjection.make()
: UsingUnsafeOverride.make();
} else {
return Direct.make();
}
} catch (InvocationTargetException exception) {
return new Initializable.Unavailable(exception.getTargetException().getMessage());
} catch (Exception exception) {
return new Initializable.Unavailable(exception.getMessage());
}
}
}
/**
* A class injection dispatcher that is using reflection on the {@link ClassLoader} methods.
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class Direct implements Dispatcher, Initializable {
/**
* An instance of {@link ClassLoader#findLoadedClass(String)}.
*/
protected final Method findLoadedClass;
/**
* An instance of {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)}.
*/
protected final Method defineClass;
/**
* An instance of {@code java.lang.ClassLoader#getDefinedPackage(String)}. May be {@code null}.
*/
@UnknownNull
protected final Method getDefinedPackage;
/**
* An instance of {@link ClassLoader#getPackage(String)}.
*/
protected final Method getPackage;
/**
* An instance of {@link ClassLoader#definePackage(String, String, String, String, String, String, String, URL)}.
*/
protected final Method definePackage;
/**
* Creates a new direct injection dispatcher.
*
* @param findLoadedClass An instance of {@link ClassLoader#findLoadedClass(String)}.
* @param defineClass An instance of {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)}.
* @param getDefinedPackage An instance of {@code java.lang.ClassLoader#getDefinedPackage(String)}. May be {@code null}.
* @param getPackage An instance of {@link ClassLoader#getPackage(String)}.
* @param definePackage An instance of {@link ClassLoader#definePackage(String, String, String, String, String, String, String, URL)}.
*/
protected Direct(Method findLoadedClass,
Method defineClass,
@MaybeNull Method getDefinedPackage,
Method getPackage,
Method definePackage) {
this.findLoadedClass = findLoadedClass;
this.defineClass = defineClass;
this.getDefinedPackage = getDefinedPackage;
this.getPackage = getPackage;
this.definePackage = definePackage;
}
/**
* Creates a direct dispatcher.
*
* @return A direct dispatcher for class injection.
* @throws Exception If the creation is impossible.
*/
@SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "Assuring privilege is explicit user responsibility.")
protected static Initializable make() throws Exception {
Method getDefinedPackage;
if (JavaModule.isSupported()) { // Avoid accidental lookup of method with same name in Java 8 J9 VM.
try {
getDefinedPackage = ClassLoader.class.getMethod("getDefinedPackage", String.class);
} catch (NoSuchMethodException ignored) {
getDefinedPackage = null;
}
} else {
getDefinedPackage = null;
}
Method getPackage = ClassLoader.class.getDeclaredMethod("getPackage", String.class);
getPackage.setAccessible(true);
Method findLoadedClass = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
findLoadedClass.setAccessible(true);
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass",
String.class,
byte[].class,
int.class,
int.class,
ProtectionDomain.class);
defineClass.setAccessible(true);
Method definePackage = ClassLoader.class.getDeclaredMethod("definePackage",
String.class,
String.class,
String.class,
String.class,
String.class,
String.class,
String.class,
URL.class);
definePackage.setAccessible(true);
try {
Method getClassLoadingLock = ClassLoader.class.getDeclaredMethod("getClassLoadingLock", String.class);
getClassLoadingLock.setAccessible(true);
return new ForJava7CapableVm(findLoadedClass,
defineClass,
getDefinedPackage,
getPackage,
definePackage,
getClassLoadingLock);
} catch (NoSuchMethodException ignored) {
return new ForLegacyVm(findLoadedClass, defineClass, getDefinedPackage, getPackage, definePackage);
}
}
/**
* {@inheritDoc}
*/
public boolean isAvailable() {
return true;
}
/**
* {@inheritDoc}
*/
public Dispatcher initialize() {
Object securityManager = SYSTEM.getSecurityManager();
if (securityManager != null) {
try {
CHECK_PERMISSION.invoke(securityManager, SUPPRESS_ACCESS_CHECKS);
} catch (InvocationTargetException exception) {
return new Dispatcher.Unavailable(exception.getTargetException().getMessage());
} catch (Exception exception) {
return new Dispatcher.Unavailable(exception.getMessage());
}
}
return this;
}
/**
* {@inheritDoc}
*/
public Class<?> findClass(ClassLoader classLoader, String name) {
try {
return (Class<?>) findLoadedClass.invoke(classLoader, name);
} catch (IllegalAccessException exception) {
throw new IllegalStateException(exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException(exception.getTargetException());
}
}
/**
* {@inheritDoc}
*/
public Class<?> defineClass(ClassLoader classLoader, String name, byte[] binaryRepresentation, @MaybeNull ProtectionDomain protectionDomain) {
try {
return (Class<?>) defineClass.invoke(classLoader, name, binaryRepresentation, 0, binaryRepresentation.length, protectionDomain);
} catch (IllegalAccessException exception) {
throw new IllegalStateException(exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException(exception.getTargetException());
}
}
/**
* {@inheritDoc}
*/
@MaybeNull
public Package getDefinedPackage(ClassLoader classLoader, String name) {
if (getDefinedPackage == null) {
return getPackage(classLoader, name);
}
try {
return (Package) getDefinedPackage.invoke(classLoader, name);
} catch (IllegalAccessException exception) {
throw new IllegalStateException(exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException(exception.getTargetException());
}
}
/**
* {@inheritDoc}
*/
public Package getPackage(ClassLoader classLoader, String name) {
try {
return (Package) getPackage.invoke(classLoader, name);
} catch (IllegalAccessException exception) {
throw new IllegalStateException(exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException(exception.getTargetException());
}
}
/**
* {@inheritDoc}
*/
public Package definePackage(ClassLoader classLoader,
String name,
@MaybeNull String specificationTitle,
@MaybeNull String specificationVersion,
@MaybeNull String specificationVendor,
@MaybeNull String implementationTitle,
@MaybeNull String implementationVersion,
@MaybeNull String implementationVendor,
@MaybeNull URL sealBase) {
try {
return (Package) definePackage.invoke(classLoader,
name,
specificationTitle,
specificationVersion,
specificationVendor,
implementationTitle,
implementationVersion,
implementationVendor,
sealBase);
} catch (IllegalAccessException exception) {
throw new IllegalStateException(exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException(exception.getTargetException());
}
}
/**
* A resolved class dispatcher for a class injector on a VM running at least Java 7.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ForJava7CapableVm extends Direct {
/**
* An instance of {@code ClassLoader#getClassLoadingLock(String)}.
*/
private final Method getClassLoadingLock;
/**
* Creates a new resolved reflection store for a VM running at least Java 7.
*
* @param getClassLoadingLock An instance of {@code ClassLoader#getClassLoadingLock(String)}.
* @param findLoadedClass An instance of {@link ClassLoader#findLoadedClass(String)}.
* @param defineClass An instance of {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)}.
* @param getDefinedPackage An instance of {@code java.lang,ClassLoader#getDefinedPackage(String)}. May be {@code null}.
* @param getPackage An instance of {@link ClassLoader#getPackage(String)}.
* @param definePackage An instance of {@link ClassLoader#definePackage(String, String, String, String, String, String, String, URL)}.
*/
protected ForJava7CapableVm(Method findLoadedClass,
Method defineClass,
@MaybeNull Method getDefinedPackage,
Method getPackage,
Method definePackage,
Method getClassLoadingLock) {
super(findLoadedClass, defineClass, getDefinedPackage, getPackage, definePackage);
this.getClassLoadingLock = getClassLoadingLock;
}
/**
* {@inheritDoc}
*/
public Object getClassLoadingLock(ClassLoader classLoader, String name) {
try {
return getClassLoadingLock.invoke(classLoader, name);
} catch (IllegalAccessException exception) {
throw new IllegalStateException(exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException(exception.getTargetException());
}
}
}
/**
* A resolved class dispatcher for a class injector prior to Java 7.
*/
protected static class ForLegacyVm extends Direct {
/**
* Creates a new resolved reflection store for a VM prior to Java 8.
*
* @param findLoadedClass An instance of {@link ClassLoader#findLoadedClass(String)}.
* @param defineClass An instance of {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)}.
* @param getDefinedPackage An instance of {@code java.lang.ClassLoader#getDefinedPackage(String)}. May be {@code null}.
* @param getPackage An instance of {@link ClassLoader#getPackage(String)}.
* @param definePackage An instance of {@link ClassLoader#definePackage(String, String, String, String, String, String, String, URL)}.
*/
protected ForLegacyVm(Method findLoadedClass,
Method defineClass,
@MaybeNull Method getDefinedPackage,
Method getPackage,
Method definePackage) {
super(findLoadedClass, defineClass, getDefinedPackage, getPackage, definePackage);
}
/**
* {@inheritDoc}
*/
public Object getClassLoadingLock(ClassLoader classLoader, String name) {
return classLoader;
}
}
}
/**
* An indirect dispatcher that uses a redirection accessor class that was injected into the bootstrap class loader.
*/
@HashCodeAndEqualsPlugin.Enhance
class UsingUnsafeInjection implements Dispatcher, Initializable {
/**
* An instance of the accessor class that is required for using it's intentionally non-static methods.
*/
private final Object accessor;
/**
* The accessor method for using {@link ClassLoader#findLoadedClass(String)}.
*/
private final Method findLoadedClass;
/**
* The accessor method for using {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)}.
*/
private final Method defineClass;
/**
* The accessor method for using {@code java.lang.ClassLoader#getDefinedPackage(String)}. May be {@code null}.
*/
@UnknownNull
private final Method getDefinedPackage;
/**
* The accessor method for using {@link ClassLoader#getPackage(String)}.
*/
private final Method getPackage;
/**
* The accessor method for using {@link ClassLoader#definePackage(String, String, String, String, String, String, String, URL)}.
*/
private final Method definePackage;
/**
* The accessor method for using {@code ClassLoader#getClassLoadingLock(String)} or returning the supplied {@link ClassLoader}
* if this method does not exist on the current VM.
*/
private final Method getClassLoadingLock;
/**
* Creates a new class loading injection dispatcher using an unsafe injected dispatcher.
*
* @param accessor An instance of the accessor class that is required for using it's intentionally non-static methods.
* @param findLoadedClass An instance of {@link ClassLoader#findLoadedClass(String)}.
* @param defineClass An instance of {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)}.
* @param getDefinedPackage An instance of {@code java.lang.ClassLoader#getDefinedPackage(String)}. May be {@code null}.
* @param getPackage An instance of {@link ClassLoader#getPackage(String)}.
* @param definePackage An instance of {@link ClassLoader#definePackage(String, String, String, String, String, String, String, URL)}.
* @param getClassLoadingLock The accessor method for using {@code ClassLoader#getClassLoadingLock(String)} or returning the
* supplied {@link ClassLoader} if this method does not exist on the current VM.
*/
protected UsingUnsafeInjection(Object accessor,
Method findLoadedClass,
Method defineClass,
@MaybeNull Method getDefinedPackage,
Method getPackage,
Method definePackage,
Method getClassLoadingLock) {
this.accessor = accessor;
this.findLoadedClass = findLoadedClass;
this.defineClass = defineClass;
this.getDefinedPackage = getDefinedPackage;
this.getPackage = getPackage;
this.definePackage = definePackage;
this.getClassLoadingLock = getClassLoadingLock;
}
/**
* Creates an indirect dispatcher.
*
* @return An indirect dispatcher for class creation.
* @throws Exception If the dispatcher cannot be created.
*/
@SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "Assuring privilege is explicit user responsibility.")
protected static Initializable make() throws Exception {
if (Boolean.parseBoolean(java.lang.System.getProperty(UsingUnsafe.SAFE_PROPERTY, Boolean.toString(GraalImageCode.getCurrent().isDefined())))) {
return new Initializable.Unavailable("Use of Unsafe was disabled by system property");
}
Class<?> unsafe = Class.forName("sun.misc.Unsafe");
Field theUnsafe = unsafe.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Object unsafeInstance = theUnsafe.get(null);
Method getDefinedPackage;
if (JavaModule.isSupported()) { // Avoid accidental lookup of method with same name in Java 8 J9 VM.
try {
getDefinedPackage = ClassLoader.class.getDeclaredMethod("getDefinedPackage", String.class);
} catch (NoSuchMethodException ignored) {
getDefinedPackage = null;
}
} else {
getDefinedPackage = null;
}
DynamicType.Builder<?> builder = new ByteBuddy()
.with(TypeValidation.DISABLED)
.subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
.name(ClassLoader.class.getName() + "$ByteBuddyAccessor$V1")
.defineMethod("findLoadedClass", Class.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class)
.intercept(MethodCall.invoke(ClassLoader.class
.getDeclaredMethod("findLoadedClass", String.class))
.onArgument(0)
.withArgument(1))
.defineMethod("defineClass", Class.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class, byte[].class, int.class, int.class,
ProtectionDomain.class)
.intercept(MethodCall.invoke(ClassLoader.class
.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class, ProtectionDomain.class))
.onArgument(0)
.withArgument(1, 2, 3, 4, 5))
.defineMethod("getPackage", Package.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class)
.intercept(MethodCall.invoke(ClassLoader.class
.getDeclaredMethod("getPackage", String.class))
.onArgument(0)
.withArgument(1))
.defineMethod("definePackage", Package.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class, String.class, String.class, String.class,
String.class, String.class, String.class, URL.class)
.intercept(MethodCall.invoke(ClassLoader.class
.getDeclaredMethod("definePackage", String.class, String.class, String.class, String.class, String.class, String.class, String.class, URL.class))
.onArgument(0)
.withArgument(1, 2, 3, 4, 5, 6, 7, 8));
if (getDefinedPackage != null) {
builder = builder
.defineMethod("getDefinedPackage", Package.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class)
.intercept(MethodCall.invoke(getDefinedPackage)
.onArgument(0)
.withArgument(1));
}
try {
builder = builder.defineMethod("getClassLoadingLock", Object.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class)
.intercept(MethodCall.invoke(ClassLoader.class.getDeclaredMethod("getClassLoadingLock", String.class))
.onArgument(0)
.withArgument(1));
} catch (NoSuchMethodException ignored) {
builder = builder.defineMethod("getClassLoadingLock", Object.class, Visibility.PUBLIC)
.withParameters(ClassLoader.class, String.class)
.intercept(FixedValue.argument(0));
}
Class<?> type = builder.make()
.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, new ClassLoadingStrategy.ForUnsafeInjection())
.getLoaded();
return new UsingUnsafeInjection(
unsafe.getMethod("allocateInstance", Class.class).invoke(unsafeInstance, type),
type.getMethod("findLoadedClass", ClassLoader.class, String.class),
type.getMethod("defineClass", ClassLoader.class, String.class, byte[].class, int.class, int.class, ProtectionDomain.class),
getDefinedPackage != null ? type.getMethod("getDefinedPackage", ClassLoader.class, String.class) : null,
type.getMethod("getPackage", ClassLoader.class, String.class),
type.getMethod("definePackage", ClassLoader.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class, URL.class),
type.getMethod("getClassLoadingLock", ClassLoader.class, String.class));
}
/**
* {@inheritDoc}
*/
public boolean isAvailable() {
return true;
}
/**
* {@inheritDoc}
*/
public Dispatcher initialize() {
Object securityManager = SYSTEM.getSecurityManager();
if (securityManager != null) {
try {
CHECK_PERMISSION.invoke(securityManager, SUPPRESS_ACCESS_CHECKS);