io_util_md.c 18.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * 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.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 */

#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
#include "io_util.h"
#include "io_util_md.h"
#include <stdio.h>

#include <wchar.h>
#include <io.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <wincon.h>

43
static DWORD MAX_INPUT_EVENTS = 2000;
D
duke 已提交
44 45 46 47 48 49 50 51 52 53 54

/* If this returns NULL then an exception is pending */
WCHAR*
fileToNTPath(JNIEnv *env, jobject file, jfieldID id) {
    jstring path = NULL;
    if (file != NULL) {
        path = (*env)->GetObjectField(env, file, id);
    }
    return pathToNTPath(env, path, JNI_FALSE);
}

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/* Returns the working directory for the given drive, or NULL */
WCHAR*
currentDir(int di) {
    UINT dt;
    WCHAR root[4];
    // verify drive is valid as _wgetdcwd in the VC++ 2010 runtime
    // library does not handle invalid drives.
    root[0] = L'A' + (WCHAR)(di - 1);
    root[1] = L':';
    root[2] = L'\\';
    root[3] = L'\0';
    dt = GetDriveTypeW(root);
    if (dt == DRIVE_UNKNOWN || dt == DRIVE_NO_ROOT_DIR) {
        return NULL;
    } else {
        return _wgetdcwd(di, NULL, MAX_PATH);
    }
}

D
duke 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/* We cache the length of current working dir here to avoid
   calling _wgetcwd() every time we need to resolve a relative
   path. This piece of code needs to be revisited if chdir
   makes its way into java runtime.
*/

int
currentDirLength(const WCHAR* ps, int pathlen) {
    WCHAR *dir;
    if (pathlen > 2 && ps[1] == L':' && ps[2] != L'\\') {
        //drive-relative
        WCHAR d = ps[0];
        int dirlen = 0;
        int di = 0;
        if ((d >= L'a') && (d <= L'z')) di = d - L'a' + 1;
        else if ((d >= L'A') && (d <= L'Z')) di = d - L'A' + 1;
        else return 0; /* invalid drive name. */
91
        dir = currentDir(di);
D
duke 已提交
92
        if (dir != NULL){
93
            dirlen = (int)wcslen(dir);
D
duke 已提交
94 95 96 97 98 99 100 101 102 103
            free(dir);
        }
        return dirlen;
    } else {
        static int curDirLenCached = -1;
        //relative to both drive and directory
        if (curDirLenCached == -1) {
            int dirlen = -1;
            dir = _wgetcwd(NULL, MAX_PATH);
            if (dir != NULL) {
104
                curDirLenCached = (int)wcslen(dir);
D
duke 已提交
105 106 107 108 109 110 111
                free(dir);
            }
        }
        return curDirLenCached;
    }
}

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
/*
  The "abpathlen" is the size of the buffer needed by _wfullpath. If the
  "path" is a relative path, it is "the length of the current dir" + "the
  length of the path", if it's "absolute" already, it's the same as
  pathlen which is the length of "path".
 */
WCHAR* prefixAbpath(const WCHAR* path, int pathlen, int abpathlen) {
    WCHAR* pathbuf = NULL;
    WCHAR* abpath = NULL;

    abpathlen += 10;  //padding
    abpath = (WCHAR*)malloc(abpathlen * sizeof(WCHAR));
    if (abpath) {
        /* Collapse instances of "foo\.." and ensure absoluteness before
           going down to prefixing.
        */
        if (_wfullpath(abpath, path, abpathlen)) {
            pathbuf = getPrefixed(abpath, abpathlen);
        } else {
            /* _wfullpath fails if the pathlength exceeds 32k wchar.
               Instead of doing more fancy things we simply copy the
               ps into the return buffer, the subsequent win32 API will
               probably fail with FileNotFoundException, which is expected
            */
            pathbuf = (WCHAR*)malloc((pathlen + 6) * sizeof(WCHAR));
            if (pathbuf != 0) {
                wcscpy(pathbuf, path);
            }
        }
        free(abpath);
    }
    return pathbuf;
}

