Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/DynamicLinkerFactory.java
41154 views
1
/*
2
* Copyright (c) 2010, 2021, 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
/*
27
* This file is available under and governed by the GNU General Public
28
* License version 2 only, as published by the Free Software Foundation.
29
* However, the following notice accompanied the original version of this
30
* file, and Oracle licenses the original version of this file under the BSD
31
* license:
32
*/
33
/*
34
Copyright 2009-2013 Attila Szegedi
35
36
Redistribution and use in source and binary forms, with or without
37
modification, are permitted provided that the following conditions are
38
met:
39
* Redistributions of source code must retain the above copyright
40
notice, this list of conditions and the following disclaimer.
41
* Redistributions in binary form must reproduce the above copyright
42
notice, this list of conditions and the following disclaimer in the
43
documentation and/or other materials provided with the distribution.
44
* Neither the name of the copyright holder nor the names of
45
contributors may be used to endorse or promote products derived from
46
this software without specific prior written permission.
47
48
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
49
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
50
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
51
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
52
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
53
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
54
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
55
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
56
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
57
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
58
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59
*/
60
61
package jdk.dynalink;
62
63
import java.lang.invoke.MethodHandle;
64
import java.lang.invoke.MethodType;
65
import java.lang.invoke.MutableCallSite;
66
import java.security.AccessControlContext;
67
import java.security.AccessController;
68
import java.security.PrivilegedAction;
69
import java.util.ArrayList;
70
import java.util.Arrays;
71
import java.util.Collections;
72
import java.util.HashSet;
73
import java.util.Iterator;
74
import java.util.LinkedList;
75
import java.util.List;
76
import java.util.Objects;
77
import java.util.ServiceConfigurationError;
78
import java.util.ServiceLoader;
79
import java.util.Set;
80
import java.util.function.Supplier;
81
import jdk.dynalink.beans.BeansLinker;
82
import jdk.dynalink.internal.AccessControlContextFactory;
83
import jdk.dynalink.linker.GuardedInvocation;
84
import jdk.dynalink.linker.GuardedInvocationTransformer;
85
import jdk.dynalink.linker.GuardingDynamicLinker;
86
import jdk.dynalink.linker.GuardingDynamicLinkerExporter;
87
import jdk.dynalink.linker.GuardingTypeConverterFactory;
88
import jdk.dynalink.linker.LinkRequest;
89
import jdk.dynalink.linker.LinkerServices;
90
import jdk.dynalink.linker.MethodHandleTransformer;
91
import jdk.dynalink.linker.MethodTypeConversionStrategy;
92
import jdk.dynalink.linker.support.CompositeGuardingDynamicLinker;
93
import jdk.dynalink.linker.support.CompositeTypeBasedGuardingDynamicLinker;
94
import jdk.dynalink.linker.support.DefaultInternalObjectFilter;
95
import jdk.dynalink.linker.support.TypeUtilities;
96
97
/**
98
* A factory class for creating {@link DynamicLinker} objects. Dynamic linkers
99
* are the central objects in Dynalink; these are composed of several
100
* {@link GuardingDynamicLinker} objects and coordinate linking of call sites
101
* with them. The usual dynamic linker is a linker
102
* composed of all {@link GuardingDynamicLinker} objects explicitly pre-created
103
* by the user of the factory and configured with
104
* {@link #setPrioritizedLinkers(List)}, as well as any
105
* {@link #setClassLoader(ClassLoader) automatically discovered} ones, and
106
* finally the ones configured with {@link #setFallbackLinkers(List)}; this last
107
* category usually includes {@link BeansLinker}.
108
*/
109
public final class DynamicLinkerFactory {
110
@SuppressWarnings("removal")
111
private static final AccessControlContext GET_CLASS_LOADER_CONTEXT =
112
AccessControlContextFactory.createAccessControlContext("getClassLoader");
113
114
/**
115
* Default value for {@link #setUnstableRelinkThreshold(int) unstable relink
116
* threshold}.
117
*/
118
private static final int DEFAULT_UNSTABLE_RELINK_THRESHOLD = 8;
119
120
private boolean classLoaderExplicitlySet = false;
121
private ClassLoader classLoader;
122
123
private List<? extends GuardingDynamicLinker> prioritizedLinkers;
124
private List<? extends GuardingDynamicLinker> fallbackLinkers;
125
private boolean syncOnRelink = false;
126
private int unstableRelinkThreshold = DEFAULT_UNSTABLE_RELINK_THRESHOLD;
127
private GuardedInvocationTransformer prelinkTransformer;
128
private MethodTypeConversionStrategy autoConversionStrategy;
129
private MethodHandleTransformer internalObjectsFilter;
130
131
private List<ServiceConfigurationError> autoLoadingErrors = Collections.emptyList();
132
133
/**
134
* Creates a new dynamic linker factory with default configuration. Upon
135
* creation, the factory can be configured using various {@code setXxx()}
136
* methods and used to create one or more dynamic linkers according to its
137
* current configuration using {@link #createLinker()}.
138
*/
139
public DynamicLinkerFactory() {
140
}
141
142
/**
143
* Sets the class loader for automatic discovery of available guarding
144
* dynamic linkers. {@link GuardingDynamicLinkerExporter} implementations
145
* available through this class loader will be automatically instantiated
146
* using the {@link ServiceLoader} mechanism and the linkers they provide
147
* will be incorporated into {@code DynamicLinker}s that this factory
148
* creates. This allows for cross-language interoperability where call sites
149
* belonging to this language runtime can be linked by linkers from these
150
* automatically discovered runtimes if their native objects are passed to
151
* this runtime. If class loader is not set explicitly by invoking this
152
* method, then the thread context class loader of the thread invoking
153
* {@link #createLinker()} will be used. If this method is invoked
154
* explicitly with null then {@link ServiceLoader#loadInstalled(Class)} will
155
* be used to load the linkers.
156
*
157
* @param classLoader the class loader used for the automatic discovery of
158
* available linkers.
159
*/
160
public void setClassLoader(final ClassLoader classLoader) {
161
this.classLoader = classLoader;
162
classLoaderExplicitlySet = true;
163
}
164
165
/**
166
* Sets the prioritized guarding dynamic linkers. Language runtimes using
167
* Dynalink will usually have at least one linker for their own language.
168
* These linkers will be consulted first by the resulting dynamic linker
169
* when it is linking call sites, before any autodiscovered and fallback
170
* linkers. If the factory also autodiscovers a linker class matching one
171
* of the prioritized linkers, the autodiscovered class will be ignored and
172
* the explicit prioritized instance will be used.
173
*
174
* @param prioritizedLinkers the list of prioritized linkers. Can be null.
175
* @throws NullPointerException if any of the list elements are null.
176
*/
177
public void setPrioritizedLinkers(final List<? extends GuardingDynamicLinker> prioritizedLinkers) {
178
this.prioritizedLinkers = copyListRequireNonNullElements(prioritizedLinkers);
179
}
180
181
/**
182
* Sets the prioritized guarding dynamic linkers. Identical to calling
183
* {@link #setPrioritizedLinkers(List)} with
184
* {@code Arrays.asList(prioritizedLinkers)}.
185
*
186
* @param prioritizedLinkers an array of prioritized linkers. Can be null.
187
* @throws NullPointerException if any of the array elements are null.
188
*/
189
public void setPrioritizedLinkers(final GuardingDynamicLinker... prioritizedLinkers) {
190
setPrioritizedLinkers(prioritizedLinkers == null ? null : Arrays.asList(prioritizedLinkers));
191
}
192
193
/**
194
* Sets a single prioritized linker. Identical to calling
195
* {@link #setPrioritizedLinkers(List)} with a single-element list.
196
*
197
* @param prioritizedLinker the single prioritized linker. Must not be null.
198
* @throws NullPointerException if null is passed.
199
*/
200
public void setPrioritizedLinker(final GuardingDynamicLinker prioritizedLinker) {
201
this.prioritizedLinkers = Collections.singletonList(Objects.requireNonNull(prioritizedLinker));
202
}
203
204
/**
205
* Sets the fallback guarding dynamic linkers. These linkers will be
206
* consulted last by the resulting dynamic linker when it is linking call
207
* sites, after any autodiscovered and prioritized linkers. If the factory
208
* also autodiscovers a linker class matching one of the fallback linkers,
209
* the autodiscovered class will be ignored and the explicit fallback
210
* instance will be used.
211
*
212
* @param fallbackLinkers the list of fallback linkers. Can be empty to
213
* indicate the caller wishes to set no fallback linkers. Note that if this
214
* method is not invoked explicitly or is passed null, then the factory
215
* will create an instance of {@link BeansLinker} to serve as the default
216
* fallback linker.
217
* @throws NullPointerException if any of the list elements are null.
218
*/
219
public void setFallbackLinkers(final List<? extends GuardingDynamicLinker> fallbackLinkers) {
220
this.fallbackLinkers = copyListRequireNonNullElements(fallbackLinkers);
221
}
222
223
/**
224
* Sets the fallback guarding dynamic linkers. Identical to calling
225
* {@link #setFallbackLinkers(List)} with
226
* {@code Arrays.asList(fallbackLinkers)}.
227
*
228
* @param fallbackLinkers an array of fallback linkers. Can be empty to
229
* indicate the caller wishes to set no fallback linkers. Note that if this
230
* method is not invoked explicitly or is passed null, then the factory
231
* will create an instance of {@link BeansLinker} to serve as the default
232
* fallback linker.
233
* @throws NullPointerException if any of the array elements are null.
234
*/
235
public void setFallbackLinkers(final GuardingDynamicLinker... fallbackLinkers) {
236
setFallbackLinkers(fallbackLinkers == null ? null : Arrays.asList(fallbackLinkers));
237
}
238
239
/**
240
* Sets whether the dynamic linker created by this factory will invoke
241
* {@link MutableCallSite#syncAll(MutableCallSite[])} after a call site is
242
* relinked. Defaults to false. You probably want to set it to true if your
243
* runtime supports multithreaded execution of dynamically linked code.
244
* @param syncOnRelink true for invoking sync on relink, false otherwise.
245
*/
246
public void setSyncOnRelink(final boolean syncOnRelink) {
247
this.syncOnRelink = syncOnRelink;
248
}
249
250
/**
251
* Sets the unstable relink threshold; the number of times a call site is
252
* relinked after which it will be considered unstable, and subsequent link
253
* requests for it will indicate this. Defaults to 8 when not set explicitly.
254
* @param unstableRelinkThreshold the new threshold. Must not be less than
255
* zero. The value of zero means that call sites will never be considered
256
* unstable.
257
* @see LinkRequest#isCallSiteUnstable()
258
*/
259
public void setUnstableRelinkThreshold(final int unstableRelinkThreshold) {
260
if(unstableRelinkThreshold < 0) {
261
throw new IllegalArgumentException("unstableRelinkThreshold < 0");
262
}
263
this.unstableRelinkThreshold = unstableRelinkThreshold;
264
}
265
266
/**
267
* Set the pre-link transformer. This is a
268
* {@link GuardedInvocationTransformer} that will get the final chance to
269
* modify the guarded invocation after it has been created by a component
270
* linker and before the dynamic linker links it into the call site. It is
271
* normally used to adapt the return value type of the invocation to the
272
* type of the call site. When not set explicitly, a default pre-link
273
* transformer will be used that simply calls
274
* {@link GuardedInvocation#asType(LinkerServices, MethodType)}. Customized
275
* pre-link transformers are rarely needed; they are mostly used as a
276
* building block for implementing advanced techniques such as code
277
* deoptimization strategies.
278
* @param prelinkTransformer the pre-link transformer for the dynamic
279
* linker. Can be null to have the factory use the default transformer.
280
*/
281
public void setPrelinkTransformer(final GuardedInvocationTransformer prelinkTransformer) {
282
this.prelinkTransformer = prelinkTransformer;
283
}
284
285
/**
286
* Sets an object representing the conversion strategy for automatic type
287
* conversions. After
288
* {@link LinkerServices#asType(MethodHandle, MethodType)} has applied all
289
* custom conversions to a method handle, it still needs to effect
290
* {@link TypeUtilities#isMethodInvocationConvertible(Class, Class) method
291
* invocation conversions} that can usually be automatically applied as per
292
* {@link MethodHandle#asType(MethodType)}. However, sometimes language
293
* runtimes will want to customize even those conversions for their own call
294
* sites. A typical example is allowing unboxing of null return values,
295
* which is by default prohibited by ordinary
296
* {@code MethodHandles.asType()}. In this case, a language runtime can
297
* install its own custom automatic conversion strategy, that can deal with
298
* null values. Note that when the strategy's
299
* {@link MethodTypeConversionStrategy#asType(MethodHandle, MethodType)}
300
* is invoked, the custom language conversions will already have been
301
* applied to the method handle, so by design the difference between the
302
* handle's current method type and the desired final type will always only
303
* be ones that can be subjected to method invocation conversions. The
304
* strategy also doesn't need to invoke a final
305
* {@code MethodHandle.asType()} as that will be done internally as the
306
* final step.
307
* @param autoConversionStrategy the strategy for applying method invocation
308
* conversions for the linker created by this factory. Can be null for no
309
* custom strategy.
310
*/
311
public void setAutoConversionStrategy(final MethodTypeConversionStrategy autoConversionStrategy) {
312
this.autoConversionStrategy = autoConversionStrategy;
313
}
314
315
/**
316
* Sets a method handle transformer that is supposed to act as the
317
* implementation of
318
* {@link LinkerServices#filterInternalObjects(MethodHandle)} for linker
319
* services of dynamic linkers created by this factory. Some language
320
* runtimes can have internal objects that should not escape their scope.
321
* They can add a transformer here that will modify the method handle so
322
* that any parameters that can receive potentially internal language
323
* runtime objects will have a filter added on them to prevent them from
324
* escaping, potentially by wrapping them. The transformer can also
325
* potentially add an unwrapping filter to the return value.
326
* {@link DefaultInternalObjectFilter} is provided as a convenience class
327
* for easily creating such filtering transformers.
328
* @param internalObjectsFilter a method handle transformer filtering out
329
* internal objects, or null.
330
*/
331
public void setInternalObjectsFilter(final MethodHandleTransformer internalObjectsFilter) {
332
this.internalObjectsFilter = internalObjectsFilter;
333
}
334
335
/**
336
* Creates a new dynamic linker based on the current configuration. This
337
* method can be invoked more than once to create multiple dynamic linkers.
338
* Automatically discovered linkers are newly instantiated on every
339
* invocation of this method. It is allowed to change the factory's
340
* configuration between invocations. The method is not thread safe. After
341
* invocation, callers can invoke {@link #getAutoLoadingErrors()} to
342
* retrieve a list of {@link ServiceConfigurationError}s that occurred while
343
* trying to load automatically discovered linkers. These are never thrown
344
* from the call to this method as it makes every effort to recover from
345
* them and ignore the failing linkers.
346
* @return the new dynamic Linker
347
*/
348
public DynamicLinker createLinker() {
349
// Treat nulls appropriately
350
if(prioritizedLinkers == null) {
351
prioritizedLinkers = Collections.emptyList();
352
}
353
if(fallbackLinkers == null) {
354
fallbackLinkers = Collections.singletonList(new BeansLinker());
355
}
356
357
// Gather classes of all precreated (prioritized and fallback) linkers.
358
// We'll filter out any discovered linkers of the same class.
359
final Set<Class<? extends GuardingDynamicLinker>> knownLinkerClasses =
360
new HashSet<>();
361
addClasses(knownLinkerClasses, prioritizedLinkers);
362
addClasses(knownLinkerClasses, fallbackLinkers);
363
364
final List<GuardingDynamicLinker> discovered = discoverAutoLoadLinkers();
365
// Now, concatenate ...
366
final List<GuardingDynamicLinker> linkers =
367
new ArrayList<>(prioritizedLinkers.size() + discovered.size()
368
+ fallbackLinkers.size());
369
// ... prioritized linkers, ...
370
linkers.addAll(prioritizedLinkers);
371
// ... filtered discovered linkers, ...
372
for(final GuardingDynamicLinker linker: discovered) {
373
if(!knownLinkerClasses.contains(linker.getClass())) {
374
linkers.add(linker);
375
}
376
}
377
// ... and finally fallback linkers.
378
linkers.addAll(fallbackLinkers);
379
final List<GuardingDynamicLinker> optimized = CompositeTypeBasedGuardingDynamicLinker.optimize(linkers);
380
final GuardingDynamicLinker composite;
381
switch(linkers.size()) {
382
case 0: {
383
composite = (r, s) -> null; // linker that can't link anything
384
break;
385
}
386
case 1: {
387
composite = optimized.get(0);
388
break;
389
}
390
default: {
391
composite = new CompositeGuardingDynamicLinker(optimized);
392
break;
393
}
394
}
395
396
final List<GuardingTypeConverterFactory> typeConverters = new LinkedList<>();
397
for(final GuardingDynamicLinker linker: linkers) {
398
if(linker instanceof GuardingTypeConverterFactory) {
399
typeConverters.add((GuardingTypeConverterFactory)linker);
400
}
401
}
402
403
if(prelinkTransformer == null) {
404
prelinkTransformer = (inv, request, linkerServices) -> inv.asType(linkerServices, request.getCallSiteDescriptor().getMethodType());
405
}
406
407
return new DynamicLinker(new LinkerServicesImpl(new TypeConverterFactory(typeConverters,
408
autoConversionStrategy), composite, internalObjectsFilter), prelinkTransformer,
409
syncOnRelink, unstableRelinkThreshold);
410
}
411
412
/**
413
* Returns a list of {@link ServiceConfigurationError}s that were
414
* encountered while loading automatically discovered linkers during the
415
* last invocation of {@link #createLinker()}. They can be any non-Dynalink
416
* specific service configuration issues, as well as some Dynalink-specific
417
* errors when an exporter that the factory tried to automatically load:
418
* <ul>
419
* <li>did not have the runtime permission named
420
* {@link GuardingDynamicLinkerExporter#AUTOLOAD_PERMISSION_NAME} in a
421
* system with a security manager, or</li>
422
* <li>returned null from {@link GuardingDynamicLinkerExporter#get()}, or</li>
423
* <li>the list returned from {@link GuardingDynamicLinkerExporter#get()}
424
* had a null element.</li>
425
* </ul>
426
* @return an immutable list of encountered
427
* {@link ServiceConfigurationError}s. Can be empty.
428
*/
429
public List<ServiceConfigurationError> getAutoLoadingErrors() {
430
return Collections.unmodifiableList(autoLoadingErrors);
431
}
432
433
private List<GuardingDynamicLinker> discoverAutoLoadLinkers() {
434
autoLoadingErrors = new LinkedList<>();
435
final ClassLoader effectiveClassLoader = classLoaderExplicitlySet ? classLoader : getThreadContextClassLoader();
436
final List<GuardingDynamicLinker> discovered = new LinkedList<>();
437
try {
438
@SuppressWarnings("removal")
439
final ServiceLoader<GuardingDynamicLinkerExporter> linkerLoader =
440
AccessController.doPrivileged((PrivilegedAction<ServiceLoader<GuardingDynamicLinkerExporter>>)()-> {
441
if (effectiveClassLoader == null) {
442
return ServiceLoader.loadInstalled(GuardingDynamicLinkerExporter.class);
443
}
444
return ServiceLoader.load(GuardingDynamicLinkerExporter.class, effectiveClassLoader);
445
});
446
447
for(final Iterator<GuardingDynamicLinkerExporter> it = linkerLoader.iterator(); it.hasNext();) {
448
try {
449
final GuardingDynamicLinkerExporter autoLoader = it.next();
450
try {
451
discovered.addAll(requireNonNullElements(
452
Objects.requireNonNull(autoLoader.get(),
453
()->(autoLoader.getClass().getName() + " returned null from get()")),
454
()->(autoLoader.getClass().getName() + " returned a list with at least one null element")));
455
} catch (final ServiceConfigurationError|VirtualMachineError e) {
456
// Don't wrap a SCE in another SCE. Also, don't ignore
457
// any VME (e.g. StackOverflowError or OutOfMemoryError).
458
throw e;
459
} catch (final Throwable t) {
460
throw new ServiceConfigurationError(t.getMessage(), t);
461
}
462
} catch (final ServiceConfigurationError e) {
463
// Catch SCE with an individual exporter, carry on with it.hasNext().
464
autoLoadingErrors.add(e);
465
}
466
}
467
} catch (final ServiceConfigurationError e) {
468
// Catch a top-level SCE; one either in ServiceLoader.load(),
469
// ServiceLoader.iterator(), or Iterator.hasNext().
470
autoLoadingErrors.add(e);
471
}
472
return discovered;
473
}
474
475
@SuppressWarnings("removal")
476
private static ClassLoader getThreadContextClassLoader() {
477
return AccessController.doPrivileged(
478
(PrivilegedAction<ClassLoader>) () -> Thread.currentThread().getContextClassLoader(),
479
GET_CLASS_LOADER_CONTEXT);
480
}
481
482
private static void addClasses(final Set<Class<? extends GuardingDynamicLinker>> knownLinkerClasses,
483
final List<? extends GuardingDynamicLinker> linkers) {
484
for(final GuardingDynamicLinker linker: linkers) {
485
knownLinkerClasses.add(linker.getClass());
486
}
487
}
488
489
private static <T> List<T> copyListRequireNonNullElements(final List<T> list) {
490
if (list == null) {
491
return null;
492
}
493
return new ArrayList<>(requireNonNullElements(list, ()->"List has at least one null element"));
494
}
495
496
private static <T> List<T> requireNonNullElements(final List<T> list, final Supplier<String> msgSupplier) {
497
for(final T t: list) {
498
Objects.requireNonNull(t, msgSupplier);
499
}
500
return list;
501
}
502
503
}
504
505