summaryrefslogtreecommitdiff
path: root/libjava/gnu/java/nio/channels/natFileChannelWin32.cc
blob: ab238e6234cd708fa2eef7711fd64390a755fd68 (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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// natFileChannelImplWin32.cc - Native part of FileChannelImpl class.

/* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004  Free Software 
   Foundation, Inc.

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

// FIXME: In order to support interrupting of IO operations, we
// need to change to use the windows asynchronous IO functions

#include <config.h>
#include <platform.h>

#include <gcj/cni.h>
#include <gcj/javaprims.h>
#include <jvm.h>

#include <stdio.h>

#include <gnu/gcj/RawData.h>
#include <gnu/java/nio/FileLockImpl.h>
#include <gnu/java/nio/channels/FileChannelImpl.h>
#include <java/io/FileNotFoundException.h>
#include <java/io/IOException.h>
#include <java/io/SyncFailedException.h>
#include <java/io/InterruptedIOException.h>
#include <java/io/EOFException.h>
#include <java/lang/ArrayIndexOutOfBoundsException.h>
#include <java/lang/NullPointerException.h>
#include <java/lang/System.h>
#include <java/lang/String.h>
#include <java/lang/Thread.h>
#include <java/nio/ByteBuffer.h>
#include <java/nio/MappedByteBufferImpl.h>
#include <java/nio/channels/FileChannel.h>
#include <java/nio/channels/FileLock.h>
#include <gnu/java/nio/channels/FileChannelImpl.h>

using gnu::gcj::RawData;
using java::io::IOException;
using java::nio::MappedByteBufferImpl;
using java::io::InterruptedIOException;
using java::io::FileNotFoundException;
using java::lang::ArrayIndexOutOfBoundsException;
using gnu::java::nio::channels::FileChannelImpl;

#undef STRICT

static bool testCanUseGetHandleInfo()
{
  /* Test to see whether GetHandleInformation can be used
     for console input or screen buffers. This is better
     a kludgy OS version check. */
  DWORD dwFlags;
  return GetHandleInformation (GetStdHandle (STD_INPUT_HANDLE),
    &dwFlags) != 0;
}

// FIXME: casting a FILE (pointer) to a jint will not work on Win64 --
//        we should be using gnu.gcj.RawData's.

void
FileChannelImpl::init(void)
{
  in = new FileChannelImpl((jint)(GetStdHandle (STD_INPUT_HANDLE)),
			   FileChannelImpl::READ);
  out = new FileChannelImpl((jint)(GetStdHandle (STD_OUTPUT_HANDLE)),
			    FileChannelImpl::WRITE);
  err = new FileChannelImpl((jint)(GetStdHandle (STD_ERROR_HANDLE)),
			    FileChannelImpl::WRITE);
}

#if 0
FileChannelImpl::sync (void) {
  if (! FlushFileBuffers ((HANDLE)fd))
  {
    DWORD dwErrorCode = GetLastError ();
    throw new SyncFailedException (_Jv_WinStrError (dwErrorCode));
  }
}
#endif

jint
FileChannelImpl::open (jstring path, jint jflags) {

  HANDLE handle = NULL;
  DWORD access = 0;
  DWORD create = OPEN_EXISTING;
  
  JV_TEMP_STRING_WIN32(cpath, path)

  JvAssert((jflags & READ) || (jflags & WRITE));

  if ((jflags & READ) && (jflags & WRITE))
    {
      access = GENERIC_READ | GENERIC_WRITE;
      if (jflags & EXCL)
        create = CREATE_NEW; // this will raise error if file exists.
      else
        create = OPEN_ALWAYS; // equivalent to O_CREAT
    }
  else if (jflags & READ)
    {
      access = GENERIC_READ;
      create = OPEN_EXISTING; // ignore EXCL
    }
  else
    { 
      access = GENERIC_WRITE;
      if (jflags & EXCL)
        create = CREATE_NEW;
      else if (jflags & APPEND)
        create = OPEN_ALWAYS;
      else
        create = CREATE_ALWAYS;
    }

  handle = CreateFile(cpath, access, FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL, create, 0, NULL);

  if (handle == INVALID_HANDLE_VALUE)
    {
       DWORD dwErrorCode = GetLastError ();
       throw new FileNotFoundException (_Jv_WinStrError (cpath, dwErrorCode));
    }

  // For APPEND mode, move the file pointer to the end of the file.
  if (jflags & APPEND)
    {
      DWORD low = SetFilePointer (handle, 0, NULL, FILE_END);
      if ((low == (DWORD) 0xffffffff) && (GetLastError () != NO_ERROR)) 
      {
        DWORD dwErrorCode = GetLastError ();
        throw new FileNotFoundException (_Jv_WinStrError (cpath, dwErrorCode));
      }
    }
    
  // Make this handle non-inheritable so that child
  // processes don't inadvertently prevent us from
  // closing this file.
  _Jv_platform_close_on_exec (handle);

  return (jint) handle;
}

