aboutsummaryrefslogtreecommitdiff
path: root/src/java.base/share/classes/jdk/internal/jrtfs/JrtFileSystemProvider.java
blob: 4d3e0ed9d2c0f08ea4e15eee2ae0209a771d6601 (plain) (blame)
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
/*
 * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package jdk.internal.jrtfs;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.attribute.*;
import java.nio.file.spi.FileSystemProvider;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;

/**
 * File system provider for jrt file systems. Conditionally creates jrt fs on
 * .jimage file or exploded modules directory of underlying JDK.
 *
 * @implNote This class needs to maintain JDK 8 source compatibility.
 *
 * It is used internally in the JDK to implement jimage/jrtfs access,
 * but also compiled and delivered as part of the jrtfs.jar to support access
 * to the jimage file provided by the shipped JDK by tools running on JDK 8.
 */
public final class JrtFileSystemProvider extends FileSystemProvider {

    private volatile FileSystem theFileSystem;

    public JrtFileSystemProvider() {
    }

    @Override
    public String getScheme() {
        return "jrt";
    }

    /**
     * Need RuntimePermission "accessSystemModules" to create or get jrt:/
     */
    private void checkPermission() {
        @SuppressWarnings("removal")
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            RuntimePermission perm = new RuntimePermission("accessSystemModules");
            sm.checkPermission(perm);
        }
    }

    private void checkUri(URI uri) {
        if (!uri.getScheme().equalsIgnoreCase(getScheme())) {
            throw new IllegalArgumentException("URI does not match this provider");
        }
        if (uri.getAuthority() != null) {
            throw new IllegalArgumentException("Authority component present");
        }
        if (uri.getPath() == null) {
            throw new IllegalArgumentException("Path component is undefined");
        }
        if (!uri.getPath().equals("/")) {
            throw new IllegalArgumentException("Path component should be '/'");
        }
        if (uri.getQuery() != null) {
            throw new IllegalArgumentException("Query component present");
        }
        if (uri.getFragment() != null) {
            throw new IllegalArgumentException("Fragment component present");
        }
    }

    @Override
    public FileSystem newFileSystem(URI uri, Map<String, ?> env)
            throws IOException {
        Objects.requireNonNull(env);
        checkPermission();
        checkUri(uri);
        if (env.containsKey("java.home")) {
            return newFileSystem((String)env.get("java.home"), uri, env);
        } else {
            return new JrtFileSystem(this, env);
        }
    }

    private static final String JRT_FS_JAR = "jrt-fs.jar";
    private FileSystem newFileSystem(String targetHome, URI uri, Map<String, ?> env)
            throws IOException {
        Objects.requireNonNull(targetHome);
        Path jrtfs = FileSystems.getDefault().getPath(targetHome, "lib", JRT_FS_JAR);
        if (Files.notExists(jrtfs)) {
            throw new IOException(jrtfs.toString() + " not exist");
        }
        Map<String,?> newEnv = new HashMap<>(env);
        newEnv.remove("java.home");
        ClassLoader cl = newJrtFsLoader(jrtfs);
        try {
            Class<?> c = Class.forName(JrtFileSystemProvider.class.getName(), false, cl);
            @SuppressWarnings("deprecation")
            Object tmp = c.newInstance();
            return ((FileSystemProvider)tmp).newFileSystem(uri, newEnv);
        } catch (ClassNotFoundException |
                 IllegalAccessException |
                 InstantiationException e) {
            throw new IOException(e);
        }
    }

    private static class JrtFsLoader extends URLClassLoader {
        JrtFsLoader(URL[] urls) {
            super(urls);
        }
        @Override
        protected Class<?> loadClass(String cn, boolean resolve)
                throws ClassNotFoundException
        {
            Class<?> c = findLoadedClass(cn);
            if (c == null) {
                URL u = findResource(cn.replace('.', '/') + ".class");
                if (u != null) {
                    c = findClass(cn);
                } else {
                    return super.loadClass(cn, resolve);
                }
            }
            if (resolve)
                resolveClass(c);
            return c;
        }
    }

    @SuppressWarnings("removal")
    private static URLClassLoader newJrtFsLoader(Path jrtfs) {
        final URL url;
        try {
            url = jrtfs.toUri().toURL();
        } catch (MalformedURLException mue) {
            throw new IllegalArgumentException(mue);
        }

        final URL[] urls = new URL[] { url };
        return AccessController.doPrivileged(
                new PrivilegedAction<URLClassLoader>() {
                    @Override
                    public URLClassLoader run() {
                        return new JrtFsLoader(urls);
                    }
                }
        );
    }

    @Override
    public Path getPath(URI uri) {
        checkPermission();
        if (!uri.getScheme().equalsIgnoreCase(getScheme())) {
            throw new IllegalArgumentException("URI does not match this provider");
        }
        if (uri.getAuthority() != null) {
            throw new IllegalArgumentException("Authority component present");
        }
        if (uri.getQuery() != null) {
            throw new IllegalArgumentException("Query component present");
        }
        if (uri.getFragment() != null) {
            throw new IllegalArgumentException("Fragment component present");
        }
        String path = uri.getPath();
        if (path == null || path.charAt(0) != '/' || path.contains("..")) {
            throw new IllegalArgumentException("Invalid path component");
        }

        return getTheFileSystem().getPath("/modules" + path);
    }

    private FileSystem getTheFileSystem() {
        checkPermission();
        FileSystem fs = this.theFileSystem;
        if (fs == null) {
            synchronized (this) {
                fs = this.theFileSystem;
                if (fs == null) {
                    try {
                        this.theFileSystem = fs = new JrtFileSystem(this, null);
                    } catch (IOException ioe) {
                        throw new InternalError(ioe);
                    }
                }
            }
        }
        return fs;
    }

    @Override
    public FileSystem getFileSystem(URI uri) {
        checkPermission();
        checkUri(uri);
        return getTheFileSystem();
    }

    // Checks that the given file is a JrtPath
    static final JrtPath toJrtPath(Path path) {
        Objects.requireNonNull(path, "path");
        if (!(path instanceof JrtPath)) {
            throw new ProviderMismatchException();
        }
        return (JrtPath) path;
    }

    @Override
    public void checkAccess(Path path, AccessMode... modes) throws IOException {
        toJrtPath(path).checkAccess(modes);
    }

    @Override
    public Path readSymbolicLink(Path link) throws IOException {
        return toJrtPath(link).readSymbolicLink();
    }

    @Override
    public void copy(Path src, Path target, CopyOption... options)
            throws IOException {
        toJrtPath(src).copy(toJrtPath(target), options);
    }

    @Override
    public void createDirectory(Path path, FileAttribute<?>... attrs)
            throws IOException {
        toJrtPath(path).createDirectory(attrs);
    }

    @Override
    public final void delete(Path path) throws IOException {
        toJrtPath(path).delete();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <V extends FileAttributeView> V
            getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
        return JrtFileAttributeView.get(toJrtPath(path), type, options);
    }

    @Override
    public FileStore getFileStore(Path path) throws IOException {
        return toJrtPath(path).getFileStore();
    }

    @Override
    public boolean isHidden(Path path) {
        return toJrtPath(path).isHidden();
    }

    @Override
    public boolean isSameFile(Path path, Path other) throws IOException {
        return toJrtPath(path).isSameFile(other);
    }

    @Override
    public void move(Path src, Path target, CopyOption... options)
            throws IOException {
        toJrtPath(src).move(toJrtPath(target), options);
    }

    @Override
    public AsynchronousFileChannel newAsynchronousFileChannel(Path path,
            Set<? extends OpenOption> options,
            ExecutorService exec,
            FileAttribute<?>... attrs)
            throws IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public SeekableByteChannel newByteChannel(Path path,
            Set<? extends OpenOption> options,
            FileAttribute<?>... attrs)
            throws IOException {
        return toJrtPath(path).newByteChannel(options, attrs);
    }

    @Override
    public DirectoryStream<Path> newDirectoryStream(
            Path path, Filter<? super Path> filter) throws IOException {
        return toJrtPath(path).newDirectoryStream(filter);
    }

    @Override
    public FileChannel newFileChannel(Path path,
            Set<? extends OpenOption> options,
            FileAttribute<?>... attrs)
            throws IOException {
        return toJrtPath(path).newFileChannel(options, attrs);
    }

    @Override
    public InputStream newInputStream(Path path, OpenOption... options)
            throws IOException {
        return toJrtPath(path).newInputStream(options);
    }

    @Override
    public OutputStream newOutputStream(Path path, OpenOption... options)
            throws IOException {
        return toJrtPath(path).newOutputStream(options);
    }

    @Override
    @SuppressWarnings("unchecked") // Cast to A
    public <A extends BasicFileAttributes> A
            readAttributes(Path path, Class<A> type, LinkOption... options)
            throws IOException {
        if (type == BasicFileAttributes.class || type == JrtFileAttributes.class) {
            return (A) toJrtPath(path).getAttributes(options);
        }
        return null;
    }

    @Override
    public Map<String, Object>
            readAttributes(Path path, String attribute, LinkOption... options)
            throws IOException {
        return toJrtPath(path).readAttributes(attribute, options);
    }

    @Override
    public void setAttribute(Path path, String attribute,
            Object value, LinkOption... options)
            throws IOException {
        toJrtPath(path).setAttribute(attribute, value, options);
    }
}