Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/jdk/java/io/File/GetXSpace.java
66644 views
1
/*
2
* Copyright (c) 2005, 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.
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
/**
25
* @test
26
* @bug 4057701 6286712 6364377 8181919
27
* @requires (os.family == "linux" | os.family == "mac" |
28
* os.family == "windows")
29
* @summary Basic functionality of File.get-X-Space methods.
30
* @library .. /test/lib
31
* @build jdk.test.lib.Platform
32
* @run main/othervm -Djava.security.manager=allow GetXSpace
33
*/
34
35
import java.io.BufferedReader;
36
import java.io.File;
37
import java.io.FilePermission;
38
import java.io.InputStreamReader;
39
import java.io.IOException;
40
import java.nio.file.Files;
41
import java.nio.file.FileStore;
42
import java.nio.file.NoSuchFileException;
43
import java.nio.file.Path;
44
import java.security.Permission;
45
import java.util.ArrayList;
46
import java.util.regex.Matcher;
47
import java.util.regex.Pattern;
48
import jdk.test.lib.Platform;
49
import jdk.test.lib.Platform;
50
51
import static java.lang.System.err;
52
import static java.lang.System.out;
53
54
@SuppressWarnings("removal")
55
public class GetXSpace {
56
57
private static SecurityManager [] sma = { null, new Allow(), new DenyFSA(),
58
new DenyRead() };
59
60
// FileSystem Total Used Available Use% MountedOn
61
private static final Pattern DF_PATTERN = Pattern.compile("([^\\s]+)\\s+(\\d+)\\s+\\d+\\s+(\\d+)\\s+\\d+%\\s+([^\\s].*)\n");
62
63
private static int fail = 0;
64
private static int pass = 0;
65
private static Throwable first;
66
67
static void reset() {
68
fail = 0;
69
pass = 0;
70
first = null;
71
}
72
73
static void pass() {
74
pass++;
75
}
76
77
static void fail(String p) {
78
setFirst(p);
79
System.err.format("FAILED: %s%n", p);
80
fail++;
81
}
82
83
static void fail(String p, long exp, String cmp, long got) {
84
String s = String.format("'%s': %d %s %d", p, exp, cmp, got);
85
setFirst(s);
86
System.err.format("FAILED: %s%n", s);
87
fail++;
88
}
89
90
private static void fail(String p, Class ex) {
91
String s = String.format("'%s': expected %s - FAILED%n", p, ex.getName());
92
setFirst(s);
93
System.err.format("FAILED: %s%n", s);
94
fail++;
95
}
96
97
private static void setFirst(String s) {
98
if (first == null) {
99
first = new RuntimeException(s);
100
}
101
}
102
103
private static class Space {
104
private static final long KSIZE = 1024;
105
private final String name;
106
private final long total;
107
private final long free;
108
109
Space(String total, String free, String name) {
110
try {
111
this.total = Long.valueOf(total) * KSIZE;
112
this.free = Long.valueOf(free) * KSIZE;
113
} catch (NumberFormatException x) {
114
throw new RuntimeException("the regex should have caught this", x);
115
}
116
this.name = name;
117
}
118
119
String name() { return name; }
120
long total() { return total; }
121
long free() { return free; }
122
boolean woomFree(long freeSpace) {
123
return ((freeSpace >= (free / 10)) && (freeSpace <= (free * 10)));
124
}
125
public String toString() {
126
return String.format("%s (%d/%d)", name, free, total);
127
}
128
}
129
130
private static ArrayList<Space> space(String f) throws IOException {
131
ArrayList<Space> al = new ArrayList<>();
132
133
String cmd = "df -k -P" + (f == null ? "" : " " + f);
134
StringBuilder sb = new StringBuilder();
135
Process p = Runtime.getRuntime().exec(cmd);
136
try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
137
String s;
138
int i = 0;
139
while ((s = in.readLine()) != null) {
140
// skip header
141
if (i++ == 0) continue;
142
sb.append(s).append("\n");
143
}
144
}
145
out.println(sb);
146
147
Matcher m = DF_PATTERN.matcher(sb);
148
int j = 0;
149
while (j < sb.length()) {
150
if (m.find(j)) {
151
// swap can change while this test is running
152
if (!m.group(1).equals("swap")) {
153
String name = f;
154
if (name == null) {
155
// cygwin's df lists windows path as FileSystem (1st group)
156
name = Platform.isWindows() ? m.group(1) : m.group(4);
157
}
158
al.add(new Space(m.group(2), m.group(3), name));;
159
}
160
j = m.end() + 1;
161
} else {
162
throw new RuntimeException("unrecognized df output format: "
163
+ "charAt(" + j + ") = '"
164
+ sb.charAt(j) + "'");
165
}
166
}
167
168
if (al.size() == 0) {
169
// df did not produce output
170
String name = (f == null ? "" : f);
171
al.add(new Space("0", "0", name));
172
}
173
return al;
174
}
175
176
private static void tryCatch(Space s) {
177
out.format("%s:%n", s.name());
178
File f = new File(s.name());
179
SecurityManager sm = System.getSecurityManager();
180
if (sm instanceof Deny) {
181
String fmt = " %14s: \"%s\" thrown as expected%n";
182
try {
183
f.getTotalSpace();
184
fail(s.name(), SecurityException.class);
185
} catch (SecurityException x) {
186
out.format(fmt, "getTotalSpace", x);
187
pass();
188
}
189
try {
190
f.getFreeSpace();
191
fail(s.name(), SecurityException.class);
192
} catch (SecurityException x) {
193
out.format(fmt, "getFreeSpace", x);
194
pass();
195
}
196
try {
197
f.getUsableSpace();
198
fail(s.name(), SecurityException.class);
199
} catch (SecurityException x) {
200
out.format(fmt, "getUsableSpace", x);
201
pass();
202
}
203
}
204
}
205
206
private static void compare(Space s) {
207
File f = new File(s.name());
208
long ts = f.getTotalSpace();
209
long fs = f.getFreeSpace();
210
long us = f.getUsableSpace();
211
212
out.format("%s:%n", s.name());
213
String fmt = " %-4s total= %12d free = %12d usable = %12d%n";
214
out.format(fmt, "df", s.total(), 0, s.free());
215
out.format(fmt, "getX", ts, fs, us);
216
217
// If the file system can dynamically change size, this check will fail.
218
// This can happen on macOS for the /dev files system.
219
if (ts != s.total() && (!Platform.isOSX() || !s.name().equals("/dev"))) {
220
long blockSize = 1;
221
long numBlocks = 0;
222
try {
223
FileStore fileStore = Files.getFileStore(f.toPath());
224
blockSize = fileStore.getBlockSize();
225
numBlocks = fileStore.getTotalSpace()/blockSize;
226
} catch (NoSuchFileException nsfe) {
227
// On Linux, ignore the NSFE if the path is one of the
228
// /run/user/$UID mounts created by pam_systemd(8) as it
229
// might be deleted during the test
230
if (!Platform.isLinux() || s.name().indexOf("/run/user") == -1)
231
throw new RuntimeException(nsfe);
232
} catch (IOException e) {
233
throw new RuntimeException(e);
234
}
235
236
// On macOS, the number of 1024 byte blocks might be incorrectly
237
// calculated by 'df' using integer division by 2 of the number of
238
// 512 byte blocks, resulting in a size smaller than the actual
239
// value when the number of blocks is odd.
240
if (!Platform.isOSX() || blockSize != 512 || numBlocks % 2 == 0
241
|| ts - s.total() != 512) {
242
fail(s.name(), s.total(), "!=", ts);
243
}
244
} else {
245
pass();
246
}
247
248
// unix df returns statvfs.f_bavail
249
long tsp = (!Platform.isWindows() ? us : fs);
250
if (!s.woomFree(tsp)) {
251
fail(s.name(), s.free(), "??", tsp);
252
} else {
253
pass();
254
}
255
256
if (fs > s.total()) {
257
fail(s.name(), s.total(), ">", fs);
258
} else {
259
pass();
260
}
261
262
if (us > s.total()) {
263
fail(s.name(), s.total(), ">", us);
264
} else {
265
pass();
266
}
267
}
268
269
private static String FILE_PREFIX = "/getSpace.";
270
private static void compareZeroNonExist() {
271
File f;
272
while (true) {
273
f = new File(FILE_PREFIX + Math.random());
274
if (f.exists()) {
275
continue;
276
}
277
break;
278
}
279
280
long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };
281
282
for (int i = 0; i < s.length; i++) {
283
if (s[i] != 0L) {
284
fail(f.getName(), s[i], "!=", 0L);
285
} else {
286
pass();
287
}
288
}
289
}
290
291
private static void compareZeroExist() {
292
try {
293
File f = File.createTempFile("tmp", null, new File("."));
294
295
long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };
296
297
for (int i = 0; i < s.length; i++) {
298
if (s[i] == 0L) {
299
fail(f.getName(), s[i], "==", 0L);
300
} else {
301
pass();
302
}
303
}
304
} catch (IOException x) {
305
x.printStackTrace();
306
fail("Couldn't create temp file for test");
307
}
308
}
309
310
private static class Allow extends SecurityManager {
311
public void checkRead(String file) {}
312
public void checkPermission(Permission p) {}
313
public void checkPermission(Permission p, Object context) {}
314
}
315
316
private static class Deny extends SecurityManager {
317
public void checkPermission(Permission p) {
318
if (p.implies(new RuntimePermission("setSecurityManager"))
319
|| p.implies(new RuntimePermission("getProtectionDomain")))
320
return;
321
super.checkPermission(p);
322
}
323
324
public void checkPermission(Permission p, Object context) {
325
if (p.implies(new RuntimePermission("setSecurityManager"))
326
|| p.implies(new RuntimePermission("getProtectionDomain")))
327
return;
328
super.checkPermission(p, context);
329
}
330
}
331
332
private static class DenyFSA extends Deny {
333
private String err = "sorry - getFileSystemAttributes";
334
335
public void checkPermission(Permission p) {
336
if (p.implies(new RuntimePermission("getFileSystemAttributes")))
337
throw new SecurityException(err);
338
super.checkPermission(p);
339
}
340
341
public void checkPermission(Permission p, Object context) {
342
if (p.implies(new RuntimePermission("getFileSystemAttributes")))
343
throw new SecurityException(err);
344
super.checkPermission(p, context);
345
}
346
}
347
348
private static class DenyRead extends Deny {
349
private String err = "sorry - checkRead()";
350
351
public void checkRead(String file) {
352
throw new SecurityException(err);
353
}
354
}
355
356
private static int testFile(Path dir) {
357
String dirName = dir.toString();
358
out.format("--- Testing %s%n", dirName);
359
ArrayList<Space> l;
360
try {
361
l = space(dirName);
362
} catch (IOException x) {
363
throw new RuntimeException(dirName + " can't get file system information", x);
364
}
365
compare(l.get(0));
366
367
if (fail != 0) {
368
err.format("%d tests: %d failure(s); first: %s%n",
369
fail + pass, fail, first);
370
} else {
371
out.format("all %d tests passed%n", fail + pass);
372
}
373
374
return fail != 0 ? 1 : 0;
375
}
376
377
private static int testDF() {
378
out.println("--- Testing df");
379
// Find all of the partitions on the machine and verify that the size
380
// returned by "df" is equivalent to File.getXSpace() values.
381
ArrayList<Space> l;
382
try {
383
l = space(null);
384
} catch (IOException x) {
385
throw new RuntimeException("can't get file system information", x);
386
}
387
if (l.size() == 0)
388
throw new RuntimeException("no partitions?");
389
390
for (int i = 0; i < sma.length; i++) {
391
System.setSecurityManager(sma[i]);
392
SecurityManager sm = System.getSecurityManager();
393
if (sma[i] != null && sm == null)
394
throw new RuntimeException("Test configuration error "
395
+ " - can't set security manager");
396
397
out.format("%nSecurityManager = %s%n" ,
398
(sm == null ? "null" : sm.getClass().getName()));
399
for (var s : l) {
400
if (sm instanceof Deny) {
401
tryCatch(s);
402
} else {
403
compare(s);
404
compareZeroNonExist();
405
compareZeroExist();
406
}
407
}
408
}
409
410
System.setSecurityManager(null);
411
412
if (fail != 0) {
413
err.format("%d tests: %d failure(s); first: %s%n",
414
fail + pass, fail, first);
415
} else {
416
out.format("all %d tests passed%n", fail + pass);
417
}
418
419
return fail != 0 ? 1 : 0;
420
}
421
422
private static void perms(File file, boolean allow) throws IOException {
423
file.setExecutable(allow, false);
424
file.setReadable(allow, false);
425
file.setWritable(allow, false);
426
}
427
428
private static void deny(Path path) throws IOException {
429
perms(path.toFile(), false);
430
}
431
432
private static void allow(Path path) throws IOException {
433
perms(path.toFile(), true);
434
}
435
436
public static void main(String[] args) throws Exception {
437
int failedTests = testDF();
438
reset();
439
440
Path tmpDir = Files.createTempDirectory(null);
441
Path tmpSubdir = Files.createTempDirectory(tmpDir, null);
442
Path tmpFile = Files.createTempFile(tmpSubdir, "foo", null);
443
444
deny(tmpSubdir);
445
failedTests += testFile(tmpFile);
446
447
allow(tmpSubdir);
448
Files.delete(tmpFile);
449
Files.delete(tmpSubdir);
450
Files.delete(tmpDir);
451
452
if (failedTests > 0) {
453
throw new RuntimeException(failedTests + " test(s) failed");
454
}
455
}
456
}
457
458