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