D
duke 已提交
146 147 148 149 150
/* If this returns NULL then an exception is pending */
WCHAR*
pathToNTPath(JNIEnv *env, jstring path, jboolean throwFNFE) {
    int pathlen = 0;
    WCHAR *pathbuf = NULL;
151 152
    int max_path = 248; /* CreateDirectoryW() has the limit of 248 */

D
duke 已提交
153
    WITH_UNICODE_STRING(env, path, ps) {
154
        pathlen = (int)wcslen(ps);
D
duke 已提交
155 156 157
        if (pathlen != 0) {
            if (pathlen > 2 &&
                (ps[0] == L'\\' && ps[1] == L'\\' ||   //UNC
158 159
                 ps[1] == L':' && ps[2] == L'\\'))     //absolute
            {
D
duke 已提交
160
                 if (pathlen > max_path - 1) {
161
                     pathbuf = prefixAbpath(ps, pathlen, pathlen);
D
duke 已提交
162 163 164 165 166 167 168 169 170 171 172
                 } else {
                     pathbuf = (WCHAR*)malloc((pathlen + 6) * sizeof(WCHAR));
                     if (pathbuf != 0) {
                         wcscpy(pathbuf, ps);
                     }
                 }
            } else {
                /* If the path came in as a relative path, need to verify if
                   its absolute form is bigger than max_path or not, if yes
                   need to (1)convert it to absolute and (2)prefix. This is
                   obviously a burden to all relative paths (The current dir/len
173
                   for "drive & directory" relative path is cached, so we only
D
duke 已提交
174 175 176 177 178 179 180 181 182 183
                   calculate it once but for "drive-relative path we call
                   _wgetdcwd() and wcslen() everytime), but a hit we have
                   to take if we want to support relative path beyond max_path.
                   There is no way to predict how long the absolute path will be
                   (therefor allocate the sufficient memory block) before calling
                   _wfullpath(), we have to get the length of "current" dir first.
                */
                WCHAR *abpath = NULL;
                int dirlen = currentDirLength(ps, pathlen);
                if (dirlen + pathlen + 1 > max_path - 1) {
184
                    pathbuf = prefixAbpath(ps, pathlen, dirlen + pathlen);
D
duke 已提交
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
                } else {
                    pathbuf = (WCHAR*)malloc((pathlen + 6) * sizeof(WCHAR));
                    if (pathbuf != 0) {
                        wcscpy(pathbuf, ps);
                    }
                }
            }
        }
    } END_UNICODE_STRING(env, ps);

    if (pathlen == 0) {
        if (throwFNFE == JNI_TRUE) {
            throwFileNotFoundException(env, path);
            return NULL;
        } else {
            pathbuf = (WCHAR*)malloc(sizeof(WCHAR));
            pathbuf[0] = L'\0';
        }
    }
    if (pathbuf == 0) {
        JNU_ThrowOutOfMemoryError(env, 0);
        return NULL;
    }
    return pathbuf;
}

211
FD
D
duke 已提交
212 213 214 215
winFileHandleOpen(JNIEnv *env, jstring path, int flags)
{
    const DWORD access =
        (flags & O_WRONLY) ?  GENERIC_WRITE :
216
        (flags & O_RDWR)   ? (GENERIC_READ | GENERIC_WRITE) :
D
duke 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        GENERIC_READ;
    const DWORD sharing =
        FILE_SHARE_READ | FILE_SHARE_WRITE;
    const DWORD disposition =
        /* Note: O_TRUNC overrides O_CREAT */
        (flags & O_TRUNC) ? CREATE_ALWAYS :
        (flags & O_CREAT) ? OPEN_ALWAYS   :
        OPEN_EXISTING;
    const DWORD  maybeWriteThrough =
        (flags & (O_SYNC | O_DSYNC)) ?
        FILE_FLAG_WRITE_THROUGH :
        FILE_ATTRIBUTE_NORMAL;
    const DWORD maybeDeleteOnClose =
        (flags & O_TEMPORARY) ?
        FILE_FLAG_DELETE_ON_CLOSE :
        FILE_ATTRIBUTE_NORMAL;
    const DWORD flagsAndAttributes = maybeWriteThrough | maybeDeleteOnClose;
    HANDLE h = NULL;

D
dxu 已提交
236 237 238 239
    WCHAR *pathbuf = pathToNTPath(env, path, JNI_TRUE);
    if (pathbuf == NULL) {
        /* Exception already pending */
        return -1;
D
duke 已提交
240
    }
D
dxu 已提交
241 242 243 244 245 246 247 248 249 250
    h = CreateFileW(
        pathbuf,            /* Wide char path name */
        access,             /* Read and/or write permission */
        sharing,            /* File sharing flags */
        NULL,               /* Security attributes */
        disposition,        /* creation disposition */
        flagsAndAttributes, /* flags and attributes */
        NULL);
    free(pathbuf);

D
duke 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    if (h == INVALID_HANDLE_VALUE) {
        int error = GetLastError();
        if (error == ERROR_TOO_MANY_OPEN_FILES) {
            JNU_ThrowByName(env, JNU_JAVAIOPKG "IOException",
                            "Too many open files");
            return -1;
        }
        throwFileNotFoundException(env, path);
        return -1;
    }
    return (jlong) h;
}

