Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/lang/Class/getDeclaredField/FieldSetAccessibleTest.java
38828 views
1
/*
2
* Copyright (c) 2014, 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.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import java.io.File;
25
import java.io.FilePermission;
26
import java.io.IOException;
27
import java.lang.reflect.Field;
28
import java.lang.reflect.ReflectPermission;
29
import java.nio.file.Files;
30
import java.nio.file.Path;
31
import java.security.CodeSource;
32
import java.security.Permission;
33
import java.security.PermissionCollection;
34
import java.security.Permissions;
35
import java.security.Policy;
36
import java.security.ProtectionDomain;
37
import java.util.ArrayList;
38
import java.util.Arrays;
39
import java.util.Collections;
40
import java.util.Enumeration;
41
import java.util.Iterator;
42
import java.util.List;
43
import java.util.PropertyPermission;
44
import java.util.concurrent.atomic.AtomicBoolean;
45
import java.util.concurrent.atomic.AtomicLong;
46
import java.util.jar.JarEntry;
47
import java.util.jar.JarFile;
48
import java.util.stream.Stream;
49
50
/**
51
* @test
52
* @bug 8065552
53
* @summary test that all fields returned by getDeclaredFields() can be
54
* set accessible if the right permission is granted; this test
55
* loads all the classes in the BCL, get their declared fields,
56
* and call setAccessible(false) followed by setAccessible(true);
57
* @run main/othervm FieldSetAccessibleTest UNSECURE
58
* @run main/othervm FieldSetAccessibleTest SECURE
59
*
60
* @author danielfuchs
61
*/
62
public class FieldSetAccessibleTest {
63
64
static final List<String> skipped = new ArrayList<>();
65
static final List<String> cantread = new ArrayList<>();
66
static final List<String> failed = new ArrayList<>();
67
static final AtomicLong classCount = new AtomicLong();
68
static final AtomicLong fieldCount = new AtomicLong();
69
static long startIndex = 0;
70
static long maxSize = Long.MAX_VALUE;
71
static long maxIndex = Long.MAX_VALUE;
72
73
74
// Test that all fields for any given class can be made accessibles
75
static void testSetFieldsAccessible(Class<?> c) {
76
for (Field f : c.getDeclaredFields()) {
77
fieldCount.incrementAndGet();
78
f.setAccessible(false);
79
f.setAccessible(true);
80
}
81
}
82
83
// Performs a series of test on the given class.
84
// At this time, we only call testSetFieldsAccessible(c)
85
public static boolean test(Class<?> c) {
86
//System.out.println(c.getName());
87
classCount.incrementAndGet();
88
89
// Call getDeclaredFields() and try to set their accessible flag.
90
testSetFieldsAccessible(c);
91
92
// add more tests here...
93
94
return c == Class.class;
95
}
96
97
// Prints a summary at the end of the test.
98
static void printSummary(long secs, long millis, long nanos) {
99
System.out.println("Tested " + fieldCount.get() + " fields of "
100
+ classCount.get() + " classes in "
101
+ secs + "s " + millis + "ms " + nanos + "ns");
102
}
103
104
105
/**
106
* @param args the command line arguments:
107
*
108
* SECURE|UNSECURE [startIndex (default=0)] [maxSize (default=Long.MAX_VALUE)]
109
*
110
* @throws java.lang.Exception if the test fails
111
*/
112
public static void main(String[] args) throws Exception {
113
if (args == null || args.length == 0) {
114
args = new String[] {"SECURE", "0"};
115
} else if (args.length > 3) {
116
throw new RuntimeException("Expected at most one argument. Found "
117
+ Arrays.asList(args));
118
}
119
try {
120
if (args.length > 1) {
121
startIndex = Long.parseLong(args[1]);
122
if (startIndex < 0) {
123
throw new IllegalArgumentException("startIndex args[1]: "
124
+ startIndex);
125
}
126
}
127
if (args.length > 2) {
128
maxSize = Long.parseLong(args[2]);
129
if (maxSize <= 0) {
130
maxSize = Long.MAX_VALUE;
131
}
132
maxIndex = (Long.MAX_VALUE - startIndex) < maxSize
133
? Long.MAX_VALUE : startIndex + maxSize;
134
}
135
TestCase.valueOf(args[0]).run();
136
} catch (OutOfMemoryError oome) {
137
System.err.println(classCount.get());
138
throw oome;
139
}
140
}
141
142
public static void run(TestCase test) {
143
System.out.println("Testing " + test);
144
test(listAllClassNames());
145
System.out.println("Passed " + test);
146
}
147
148
static Iterable<String> listAllClassNames() {
149
return new ClassNameStreamBuilder();
150
}
151
152
static void test(Iterable<String> iterable) {
153
final long start = System.nanoTime();
154
boolean classFound = false;
155
int index = 0;
156
for (String s: iterable) {
157
if (index == maxIndex) break;
158
try {
159
if (index < startIndex) continue;
160
if (test(s)) {
161
classFound = true;
162
}
163
} finally {
164
index++;
165
}
166
}
167
long elapsed = System.nanoTime() - start;
168
long secs = elapsed / 1000_000_000;
169
long millis = (elapsed % 1000_000_000) / 1000_000;
170
long nanos = elapsed % 1000_000;
171
System.out.println("Unreadable path elements: " + cantread);
172
System.out.println("Skipped path elements: " + skipped);
173
System.out.println("Failed path elements: " + failed);
174
printSummary(secs, millis, nanos);
175
176
if (!failed.isEmpty()) {
177
throw new RuntimeException("Test failed for the following classes: " + failed);
178
}
179
if (!classFound && startIndex == 0 && index < maxIndex) {
180
// this is just to verify that we have indeed parsed rt.jar
181
// (or the java.base module)
182
throw new RuntimeException("Test failed: Class.class not found...");
183
}
184
if (classCount.get() == 0 && startIndex == 0) {
185
throw new RuntimeException("Test failed: no class found?");
186
}
187
}
188
189
static boolean test(String s) {
190
try {
191
if (s.startsWith("WrapperGenerator")) {
192
System.out.println("Skipping "+ s);
193
return false;
194
}
195
final Class<?> c = Class.forName(
196
s.replace('/', '.').substring(0, s.length() - 6),
197
false,
198
null);
199
return test(c);
200
} catch (Exception t) {
201
t.printStackTrace(System.err);
202
failed.add(s);
203
} catch (NoClassDefFoundError e) {
204
e.printStackTrace(System.err);
205
failed.add(s);
206
}
207
return false;
208
}
209
210
static class ClassNameStreamBuilder implements Iterable<String>{
211
String[] bcp;
212
ClassNameStreamBuilder() {
213
bcp = System.getProperty("sun.boot.class.path").split(File.pathSeparator);
214
}
215
216
Stream<String> bcpElementToStream(String s) {
217
return s.endsWith(".jar") ? jarToStream(s) : folderToStream(s);
218
}
219
220
Stream<String> jarToStream(String jarName) {
221
File f = new File(jarName);
222
if (f.canRead() && f.isFile()) {
223
try {
224
JarFile jarFile = new JarFile(f);
225
return jarFile.stream()
226
.filter(e -> !e.isDirectory())
227
.map(JarEntry::getName)
228
.filter(s -> s.endsWith(".class"));
229
} catch(IOException x) {
230
x.printStackTrace(System.err);
231
skipped.add(jarName);
232
}
233
} else {
234
cantread.add(jarName);
235
}
236
return Collections.<String>emptyList().stream();
237
}
238
239
Stream<String> folderToStream(String folderName) {
240
final File root = new File(folderName);
241
if (root.canRead() && root.isDirectory()) {
242
final Path rootPath = root.toPath();
243
try {
244
return Files.walk(rootPath)
245
.filter(p -> p.getFileName().toString().endsWith(".class"))
246
.map(rootPath::relativize)
247
.map(p -> p.toString().replace(File.separatorChar, '/'));
248
} catch (IOException x) {
249
x.printStackTrace(System.err);
250
skipped.add(folderName);
251
}
252
} else {
253
cantread.add(folderName);
254
}
255
return Collections.<String>emptyList().stream();
256
}
257
258
public Stream<String> build() {
259
return Stream.of(bcp).flatMap(this::bcpElementToStream);
260
}
261
262
@Override
263
public Iterator<String> iterator() {
264
return build().iterator();
265
}
266
}
267
268
// Test with or without a security manager
269
public static enum TestCase {
270
UNSECURE, SECURE;
271
public void run() throws Exception {
272
System.out.println("Running test case: " + name());
273
Configure.setUp(this);
274
FieldSetAccessibleTest.run(this);
275
}
276
}
277
278
// A helper class to configure the security manager for the test,
279
// and bypass it when needed.
280
static class Configure {
281
static Policy policy = null;
282
static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {
283
@Override
284
protected AtomicBoolean initialValue() {
285
return new AtomicBoolean(false);
286
}
287
};
288
static void setUp(TestCase test) {
289
switch (test) {
290
case SECURE:
291
if (policy == null && System.getSecurityManager() != null) {
292
throw new IllegalStateException("SecurityManager already set");
293
} else if (policy == null) {
294
policy = new SimplePolicy(TestCase.SECURE, allowAll);
295
Policy.setPolicy(policy);
296
System.setSecurityManager(new SecurityManager());
297
}
298
if (System.getSecurityManager() == null) {
299
throw new IllegalStateException("No SecurityManager.");
300
}
301
if (policy == null) {
302
throw new IllegalStateException("policy not configured");
303
}
304
break;
305
case UNSECURE:
306
if (System.getSecurityManager() != null) {
307
throw new IllegalStateException("SecurityManager already set");
308
}
309
break;
310
default:
311
throw new InternalError("No such testcase: " + test);
312
}
313
}
314
static void doPrivileged(Runnable run) {
315
allowAll.get().set(true);
316
try {
317
run.run();
318
} finally {
319
allowAll.get().set(false);
320
}
321
}
322
}
323
324
// A Helper class to build a set of permissions.
325
final static class PermissionsBuilder {
326
final Permissions perms;
327
public PermissionsBuilder() {
328
this(new Permissions());
329
}
330
public PermissionsBuilder(Permissions perms) {
331
this.perms = perms;
332
}
333
public PermissionsBuilder add(Permission p) {
334
perms.add(p);
335
return this;
336
}
337
public PermissionsBuilder addAll(PermissionCollection col) {
338
if (col != null) {
339
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
340
perms.add(e.nextElement());
341
}
342
}
343
return this;
344
}
345
public Permissions toPermissions() {
346
final PermissionsBuilder builder = new PermissionsBuilder();
347
builder.addAll(perms);
348
return builder.perms;
349
}
350
}
351
352
// Policy for the test...
353
public static class SimplePolicy extends Policy {
354
355
final Permissions permissions;
356
final Permissions allPermissions;
357
final ThreadLocal<AtomicBoolean> allowAll;
358
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
359
this.allowAll = allowAll;
360
361
// Permission needed by the tested code exercised in the test
362
permissions = new Permissions();
363
permissions.add(new RuntimePermission("fileSystemProvider"));
364
permissions.add(new RuntimePermission("createClassLoader"));
365
permissions.add(new RuntimePermission("closeClassLoader"));
366
permissions.add(new RuntimePermission("getClassLoader"));
367
permissions.add(new RuntimePermission("accessDeclaredMembers"));
368
permissions.add(new ReflectPermission("suppressAccessChecks"));
369
permissions.add(new PropertyPermission("*", "read"));
370
permissions.add(new FilePermission("<<ALL FILES>>", "read"));
371
372
// these are used for configuring the test itself...
373
allPermissions = new Permissions();
374
allPermissions.add(new java.security.AllPermission());
375
}
376
377
@Override
378
public boolean implies(ProtectionDomain domain, Permission permission) {
379
if (allowAll.get().get()) return allPermissions.implies(permission);
380
if (permissions.implies(permission)) return true;
381
if (permission instanceof java.lang.RuntimePermission) {
382
if (permission.getName().startsWith("accessClassInPackage.")) {
383
// add these along to the set of permission we have, when we
384
// discover that we need them.
385
permissions.add(permission);
386
return true;
387
}
388
}
389
return false;
390
}
391
392
@Override
393
public PermissionCollection getPermissions(CodeSource codesource) {
394
return new PermissionsBuilder().addAll(allowAll.get().get()
395
? allPermissions : permissions).toPermissions();
396
}
397
398
@Override
399
public PermissionCollection getPermissions(ProtectionDomain domain) {
400
return new PermissionsBuilder().addAll(allowAll.get().get()
401
? allPermissions : permissions).toPermissions();
402
}
403
}
404
405
}
406
407