Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FileDispatcherImpl.java « ch « nio « sun « openjdk - github.com/mono/ikvm-fork.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 971df81ba37fd37ce454926583d87c24d6817532 (plain)
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
/*
 * Copyright (c) 2000, 2010, 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 sun.nio.ch;

import java.io.*;
import java.nio.ByteBuffer;
import cli.Microsoft.Win32.SafeHandles.SafeFileHandle;
import cli.System.IntPtr;
import cli.System.IO.FileStream;
import cli.System.Runtime.InteropServices.DllImportAttribute;
import cli.System.Runtime.InteropServices.StructLayoutAttribute;
import cli.System.Runtime.InteropServices.LayoutKind;
import cli.System.Runtime.InteropServices.Marshal;
import static ikvm.internal.Util.WINDOWS;

class FileDispatcherImpl extends FileDispatcher
{
    /**
     * Indicates if the dispatcher should first advance the file position
     * to the end of file when writing.
     */
    private final boolean append;

    FileDispatcherImpl(boolean append) {
        this.append = append;
    }

    FileDispatcherImpl() {
        this(false);
    }

    int read(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException {
        return fd.readBytes(buf, offset, length);
    }

    int write(FileDescriptor fd, byte[] buf, int offset, int length) throws IOException {
        fd.writeBytes(buf, offset, length);
        return length;
    }

    long read(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException {
        long totalRead = 0;
        try
        {
            for (int i = offset; i < offset + length; i++)
            {
                int size = bufs[i].remaining();
                if (size > 0)
                {
                    int read = IOUtil.read(fd, bufs[i], -1, this, this);
                    if (read < 0)
                    {
                        break;
                    }
                    totalRead += read;
                    if (read < size || fd.available() == 0)
                    {
                        break;
                    }
                }
            }
        }
        catch (IOException x)
        {
            if (totalRead == 0)
            {
                throw x;
            }
        }
        return totalRead;
    }

    long write(FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) throws IOException {
        long totalWritten = 0;
        try
        {
            for (int i = offset; i < offset + length; i++)
            {
                int size = bufs[i].remaining();
                if (size > 0)
                {
                    int written = IOUtil.write(fd, bufs[i], -1, this, this);
                    totalWritten += written;
                    if (written < size)
                    {
                        break;
                    }
                }
            }
        }
        catch (IOException x)
        {
            if (totalWritten == 0)
            {
                throw x;
            }
        }
        return totalWritten;
    }

    int force(FileDescriptor fd, boolean metaData) throws IOException {
        fd.sync();
        return 0;
    }

    int truncate(FileDescriptor fd, long size) throws IOException {
        if (append) {
            // HACK in append mode we're not allowed to truncate, so we try to reopen the file and truncate that
            try (FileOutputStream fos = new FileOutputStream(((FileStream)fd.getStream()).get_Name())) {
                fos.getFD().setLength(size);
            }
        } else {
            fd.setLength(size);
        }
        return 0;
    }

    long size(FileDescriptor fd) throws IOException {
        return fd.length();
    }

    @StructLayoutAttribute.Annotation(LayoutKind.__Enum.Sequential)
    private static final class OVERLAPPED extends cli.System.Object
    {
        IntPtr Internal;
        IntPtr InternalHigh;
        int OffsetLow;
        int OffsetHigh;
        IntPtr hEvent;
    }

    @cli.System.Security.SecuritySafeCriticalAttribute.Annotation
    int lock(FileDescriptor fd, boolean blocking, long pos, long size,
             boolean shared) throws IOException
    {
        FileStream fs = (FileStream)fd.getStream();
        if (WINDOWS)
        {
            int LOCKFILE_FAIL_IMMEDIATELY = 1;
            int LOCKFILE_EXCLUSIVE_LOCK = 2;
            int ERROR_LOCK_VIOLATION = 33;
            int flags = 0;
            OVERLAPPED o = new OVERLAPPED();
            o.OffsetLow = (int)pos;
            o.OffsetHigh = (int)(pos >> 32);
            if (!blocking)
            {
                flags |= LOCKFILE_FAIL_IMMEDIATELY;
            }
            if (!shared)
            {
                flags |= LOCKFILE_EXCLUSIVE_LOCK;
            }
            int result = LockFileEx(fs.get_SafeFileHandle(), flags, 0, (int)size, (int)(size >> 32), o);
            if (result == 0)
            {
                int error = Marshal.GetLastWin32Error();
                if (!blocking && error == ERROR_LOCK_VIOLATION)
                {
                    return NO_LOCK;
                }
                throw new IOException("Lock failed");
            }
            return LOCKED;
        }
        else
        {
            try
            {
                if (false) throw new cli.System.ArgumentOutOfRangeException();
                for (;;)
                {
                    try
                    {
                        if (false) throw new cli.System.IO.IOException();
                        if (false) throw new cli.System.ObjectDisposedException("");
                        fs.Lock(pos, size);
                        return shared ? RET_EX_LOCK : LOCKED;
                    }
                    catch (cli.System.IO.IOException x)
                    {
                        if (!blocking)
                        {
                            return NO_LOCK;
                        }
                        cli.System.Threading.Thread.Sleep(100);
                    }
                    catch (cli.System.ObjectDisposedException x)
                    {
                        throw new IOException(x.getMessage());
                    }
                }
            }
            catch (cli.System.ArgumentOutOfRangeException x)
            {
                throw new IOException(x.getMessage());
            }
        }
    }

    @cli.System.Security.SecuritySafeCriticalAttribute.Annotation
    void release(FileDescriptor fd, long pos, long size) throws IOException {
        FileStream fs = (FileStream)fd.getStream();
        if (WINDOWS)
        {
            int ERROR_NOT_LOCKED = 158;
            OVERLAPPED o = new OVERLAPPED();
            o.OffsetLow = (int)pos;
            o.OffsetHigh = (int)(pos >> 32);
            int result = UnlockFileEx(fs.get_SafeFileHandle(), 0, (int)size, (int)(size >> 32), o);
            if (result == 0 && Marshal.GetLastWin32Error() != ERROR_NOT_LOCKED)
            {
                throw new IOException("Release failed");
            }
        }
        else
        {
            try
            {
                if (false) throw new cli.System.ArgumentOutOfRangeException();
                if (false) throw new cli.System.IO.IOException();
                if (false) throw new cli.System.ObjectDisposedException("");
                fs.Unlock(pos, size);
            }
            catch (cli.System.IO.IOException x)
            {
                if (!NotLockedHack.isErrorNotLocked(x))
                {
                    throw new IOException(x.getMessage());
                }
            }
            catch (cli.System.ArgumentOutOfRangeException
                | cli.System.ObjectDisposedException x)
            {
                throw new IOException(x.getMessage());
            }
        }
    }

    static class NotLockedHack {
        private static String msg;
        static {
            try {
                File tmp = File.createTempFile("lock", null);
                try (FileStream fs = new FileStream(tmp.getPath(), cli.System.IO.FileMode.wrap(cli.System.IO.FileMode.Create))) {
                    try {
                        if (false) throw new cli.System.IO.IOException();
                        fs.Unlock(0, 1);
                    } catch (cli.System.IO.IOException x) {
                        msg = x.get_Message();
                    }
                }
                tmp.delete();
            } catch (Throwable _) {
            }
        }
        static boolean isErrorNotLocked(cli.System.IO.IOException x) {
            return x.get_Message().equals(msg);
        }
    }


    void close(FileDescriptor fd) throws IOException {
        fd.close();
    }

    FileDescriptor duplicateForMapping(FileDescriptor fd) throws IOException {
        // we return a dummy FileDescriptor, because we don't need it for mapping operations
        // and we don't want the original to be closed
        return new FileDescriptor();
    }

    @DllImportAttribute.Annotation(value="kernel32", SetLastError=true)
    private static native int LockFileEx(SafeFileHandle hFile, int dwFlags, int dwReserved, int nNumberOfBytesToLockLow, int nNumberOfBytesToLockHigh, OVERLAPPED lpOverlapped);

    @DllImportAttribute.Annotation(value="kernel32", SetLastError=true)
    private static native int UnlockFileEx(SafeFileHandle hFile, int dwReserved, int nNumberOfBytesToUnlockLow, int nNumberOfBytesToUnlockHigh, OVERLAPPED lpOverlapped);
}