void
fileOpen(JNIEnv *env, jobject this, jstring path, jfieldID fid, int flags)
{
267
    FD h = winFileHandleOpen(env, path, flags);
D
duke 已提交
268 269 270 271 272 273 274 275 276
    if (h >= 0) {
        SET_FD(this, h, fid);
    }
}

/* These are functions that use a handle fd instead of the
   old C style int fd as is used in HPI layer */

static int
277
handleNonSeekAvailable(FD, long *);
D
duke 已提交
278
static int
279
handleStdinAvailable(FD, long *);
D
duke 已提交
280 281

int
282
handleAvailable(FD fd, jlong *pbytes) {
D
duke 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    HANDLE h = (HANDLE)fd;
    DWORD type = 0;

    type = GetFileType(h);
    /* Handle is for keyboard or pipe */
    if (type == FILE_TYPE_CHAR || type == FILE_TYPE_PIPE) {
        int ret;
        long lpbytes;
        HANDLE stdInHandle = GetStdHandle(STD_INPUT_HANDLE);
        if (stdInHandle == h) {
            ret = handleStdinAvailable(fd, &lpbytes); /* keyboard */
        } else {
            ret = handleNonSeekAvailable(fd, &lpbytes); /* pipe */
        }
        (*pbytes) = (jlong)(lpbytes);
        return ret;
    }
    /* Handle is for regular file */
    if (type == FILE_TYPE_DISK) {
302 303 304 305 306
        jlong current, end;

        LARGE_INTEGER filesize;
        current = handleLseek(fd, 0, SEEK_CUR);
        if (current < 0) {
D
duke 已提交
307 308
            return FALSE;
        }
309
        if (GetFileSizeEx(h, &filesize) == 0) {
D
duke 已提交
310 311
            return FALSE;
        }
312
        end = long_to_jlong(filesize.QuadPart);
D
duke 已提交
313 314 315 316 317 318 319
        *pbytes = end - current;
        return TRUE;
    }
    return FALSE;
}

static int
320
handleNonSeekAvailable(FD fd, long *pbytes) {
D
duke 已提交
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
    /* This is used for available on non-seekable devices
     * (like both named and anonymous pipes, such as pipes
     *  connected to an exec'd process).
     * Standard Input is a special case.
     *
     */
    HANDLE han;

    if ((han = (HANDLE) fd) == INVALID_HANDLE_VALUE) {
        return FALSE;
    }

    if (! PeekNamedPipe(han, NULL, 0, NULL, pbytes, NULL)) {
        /* PeekNamedPipe fails when at EOF.  In that case we
         * simply make *pbytes = 0 which is consistent with the
         * behavior we get on Solaris when an fd is at EOF.
         * The only alternative is to raise and Exception,
         * which isn't really warranted.
         */
        if (GetLastError() != ERROR_BROKEN_PIPE) {
            return FALSE;
        }
        *pbytes = 0;
    }
    return TRUE;
}