void
FileChannelImpl::write (jint b)
{
  DWORD bytesWritten;
  jbyte buf = (jbyte)b;

  if (WriteFile ((HANDLE)fd, &buf, 1, &bytesWritten, NULL))
    {
      if (::java::lang::Thread::interrupted())
        {
          InterruptedIOException *iioe = new InterruptedIOException (JvNewStringLatin1 ("write interrupted"));
          iioe->bytesTransferred = bytesWritten;
    throw iioe;
        }
      if (bytesWritten != 1)
        _Jv_ThrowIOException ();
    }
  else
    _Jv_ThrowIOException ();
  // FIXME: loop until bytesWritten == 1
}

void
FileChannelImpl::write(jbyteArray b, jint offset, jint len)
{
  if (! b)
    throw new ::java::lang::NullPointerException;
  if(offset < 0 || len < 0 || offset + len > JvGetArrayLength (b))
    throw new ArrayIndexOutOfBoundsException;

  jbyte *buf = elements (b) + offset;
  DWORD bytesWritten;

  if (WriteFile ((HANDLE)fd, buf, len, &bytesWritten, NULL))
    {
      if (::java::lang::Thread::interrupted())
        {
          InterruptedIOException *iioe = new InterruptedIOException (JvNewStringLatin1 ("write interrupted"));
          iioe->bytesTransferred = bytesWritten;
          throw iioe;
        }
    }
  else
    _Jv_ThrowIOException ();
  // FIXME: loop until bytesWritten == len
}

void
FileChannelImpl::implCloseChannel (void)
{
  HANDLE save = (HANDLE)fd;
  fd = (jint)INVALID_HANDLE_VALUE;
  if (! CloseHandle (save))
    _Jv_ThrowIOException ();
}

void
FileChannelImpl::implTruncate (jlong size)
{
  LONG liOrigFilePointer;
  LONG liNewFilePointer;
  LONG liEndFilePointer;

  // Get the original file pointer.
  if (SetFilePointer((HANDLE) fd, (LONG) 0, &liOrigFilePointer,
         FILE_CURRENT) != (BOOL) 0
      && (GetLastError() != NO_ERROR))
    _Jv_ThrowIOException ();

  // Get the length of the file.
  if (SetFilePointer((HANDLE) fd, (LONG) 0, &liEndFilePointer,
         FILE_END) != (BOOL) 0
      && (GetLastError() != NO_ERROR))
    _Jv_ThrowIOException ();

  if ((jlong)liEndFilePointer == size)
    {
      // Restore the file pointer.
      if (liOrigFilePointer != liEndFilePointer)
  {
    if (SetFilePointer((HANDLE) fd, liOrigFilePointer, &liNewFilePointer,
           FILE_BEGIN) != (BOOL) 0
        && (GetLastError() != NO_ERROR))
      _Jv_ThrowIOException ();
  }
      return;
    }

  // Seek to the new end of file.
  if (SetFilePointer((HANDLE) fd, (LONG) size, &liNewFilePointer,
         FILE_BEGIN) != (BOOL) 0
      && (GetLastError() != NO_ERROR))
    _Jv_ThrowIOException ();

  // Truncate the file at this point.
  if (SetEndOfFile((HANDLE) fd) != (BOOL) 0 && (GetLastError() != NO_ERROR))
    _Jv_ThrowIOException ();

  if (liOrigFilePointer < liNewFilePointer)
    {
      // Restore the file pointer.
      if (SetFilePointer((HANDLE) fd, liOrigFilePointer, &liNewFilePointer,
        FILE_BEGIN) != (BOOL) 0
        && (GetLastError() != NO_ERROR))
        _Jv_ThrowIOException ();
    }
}

void
FileChannelImpl::seek (jlong newPos)
{
  LONG high = pos >> 32;
  DWORD low = SetFilePointer ((HANDLE)fd, (DWORD)(0xffffffff & newPos), &high, FILE_BEGIN);
  if ((low == 0xffffffff) && (GetLastError () != NO_ERROR))
    _Jv_ThrowIOException ();
}

jlong
FileChannelImpl::implPosition (void)
{
  LONG high = 0;
  DWORD low = SetFilePointer ((HANDLE)fd, 0, &high, FILE_CURRENT);
  if ((low == 0xffffffff) && (GetLastError() != NO_ERROR))
    _Jv_ThrowIOException ();
  return (((jlong)high) << 32L) | (jlong)low;
}

jlong
FileChannelImpl::size (void)
{
  DWORD high;
  DWORD low;

  low = GetFileSize ((HANDLE)fd, &high);
  // FIXME: Error checking
  return (((jlong)high) << 32L) | (jlong)low;
}

