Kevin Herron
Kevin Herron

Reputation: 6985

Java JNI call to CreateFile always returns INVALID_HANDLE_VALUE with ERROR_ACCESS_DENIED

EDIT I seem to have gotten one step farther. I neglected to mention that this was a directory I was dealing with here. I needed to pass the FILE_FLAG_BACKUP_SEMANTICS to CreateFile. Unfortunately I've hit another road block... GetFinalPathNameByHandle seems to return only "\" as the final path...

I am calling the following function using JNI but the file handle is always INVALID_HANDLE_VALUE with GetLastError() returning 5 (ERROR_ACCESS_DENIED). I'm sure the file exists (I'm printing out the path right now to verify when an error occurs).

I'm using Windows 7, running the jar file from cmd.exe opened using Run As Administrator, and I've also turned off UAC+rebooted to see if that helped.

Anybody got any ideas?

JNIEXPORT jstring JNICALL Java_com_inductiveautomation_linkmgr_LinkTool_getLinkTarget
  (JNIEnv *env, jclass clazz, jstring path)
{
    TCHAR Path[BUFSIZE];
    HANDLE hFile;
    DWORD dwRet;

    LPCWSTR nativePath = (*env)->GetStringChars(env, path, 0);

    hFile = CreateFileW(nativePath,            // file to open
                        GENERIC_READ,          // open for reading
                        FILE_SHARE_READ,       // share for reading
                        NULL,                  // default security
                        OPEN_EXISTING,         // existing file only
                        FILE_ATTRIBUTE_NORMAL, // normal file
                        NULL);                 // no attr. template

    if(hFile == INVALID_HANDLE_VALUE)
    {
        char msg[120];
        int lastError = GetLastError();
        sprintf(msg, "Last Error: %d (%s)", lastError, (*env)->GetStringUTFChars(env, path, 0));
        return (*env)->NewStringUTF(env, msg);
    }



    dwRet = GetFinalPathNameByHandle(hFile, Path, BUFSIZE, VOLUME_NAME_NT);
    if(dwRet < BUFSIZE)
    {
        return WindowsToJstring(env, Path);    
    }
    else
    {
        return NULL;
    }

    CloseHandle(hFile);
    (*env)->ReleaseStringChars(env, path, nativePath);
}

Upvotes: 0

Views: 887

Answers (1)

Erik
Erik

Reputation: 91270

JNI GetStringChars does not return a 0-terminated string. You'll need to use GetStringLength and set up your own 0-terminated string.

Upvotes: 1

Related Questions