static int
349
handleStdinAvailable(FD fd, long *pbytes) {
D
duke 已提交
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
    HANDLE han;
    DWORD numEventsRead = 0;    /* Number of events read from buffer */
    DWORD numEvents = 0;        /* Number of events in buffer */
    DWORD i = 0;                /* Loop index */
    DWORD curLength = 0;        /* Position marker */
    DWORD actualLength = 0;     /* Number of bytes readable */
    BOOL error = FALSE;         /* Error holder */
    INPUT_RECORD *lpBuffer;     /* Pointer to records of input events */
    DWORD bufferSize = 0;

    if ((han = GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) {
        return FALSE;
    }

    /* Construct an array of input records in the console buffer */
    error = GetNumberOfConsoleInputEvents(han, &numEvents);
    if (error == 0) {
        return handleNonSeekAvailable(fd, pbytes);
    }

    /* lpBuffer must fit into 64K or else PeekConsoleInput fails */
    if (numEvents > MAX_INPUT_EVENTS) {
        numEvents = MAX_INPUT_EVENTS;
    }

    bufferSize = numEvents * sizeof(INPUT_RECORD);
    if (bufferSize == 0)
        bufferSize = 1;
    lpBuffer = malloc(bufferSize);
    if (lpBuffer == NULL) {
        return FALSE;
    }

    error = PeekConsoleInput(han, lpBuffer, numEvents, &numEventsRead);
    if (error == 0) {
        free(lpBuffer);
        return FALSE;
    }

    /* Examine input records for the number of bytes available */
    for(i=0; i<numEvents; i++) {
        if (lpBuffer[i].EventType == KEY_EVENT) {
            KEY_EVENT_RECORD *keyRecord = (KEY_EVENT_RECORD *)
                                          &(lpBuffer[i].Event);
            if (keyRecord->bKeyDown == TRUE) {
                CHAR *keyPressed = (CHAR *) &(keyRecord->uChar);
                curLength++;
                if (*keyPressed == '\r')
                    actualLength = curLength;
            }
        }
    }
    if(lpBuffer != NULL)
        free(lpBuffer);
    *pbytes = (long) actualLength;
    return TRUE;
}

/*
 * This is documented to succeed on read-only files, but Win32's
 * FlushFileBuffers functions fails with "access denied" in such a
 * case.  So we only signal an error if the error is *not* "access
 * denied".
 */

415 416
int
handleSync(FD fd) {
D
duke 已提交
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
    /*
     * From the documentation:
     *
     *     On Windows NT, the function FlushFileBuffers fails if hFile
     *     is a handle to console output. That is because console
     *     output is not buffered. The function returns FALSE, and
     *     GetLastError returns ERROR_INVALID_HANDLE.
     *
     * On the other hand, on Win95, it returns without error.  I cannot
     * assume that 0, 1, and 2 are console, because if someone closes
     * System.out and then opens a file, they might get file descriptor
     * 1.  An error on *that* version of 1 should be reported, whereas
     * an error on System.out (which was the original 1) should be
     * ignored.  So I use isatty() to ensure that such an error was due
     * to this bogosity, and if it was, I ignore the error.
     */

    HANDLE handle = (HANDLE)fd;

    if (!FlushFileBuffers(handle)) {
        if (GetLastError() != ERROR_ACCESS_DENIED) {    /* from winerror.h */
            return -1;
        }
    }
    return 0;
}


int
446
handleSetLength(FD fd, jlong length) {
D
duke 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460
    HANDLE h = (HANDLE)fd;
    long high = (long)(length >> 32);
    DWORD ret;

    if (h == (HANDLE)(-1)) return -1;
    ret = SetFilePointer(h, (long)(length), &high, FILE_BEGIN);
    if (ret == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
        return -1;
    }
    if (SetEndOfFile(h) == FALSE) return -1;
    return 0;
}

JNIEXPORT
461
jint
462
handleRead(FD fd, void *buf, jint len)
D
duke 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
{
    DWORD read = 0;
    BOOL result = 0;
    HANDLE h = (HANDLE)fd;
    if (h == INVALID_HANDLE_VALUE) {
        return -1;
    }
    result = ReadFile(h,          /* File handle to read */
                      buf,        /* address to put data */
                      len,        /* number of bytes to read */
                      &read,      /* number of bytes read */
                      NULL);      /* no overlapped struct */
    if (result == 0) {
        int error = GetLastError();
        if (error == ERROR_BROKEN_PIPE) {
            return 0; /* EOF */
        }
        return -1;
    }
482
    return (jint)read;
D
duke 已提交
483 484
}

485
static jint writeInternal(FD fd, const void *buf, jint len, jboolean append)
D
duke 已提交
486 487 488 489 490
{
    BOOL result = 0;
    DWORD written = 0;
    HANDLE h = (HANDLE)fd;
    if (h != INVALID_HANDLE_VALUE) {
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        OVERLAPPED ov;
        LPOVERLAPPED lpOv;
        if (append == JNI_TRUE) {
            ov.Offset = (DWORD)0xFFFFFFFF;
            ov.OffsetHigh = (DWORD)0xFFFFFFFF;
            ov.hEvent = NULL;
            lpOv = &ov;
        } else {
            lpOv = NULL;
        }
        result = WriteFile(h,                /* File handle to write */
                           buf,              /* pointers to the buffers */
                           len,              /* number of bytes to write */
                           &written,         /* receives number of bytes written */
                           lpOv);            /* overlapped struct */
D
duke 已提交
506 507 508 509
    }
    if ((h == INVALID_HANDLE_VALUE) || (result == 0)) {
        return -1;
    }
510
    return (jint)written;
511 512
}

513
jint handleWrite(FD fd, const void *buf, jint len) {
514 515 516
    return writeInternal(fd, buf, len, JNI_FALSE);
}

517
jint handleAppend(FD fd, const void *buf, jint len) {
518
    return writeInternal(fd, buf, len, JNI_TRUE);
D
duke 已提交
519 520 521 522 523 524 525 526
}

jint
handleClose(JNIEnv *env, jobject this, jfieldID fid)
{
    FD fd = GET_FD(this, fid);
    HANDLE h = (HANDLE)fd;

527
    if (h == INVALID_HANDLE_VALUE) {
D
duke 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        return 0;
    }

    /* Set the fd to -1 before closing it so that the timing window
     * of other threads using the wrong fd (closed but recycled fd,
     * that gets re-opened with some other filename) is reduced.
     * Practically the chance of its occurance is low, however, we are
     * taking extra precaution over here.
     */
    SET_FD(this, -1, fid);

    if (CloseHandle(h) == 0) { /* Returns zero on failure */
        JNU_ThrowIOExceptionWithLastError(env, "close failed");
    }
    return 0;
}

jlong
546
handleLseek(FD fd, jlong offset, jint whence)
D
duke 已提交
547
{
548
    LARGE_INTEGER pos, distance;
D
duke 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    DWORD lowPos = 0;
    long highPos = 0;
    DWORD op = FILE_CURRENT;
    HANDLE h = (HANDLE)fd;

    if (whence == SEEK_END) {
        op = FILE_END;
    }
    if (whence == SEEK_CUR) {
        op = FILE_CURRENT;
    }
    if (whence == SEEK_SET) {
        op = FILE_BEGIN;
    }

564 565 566
    distance.QuadPart = offset;
    if (SetFilePointerEx(h, distance, &pos, op) == 0) {
        return -1;
D
duke 已提交
567
    }
568
    return long_to_jlong(pos.QuadPart);
D
duke 已提交
569
}
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

size_t
getLastErrorString(char *buf, size_t len)
{
    DWORD errval;
    if (len > 0) {
        if ((errval = GetLastError()) != 0) {
            // DOS error
            size_t n = (size_t)FormatMessage(
                FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                errval,
                0,
                buf,
                (DWORD)len,
                NULL);
            if (n > 3) {
                // Drop final '.', CR, LF
                if (buf[n - 1] == '\n') n--;
                if (buf[n - 1] == '\r') n--;
                if (buf[n - 1] == '.') n--;
                buf[n] = '\0';
            }
            return n;
        }

        if (errno != 0) {
            // C runtime error that has no corresponding DOS error code
            const char *err = strerror(errno);
            size_t n = strlen(err);
            if (n >= len)
                n = len - 1;

            strncpy(buf, err, n);
            buf[n] = '\0';
            return n;
        }
    }

    return 0;
}