jint
FileChannelImpl::read (void)
{
  CHAR buf;
  DWORD read;

  if (! ReadFile ((HANDLE)fd, &buf, 1, &read, NULL))
    {
      if (GetLastError () == ERROR_BROKEN_PIPE)
        return -1;
      else
        _Jv_ThrowIOException ();
    }

  if (! read)
    return -1;
  else
    return (jint)(buf & 0xff);
}

jint
FileChannelImpl::read (jbyteArray buffer, jint offset, jint count)
{
  if (! buffer)
    throw new ::java::lang::NullPointerException;

  jsize bsize = JvGetArrayLength (buffer);
  if (offset < 0 || count < 0 || offset + count > bsize)
    throw new ArrayIndexOutOfBoundsException;

  // Must return 0 if an attempt is made to read 0 bytes.
  if (count == 0)
    return 0;

  jbyte *bytes = elements (buffer) + offset;

  DWORD read;
  if (! ReadFile((HANDLE)fd, bytes, count, &read, NULL))
    {
      if (GetLastError () == ERROR_BROKEN_PIPE)
        return -1;
      else
        _Jv_ThrowIOException ();
    }

  if (read == 0) return -1;

  return (jint)read;
}

jint
FileChannelImpl::available (void)
{
  // FIXME:
  return size() - position();
}

jboolean
FileChannelImpl::lock (jlong pos, jlong len, jboolean shared, jboolean wait)
{
  DWORD flags = 0;
  OVERLAPPED ovlpd;

  ZeroMemory(&ovlpd,sizeof(OVERLAPPED));

  if(!shared)
    flags |= LOCKFILE_EXCLUSIVE_LOCK;
  if(!wait)
    flags |= LOCKFILE_FAIL_IMMEDIATELY;

  ovlpd.Offset = (DWORD)pos;
  ovlpd.OffsetHigh = pos>>32;

  DWORD lenlow = (DWORD)len;
  DWORD lenhigh = len>>32;

  BOOL ret = LockFileEx((HANDLE)fd,flags,0,lenlow,lenhigh,&ovlpd);

  if(ret==ERROR_IO_PENDING && !shared && wait)
    ret = GetOverlappedResult((HANDLE)fd,&ovlpd,NULL,wait);

  if(!ret)
    _Jv_ThrowIOException(GetLastError());

  return true;
}

void
FileChannelImpl::unlock (jlong pos, jlong len)
{
  OVERLAPPED ovlpd;

  ZeroMemory(&ovlpd,sizeof(OVERLAPPED));

  ovlpd.Offset = (DWORD)pos;
  ovlpd.OffsetHigh = pos>>32;

  DWORD lenlow = (DWORD)len;
  DWORD lenhigh = len>>32;

  BOOL ret = UnlockFileEx((HANDLE)fd,0,lenlow,lenhigh,&ovlpd);

  if(!ret)
    _Jv_ThrowIOException(GetLastError());
}

java::nio::MappedByteBuffer *
FileChannelImpl::mapImpl (jchar mmode, jlong position, jint size)
{
  SYSTEM_INFO siSysInfo;
  GetSystemInfo(&siSysInfo); 
  DWORD page_size = siSysInfo.dwPageSize;
  jlong offset = position & ~(page_size-1);
  jint align = position - offset;
  jlong high = position + size;
  jlong max_size;
  if (mmode == '+')
    max_size = high - offset;
  else
    max_size = 0;
  DWORD access, protect;
  if (mmode == 'r')
    {
      access = FILE_MAP_READ;
      protect = PAGE_READONLY;
    }
  else if (mmode == '+')
    {
      access = FILE_MAP_WRITE;
      protect = PAGE_READWRITE;
    }
  else
    {
      access = FILE_MAP_COPY;
      protect = PAGE_WRITECOPY;
    }
  HANDLE hFileMapping = CreateFileMapping((HANDLE) fd,
					  (LPSECURITY_ATTRIBUTES) NULL,
					  protect,
					  (DWORD) (max_size >> 32),
					  (DWORD) max_size,
					  (LPCTSTR) NULL);
  if (hFileMapping == NULL)
    throw new IOException();
  void *ptr = MapViewOfFile(hFileMapping, access,
			    (DWORD) (offset >> 32), (DWORD) offset,
			    (SIZE_T) (high - offset));
  if (ptr == NULL)
    throw new IOException();
  MappedByteBufferImpl *buf
    = new MappedByteBufferImpl((RawData *) ((char *) ptr + align),
			       size, mode == 'r');
  buf->implPtr = reinterpret_cast<RawData*> (ptr);
  buf->implLen = (jlong) (size_t) hFileMapping;
  return buf;
}

void
MappedByteBufferImpl::unmapImpl ()
{
  UnmapViewOfFile((void*)implPtr);
  CloseHandle((HANDLE) (size_t) implLen);
}

void
MappedByteBufferImpl::loadImpl ()
{
}

jboolean
MappedByteBufferImpl::isLoadedImpl ()
{
  return true;
}

void
MappedByteBufferImpl::forceImpl ()
{
}