From 403360d42af4b73be540cc25f2a457c2c1050b00 Mon Sep 17 00:00:00 2001 From: Lyor Goldstein Date: Thu, 6 Aug 2015 10:46:05 +0300 Subject: [PATCH] Found and fixed duplicate method definitions for the same API --- CHANGES.md | 1 + .../com/sun/jna/platform/win32/Kernel32.java | 584 +++++++---------- .../com/sun/jna/platform/win32/User32.java | 607 ++++++++---------- .../win32/AbstractWin32TestSupport.java | 47 +- .../sun/jna/platform/win32/Advapi32Test.java | 370 ++++++----- .../Kernel32DiskManagementFunctionsTest.java | 120 ++++ .../platform/win32/Kernel32NamedPipeTest.java | 89 ++- .../sun/jna/platform/win32/Kernel32Test.java | 106 +-- .../sun/jna/platform/win32/User32Test.java | 54 +- 9 files changed, 996 insertions(+), 982 deletions(-) create mode 100644 contrib/platform/test/com/sun/jna/platform/win32/Kernel32DiskManagementFunctionsTest.java diff --git a/CHANGES.md b/CHANGES.md index 2ea2bbc6ab..d0a9e6b5e3 100755 --- a/CHANGES.md +++ b/CHANGES.md @@ -49,6 +49,7 @@ Features * Loosen OSGI OS name matching to accommodate Windows 8 family - Niels Bertram. * [#436] (https://github.com/twall/jna/pull/469): Added basic Pdh API implementation to 'com.sun.jna.platform.win32' - [@lgoldstein](https://github.com/lgoldstein). * [#481] (https://github.com/twall/jna/pull/481): Added volume management functions to 'com.sun.jna.platform.win32' - [@lgoldstein](https://github.com/lgoldstein). +* [#483] (https://github.com/twall/jna/pull/483): Found and fixed duplicate method definitions for the same API in 'com.sun.jna.platform.win32' - [@lgoldstein](https://github.com/lgoldstein). Bug Fixes --------- diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java b/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java index 1ffb32eb8b..cb43ebc5a0 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Kernel32.java @@ -12,12 +12,9 @@ */ package com.sun.jna.platform.win32; -import java.nio.Buffer; - import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.win32.W32APIOptions; @@ -32,58 +29,15 @@ public interface Kernel32 extends WinNT, Wincon { Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class, W32APIOptions.UNICODE_OPTIONS); - /** - * The FormatMessage function formats a message string. The function - * requires a message definition as input. The message definition can come - * from a buffer passed into the function. It can come from a message table - * resource in an already-loaded module. Or the caller can ask the function - * to search the system's message table resource(s) for the message - * definition. The function finds the message definition in a message table - * resource based on a message identifier and a language identifier. The - * function copies the formatted message text to an output buffer, - * processing any embedded insert sequences if requested. - * - * @param dwFlags - * Formatting options, and how to interpret the lpSource - * parameter. The low-order byte of dwFlags specifies how the - * function handles line breaks in the output buffer. The - * low-order byte can also specify the maximum width of a - * formatted output line. - *

- * This version of the function assumes - * FORMAT_MESSAGE_ALLOCATE_BUFFER is not set. - * @param lpSource - * Location of the message definition. - * @param dwMessageId - * Message identifier for the requested message. - * @param dwLanguageId - * Language identifier for the requested message. - * @param lpBuffer - * Pointer to a buffer that receives the null-terminated string - * that specifies the formatted message. - * @param nSize - * This this parameter specifies the size of the output buffer, - * in TCHARs. If FORMAT_MESSAGE_ALLOCATE_BUFFER is - * @param va_list - * Pointer to an array of values that are used as insert values - * in the formatted message. - * @return If the function succeeds, the return value is the number of - * TCHARs stored in the output buffer, excluding the terminating - * null character. If the function fails, the return value is zero. - * To get extended error information, call GetLastError. - */ - int FormatMessage(int dwFlags, Pointer lpSource, int dwMessageId, - int dwLanguageId, Buffer lpBuffer, int nSize, Pointer va_list); - /** * Reads data from the specified file or input/output (I/O) device. Reads * occur at the position specified by the file pointer if supported by the * device. - * + * * This function is designed for both synchronous and asynchronous * operations. For a similar function designed solely for asynchronous * operation, see ReadFileEx - * + * * @param hFile * A handle to the device (for example, a file, file stream, * physical disk, volume, console buffer, tape drive, socket, @@ -104,17 +58,17 @@ int FormatMessage(int dwFlags, Pointer lpSource, int dwMessageId, * the function fails, or is completing asynchronously, the return * value is zero (FALSE). To get extended error information, call * the GetLastError function. - * + * * Note The GetLastError code ERROR_IO_PENDING is not a failure; it * designates the read operation is pending completion * asynchronously. For more information, see Remarks. */ - boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, + boolean ReadFile(HANDLE hFile, byte[] lpBuffer, int nNumberOfBytesToRead, IntByReference lpNumberOfBytesRead, WinBase.OVERLAPPED lpOverlapped); /** * Frees the specified local memory object and invalidates its handle. - * + * * @param hLocal * A handle to the local memory object. * @return If the function succeeds, the return value is NULL. If the @@ -126,7 +80,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * Frees the specified global memory object and invalidates its handle. - * + * * @param hGlobal * A handle to the global memory object. * @return If the function succeeds, the return value is NULL If the @@ -140,7 +94,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, * The GetModuleHandle function retrieves a module handle for the specified * module if the file has been mapped into the address space of the calling * process. - * + * * @param name * Pointer to a null-terminated string that contains the name of * the module (either a .dll or .exe file). @@ -153,7 +107,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The GetSystemTime function retrieves the current system date and time. * The system time is expressed in Coordinated Universal Time (UTC). - * + * * @param lpSystemTime * Pointer to a {@link #SYSTEMTIME} structure to receive the current * system date and time. @@ -165,7 +119,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The SetSystemTime function modifies the current system date and time. * The system time is expressed in Coordinated Universal Time (UTC). - * + * * @param lpSystemTime * Pointer to a {@link #SYSTEMTIME} structure holding the new * system date and time. Note: The {@code wDayOfWeek} @@ -180,7 +134,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * Retrieves the current local date and time. - * + * * @param lpSystemTime * A pointer to a {@link #SYSTEMTIME} structure to receive the current * local date and time. @@ -191,7 +145,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * Sets the current local time and date - * + * * @param lpSystemTime * Pointer to a {@link #SYSTEMTIME} structure holding the new * system date and time. Note: The {@code wDayOfWeek} @@ -207,7 +161,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The GetTickCount function retrieves the number of milliseconds that have * elapsed since the system was started, up to 49.7 days. - * + * * @return Number of milliseconds that have elapsed since the system was * started. */ @@ -216,7 +170,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The GetCurrentThreadId function retrieves the thread identifier of the * calling thread. - * + * * @return The return value is the thread identifier of the calling thread. */ int GetCurrentThreadId(); @@ -224,14 +178,14 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The GetCurrentThread function retrieves a pseudo handle for the current * thread. - * + * * @return The return value is a pseudo handle for the current thread. */ HANDLE GetCurrentThread(); /** * This function returns the process identifier of the calling process. - * + * * @return The return value is the process identifier of the calling * process. */ @@ -239,7 +193,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * This function returns a pseudohandle for the current process. - * + * * @return The return value is a pseudohandle to the current process. */ HANDLE GetCurrentProcess(); @@ -247,7 +201,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The GetProcessId function retrieves the process identifier of the * specified process. - * + * * @param process * Handle to the process. The handle must have the * PROCESS_QUERY_INFORMATION access right. @@ -261,7 +215,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The GetProcessVersion function retrieves the major and minor version * numbers of the system on which the specified process expects to run. - * + * * @param processId * Process identifier of the process of interest. A value of zero * specifies the calling process. @@ -277,14 +231,14 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * Retrieves the termination status of the specified process. - * + * * @param hProcess * A handle to the process. * @param lpExitCode * A pointer to a variable to receive the process termination * status. * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -292,14 +246,14 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * Terminates the specified process and all of its threads. - * + * * @param hProcess * A handle to the process to be terminated. * @param uExitCode * The exit code to be used by the process and threads terminated * as a result of this call. * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -309,7 +263,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, * The GetLastError function retrieves the calling thread's last-error code * value. The last-error code is maintained on a per-thread basis. Multiple * threads do not overwrite each other's last-error code. - * + * * @return The return value is the calling thread's last-error code value. */ int GetLastError(); @@ -317,7 +271,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * The SetLastError function sets the last-error code for the calling * thread. - * + * * @param dwErrCode * Last-error code for the thread. */ @@ -326,7 +280,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, /** * Determines whether a disk drive is a removable, fixed, CD-ROM, RAM * disk, or network drive. - * + * * @param lpRootPathName * Pointer to a null-terminated string that specifies the root * directory of the disk to return information about. A trailing @@ -347,50 +301,7 @@ boolean ReadFile(HANDLE hFile, Buffer lpBuffer, int nNumberOfBytesToRead, * resource based on a message identifier and a language identifier. The * function copies the formatted message text to an output buffer, * processing any embedded insert sequences if requested. - * - * @param dwFlags - * Formatting options, and how to interpret the lpSource - * parameter. The low-order byte of dwFlags specifies how the - * function handles line breaks in the output buffer. The - * low-order byte can also specify the maximum width of a - * formatted output line. - *

- * This version of the function assumes - * FORMAT_MESSAGE_ALLOCATE_BUFFER is not set. - * @param lpSource - * Location of the message definition. - * @param dwMessageId - * Message identifier for the requested message. - * @param dwLanguageId - * Language identifier for the requested message. - * @param lpBuffer - * Pointer to a buffer that receives the null-terminated string - * that specifies the formatted message. - * @param nSize - * This this parameter specifies the size of the output buffer, - * in TCHARs. If FORMAT_MESSAGE_ALLOCATE_BUFFER is - * @param va_list - * Pointer to an array of values that are used as insert values - * in the formatted message. - * @return If the function succeeds, the return value is the number of - * TCHARs stored in the output buffer, excluding the terminating - * null character. If the function fails, the return value is zero. - * To get extended error information, call GetLastError. - */ - int FormatMessage(int dwFlags, Pointer lpSource, int dwMessageId, - int dwLanguageId, Pointer lpBuffer, int nSize, Pointer va_list); - - /** - * The FormatMessage function formats a message string. The function - * requires a message definition as input. The message definition can come - * from a buffer passed into the function. It can come from a message table - * resource in an already-loaded module. Or the caller can ask the function - * to search the system's message table resource(s) for the message - * definition. The function finds the message definition in a message table - * resource based on a message identifier and a language identifier. The - * function copies the formatted message text to an output buffer, - * processing any embedded insert sequences if requested. - * + * * @param dwFlags * Formatting options, and how to interpret the lpSource * parameter. The low-order byte of dwFlags specifies how the @@ -430,7 +341,7 @@ int FormatMessage(int dwFlags, Pointer lpSource, int dwMessageId, * physical disk, volume, console buffer, tape drive, communications * resource, mailslot, or named pipe. The function returns a handle that can * be used to access an object. - * + * * @param lpFileName * A pointer to a null-terminated string that specifies the name * of an object to create or open. @@ -469,30 +380,30 @@ HANDLE CreateFile(String lpFileName, int dwDesiredAccess, int dwShareMode, /** * Copies an existing file to a new file. - * + * * @param lpExistingFileName * The name of an existing file. - * + * * The name is limited to MAX_PATH characters. To extend this * limit to 32,767 wide characters, prepend "\\?\" to the path. * For more information, see Naming a File. - * + * * If lpExistingFileName does not exist, CopyFile fails, and * GetLastError returns ERROR_FILE_NOT_FOUND. - * + * * @param lpNewFileName * The name of the new file. - * + * * The name is limited to MAX_PATH characters. To extend this * limit to 32,767 wide characters, prepend "\\?\" to the path. * For more information, see Naming a File. - * + * * @param bFailIfExists * If this parameter is TRUE and the new file specified by * lpNewFileName already exists, the function fails. If this * parameter is FALSE and the new file already exists, the * function overwrites the existing file and succeeds. - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. To get extended error * information, call GetLastError. @@ -502,11 +413,11 @@ boolean CopyFile(String lpExistingFileName, String lpNewFileName, /** * Moves an existing file or a directory, including its children. - * + * * @param lpExistingFileName * The current name of the file or directory on the local * computer. - * + * * The name is limited to MAX_PATH characters. To extend this * limit to 32,767 wide characters, prepend "\\?\" to the path. * For more information, see Naming a File. @@ -514,13 +425,13 @@ boolean CopyFile(String lpExistingFileName, String lpNewFileName, * The new name for the file or directory. The new name must not * already exist. A new file may be on a different file system or * drive. A new directory must be on the same drive. - * + * * The name is limited to MAX_PATH characters. To extend this * limit to 32,767 wide characters, prepend "\\?\" to the path. * For more information, see Naming a File. * @return true, if successful If the function succeeds, the return value is * nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -529,32 +440,32 @@ boolean CopyFile(String lpExistingFileName, String lpNewFileName, /** * Moves an existing file or directory, including its children, with various * move options. - * + * * @param lpExistingFileName * The current name of the file or directory on the local * computer. - * + * * If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT, the file * cannot exist on a remote share, because delayed operations are * performed before the network is available. - * + * * The name is limited to MAX_PATH characters. To extend this * limit to 32,767 wide characters, prepend "\\?\" to the path. * For more information, see Naming a File - * + * * Windows 2000: If you prepend the file name with "\\?\", you * cannot also specify the MOVEFILE_DELAY_UNTIL_REBOOT flag for * dwFlags. * @param lpNewFileName * The new name of the file or directory on the local computer. - * + * * When moving a file, the destination can be on a different file * system or volume. If the destination is on another drive, you * must set the MOVEFILE_COPY_ALLOWED flag in dwFlags. - * + * * When moving a directory, the destination must be on the same * drive. - * + * * If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and * lpNewFileName is NULL, MoveFileEx registers the * lpExistingFileName file to be deleted when the system @@ -565,7 +476,7 @@ boolean CopyFile(String lpExistingFileName, String lpNewFileName, * This parameter can be one or more of the following values. * @return true, if successful If the function succeeds, the return value is * nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -576,7 +487,7 @@ boolean MoveFileEx(String lpExistingFileName, String lpNewFileName, * The CreateDirectory function creates a new directory. If the underlying * file system supports security on files and directories, the function * applies a specified security descriptor to the new directory. - * + * * @param lpPathName * Pointer to a null-terminated string that specifies the path of * the directory to be created. @@ -593,48 +504,11 @@ boolean MoveFileEx(String lpExistingFileName, String lpNewFileName, boolean CreateDirectory(String lpPathName, WinBase.SECURITY_ATTRIBUTES lpSecurityAttributes); - /** - * Reads data from the specified file or input/output (I/O) device. Reads - * occur at the position specified by the file pointer if supported by the - * device. - * - * This function is designed for both synchronous and asynchronous - * operations. For a similar function designed solely for asynchronous - * operation, see ReadFileEx - * - * @param hFile - * A handle to the device (for example, a file, file stream, - * physical disk, volume, console buffer, tape drive, socket, - * communications resource, mailslot, or pipe). - * @param lpBuffer - * A pointer to the buffer that receives the data read from a - * file or device. - * @param nNumberOfBytesToRead - * The maximum number of bytes to be read. - * @param lpNumberOfBytesRead - * A pointer to the variable that receives the number of bytes - * read when using a synchronous hFile parameter - * @param lpOverlapped - * A pointer to an OVERLAPPED structure is required if the hFile - * parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it - * can be NULL. - * @return If the function succeeds, the return value is nonzero (TRUE). If - * the function fails, or is completing asynchronously, the return - * value is zero (FALSE). To get extended error information, call - * the GetLastError function. - * - * Note The GetLastError code ERROR_IO_PENDING is not a failure; it - * designates the read operation is pending completion - * asynchronously. For more information, see Remarks. - */ - boolean ReadFile(HANDLE hFile, Pointer lpBuffer, int nNumberOfBytesToRead, - IntByReference lpNumberOfBytesRead, WinBase.OVERLAPPED lpOverlapped); - /** * Creates an input/output (I/O) completion port and associates it with a * specified file handle, or creates an I/O completion port that is not yet * associated with a file handle, allowing association at a later time. - * + * * @param FileHandle * An open file handle or INVALID_HANDLE_VALUE. * @param ExistingCompletionPort @@ -665,7 +539,7 @@ HANDLE CreateIoCompletionPort(HANDLE FileHandle, * completion port. If there is no completion packet queued, the function * waits for a pending I/O operation associated with the completion port to * complete. - * + * * @param CompletionPort * A handle to the completion port. * @param lpNumberOfBytes @@ -691,7 +565,7 @@ boolean GetQueuedCompletionStatus(HANDLE CompletionPort, /** * Posts an I/O completion packet to an I/O completion port. - * + * * @param CompletionPort * A handle to an I/O completion port to which the I/O completion * packet is to be posted. @@ -718,7 +592,7 @@ boolean PostQueuedCompletionStatus(HANDLE CompletionPort, * interval elapses. To enter an alertable wait state, use the * WaitForSingleObjectEx function. To wait for multiple objects, use the * WaitForMultipleObjects. - * + * * @param hHandle * A handle to the object. For a list of the object types whose * handles can be specified, see the following Remarks section. @@ -742,7 +616,7 @@ boolean PostQueuedCompletionStatus(HANDLE CompletionPort, * Waits until one or all of the specified objects are in the signaled state * or the time-out interval elapses. To enter an alertable wait state, use * the WaitForMultipleObjectsEx function. - * + * * @param nCount * The number of object handles in the array pointed to by * lpHandles. The maximum number of object handles is @@ -779,7 +653,7 @@ int WaitForMultipleObjects(int nCount, HANDLE[] hHandle, boolean bWaitAll, /** * The DuplicateHandle function duplicates an object handle. - * + * * @param hSourceProcessHandle * Handle to the process with the handle to duplicate. The handle * must have the PROCESS_DUP_HANDLE access right. @@ -812,7 +686,7 @@ boolean DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, /** * The CloseHandle function closes an open object handle. - * + * * @param hObject * Handle to an open object. This parameter can be a pseudo * handle or INVALID_HANDLE_VALUE. @@ -826,7 +700,7 @@ boolean DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, * Retrieves information that describes the changes within the specified * directory. The function does not report changes to the specified * directory itself. Note: there's no ReadDirectoryChangesA. - * + * * @param directory * A handle to the directory to be monitored. This directory must * be opened with the FILE_LIST_DIRECTORY access right. @@ -875,7 +749,7 @@ public boolean ReadDirectoryChangesW(HANDLE directory, /** * Retrieves the short path form of the specified path. - * + * * @param lpszLongPath * The path string. * @param lpdzShortPath @@ -900,7 +774,7 @@ int GetShortPathName(String lpszLongPath, char[] lpdzShortPath, * The LocalAlloc function allocates the specified number of bytes from the * heap. Windows memory management does not provide a separate local heap * and global heap. - * + * * @param uFlags * Memory allocation attributes. The default is the LMEM_FIXED * value. @@ -917,7 +791,7 @@ int GetShortPathName(String lpszLongPath, char[] lpdzShortPath, /** * Writes data to the specified file or input/output (I/O) device. - * + * * @param hFile * A handle to the file or I/O device (for example, a file, file * stream, physical disk, volume, console buffer, tape drive, @@ -950,7 +824,7 @@ boolean WriteFile(HANDLE hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, * device, the function only flushes the transmit buffer. If a handle to the * server end of a named pipe, the function does not return until the client * has read all buffered data from the pipe. - * @return {@code true} if successful, {@code false} otherwise. + * @return {@code true} if successful, {@code false} otherwise. * To get extended error information, call {@link #GetLastError()}. * @see FlushFileBuffers * documentation @@ -959,7 +833,7 @@ boolean WriteFile(HANDLE hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, /** * Creates or opens a named or unnamed event object. - * + * * @param lpEventAttributes * A pointer to a SECURITY_ATTRIBUTES structure. If this * parameter is NULL, the handle cannot be inherited by child @@ -989,7 +863,7 @@ HANDLE CreateEvent(WinBase.SECURITY_ATTRIBUTES lpEventAttributes, /** * Sets the specified event object to the signaled state. - * + * * @param hEvent * A handle to the event object. The CreateEvent or OpenEvent * function returns this handle. @@ -1001,10 +875,10 @@ HANDLE CreateEvent(WinBase.SECURITY_ATTRIBUTES lpEventAttributes, /** * Resets (to non-signaled state) the specified event object. - * + * * @param hEvent * A handle to the event object - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails the return value is zero. To get extended error * information, call GetLastError. @@ -1015,7 +889,7 @@ HANDLE CreateEvent(WinBase.SECURITY_ATTRIBUTES lpEventAttributes, * Sets the specified event object to the signaled state and then resets it * to the nonsignaled state after releasing the appropriate number of * waiting threads. - * + * * @param hEvent * A handle to the event object. The CreateEvent or OpenEvent * function returns this handle. @@ -1028,7 +902,7 @@ HANDLE CreateEvent(WinBase.SECURITY_ATTRIBUTES lpEventAttributes, /** * Creates or opens a named or unnamed file mapping object for a specified * file. - * + * * @param hFile * A handle to the file from which to create a file mapping * object. @@ -1065,7 +939,7 @@ HANDLE CreateFileMapping(HANDLE hFile, /** * Maps a view of a file mapping into the address space of a calling * process. - * + * * @param hFileMappingObject * A handle to a file mapping object. The CreateFileMapping and * OpenFileMapping functions return this handle. @@ -1089,7 +963,7 @@ Pointer MapViewOfFile(HANDLE hFileMappingObject, int dwDesiredAccess, /** * Unmaps a mapped view of a file from the calling process's address space. - * + * * @param lpBaseAddress * A pointer to the base address of the mapped view of a file * that is to be unmapped. @@ -1102,7 +976,7 @@ Pointer MapViewOfFile(HANDLE hFileMappingObject, int dwDesiredAccess, /** * Retrieves only the NetBIOS name of the local computer. - * + * * @param buffer * A pointer to a buffer that receives the computer name or the * cluster virtual server name. The buffer size should be large @@ -1124,7 +998,7 @@ Pointer MapViewOfFile(HANDLE hFileMappingObject, int dwDesiredAccess, /** * Retrieves a NetBIOS or DNS name associated with the local computer, * according to the nameType enumeration value - * + * * @param nameType * An enumeration value specifying the type of name to be * retrieved - this parameter is a value from the @@ -1152,7 +1026,7 @@ Pointer MapViewOfFile(HANDLE hFileMappingObject, int dwDesiredAccess, /** * The OpenThread function opens an existing thread object. - * + * * @param dwDesiredAccess * Access to the thread object. This access right is checked * against any security descriptor for the thread. @@ -1172,7 +1046,7 @@ HANDLE OpenThread(int dwDesiredAccess, boolean bInheritHandle, /** * Creates a new process and its primary thread. The new process runs in the * security context of the calling process. - * + * * @param lpApplicationName * The name of the module to be executed. * @param lpCommandLine @@ -1182,20 +1056,20 @@ HANDLE OpenThread(int dwDesiredAccess, boolean bInheritHandle, * whether the returned handle to the new process object can be * inherited by child processes. If lpProcessAttributes is NULL, * the handle cannot be inherited. - * + * * @param lpThreadAttributes * A pointer to a SECURITY_ATTRIBUTES structure that determines * whether the returned handle to the new thread object can be * inherited by child processes. If lpThreadAttributes is NULL, * the handle cannot be inherited. - * + * * @param bInheritHandles * If this parameter TRUE, each inheritable handle in the calling * process is inherited by the new process. If the parameter is * FALSE, the handles are not inherited. Note that inherited * handles have the same value and access rights as the original * handles. - * + * * @param dwCreationFlags * The flags that control the priority class and the creation of * the process. @@ -1203,7 +1077,7 @@ HANDLE OpenThread(int dwDesiredAccess, boolean bInheritHandle, * A pointer to the environment block for the new process. If * this parameter is NULL, the new process uses the environment * of the calling process. - * + * * @param lpCurrentDirectory * The full path to the current directory for the process. * @param lpStartupInfo @@ -1224,7 +1098,7 @@ boolean CreateProcess(String lpApplicationName, String lpCommandLine, /** * Creates a new process and its primary thread. The new process runs in the * security context of the calling process. - * + * * @param lpApplicationName * The name of the module to be executed. * @param lpCommandLine @@ -1330,7 +1204,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * This function returns a handle to an existing process object. - * + * * @param fdwAccess * Not supported; set to zero. * @param fInherit @@ -1346,7 +1220,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * The GetTempPath function retrieves the path of the directory designated * for temporary files. - * + * * @param nBufferLength * Size of the string buffer identified by lpBuffer, in TCHARs. * @param buffer @@ -1358,7 +1232,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, * terminating null character. If the return value is greater than * nBufferLength, the return value is the length, in TCHARs, of the * buffer required to hold the path. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -1367,7 +1241,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * The GetVersion function returns the current version number of the * operating system. - * + * * @return If the function succeeds, the return value includes the major and * minor version numbers of the operating system in the low order * word, and information about the operating system platform in the @@ -1378,7 +1252,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * The GetVersionEx function obtains extended information about the version * of the operating system that is currently running. - * + * * @param lpVersionInfo * Pointer to an OSVERSIONINFO data structure that the function * fills with operating system version information. @@ -1393,7 +1267,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * The GetVersionEx function obtains extended information about the version * of the operating system that is currently running. - * + * * @param lpVersionInfo * Pointer to an OSVERSIONINFOEX data structure that the function * fills with operating system version information. @@ -1407,7 +1281,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * The GetSystemInfo function returns information about the current system. - * + * * @param lpSystemInfo * Pointer to a SYSTEM_INFO structure that receives the * information. @@ -1419,7 +1293,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, * system to an application running under WOW64. If the function is called * from a 64-bit application, it is equivalent to the GetSystemInfo * function. - * + * * @param lpSystemInfo * Pointer to a SYSTEM_INFO structure that receives the * information. @@ -1429,7 +1303,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * The IsWow64Process function determines whether the specified process is * running under WOW64. - * + * * @param hProcess * Handle to a process. * @param Wow64Process @@ -1443,7 +1317,7 @@ boolean CreateProcessW(String lpApplicationName, char[] lpCommandLine, /** * Retrieves information about logical processors and related hardware. - * + * * @param buffer * a buffer which receives an array of * {@link WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION} structures. @@ -1462,7 +1336,7 @@ boolean GetLogicalProcessorInformation(Pointer buffer, /** * Retrieves information about the system's current usage of both physical * and virtual memory. - * + * * @param lpBuffer * A pointer to a MEMORYSTATUSEX structure that receives * information about current memory availability. @@ -1475,17 +1349,17 @@ boolean GetLogicalProcessorInformation(Pointer buffer, /** * Retrieves the date and time that a file or directory was created, last * accessed, and last modified. - * + * * @param hFile * A handle to the file or directory for which dates and times * are to be retrieved. The handle must have been created using * the CreateFile function with the GENERIC_READ access right. - * + * * @param lpCreationTime * A pointer to a FILETIME structure to receive the date and time * the file or directory was created. This parameter can be NULL * if the application does not require this information. - * + * * @param lpLastAccessTime * A pointer to a FILETIME structure to receive the date and time * the file or directory was last accessed. The last access time @@ -1493,7 +1367,7 @@ boolean GetLogicalProcessorInformation(Pointer buffer, * read from, or, in the case of executable files, run. This * parameter can be NULL if the application does not require this * information. - * + * * @param lpLastWriteTime * A pointer to a FILETIME structure to receive the date and time * the file or directory was last written to, truncated, or @@ -1501,7 +1375,7 @@ boolean GetLogicalProcessorInformation(Pointer buffer, * This date and time is not updated when file attributes or * security descriptors are changed. This parameter can be NULL * if the application does not require this information. - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. To get extended error * information, call GetLastError. @@ -1512,7 +1386,7 @@ boolean GetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, /** * Sets the date and time that the specified file or directory was created, * last accessed, or last modified. - * + * * @param hFile * A handle to the file or directory. The handle must have been * created using the CreateFile function with the @@ -1530,7 +1404,7 @@ boolean GetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, * written to, read from, or (in the case of executable files) * run. This parameter can be NULL if the application does not * need to change this information. - * + * * To preserve the existing last access time for a file even * after accessing a file, call SetFileTime immediately after * opening the file handle with this parameter's FILETIME @@ -1541,7 +1415,7 @@ boolean GetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, * parameter can be NULL if the application does not need to * change this information. * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -1550,18 +1424,18 @@ int SetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, /** * Sets the attributes for a file or directory. - * + * * @param lpFileName * The name of the file whose attributes are to be set. - * + * * The name is limited to MAX_PATH characters. To extend this * limit to 32,767 wide characters, prepend "\\?\" to the path. - * + * * @param dwFileAttributes * The file attributes to set for the file. This parameter can be * one or more values, combined using the bitwise-OR operator. * However, all other values override FILE_ATTRIBUTE_NORMAL. - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. To get extended error * information, call GetLastError. @@ -1571,7 +1445,7 @@ int SetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, /** * The GetLogicalDriveStrings function fills a buffer with strings that * specify valid drives in the system. - * + * * @param nBufferLength * Maximum size of the buffer pointed to by lpBuffer, in TCHARs. * This size does not include the terminating null character. If @@ -1592,18 +1466,54 @@ int SetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, */ DWORD GetLogicalDriveStrings(DWORD nBufferLength, char[] lpBuffer); + /** + * Retrieves information about the specified disk, including the amount of + * free space on the disk + * + * @param lpRootPathName + * The root directory of the disk for which information is to be + * returned. If this parameter is NULL, the function uses the root + * of the current disk. If this parameter is a UNC name, it must + * include a trailing backslash (for example, "\\MyServer\MyShare\"). + * Furthermore, a drive specification must have a trailing backslash + * (for example, "C:\"). The calling application must + * have FILE_LIST_DIRECTORY access rights for this directory. + * @param lpSectorsPerCluster + * A variable that receives the number of sectors per cluster. + * @param lpBytesPerSector + * A variable that receives the number of bytes per sector. + * @param lpNumberOfFreeClusters + * A variable that receives the total number of free clusters on the + * disk that are available to the user who is associated with the + * calling thread. If per-user disk quotas are in use, this value + * may be less than the total number of free clusters on the disk. + * @param lpTotalNumberOfClusters + * A variable that receives the total number of clusters on the + * disk that are available to the user who is associated with the + * calling thread. If per-user disk quotas are in use, this value + * may be less than the total number of clusters on the disk. + * @return {@code true} if the function succeeds - to get extended error + * information, call {@link #GetLastError()}. + * @see GetDiskFreeSpace + */ + boolean GetDiskFreeSpace(String lpRootPathName, + DWORDByReference lpSectorsPerCluster, + DWORDByReference lpBytesPerSector, + DWORDByReference lpNumberOfFreeClusters, + DWORDByReference lpTotalNumberOfClusters); + /** * The GetDiskFreeSpaceEx function retrieves information about the amount of * space that is available on a disk volume, which is the total amount of * space, the total amount of free space, and the total amount of free space * available to the user that is associated with the calling thread. - * + * * @param lpDirectoryName - * A pointer to a null-terminated string that specifies a - * directory on a disk. If this parameter is NULL, the function - * uses the root of the current disk. If this parameter is a UNC - * name, it must include a trailing backslash, for example, - * \\MyServer\MyShare\. This parameter does not have to specify + * A string that specifies a directory on a disk. If this parameter + * is NULL, the function uses the root of the current disk. If this + * parameter is a UNC name, it must include a trailing backslash, + * for example, + * {@code \\MyServer\MyShare\}. This parameter does not have to specify * the root directory on a disk. The function accepts any * directory on a disk. * @param lpFreeBytesAvailable @@ -1619,9 +1529,9 @@ int SetFileTime(HANDLE hFile, WinBase.FILETIME lpCreationTime, * @param lpTotalNumberOfFreeBytes * A pointer to a variable that receives the total number of free * bytes on a disk. This parameter can be NULL. - * @return If the function succeeds, the return value is nonzero. If the - * function fails, the return value is 0 (zero). To get extended - * error information, call GetLastError. + * @return {@code true} if the function succeeds - to get extended error + * information, call {@link #GetLastError()}. + * @see GetDiskFreeSpaceEx */ boolean GetDiskFreeSpaceEx(String lpDirectoryName, LARGE_INTEGER lpFreeBytesAvailable, @@ -1630,7 +1540,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Deletes an existing file. - * + * * @param filename * The name of the file to be deleted. * @return If the function succeeds, the return value is nonzero. If the @@ -1642,7 +1552,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Creates an anonymous pipe, and returns handles to the read and write ends * of the pipe. - * + * * @param hReadPipe * A pointer to a variable that receives the read handle for the * pipe. @@ -1674,9 +1584,9 @@ public boolean CreatePipe(HANDLEByReference hReadPipe, * @param lpBytesRead A variable that receives the number of bytes read from * the pipe. * @param nTimeOut The number of milliseconds to wait for the named pipe to - * be available. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * be available. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see CallNamedPipe * documentation */ @@ -1721,13 +1631,13 @@ public boolean CallNamedPipe(String lpNamedPipeName, * 0 or the allowed flags * @param nMaxInstances The maximum number of instances that can be created for this pipe. * Acceptable values are in the range 1 through {@link #PIPE_UNLIMITED_INSTANCES} - * @param nOutBufferSize The number of bytes to reserve for the output buffer. + * @param nOutBufferSize The number of bytes to reserve for the output buffer. * @param nInBufferSize The number of bytes to reserve for the input buffer. * @param nDefaultTimeOut The default time-out value, in milliseconds. A value of zero will * result in a default time-out of 50 milliseconds * @param lpSecurityAttributes A pointer to a {@link #SECURITY_ATTRIBUTES} structure that * specifies a security descriptor for the new named pipe. If {@code null} the named pipe - * gets a default security descriptor and the handle cannot be inherited. + * gets a default security descriptor and the handle cannot be inherited. * @return If the function succeeds, the return value is a handle to the server end of a * named pipe instance. If the function fails, the return value is {@link #INVALID_HANDLE_VALUE}. * To get extended error information, call {@link #GetLastError()}. @@ -1741,13 +1651,13 @@ public HANDLE CreateNamedPipe(String lpName, int dwOpenMode, int dwPipeMode, int /** * Disconnects the server end of a named pipe instance from a client process. * @param hNamedPipe A handle to an instance of a named pipe. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see DisconnectNamedPipe * documentation */ public boolean DisconnectNamedPipe(HANDLE hNamedPipe); - + /** * Retrieves the client computer name for the specified named pipe. * @param Pipe A handle to an instance of a named pipe. @@ -1756,8 +1666,8 @@ public HANDLE CreateNamedPipe(String lpName, int dwOpenMode, int dwPipeMode, int * to a {@link String} * @param ClientComputerNameLength The size of the ClientComputerName * buffer, in bytes. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeClientComputerName * documentation */ @@ -1766,8 +1676,8 @@ public HANDLE CreateNamedPipe(String lpName, int dwOpenMode, int dwPipeMode, int /** * @param Pipe A handle to an instance of a named pipe. * @param ClientProcessId Recipient of the process identifier - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeClientProcessId * documentation */ @@ -1776,8 +1686,8 @@ public HANDLE CreateNamedPipe(String lpName, int dwOpenMode, int dwPipeMode, int /** * @param Pipe A handle to an instance of a named pipe. * @param ClientSessionId Recipient of the session identifier - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeClientProcessId * documentation */ @@ -1785,7 +1695,7 @@ public HANDLE CreateNamedPipe(String lpName, int dwOpenMode, int dwPipeMode, int /** * Retrieves information about a specified named pipe. - * @param hNamedPipe A handle to the named pipe for which information is wanted. + * @param hNamedPipe A handle to the named pipe for which information is wanted. * @param lpState A pointer to a variable that indicates the current * state of the handle. This parameter can be {@code null} if this information * is not needed. @@ -1799,14 +1709,14 @@ public HANDLE CreateNamedPipe(String lpName, int dwOpenMode, int dwPipeMode, int * @param lpCollectDataTimeout A pointer to a variable that receives the * maximum time, in milliseconds, that can pass before a remote named pipe * transfers information over the network. This parameter can be {@code null} - * if this information is not needed. + * if this information is not needed. * @param lpUserName A buffer that receives the user name string associated * with the client application. This parameter can be {@code null} if this * information is not needed. * @param nMaxUserNameSize The size of the buffer specified by the lpUserName * parameter. This parameter is ignored if lpUserName is {@code null}. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeHandleState * documentation */ @@ -1829,8 +1739,8 @@ public boolean GetNamedPipeHandleState(HANDLE hNamedPipe, IntByReference lpState * @param lpMaxInstances A pointer to a variable that receives the maximum * number of pipe instances that can be created. This parameter can be {@code null} * if this information is not needed. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeInfo * documentation */ @@ -1841,8 +1751,8 @@ public boolean GetNamedPipeInfo(HANDLE hNamedPipe, IntByReference lpFlags, /** * @param Pipe A handle to an instance of a named pipe. * @param ServerProcessId Recipient of the process identifier. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeServerProcessId * documentation */ @@ -1851,8 +1761,8 @@ public boolean GetNamedPipeInfo(HANDLE hNamedPipe, IntByReference lpFlags, /** * @param Pipe A handle to an instance of a named pipe. * @param ServerProcessId Recipient of the session identifier. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see GetNamedPipeServerSessionId * documentation */ @@ -1860,7 +1770,7 @@ public boolean GetNamedPipeInfo(HANDLE hNamedPipe, IntByReference lpFlags, /** * Copies data from a named or anonymous pipe into a buffer without - * removing it from the pipe. + * removing it from the pipe. * @param hNamedPipe A handle to the pipe. * @param lpBuffer A buffer that receives data read from the pipe. * This parameter can be {@code null} if no data is to be read. @@ -1875,8 +1785,8 @@ public boolean GetNamedPipeInfo(HANDLE hNamedPipe, IntByReference lpFlags, * @param lpBytesLeftThisMessage A variable that receives the number of * bytes remaining in this message. This parameter can be {@code null} * if no data is to be read. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see PeekNamedPipe * documentation */ @@ -1888,15 +1798,15 @@ public boolean PeekNamedPipe(HANDLE hNamedPipe, byte[] lpBuffer, int nBufferSize * @param hNamedPipe A handle to the named pipe instance. * @param lpMode The new pipe mode. The mode is a combination of a read-mode * flag and a wait-mode flag. This parameter can be {@code null} if the - * mode is not being set. + * mode is not being set. * @param lpMaxCollectionCount The maximum number of bytes collected on * the client computer before transmission to the server. This parameter - * can be {@code null} if the count is not being set. + * can be {@code null} if the count is not being set. * @param lpCollectDataTimeout The maximum time, in milliseconds, that can * pass before a remote named pipe transfers information over the network. - * This parameter can be {@code null} if the timeout is not being set. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * This parameter can be {@code null} if the timeout is not being set. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see SetNamedPipeHandleState * documentation */ @@ -1913,9 +1823,9 @@ public boolean SetNamedPipeHandleState(HANDLE hNamedPipe, IntByReference lpMode, * @param nOutBufferSize The size of the output buffer, in bytes. * @param lpBytesRead Variable that receives the number of bytes read from the pipe. * @param lpOverlapped A pointer to an {@link #OVERLAPPED} structure. Can - * be {@code null} if pipe not opened with {@link #FILE_FLAG_OVERLAPPED}. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * be {@code null} if pipe not opened with {@link #FILE_FLAG_OVERLAPPED}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see TransactNamedPipe * documentation */ @@ -1938,7 +1848,7 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, *

A period may be used for the servername if the pipe is local.

* @param nTimeOut The number of milliseconds that the function will wait for * an instance of the named pipe to be available. - * @return {@code true} if successful, {@code false} otherwise. + * @return {@code true} if successful, {@code false} otherwise. * To get extended error information, call {@link #GetLastError()}. * @see WaitNamedPipe * documentation @@ -1947,7 +1857,7 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, /** * Sets certain properties of an object handle. - * + * * @param hObject * A handle to an object whose information is to be set. * @param dwMask @@ -1964,7 +1874,7 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, /** * Retrieves file system attributes for a specified file or directory. - * + * * @param lpFileName * The name of the file or directory. Prepend \\?\ to the path * for names up to 32,767 wide characters @@ -1975,7 +1885,7 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, /** * Retrieves the file type of the specified file. - * + * * @param hFile * A handle to the file. * @return FILE_TYPE_UNKNOWN if the function fails, or if the type is @@ -1991,13 +1901,13 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, /** * Sends a control code directly to a specified device driver, causing the * corresponding device to perform the corresponding operation. - * + * * @param hDevice * A handle to the device on which the operation is to be * performed. The device is typically a volume, directory, file, * or stream. To retrieve a device handle, use the CreateFile * function. For more information, see Remarks. - * + * * @param dwIoControlCode * The control code for the operation. This value identifies the * specific operation to be performed and the type of device on @@ -2005,27 +1915,27 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, * Remarks. The documentation for each control code provides * usage details for the lpInBuffer, nInBufferSize, lpOutBuffer, * and nOutBufferSize parameters. - * + * * @param lpInBuffer * A pointer to the input buffer that contains the data required * to perform the operation. The format of this data depends on * the value of the dwIoControlCode parameter. This parameter can * be NULL if dwIoControlCode specifies an operation that does * not require input data. - * + * * @param nInBufferSize * The size of the input buffer, in bytes. - * + * * @param lpOutBuffer * A pointer to the output buffer that is to receive the data * returned by the operation. The format of this data depends on * the value of the dwIoControlCode parameter. This parameter can * be NULL if dwIoControlCode specifies an operation that does * not return data. - * + * * @param nOutBufferSize * The size of the output buffer, in bytes. - * + * * @param lpBytesReturned * A pointer to a variable that receives the size of the data * stored in the output buffer, in bytes. If the output buffer is @@ -2049,7 +1959,7 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, * is associated with an I/O completion port, you can retrieve * the number of bytes returned by calling * GetQueuedCompletionStatus. - * + * * @param lpOverlapped * A pointer to an OVERLAPPED structure. If hDevice was opened * without specifying FILE_FLAG_OVERLAPPED, lpOverlapped is @@ -2063,9 +1973,9 @@ public boolean TransactNamedPipe(HANDLE hNamedPipe, * operation has been completed. Otherwise, the function does not * return until the operation has been completed or an error * occurs. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -2074,37 +1984,13 @@ boolean DeviceIoControl(HANDLE hDevice, int dwIoControlCode, int nOutBufferSize, IntByReference lpBytesReturned, Pointer lpOverlapped); - /** - * Retrieves information about the amount of space that is available on a - * disk volume, which is the total amount of space, the total amount of free - * space, and the total amount of free space available to the user that is - * associated with the calling thread. - * - * @param lpDirectoryName - * the lp directory name - * @param lpFreeBytesAvailable - * the lp free bytes available - * @param lpTotalNumberOfBytes - * the lp total number of bytes - * @param lpTotalNumberOfFreeBytes - * the lp total number of free bytes - * @return If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero (0). To get - * extended error information, call GetLastError. - */ - boolean GetDiskFreeSpaceEx(String lpDirectoryName, - LongByReference lpFreeBytesAvailable, - LongByReference lpTotalNumberOfBytes, - LongByReference lpTotalNumberOfFreeBytes); - /** * Takes a snapshot of the specified processes, as well as the heaps, * modules, and threads used by these processes. - * + * * @param dwFlags * The portions of the system to be included in the snapshot. - * + * * @param th32ProcessID * The process identifier of the process to be included in the * snapshot. This parameter can be zero to indicate the current @@ -2112,19 +1998,19 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, * TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, or TH32CS_SNAPALL * value is specified. Otherwise, it is ignored and all processes * are included in the snapshot. - * + * * If the specified process is the Idle process or one of the * CSRSS processes, this function fails and the last error code * is ERROR_ACCESS_DENIED because their access restrictions * prevent user-level code from opening them. - * + * * If the specified process is a 64-bit process and the caller is * a 32-bit process, this function fails and the last error code * is ERROR_PARTIAL_COPY (299). - * + * * @return If the function succeeds, it returns an open handle to the * specified snapshot. - * + * * If the function fails, it returns INVALID_HANDLE_VALUE. To get * extended error information, call GetLastError. Possible error * codes include ERROR_BAD_LENGTH. @@ -2134,7 +2020,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Retrieves information about the first process encountered in a system * snapshot. - * + * * @param hSnapshot * A handle to the snapshot returned from a previous call to the * CreateToolhelp32Snapshot function. @@ -2154,7 +2040,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Retrieves information about the next process recorded in a system * snapshot. - * + * * @param hSnapshot * A handle to the snapshot returned from a previous call to the * CreateToolhelp32Snapshot function. @@ -2171,7 +2057,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * The SetEnvironmentVariable function sets the contents of the specified * environment variable for the current process. - * + * * @param lpName * Pointer to a string containing the name of the environment * variable to set. @@ -2179,7 +2065,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, * Pointer to a string containing the value to set it to. if this * value is NULL, the variable is deleted from the current * process' environment. - * + * * @return If the function succeeds, the return value is non-zero. If the * function fails, the return value is zero. To get extended error * information, call GetLastError. @@ -2189,7 +2075,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Retrieves the contents of the specified variable from the environment * block of the calling process. - * + * * @param lpName * The name of the environment variable. * @param lpBuffer @@ -2232,8 +2118,8 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * @param lpszEnvironmentBlock A pointer to a block of environment strings * obtained by calling the {@link #GetEnvironmentStrings()} function - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see FreeEnvironmentStrings * documentation */ @@ -2241,7 +2127,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Returns the locale identifier for the system locale. - * + * * @return Returns the locale identifier for the system default locale, * identified by LOCALE_SYSTEM_DEFAULT. */ @@ -2249,7 +2135,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Returns the locale identifier for the user default locale. - * + * * @return Returns the locale identifier for the user default locale, * represented as LOCALE_USER_DEFAULT. If the user default locale is * a custom locale, this function always returns @@ -2263,7 +2149,7 @@ boolean GetDiskFreeSpaceEx(String lpDirectoryName, /** * Retrieves an integer associated with a key in the specified section of an * initialization file. - * + * * @param appName * The name of the section in the initialization file. * @param keyName @@ -2288,7 +2174,7 @@ int GetPrivateProfileInt(String appName, String keyName, int defaultValue, /** * Retrieves a string from the specified section in an initialization file. - * + * * @param lpAppName * The name of the section containing the key name. If this * parameter is {@code null}, the @@ -2351,11 +2237,11 @@ DWORD GetPrivateProfileString(String lpAppName, String lpKeyName, /** * Copies a string into the specified section of an initialization file. - * + * * If the file was created using Unicode characters, the function writes * Unicode characters to the file. Otherwise, the function writes ANSI * characters. - * + * * @param lpAppName * The name of the section to which the string will be copied. If * the section does not exist, it is created. The name of the @@ -2387,7 +2273,7 @@ boolean WritePrivateProfileString(String lpAppName, String lpKeyName, /** * Retrieves all the keys and values for the specified section of an * initialization file. - * + * *

* Each string has the following format: {@code key=string}. *

@@ -2397,7 +2283,7 @@ boolean WritePrivateProfileString(String lpAppName, String lpKeyName, * copied to the buffer pointed to by the {@code lpReturnedString} * parameter. *

- * + * * @param lpAppName * The name of the section in the initialization file. * @param lpReturnedString @@ -2428,7 +2314,7 @@ DWORD GetPrivateProfileSection(String lpAppName, char[] lpReturnedString, * This operation is atomic; no updates to the initialization file are * allowed while the section names are being copied to the buffer. *

- * + * * @param lpszReturnBuffer * A pointer to a buffer that receives the section names * associated with the named file. The buffer is filled with one @@ -2476,7 +2362,7 @@ boolean WritePrivateProfileSection(String lpAppName, String lpString, /** * Converts a file time to a local file time. - * + * * @param lpFileTime * [in] A pointer to a FILETIME structure containing the * UTC-based file time to be converted into a local file time. @@ -2494,7 +2380,7 @@ boolean FileTimeToLocalFileTime(FILETIME lpFileTime, /** * Converts a time in Coordinated Universal Time (UTC) to a specified time * zone's corresponding local time. - * + * * @param lpTimeZone * [in, optional] A pointer to a TIME_ZONE_INFORMATION structure * that specifies the time zone of interest. If lpTimeZone is @@ -2512,7 +2398,7 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, /** * Converts a system time to file time format. System time is based on * Coordinated Universal Time (UTC). - * + * * @param lpSystemTime * [in] A pointer to a SYSTEMTIME structure that contains the * system time to be converted from UTC to file time format. @@ -2549,7 +2435,7 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, * documentation */ HANDLE CreateRemoteThread(HANDLE hProcess, WinBase.SECURITY_ATTRIBUTES lpThreadAttributes, int dwStackSize, FOREIGN_THREAD_START_ROUTINE lpStartAddress, Pointer lpParameter, DWORD dwCreationFlags, Pointer lpThreadId); - + /** * Writes data to an area of memory in a specified process. The entire area * to be written to must be accessible or the operation fails. @@ -2561,13 +2447,13 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, * @param nSize The number of bytes to be written to the specified process. * @param lpNumberOfBytesWritten A variable that receives the number of bytes * transferred into the specified process. If {@code null} the parameter is ignored. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see WriteProcessMemory * documentation */ boolean WriteProcessMemory(HANDLE hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, IntByReference lpNumberOfBytesWritten); - + /** * Reads data from an area of memory in a specified process. The entire area * to be read must be accessible or the operation fails. @@ -2579,8 +2465,8 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, * @param nSize The number of bytes to be read from the specified process. * @param lpNumberOfBytesRead A variable that receives the number of bytes * transferred into the specified buffer. If {@code null} the parameter is ignored. - * @return {@code true} if successful, {@code false} otherwise. - * To get extended error information, call {@link #GetLastError()}. + * @return {@code true} if successful, {@code false} otherwise. + * To get extended error information, call {@link #GetLastError()}. * @see ReadProcessMemory * documentation */ @@ -2602,7 +2488,7 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, * documentation */ SIZE_T VirtualQueryEx(HANDLE hProcess, Pointer lpAddress, MEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength); - + /** * Defines, redefines, or deletes MS-DOS device names. * @param dwFlags The controllable aspects of the function - see the @@ -2621,7 +2507,7 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, * @see DefineDosDevice */ boolean DefineDosDevice(int dwFlags, String lpDeviceName, String lpTargetPath); - + /** * Retrieves information about MS-DOS device names * @param lpDeviceName An MS-DOS device name string specifying the target @@ -2638,7 +2524,7 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, * strings represent undeleted prior mappings for the device. Each * null-terminated string stored into the buffer is the name of an existing * MS-DOS device, for example, {@code \Device\HarddiskVolume1} or {@code \Device\Floppy0}. - * @param ucchMax The maximum number of characters that can be stored into the buffer + * @param ucchMax The maximum number of characters that can be stored into the buffer * @return If the function succeeds, the return value is the number of characters stored * into the buffer, otherwise zero. Use {@link #GetLastError()} to get extended * error information. If the buffer is too small, the function fails and the last error @@ -2684,7 +2570,7 @@ boolean SystemTimeToTzSpecificLocalTime(TIME_ZONE_INFORMATION lpTimeZone, boolean FindNextVolumeMountPoint(HANDLE hFindVolumeMountPoint, char[] lpszVolumeMountPoint, int cchBufferLength); /** - * Closes the specified mounted folder search handle. + * Closes the specified mounted folder search handle. * @param hFindVolumeMountPoint A mounted folder search handle returned by * a previous call to the {@link #FindFirstVolumeMountPoint(String, char[], int)} * function. @@ -2789,7 +2675,7 @@ boolean GetVolumeInformation(String lpRootPathName, * Retrieves the volume mount point where the specified path is mounted. * @param lpszFileName The input path string. Both absolute and relative * file and directory names, for example "..", are acceptable in - * this path. If you specify a relative directory or file name without a + * this path. If you specify a relative directory or file name without a * volume qualifier, returns the drive letter of the boot volume. If this * parameter is an empty string, the function fails but the last error is * set to {@code ERROR_SUCCESS}. @@ -2840,7 +2726,7 @@ boolean GetVolumePathNamesForVolumeName(String lpszVolumeName, * @see Kernel32Util#extractVolumeGUID(String) */ HANDLE FindFirstVolume(char[] lpszVolumeName, int cchBufferLength); - + /** * Continues a volume search started by a call to the {@link #FindFirstVolume(char[], int)} * function - finds one volume per call. @@ -2856,9 +2742,9 @@ boolean GetVolumePathNamesForVolumeName(String lpszVolumeName, * @see Kernel32Util#extractVolumeGUID(String) */ boolean FindNextVolume(HANDLE hFindVolume, char[] lpszVolumeName, int cchBufferLength); - + /** - * Closes the specified volume search handle. + * Closes the specified volume search handle. * @param hFindVolume The volume search handle returned by a previous call to the * {@link #FindFirstVolume(char[], int)}. * @return {@code true} if succeeds. If fails then call {@link #GetLastError()} diff --git a/contrib/platform/src/com/sun/jna/platform/win32/User32.java b/contrib/platform/src/com/sun/jna/platform/win32/User32.java index 824ce4abac..b10c728a5a 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/User32.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/User32.java @@ -25,7 +25,7 @@ /** * Provides access to the w32 user32 library. Incomplete implementation to * support demos. - * + * * @author Todd Fast, todd.fast@sun.com * @author twalljava@dev.java.net * @author Tobias Wolf, wolf.tobias@gmx.net @@ -42,28 +42,28 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { * Handle for message-only window. */ public static final HWND HWND_MESSAGE = new HWND(Pointer.createConstant(-3)); - + /** The cs globalclass. */ int CS_GLOBALCLASS = 0x4000; /** The ws ex topmost. */ int WS_EX_TOPMOST = 0x00000008; - + /** The hRecipient parameter is a window handle. */ int DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000; /** The hRecipient parameter is a service status handle. */ int DEVICE_NOTIFY_SERVICE_HANDLE = 0x00000001; - + /** The device notify all interface classes. */ int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x00000004; - + /** * This function retrieves a handle to a display device context (DC) for the * client area of the specified window. The display device context can be * used in subsequent graphics display interface (GDI) functions to draw in * the client area of the window. - * + * * @param hWnd * Handle to the window whose device context is to be retrieved. * If this value is NULL, GetDC retrieves the device context for @@ -78,7 +78,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { * This function releases a device context (DC), freeing it for use by other * applications. The effect of ReleaseDC depends on the type of device * context. - * + * * @param hWnd * Handle to the window whose device context is to be released. * @param hDC @@ -93,7 +93,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { * This function retrieves the handle to the top-level window whose class * name and window name match the specified strings. This function does not * search child windows. - * + * * @param lpClassName * Long pointer to a null-terminated string that specifies the * class name or is an atom that identifies the class-name @@ -114,7 +114,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { /** * This function retrieves the name of the class to which the specified * window belongs. - * + * * @param hWnd * Handle to the window and, indirectly, the class to which the * window belongs. @@ -134,7 +134,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { /** * Retrieves information about the active window or a specified graphical * user interface (GUI) thread. - * + * * @param idThread * Identifies the thread for which information is to be * retrieved. To retrieve this value, use the @@ -154,7 +154,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { /** * The GetWindowInfo function retrieves information about the specified * window. - * + * * @param hWnd * Handle to the window whose information is to be retrieved. * @param pwi @@ -170,7 +170,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { * This function retrieves the dimensions of the bounding rectangle of the * specified window. The dimensions are given in screen coordinates that are * relative to the upper-left corner of the screen. - * + * * @param hWnd * Handle to the window. * @param rect @@ -186,7 +186,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { * This function copies the text of the specified window's title bar - if it * has one - into a buffer. If the specified window is a control, the text * of the control is copied. - * + * * @param hWnd * Handle to the window or control containing the text. * @param lpString @@ -210,7 +210,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { * window's title bar text - if the window has a title bar. If the specified * window is a control, the function retrieves the length of the text within * the control. - * + * * @param hWnd * Handle to the window or control. * @return The length, in characters, of the text indicates success. Under @@ -223,7 +223,7 @@ public interface User32 extends StdCallLibrary, WinUser, WinNT { /** * The GetWindowModuleFileName function retrieves the full path and file * name of the module associated with the specified window handle. - * + * * @param hWnd * Handle to the window whose module file name will be retrieved. * @param lpszFileName @@ -241,7 +241,7 @@ int GetWindowModuleFileName(HWND hWnd, char[] lpszFileName, * This function retrieves the identifier of the thread that created the * specified window and, optionally, the identifier of the process that * created the window. - * + * * @param hWnd * Handle to the window. * @param lpdwProcessId @@ -259,7 +259,7 @@ int GetWindowModuleFileName(HWND hWnd, char[] lpszFileName, * the handle to each window, in turn, to an application-defined callback * function. EnumWindows continues until the last top-level window is * enumerated or the callback function returns FALSE. - * + * * @param lpEnumFunc * Long pointer to an application-defined callback function. * @param data @@ -276,7 +276,7 @@ int GetWindowModuleFileName(HWND hWnd, char[] lpszFileName, * in turn, to an application-defined callback function. EnumChildWindows * continues until the last child window is enumerated or the callback * function returns FALSE. - * + * * @param hWnd * Handle to the parent window whose child windows are to be * enumerated. If this parameter is NULL, this function is @@ -302,7 +302,7 @@ int GetWindowModuleFileName(HWND hWnd, char[] lpszFileName, * the last window is enumerated or the callback function returns FALSE. To * enumerate child windows of a particular window, use the EnumChildWindows * function. - * + * * @param dwThreadId * Identifies the thread whose windows are to be enumerated. * @param lpEnumFunc @@ -322,7 +322,7 @@ boolean EnumThreadWindows(int dwThreadId, WNDENUMPROC lpEnumFunc, /** * The FlashWindowEx function flashes the specified window. It does not * change the active state of the window. - * + * * @param pfwi * Pointer to the FLASHWINFO structure. * @return The return value specifies the window's state before the call to @@ -335,7 +335,7 @@ boolean EnumThreadWindows(int dwThreadId, WNDENUMPROC lpEnumFunc, /** * This function loads the specified icon resource from the executable * (.exe) file associated with an application instance. - * + * * @param hInstance * Handle to an instance of the module whose executable file * contains the icon to be loaded. This parameter must be NULL @@ -358,7 +358,7 @@ boolean EnumThreadWindows(int dwThreadId, WNDENUMPROC lpEnumFunc, /** * This function loads an icon, cursor, or bitmap. - * + * * @param hinst * Handle to an instance of the module that contains the image to * be loaded. @@ -389,7 +389,7 @@ HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, /** * This function destroys an icon and frees any memory the icon occupied. - * + * * @param hicon * Handle to the icon to be destroyed. The icon must not be in * use. @@ -402,7 +402,7 @@ HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, * This function retrieves information about the specified window. * GetWindowLong also retrieves the 32-bit (long) value at the specified * offset into the extra window memory of a window. - * + * * @param hWnd * Handle to the window and, indirectly, the class to which the * window belongs. @@ -417,7 +417,7 @@ HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, * This function changes an attribute of the specified window. SetWindowLong * also sets a 32-bit (LONG) value at the specified offset into the extra * window memory of a window. - * + * * @param hWnd * Handle to the window and, indirectly, the class to which the * window belongs. @@ -431,29 +431,11 @@ HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, */ int SetWindowLong(HWND hWnd, int nIndex, int dwNewLong); - /** - * This function changes an attribute of the specified window. SetWindowLong - * also sets a 32-bit (LONG) value at the specified offset into the extra - * window memory of a window. Do not use this version on Windows-64. - * - * @param hWnd - * Handle to the window and, indirectly, the class to which the - * window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be set. - * @param dwNewLong - * Specifies the replacement value. - * @return The previous value of the specified 32-bit integer indicates - * success. Zero indicates failure. To get extended error - * information, call GetLastError. - */ - Pointer SetWindowLong(HWND hWnd, int nIndex, Pointer dwNewLong); - /** * The GetWindowLongPtr function retrieves information about the specified * window. The function also retrieves the value at a specified offset into * the extra window memory. - * + * * @param hWnd * Handle to the window and, indirectly, the class to which the * window belongs. @@ -472,31 +454,7 @@ HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, * The SetWindowLongPtr function changes an attribute of the specified * window. The function also sets a value at the specified offset in the * extra window memory. - * - * @param hWnd - * Handle to the window and, indirectly, the class to which the - * window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be set. - * @param dwNewLongPtr - * Specifies the replacement value. - * @return If the function succeeds, the return value is the previous value - * of the specified offset. If the function fails, the return value - * is zero. To get extended error information, call GetLastError. If - * the previous value is zero and the function succeeds, the return - * value is zero, but the function does not clear the last error - * information. To determine success or failure, clear the last - * error information by calling SetLastError(0), then call - * SetWindowLongPtr. Function failure will be indicated by a return - * value of zero and a GetLastError result that is nonzero. - */ - LONG_PTR SetWindowLongPtr(HWND hWnd, int nIndex, LONG_PTR dwNewLongPtr); - - /** - * The SetWindowLongPtr function changes an attribute of the specified - * window. The function also sets a value at the specified offset in the - * extra window memory. - * + * * @param hWnd * Handle to the window and, indirectly, the class to which the * window belongs. @@ -519,7 +477,7 @@ HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, /** * The SetLayeredWindowAttributes function sets the opacity and transparency * color key of a layered window. - * + * * @param hwnd * Handle to the layered window. * @param crKey @@ -540,7 +498,7 @@ boolean SetLayeredWindowAttributes(HWND hwnd, int crKey, byte bAlpha, /** * The GetLayeredWindowAttributes function retrieves the opacity and * transparency color key of a layered window. - * + * * @param hwnd * Handle to the layered window. A layered window is created by * specifying WS_EX_LAYERED when creating the window with the @@ -572,7 +530,7 @@ boolean GetLayeredWindowAttributes(HWND hwnd, IntByReference pcrKey, /** * The UpdateLayeredWindow function updates the position, size, shape, * content, and translucency of a layered window. - * + * * @param hwnd * Handle to a layered window. A layered window is created by * specifying WS_EX_LAYERED when creating the window with the @@ -623,7 +581,7 @@ boolean UpdateLayeredWindow(HWND hwnd, HDC hdcDst, POINT pptDst, * determines the area within the window where the system permits drawing. * The system does not display any portion of a window that lies outside of * the window region. - * + * * @param hWnd * Handle to the window whose window region is to be set. * @param hRgn @@ -643,7 +601,7 @@ boolean UpdateLayeredWindow(HWND hwnd, HDC hdcDst, POINT pptDst, /** * The GetKeyboardState function copies the status of the 256 virtual keys * to the specified buffer. - * + * * @param lpKeyState * Pointer to the 256-byte array that receives the status data * for each virtual key. @@ -657,7 +615,7 @@ boolean UpdateLayeredWindow(HWND hwnd, HDC hdcDst, POINT pptDst, * This function determines whether a key is up or down at the time the * function is called, and whether the key was pressed after a previous call * to GetAsyncKeyState. - * + * * @param vKey * Specifies one of 256 possible virtual-key codes. * @return If the function succeeds, the return value specifies whether the @@ -673,7 +631,7 @@ boolean UpdateLayeredWindow(HWND hwnd, HDC hdcDst, POINT pptDst, * monitor the system for certain types of events. These events are * associated either with a specific thread or with all threads in the same * desktop as the calling thread. - * + * * @param idHook * Specifies the type of hook procedure to be installed. * @param lpfn @@ -695,7 +653,7 @@ HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, * The CallNextHookEx function passes the hook information to the next hook * procedure in the current hook chain. A hook procedure can call this * function either before or after processing the hook information. - * + * * @param hhk * Ignored. * @param nCode @@ -716,35 +674,10 @@ HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, */ LRESULT CallNextHookEx(HHOOK hhk, int nCode, WPARAM wParam, LPARAM lParam); - /** - * The CallNextHookEx function passes the hook information to the next hook - * procedure in the current hook chain. A hook procedure can call this - * function either before or after processing the hook information. - * - * @param hhk - * Ignored. - * @param nCode - * Specifies the hook code passed to the current hook procedure. - * The next hook procedure uses this code to determine how to - * process the hook information. - * @param wParam - * Specifies the wParam value passed to the current hook - * procedure. The meaning of this parameter depends on the type - * of hook associated with the current hook chain. - * @param lParam - * Specifies the lParam value passed to the current hook - * procedure. The meaning of this parameter depends on the type - * of hook associated with the current hook chain. - * @return This value is returned by the next hook procedure in the chain. - * The current hook procedure must also return this value. The - * meaning of the return value depends on the hook type. - */ - LRESULT CallNextHookEx(HHOOK hhk, int nCode, WPARAM wParam, Pointer lParam); - /** * The UnhookWindowsHookEx function removes a hook procedure installed in a * hook chain by the SetWindowsHookEx function. - * + * * @param hhk * Handle to the hook to be removed. This parameter is a hook * handle obtained by a previous call to SetWindowsHookEx. @@ -757,7 +690,7 @@ HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, /** * This function retrieves a message from the calling thread's message queue * and places it in the specified structure. - * + * * @param lpMsg * Pointer to an MSG structure that receives message information * from the thread's message queue. @@ -780,7 +713,7 @@ HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, /** * This function checks a thread message queue for a message and places the * message (if any) in the specified structure. - * + * * @param lpMsg * Pointer to an MSG structure that receives message information. * @param hWnd @@ -804,7 +737,7 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, * The character messages are posted to the calling thread's message queue, * to be read the next time the thread calls the GetMessage or PeekMessage * function. - * + * * @param lpMsg * Pointer to an MSG structure that contains message information * retrieved from the calling thread's message queue by using the @@ -821,7 +754,7 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, /** * This function dispatches a message to a window procedure. It is typically * used to dispatch a message retrieved by the GetMessage function. - * + * * @param lpMsg * Pointer to an MSG structure that contains the message. * @return The return value specifies the value returned by the window @@ -835,7 +768,7 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, * thread that created the specified window and then returns without waiting * for the thread to process the message. Messages in a message queue are * retrieved by calls to the GetMessage or PeekMessage function. - * + * * @param hWnd * Handle to the window whose window procedure is to receive the * message. @@ -852,7 +785,7 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, * This function indicates to Windows that a thread has made a request to * terminate (quit). It is typically used in response to a WM_DESTROY * message. - * + * * @param nExitCode * Specifies an application exit code. This value is used as the * wParam parameter of the WM_QUIT message. @@ -863,7 +796,7 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, * The GetSystemMetrics function retrieves various system metrics (widths * and heights of display elements) and system configuration settings. All * dimensions retrieved by GetSystemMetrics are in pixels. - * + * * @param nIndex * System metric or configuration setting to retrieve. This * parameter can be one of the following values. Note that all @@ -880,18 +813,18 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, /** * Changes the parent window of the specified child window. - * + * * @param hWndChild * A handle to the child window. - * + * * @param hWndNewParent * A handle to the new parent window. If this parameter is NULL, * the desktop window becomes the new parent window. If this * parameter is HWND_MESSAGE, the child window becomes a * message-only window. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -899,14 +832,14 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, /** * Determines the visibility state of the specified window. - * + * * @param hWnd * A handle to the window to be tested. - * + * * @return If the specified window, its parent window, its parent's parent * window, and so forth, have the WS_VISIBLE style, the return value * is nonzero. Otherwise, the return value is zero. - * + * * Because the return value specifies whether the window has the * WS_VISIBLE style, it may be nonzero even if the window is totally * obscured by other windows. @@ -918,22 +851,22 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, * top-level window, the position and dimensions are relative to the * upper-left corner of the screen. For a child window, they are relative to * the upper-left corner of the parent window's client area. - * + * * @param hWnd * A handle to the window. - * + * * @param X * The new position of the left side of the window. - * + * * @param Y * The new position of the top of the window. - * + * * @param nWidth * The new width of the window. - * + * * @param nHeight * The new height of the window. - * + * * @param bRepaint * Indicates whether the window is to be repainted. If this * parameter is TRUE, the window receives a message. If the @@ -941,9 +874,9 @@ boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, * applies to the client area, the nonclient area (including the * title bar and scroll bars), and any part of the parent window * uncovered as a result of moving a child window. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -955,33 +888,33 @@ boolean MoveWindow(HWND hWnd, int X, int Y, int nWidth, int nHeight, * window. These windows are ordered according to their appearance on the * screen. The topmost window receives the highest rank and is the first * window in the Z order. - * + * * @param hWnd * A handle to the window. - * + * * @param hWndInsertAfter * A handle to the window to precede the positioned window in the * Z order. - * + * * @param X * The new position of the left side of the window, in client * coordinates. - * + * * @param Y * The new position of the top of the window, in client * coordinates. - * + * * @param cx * The new width of the window, in pixels. - * + * * @param cy * The new height of the window, in pixels. - * + * * @param uFlags * The window sizing and positioning flags. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -991,21 +924,21 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, /** * Attaches or detaches the input processing mechanism of one thread to that * of another thread. - * + * * @param idAttach * The identifier of the thread to be attached to another thread. * The thread to be attached cannot be a system thread. - * + * * @param idAttachTo * The identifier of the thread to which idAttach will be * attached. This thread cannot be a system thread. A thread * cannot attach to itself. Therefore, idAttachTo cannot equal * idAttach. - * + * * @param fAttach * If this parameter is TRUE, the two threads are attached. If * the parameter is FALSE, the threads are detached. - * + * * @return If the function succeeds, the return value is nonzero. */ boolean AttachThreadInput(DWORD idAttach, DWORD idAttachTo, boolean fAttach); @@ -1016,11 +949,11 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, * various visual cues are changed for the user. The system assigns a * slightly higher priority to the thread that created the foreground window * than it does to other threads. - * + * * @param hWnd * A handle to the window that should be activated and brought to * the foreground. - * + * * @return If the window was brought to the foreground, the return value is * nonzero. */ @@ -1031,7 +964,7 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, * user is currently working). The system assigns a slightly higher priority * to the thread that creates the foreground window than it does to other * threads. - * + * * @return The return value is a handle to the foreground window. The * foreground window can be NULL in certain circumstances, such as * when a window is losing activation. @@ -1041,11 +974,11 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, /** * Sets the keyboard focus to the specified window. The window must be * attached to the calling thread's message queue. - * + * * @param hWnd * A handle to the window that will receive the keyboard input. * If this parameter is NULL, keystrokes are ignored. - * + * * @return If the function succeeds, the return value is the handle to the * window that previously had the keyboard focus. If the hWnd * parameter is invalid or the window is not attached to the calling @@ -1056,23 +989,23 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, /** * Synthesizes keystrokes, mouse motions, and button clicks. - * + * * @param nInputs * The number of structures in the pInputs array. - * + * * @param pInputs * An array of INPUT structures. Each structure represents an * event to be inserted into the keyboard or mouse input stream. - * + * * @param cbSize * The size, in bytes, of an INPUT structure. If cbSize is not * the size of an INPUT structure, the function fails. - * + * * @return The function returns the number of events that it successfully * inserted into the keyboard or mouse input stream. If the function * returns zero, the input was already blocked by another thread. To * get extended error information, call GetLastError. - * + * * This function fails when it is blocked by UIPI. Note that neither * GetLastError nor the return value will indicate the failure was * caused by UIPI blocking. @@ -1083,17 +1016,17 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, * Waits until the specified process has finished processing its initial * input and is waiting for user input with no input pending, or until the * time-out interval has elapsed. - * + * * @param hProcess * A handle to the process. If this process is a console * application or does not have a message queue, WaitForInputIdle * returns immediately. - * + * * @param dwMilliseconds * The time-out interval, in milliseconds. If dwMilliseconds is * INFINITE, the function does not return until the process is * idle. - * + * * @return The following table shows the possible return values for this * function. * @@ -1122,27 +1055,27 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, * The InvalidateRect function adds a rectangle to the specified window's * update region. The update region represents the portion of the window's * client area that must be redrawn. - * + * * @param hWnd * A handle to the window whose update region has changed. If * this parameter is NULL, the system invalidates and redraws all * windows, not just the windows for this application, and sends * the WM_ERASEBKGND and WM_NCPAINT messages before the function * returns. Setting this parameter to NULL is not recommended. - * + * * @param lpRect * A pointer to a RECT structure that contains the client * coordinates of the rectangle to be added to the update region. * If this parameter is NULL, the entire client area is added to * the update region. - * + * * @param bErase * Specifies whether the background within the update region is * to be erased when the update region is processed. If this * parameter is TRUE, the background is erased when the * BeginPaint function is called. If this parameter is FALSE, the * background remains unchanged. - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. */ @@ -1151,26 +1084,26 @@ boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, /** * The RedrawWindow function updates the specified rectangle or region in a * window's client area. - * + * * @param hWnd * A handle to the window to be redrawn. If this parameter is * NULL, the desktop window is updated. - * + * * @param lprcUpdate * A pointer to a RECT structure containing the coordinates, in * device units, of the update rectangle. This parameter is * ignored if the hrgnUpdate parameter identifies a region. - * + * * @param hrgnUpdate * A handle to the update region. If both the hrgnUpdate and * lprcUpdate parameters are NULL, the entire client area is * added to the update region. - * + * * @param flags * One or more redraw flags. This parameter can be used to * invalidate or validate a window, control repainting, and * control which windows are affected by RedrawWindow. - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. */ @@ -1180,15 +1113,15 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Retrieves a handle to a window that has the specified relationship * (Z-Order or owner) to the specified window. - * + * * @param hWnd * A handle to a window. The window handle retrieved is relative * to this window, based on the value of the uCmd parameter. - * + * * @param uCmd * The relationship between the specified window and the window * whose handle is to be retrieved. - * + * * @return If the function succeeds, the return value is a window handle. If * no window exists with the specified relationship to the specified * window, the return value is NULL. To get extended error @@ -1202,10 +1135,10 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * is not empty. The function sends a WM_PAINT message directly to the * window procedure of the specified window, bypassing the application * queue. If the update region is empty, no message is sent. - * + * * @param hWnd * Handle to the window to be updated. - * + * * @return If the function succeeds, the return value is nonzero. If the * function fails, the return value is zero. */ @@ -1213,10 +1146,10 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Sets the specified window's show state. - * + * * @param hWnd * A handle to the window. - * + * * @param nCmdShow * Controls how the window is to be shown. This parameter is * ignored the first time an application calls ShowWindow, if the @@ -1224,9 +1157,9 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * structure. Otherwise, the first time ShowWindow is called, the * value should be the value obtained by the WinMain function in * its nCmdShow parameter. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -1234,12 +1167,12 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Minimizes (but does not destroy) the specified window. - * + * * @param hWnd * A handle to the window to be minimized. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -1247,7 +1180,7 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Defines a system-wide hot key. - * + * * @param hWnd * A handle to the window that will receive * @param id @@ -1258,7 +1191,7 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * @param vk * The virtual-key code of the hot key * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. * {@link WinUser#WM_HOTKEY} messages generated by the hot key @@ -1283,17 +1216,17 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Frees a hot key previously registered by the calling thread. - * + * * @param hWnd * A handle to the window associated with the hot key to be * freed. This parameter should be NULL if the hot key is not * associated with a window. - * + * * @param id * The identifier of the hot key to be freed. - * + * * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. */ @@ -1301,11 +1234,11 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Retrieves the time of the last input event. - * + * * @param plii * structure that receives the time of the last input event * @return If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. */ @@ -1314,18 +1247,18 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Registers a window class for subsequent use in calls to the CreateWindow * or CreateWindowEx function. - * + * * @param lpwcx * Type: const WNDCLASSEX* A pointer to a WNDCLASSEX structure. * You must fill the structure with the appropriate class * attributes before passing it to the function. - * + * * @return If the function succeeds, the return value is a class atom that * uniquely identifies the class being registered. This atom can * only be used by the CreateWindow, CreateWindowEx, GetClassInfo, * GetClassInfoEx, FindWindow, FindWindowEx, and UnregisterClass * functions and the IActiveIMMap::FilterClientWindows method. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. */ @@ -1333,10 +1266,10 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, /** * Unregisters a window class, freeing the memory required for the class. - * + * * @param lpClassName * [in] Type: LPCTSTR - * + * * A null-terminated string or a class atom. If lpClassName is a * string, it specifies the window class name. This class name * must have been registered by a previous call to the @@ -1346,13 +1279,13 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * previous call to the RegisterClass or RegisterClassEx * function. The atom must be in the low-order word of * lpClassName; the high-order word must be zero. - * + * * @param hInstance * [in,optional] Type: HINSTANCE A handle to the instance of the * module that created the class. * - * + * * @return Type: BOOL If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. */ @@ -1363,16 +1296,16 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * style; otherwise, this function is identical to the CreateWindow * function. For more information about creating a window and for full * descriptions of the other parameters of CreateWindowEx, see CreateWindow. - * + * * @param dwExStyle * [in] Type: DWORD - * + * * The extended window style of the window being created. For a * list of possible values,see Extended Window Styles. - * + * * @param lpClassName * [in, optional] Type: LPCTSTR - * + * * A null-terminated string or a class atom created by a previous * call to the RegisterClass or RegisterClassEx function. The * atom must be in the low-order word of lpClassName; the @@ -1382,10 +1315,10 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * provided that the module that registers the class is also the * module that creates the window. The class name can also be any * of the predefined system class names. - * + * * @param lpWindowName * [in, optional] Type: LPCTSTR - * + * * The window name. If the window style specifies a title bar, * the window title pointed to by lpWindowName is displayed in * the title bar. When using CreateWindow to create controls, @@ -1394,17 +1327,17 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * a static control with the SS_ICON style, use lpWindowName to * specify the icon name or identifier. To specify an identifier, * use the syntax "#num". - * + * * @param dwStyle * [in] Type: DWORD - * + * * The style of the window being created. This parameter can be a * combination of the window style values, plus the control * styles indicated in the Remarks section. - * + * * @param x * [in] Type: int - * + * * The initial horizontal position of the window. For an * overlapped or pop-up window, the x parameter is the initial * x-coordinate of the window's upper-left corner, in screen @@ -1416,10 +1349,10 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * CW_USEDEFAULT is valid only for overlapped windows; if it is * specified for a pop-up or child window, the x and y parameters * are set to zero. - * + * * @param y * [in] Type: int - * + * * The initial vertical position of the window. For an overlapped * or pop-up window, the y parameter is the initial y-coordinate * of the window's upper-left corner, in screen coordinates. For @@ -1429,7 +1362,7 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * list box y is the initial y-coordinate of the upper-left * corner of the list box's client area relative to the * upper-left corner of the parent window's client area. - * + * * If an overlapped window is created with the WS_VISIBLE style * bit set and the x parameter is set to CW_USEDEFAULT, then the * y parameter determines how the window is shown. If the y @@ -1438,10 +1371,10 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * created. If the y parameter is some other value, then the * window manager calls ShowWindow with that value as the * nCmdShow parameter. - * + * * @param nWidth * [in] Type: int - * + * * The width, in device units, of the window. For overlapped * windows, nWidth is the window's width, in screen coordinates, * or CW_USEDEFAULT. If nWidth is CW_USEDEFAULT, the system @@ -1452,29 +1385,29 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * valid only for overlapped windows; if CW_USEDEFAULT is * specified for a pop-up or child window, the nWidth and nHeight * parameter are set to zero. - * + * * @param nHeight * [in] Type: int - * + * * The height, in device units, of the window. For overlapped * windows, nHeight is the window's height, in screen * coordinates. If the nWidth parameter is set to CW_USEDEFAULT, * the system ignores nHeight. - * + * * @param hWndParent * [in, optional] Type: HWND - * + * * A handle to the parent or owner window of the window being * created. To create a child window or an owned window, supply a * valid window handle. This parameter is optional for pop-up * windows. - * + * * To create a message-only window, supply HWND_MESSAGE or a * handle to an existing message-only window. - * + * * @param hMenu * [in, optional] Type: HMENU - * + * * A handle to a menu, or specifies a child-window identifier, * depending on the window style. For an overlapped or pop-up * window, hMenu identifies the menu to be used with the window; @@ -1484,36 +1417,36 @@ boolean RedrawWindow(HWND hWnd, RECT lprcUpdate, * parent about events. The application determines the * child-window identifier; it must be unique for all child * windows with the same parent window. - * + * * @param hInstance * [in, optional] Type: HINSTANCE - * + * * A handle to the instance of the module to be associated with * the window. - * + * * @param lpParam * [in, optional] Type: LPVOID - * + * * Pointer to a value to be passed to the window through the * CREATESTRUCT structure (lpCreateParams member) pointed to by * the lParam param of the WM_CREATE message. This message is * sent to the created window by this function before it returns. - * + * * If an application calls CreateWindow to create a MDI client * window, lpParam should point to a CLIENTCREATESTRUCT * structure. If an MDI client window calls CreateWindow to * create an MDI child window, lpParam should point to a * MDICREATESTRUCT structure. lpParam may be NULL if no * additional data is needed. - * + * * @return Type: HWND - * + * * If the function succeeds, the return value is a handle to the new * window. - * + * * If the function fails, the return value is NULL. To get extended * error information, call GetLastError. - * + * * This function typically fails for one of the following reasons:

* - an invalid parameter value

* - the system class was registered by a different module

@@ -1533,20 +1466,20 @@ public HWND CreateWindowEx(int dwExStyle, WString lpClassName, * flushes the thread message queue, destroys timers, removes clipboard * ownership, and breaks the clipboard viewer chain (if the window is at the * top of the viewer chain). - * + * * If the specified window is a parent or owner window, DestroyWindow * automatically destroys the associated child or owned windows when it * destroys the parent or owner window. The function first destroys child or * owned windows, and then it destroys the parent or owner window. - * + * * DestroyWindow also destroys modeless dialog boxes created by the * CreateDialog function. - * + * * @param hWnd * [in] Type: HWND A handle to the window to be destroyed. - * + * * @return Type: BOOL If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. */ @@ -1556,34 +1489,34 @@ public HWND CreateWindowEx(int dwExStyle, WString lpClassName, * Retrieves information about a window class, including a handle to the * small icon associated with the window class. The GetClassInfo function * does not retrieve a handle to the small icon. - * + * * @param hinst * [in, optional] Type: HINSTANCE - * + * * A handle to the instance of the application that created the * class. To retrieve information about classes defined by the * system (such as buttons or list boxes), set this parameter to * NULL. - * + * * @param lpszClass * [in] Type: LPCTSTR - * + * * The class name. The name must be that of a preregistered class * or a class registered by a previous call to the RegisterClass * or RegisterClassEx function. Alternatively, this parameter can * be a class atom created by a previous call to RegisterClass or * RegisterClassEx. The atom must be in the low-order word of * lpszClass; the high-order word must be zero. - * + * * @param lpwcx * [out] Type: LPWNDCLASSEX - * + * * A pointer to a WNDCLASSEX structure that receives the * information about the class. - * + * * @return Type: BOOL If the function finds a matching class and * successfully copies the data, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError} . */ @@ -1595,32 +1528,32 @@ public boolean GetClassInfoEx(HINSTANCE hinst, WString lpszClass, * window messages that an application does not process. This function * ensures that every message is processed. DefWindowProc is called with the * same parameters received by the window procedure. - * + * * @param hWnd * [in] Type: HWND - * + * * A handle to the window procedure that received the message. - * + * * @param Msg * [in] Type: UINT - * + * * The message. - * + * * @param wParam * [in] Type: WPARAM - * + * * Additional message information. The content of this parameter * depends on the value of the Msg parameter. - * + * * @param lParam * [in] Type: LPARAM - * + * * Additional message information. The content of this parameter * depends on the value of the Msg parameter. - * + * * @return Type: LRESULT The return value is the result of the message * processing and depends on the message. - * + * * If the function fails, the return value is zero. To get extended * error information, call {@link Kernel32#GetLastError}. */ @@ -1630,15 +1563,15 @@ public LRESULT DefWindowProc(HWND hWnd, int Msg, WPARAM wParam, /** * Registers the device or type of device for which a window will receive * notifications. - * + * * @param hRecipient [in] A handle to the window or service that will receive * device events for the devices specified in the * NotificationFilter parameter. The same window handle can be * used in multiple calls to RegisterDeviceNotification. - * + * * Services can specify either a window handle or service status * handle. - * + * * @param notificationFilter * [in] A pointer to a block of data that specifies the type of * device for which notifications should be sent. This block @@ -1647,29 +1580,29 @@ public LRESULT DefWindowProc(HWND hWnd, int Msg, WPARAM wParam, * dbch_devicetype member, which can be * DBT_DEVTYP_DEVICEINTERFACE or DBT_DEVTYP_HANDLE. For more * information, see Remarks. - * + * * @param Flags * [in] This parameter can be one of the following values. * DEVICE_NOTIFY_WINDOW_HANDLE0x00000000 The hRecipient parameter * is a window handle. - * + * * DEVICE_NOTIFY_SERVICE_HANDLE0x00000001 The hRecipient * parameter is a service status handle. - * + * * In addition, you can specify the following value. - * + * * DEVICE_NOTIFY_ALL_INTERFACE_CLASSES0x00000004 Notifies the * recipient of device interface events for all device interface * classes. (The dbcc_classguid member is ignored.) - * + * * This value can be used only if the dbch_devicetype member is * DBT_DEVTYP_DEVICEINTERFACE. - * + * * @return value - * + * * If the function succeeds, the return value is a device * notification handle. - * + * * If the function fails, the return value is NULL. To get extended * error information, call GetLastError. */ @@ -1678,14 +1611,14 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Closes the specified device notification handle. - * + * * @param Handle [in] Device notification handle returned by the * RegisterDeviceNotification function. - * + * * @return Return value - * + * * If the function succeeds, the return value is nonzero. - * + * * If the function fails, the return value is zero. To get extended * error information, call GetLastError. */ @@ -1694,10 +1627,10 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Defines a new window message that is guaranteed to be unique throughout the system. * The message value can be used when sending or posting messages. - * + * * @param string * The message to be registered. - * + * * @return If the message is successfully registered, the return value is a message identifier in the range 0xC000 through 0xFFFF. *

* If the function fails, the return value is zero. To get extended error information, call GetLastError. @@ -1707,51 +1640,51 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Retrieves a handle to the display monitor that contains a specified point. - * @param pt A POINT structure that specifies the point of interest in virtual-screen + * @param pt A POINT structure that specifies the point of interest in virtual-screen * coordinates. - * @param dwFlags Determines the function's return value if the window does not intersect + * @param dwFlags Determines the function's return value if the window does not intersect * any display monitor. This parameter can be one of the following values. *

  • MONITOR_DEFAULTTONEAREST
  • *
  • MONITOR_DEFAULTTONULL
  • *
  • MONITOR_DEFAULTTOPRIMARY
  • - * @return If the point is contained by a display monitor, the return value is an HMONITOR - * handle to that display monitor. If the point is not contained by a display monitor, + * @return If the point is contained by a display monitor, the return value is an HMONITOR + * handle to that display monitor. If the point is not contained by a display monitor, * the return value depends on the value of dwFlags. */ HMONITOR MonitorFromPoint(POINT pt, int dwFlags); /** - * Retrieves a handle to the display monitor that has the largest area of intersection with + * Retrieves a handle to the display monitor that has the largest area of intersection with * a specified rectangle. - * @param lprc A pointer to a RECT structure that specifies the rectangle of interest in + * @param lprc A pointer to a RECT structure that specifies the rectangle of interest in * virtual-screen coordinates. - * @param dwFlags Determines the function's return value if the window does not intersect + * @param dwFlags Determines the function's return value if the window does not intersect * any display monitor. This parameter can be one of the following values. *
  • MONITOR_DEFAULTTONEAREST
  • *
  • MONITOR_DEFAULTTONULL
  • *
  • MONITOR_DEFAULTTOPRIMARY
  • - * @return If the rectangle intersects one or more display monitor rectangles, the return - * value is an HMONITOR handle to the display monitor that has the largest area of - * intersection with the rectangle. If the rectangle does not intersect a display + * @return If the rectangle intersects one or more display monitor rectangles, the return + * value is an HMONITOR handle to the display monitor that has the largest area of + * intersection with the rectangle. If the rectangle does not intersect a display * monitor, the return value depends on the value of dwFlags. */ HMONITOR MonitorFromRect(RECT lprc, int dwFlags); /** - * Retrieves a handle to the display monitor that has the largest area of intersection with + * Retrieves a handle to the display monitor that has the largest area of intersection with * the bounding rectangle of a specified window. *

    - * If the window is currently minimized, MonitorFromWindow uses the rectangle of the window + * If the window is currently minimized, MonitorFromWindow uses the rectangle of the window * before it was minimized. * @param hwnd A handle to the window of interest. - * @param dwFlags Determines the function's return value if the window does not intersect + * @param dwFlags Determines the function's return value if the window does not intersect * any display monitor. This parameter can be one of the following values. *
  • MONITOR_DEFAULTTONEAREST
  • *
  • MONITOR_DEFAULTTONULL
  • *
  • MONITOR_DEFAULTTOPRIMARY
  • * @return If the window intersects one or more display monitor rectangles, the return value - * is an HMONITOR handle to the display monitor that has the largest area of - * intersection with the window. If the window does not intersect a display monitor, + * is an HMONITOR handle to the display monitor that has the largest area of + * intersection with the window. If the window does not intersect a display monitor, * the return value depends on the value of dwFlags. */ HMONITOR MonitorFromWindow(HWND hwnd, int dwFlags); @@ -1759,9 +1692,9 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Retrieves information about a display monitor. * @param hMonitor A handle to the display monitor of interest. - * @param lpmi A pointer to a {@link WinUser.MONITORINFO} structure that receives information about + * @param lpmi A pointer to a {@link WinUser.MONITORINFO} structure that receives information about * the specified display monitor. - * @return If the function succeeds, the return value is nonzero. If the function + * @return If the function succeeds, the return value is nonzero. If the function * fails, the return value is zero. */ BOOL GetMonitorInfo(HMONITOR hMonitor, MONITORINFO lpmi); @@ -1769,43 +1702,43 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Retrieves information about a display monitor. * @param hMonitor A handle to the display monitor of interest. - * @param lpmi A pointer to a {@link WinUser.MONITORINFOEX} structure that receives information about + * @param lpmi A pointer to a {@link WinUser.MONITORINFOEX} structure that receives information about * the specified display monitor. - * @return If the function succeeds, the return value is nonzero. If the function + * @return If the function succeeds, the return value is nonzero. If the function * fails, the return value is zero. */ BOOL GetMonitorInfo(HMONITOR hMonitor, MONITORINFOEX lpmi); /** - * Enumerates display monitors (including invisible pseudo-monitors associated with the mirroring drivers) - * that intersect a region formed by the intersection of a specified clipping rectangle and the visible - * region of a device context. EnumDisplayMonitors calls an application-defined MonitorEnumProc callback - * function once for each monitor that is enumerated. Note that GetSystemMetrics (SM_CMONITORS) counts + * Enumerates display monitors (including invisible pseudo-monitors associated with the mirroring drivers) + * that intersect a region formed by the intersection of a specified clipping rectangle and the visible + * region of a device context. EnumDisplayMonitors calls an application-defined MonitorEnumProc callback + * function once for each monitor that is enumerated. Note that GetSystemMetrics (SM_CMONITORS) counts * only the display monitors. - * - * @param hdc A handle to a display device context that defines the visible region of interest. If this - * parameter is NULL, the hdcMonitor parameter passed to the callback function will be NULL, and - * the visible region of interest is the virtual screen that encompasses all the displays on the + * + * @param hdc A handle to a display device context that defines the visible region of interest. If this + * parameter is NULL, the hdcMonitor parameter passed to the callback function will be NULL, and + * the visible region of interest is the virtual screen that encompasses all the displays on the * desktop. - * @param lprcClip A pointer to a RECT structure that specifies a clipping rectangle. The region of + * @param lprcClip A pointer to a RECT structure that specifies a clipping rectangle. The region of * interest is the intersection of the clipping rectangle with the visible region specified by hdc. - * If hdc is non-NULL, the coordinates of the clipping rectangle are relative to the origin of the - * hdc. If hdc is NULL, the coordinates are virtual-screen coordinates. This parameter can be NULL + * If hdc is non-NULL, the coordinates of the clipping rectangle are relative to the origin of the + * hdc. If hdc is NULL, the coordinates are virtual-screen coordinates. This parameter can be NULL * if you don't want to clip the region specified by hdc. * @param lpfnEnum A pointer to an application-defined callback function. * @param dwData Application-defined data that EnumDisplayMonitors passes directly to the lpfnEnum function. - * @return If the function succeeds, the return value is nonzero. If the function fails, the return value + * @return If the function succeeds, the return value is nonzero. If the function fails, the return value * is zero. */ BOOL EnumDisplayMonitors(HDC hdc, RECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData); - + /** * Retrieves the show state and the restored, minimized, and maximized - * positions of the specified window. - * - * @param hwnd A handle to the window. + * positions of the specified window. + * + * @param hwnd A handle to the window. * @param lpwndpl A pointer to the WINDOWPLACEMENT structure that receives the - * show state and position information. + * show state and position information. * @return The number of characters copied to the specified buffer indicates * success. Zero indicates failure. To get extended error * information, call GetLastError. @@ -1814,86 +1747,86 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Sets the show state and the restored, minimized, and maximized positions - * of the specified window. - * - * @param hwnd A handle to the window. + * of the specified window. + * + * @param hwnd A handle to the window. * @param lpwndpl A pointer to a WINDOWPLACEMENT structure that specifies the * new show state and window positions. * @return The number of characters copied to the specified buffer indicates - * success. Zero indicates failure. To get extended error + * success. Zero indicates failure. To get extended error * information, call GetLastError. */ BOOL SetWindowPlacement(HWND hwnd, WINDOWPLACEMENT lpwndpl); - + /** * Calculates the required size of the window rectangle, based on the desired * client-rectangle size. The window rectangle can then be passed to the CreateWindow * function to create a window whose client area is the desired size. - * + * * To specify an extended window style, use the AdjustWindowRectEx function. - * + * * A client rectangle is the smallest rectangle that completely encloses a * client area. A window rectangle is the smallest rectangle that completely * encloses the window, which includes the client area and the nonclient area. - * + * * The AdjustWindowRect function does not add extra space when a menu bar wraps * to two or more rows. - * + * * The AdjustWindowRect function does not take the WS_VSCROLL or WS_HSCROLL * styles into account. To account for the scroll bars, call the GetSystemMetrics - * function with SM_CXVSCROLL or SM_CYHSCROLL. - * + * function with SM_CXVSCROLL or SM_CYHSCROLL. + * * @param lpRect A pointer to a RECT structure that contains the coordinates * of the top-left and bottom-right corners of the desired client area. * When the function returns, the structure contains the coordinates * of the top-left and bottom-right corners of the window to accommodate - * the desired client area. + * the desired client area. * @param dwStyle The window style of the window whose required size is to be - * calculated. Note that you cannot specify the WS_OVERLAPPED style. - * @param bMenu Indicates whether the window has a menu. + * calculated. Note that you cannot specify the WS_OVERLAPPED style. + * @param bMenu Indicates whether the window has a menu. * @return The number of characters copied to the specified buffer indicates * success. Zero indicates failure. To get extended error * information, call GetLastError. */ BOOL AdjustWindowRect(RECT lpRect, DWORD dwStyle, BOOL bMenu); - + /** * Calculates the required size of the window rectangle, based on the desired * client-rectangle size. The window rectangle can then be passed to the CreateWindowEx * function to create a window whose client area is the desired size. - * + * * A client rectangle is the smallest rectangle that completely encloses a * client area. A window rectangle is the smallest rectangle that completely * encloses the window, which includes the client area and the nonclient area. - * + * * The AdjustWindowRectEx function does not add extra space when a menu bar wraps * to two or more rows. - * + * * The AdjustWindowRectEx function does not take the WS_VSCROLL or WS_HSCROLL * styles into account. To account for the scroll bars, call the GetSystemMetrics - * function with SM_CXVSCROLL or SM_CYHSCROLL. - * + * function with SM_CXVSCROLL or SM_CYHSCROLL. + * * @param lpRect A pointer to a RECT structure that contains the coordinates * of the top-left and bottom-right corners of the desired client area. * When the function returns, the structure contains the coordinates * of the top-left and bottom-right corners of the window to accommodate - * the desired client area. + * the desired client area. * @param dwStyle The window style of the window whose required size is to be - * calculated. Note that you cannot specify the WS_OVERLAPPED style. - * @param bMenu Indicates whether the window has a menu. + * calculated. Note that you cannot specify the WS_OVERLAPPED style. + * @param bMenu Indicates whether the window has a menu. * @param dwExStyle The extended window style of the window whose required size - * is to be calculated. + * is to be calculated. * @return The number of characters copied to the specified buffer indicates * success. Zero indicates failure. To get extended error * information, call GetLastError. */ BOOL AdjustWindowRectEx(RECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle); - - /** + + /** * Logs off the interactive user, shuts down the system, or shuts down and restarts * the system. It sends the WM_QUERYENDSESSION message to all applications to * determine if they can be terminated. - * + * * When this function is called, the caller must specify whether or not applications * with unsaved changes should be forcibly closed. If the caller chooses not to force * these applications to close and an application with unsaved changes is running on @@ -1901,31 +1834,31 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, * into the console session aborts the shutdown, saves changes, closes the application, * or forces the application to close. During this period, the shutdown may not be * aborted except by the console user, and another shutdown may not be initiated. - * + * * Calling this function with the value of the uFlags parameter set to EWX_FORCE avoids * this situation. Remember that doing this may result in loss of data. - * + * * To set a shutdown priority for an application relative to other applications in the * system, use the SetProcessShutdownParameters function. - * + * * During a shutdown or log-off operation, running applications are allowed a specific * amount of time to respond to the shutdown request. If this time expires before all * applications have stopped, the system displays a user interface that allows the user * to forcibly shut down the system or to cancel the shutdown request. If the EWX_FORCE * value is specified, the system forces running applications to stop when the time expires. - * + * * If the EWX_FORCEIFHUNG value is specified, the system forces hung applications to close * and does not display the dialog box. - * + * * Console processes receive a separate notification message, CTRL_SHUTDOWN_EVENT or * CTRL_LOGOFF_EVENT, as the situation warrants. A console process routes these messages * to its HandlerRoutine function. ExitWindowsEx sends these notification messages * asynchronously; thus, an application cannot assume that the console notification messages * have been handled when a call to ExitWindowsEx returns. - * + * * To shut down or restart the system, the calling process must use the {@link com.sun.jna.platform.win32.Advapi32#AdjustTokenPrivileges} * function to enable the SE_SHUTDOWN_NAME privilege. For more information, see Running with Special Privileges. - * + * * @param uFlags The shutdown type. This parameter must include one of EWX_HYBRID_SHUTDOWN, * EWX_LOGOFF, EWX_POWEROFF, EWX_REBOOT, EWX_RESTARTAPPS, or EWX_SHUTDOWN. This * parameter can optionally include one of EWX_FORCE or EWX_FORCEIFHUNG. @@ -1944,12 +1877,12 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, * function fails, the return value is zero. To get extended error information, call GetLastError. */ BOOL ExitWindowsEx(UINT uFlags, DWORD dReason); - + /** * Locks the workstation's display. Locking a workstation protects it from unauthorized use. The * LockWorkStation function is callable only by processes running on the interactive desktop. * In addition, the user must be logged on, and the workstation cannot already be locked. - * + * * @return If the function succeeds, the return value is nonzero. Because the function executes * asynchronously, a nonzero return value indicates that the operation has been initiated. * It does not indicate whether the workstation has been successfully locked. If the @@ -1959,7 +1892,7 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Retrieves information about the specified icon or cursor. - * + * * @param hIcon * A handle to the icon or cursor. *

    @@ -1978,10 +1911,10 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, * error information, call {@link Kernel32#GetLastError()}. */ boolean GetIconInfo(HICON hIcon, ICONINFO piconinfo); - + /** * Retrieves information about the specified icon or cursor. - * + * * @param hIcon * A handle to the icon or cursor. *

    @@ -2003,7 +1936,7 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, /** * Sends the specified message to one or more windows. - * + * * @param hWnd * A handle to the window whose window procedure will receive the * message. @@ -2047,11 +1980,11 @@ HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, */ long SendMessageTimeout(HWND hWnd, int msg, long wParam, long lParam, int fuFlags, int uTimeout, DWORDByReference lpdwResult); - + /** * Retrieves the specified value from the WNDCLASSEX structure associated * with the specified window. - * + * * @param hWnd * A handle to the window and, indirectly, the class to which the * window belongs. diff --git a/contrib/platform/test/com/sun/jna/platform/win32/AbstractWin32TestSupport.java b/contrib/platform/test/com/sun/jna/platform/win32/AbstractWin32TestSupport.java index 553f2a3c00..e902e02593 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/AbstractWin32TestSupport.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/AbstractWin32TestSupport.java @@ -12,17 +12,52 @@ */ package com.sun.jna.platform.win32; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + import com.sun.jna.platform.AbstractPlatformTestSupport; import com.sun.jna.platform.win32.WinNT.HANDLE; -/** - * @author lgoldstein - */ public abstract class AbstractWin32TestSupport extends AbstractPlatformTestSupport { protected AbstractWin32TestSupport() { super(); } + /** + * Makes sure that the method names (which represent APIs) do not repeat + * themselves. This check is in order where APIs are WIN32 API functions + * since these are C functions - which means no overloading is possible. + * + * @param ifc The interface (not checked) class to test + * @see #detectDuplicateMethods(Class) + */ + public static final void assertNoDuplicateMethodsNames(Class ifc) { + Collection dupSet = detectDuplicateMethods(ifc); + assertTrue("Duplicate names found in " + ifc.getSimpleName() + ": " + dupSet, dupSet.isEmpty()); + } + + /** + * Checks if there are methods with the same name - regardless of the signature + * + * @param ifc The interface (not checked) class to test + * @return The {@link Set} of duplicate names - empty if no duplicates + */ + public static final Set detectDuplicateMethods(Class ifc) { + Method[] methods = ifc.getMethods(); + Set nameSet = new HashSet(methods.length); + Set dupSet = new HashSet(); + for (Method m : methods) { + String name = m.getName(); + if (!nameSet.add(name)) { + dupSet.add(name); + } + } + + return dupSet; + } + /** * Checks if the API call result is {@code true}. If not, then calls * {@link Kernel32#GetLastError()} and fails with the error code. @@ -35,7 +70,7 @@ public static final void assertCallSucceeded(String message, boolean result) { if (result) { return; } - + int hr = Kernel32.INSTANCE.GetLastError(); if (hr == WinError.ERROR_SUCCESS) { fail(message + " failed with unknown reason code"); @@ -43,7 +78,7 @@ public static final void assertCallSucceeded(String message, boolean result) { fail(message + " failed: hr=" + hr + " - 0x" + Integer.toHexString(hr)); } } - + /** * Checks if the status code is ERROR_SUCCESS * @param message Message to display if code is an error @@ -59,7 +94,7 @@ public static final void assertErrorSuccess(String message, int statusCode, bool assertEquals(message, WinError.ERROR_SUCCESS, statusCode); } } - + /** * Makes sure that the handle argument is not {@code null} or {@link WinBase#INVALID_HANDLE_VALUE}. * If invalid handle detected, then it invokes {@link Kernel32#GetLastError()} diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java index 6f5866a2a4..54e790578c 100755 --- a/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Advapi32Test.java @@ -1,14 +1,14 @@ /* Copyright (c) 2010 Daniel Doubrovkine, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library 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 - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna.platform.win32; @@ -16,6 +16,7 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.util.Collection; import junit.framework.TestCase; @@ -53,12 +54,29 @@ public class Advapi32Test extends TestCase { private static final String EVERYONE = "S-1-1-0"; - + public static void main(String[] args) { junit.textui.TestRunner.run(Advapi32Test.class); } - - public void testGetUserName() { + + // see https://github.com/twall/jna/issues/482 + public void testNoDuplicateMethodsNames() { + Collection dupSet = AbstractWin32TestSupport.detectDuplicateMethods(Advapi32.class); + if (dupSet.size() > 0) { + for (String name : new String[] { + // has several overloads by design since the output value can be several types of data + "RegQueryValueEx", + // has several overloads by design since the input value can be several types of data + "RegSetValueEx" + }) { + dupSet.remove(name); + } + } + + assertTrue("Duplicate methods found: " + dupSet, dupSet.isEmpty()); + } + + public void testGetUserName() { IntByReference len = new IntByReference(); assertFalse(Advapi32.INSTANCE.GetUserNameW(null, len)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); @@ -67,7 +85,7 @@ public void testGetUserName() { String username = Native.toString(buffer); assertTrue(username.length() > 0); } - + public void testLookupAccountName() { IntByReference pSid = new IntByReference(0); IntByReference pDomain = new IntByReference(0); @@ -79,13 +97,13 @@ public void testLookupAccountName() { assertTrue(pSid.getValue() > 0); Memory sidMemory = new Memory(pSid.getValue()); PSID pSidMemory = new PSID(sidMemory); - char[] referencedDomainName = new char[pDomain.getValue() + 1]; + char[] referencedDomainName = new char[pDomain.getValue() + 1]; assertTrue(Advapi32.INSTANCE.LookupAccountName( null, accountName, pSidMemory, pSid, referencedDomainName, pDomain, peUse)); assertEquals(SID_NAME_USE.SidTypeUser, peUse.getPointer().getInt(0)); assertTrue(Native.toString(referencedDomainName).length() > 0); } - + public void testIsValidSid() { String sidString = EVERYONE; PSIDByReference sid = new PSIDByReference(); @@ -102,7 +120,7 @@ public void testGetSidLength() { assertTrue("SID conversion failed", Advapi32.INSTANCE.ConvertStringSidToSid(sidString, sid)); assertEquals("Wrong SID lenght", 12, Advapi32.INSTANCE.GetLengthSid(sid.getValue())); } - + public void testLookupAccountSid() { // get SID bytes String sidString = EVERYONE; @@ -114,14 +132,14 @@ public void testLookupAccountSid() { IntByReference cchName = new IntByReference(); IntByReference cchReferencedDomainName = new IntByReference(); PointerByReference peUse = new PointerByReference(); - assertFalse(Advapi32.INSTANCE.LookupAccountSid(null, sid.getValue(), + assertFalse(Advapi32.INSTANCE.LookupAccountSid(null, sid.getValue(), null, cchName, null, cchReferencedDomainName, peUse)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); assertTrue(cchName.getValue() > 0); assertTrue(cchReferencedDomainName.getValue() > 0); char[] referencedDomainName = new char[cchReferencedDomainName.getValue()]; char[] name = new char[cchName.getValue()]; - assertTrue(Advapi32.INSTANCE.LookupAccountSid(null, sid.getValue(), + assertTrue(Advapi32.INSTANCE.LookupAccountSid(null, sid.getValue(), name, cchName, referencedDomainName, cchReferencedDomainName, peUse)); assertEquals(5, peUse.getPointer().getInt(0)); // SidTypeWellKnownGroup String nameString = Native.toString(name); @@ -131,7 +149,7 @@ public void testLookupAccountSid() { assertTrue(referencedDomainNameString.length() == 0); assertEquals(null, Kernel32.INSTANCE.LocalFree(sid.getValue().getPointer())); } - + public void testConvertSid() { String sidString = EVERYONE; PSIDByReference sid = new PSIDByReference(); @@ -145,62 +163,62 @@ public void testConvertSid() { assertEquals(null, Kernel32.INSTANCE.LocalFree(convertedSidStringPtr.getValue())); assertEquals(null, Kernel32.INSTANCE.LocalFree(sid.getValue().getPointer())); } - + public void testLogonUser() { HANDLEByReference phToken = new HANDLEByReference(); - assertFalse(Advapi32.INSTANCE.LogonUser("AccountDoesntExist", ".", "passwordIsInvalid", + assertFalse(Advapi32.INSTANCE.LogonUser("AccountDoesntExist", ".", "passwordIsInvalid", WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phToken)); assertTrue(W32Errors.ERROR_SUCCESS != Kernel32.INSTANCE.GetLastError()); } - + public void testOpenThreadTokenNoToken() { HANDLEByReference phToken = new HANDLEByReference(); HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull(threadHandle); - assertFalse(Advapi32.INSTANCE.OpenThreadToken(threadHandle, + assertFalse(Advapi32.INSTANCE.OpenThreadToken(threadHandle, WinNT.TOKEN_READ, false, phToken)); assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); } - + public void testOpenProcessToken() { HANDLEByReference phToken = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); + assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); } - + public void testOpenThreadOrProcessToken() { HANDLEByReference phToken = new HANDLEByReference(); HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); - if (! Advapi32.INSTANCE.OpenThreadToken(threadHandle, + if (! Advapi32.INSTANCE.OpenThreadToken(threadHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, true, phToken)) { assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); } assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); } - + public void testSetThreadTokenCurrentThread() { HANDLEByReference phToken = new HANDLEByReference(); HANDLEByReference phTokenDup = new HANDLEByReference(); HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread(); // See if thread has a token. If not, must duplicate process token and set thread token using that. - if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle, + if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle, WinNT.TOKEN_IMPERSONATE | WinNT.TOKEN_QUERY, false, phToken)) { assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE, phToken)); - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), WinNT.TOKEN_IMPERSONATE, null, WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, WinNT.TOKEN_TYPE.TokenImpersonation, phTokenDup)); // Null sets on current thread - assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDup.getValue())); + assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDup.getValue())); } else { //Null sets on current thread @@ -210,22 +228,22 @@ public void testSetThreadTokenCurrentThread() { assertTrue(Advapi32.INSTANCE.SetThreadToken(null, null)); assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); if (phTokenDup.getValue() != null) - assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); + assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); } - + public void testSetThreadTokenThisThread() { HANDLEByReference phToken = new HANDLEByReference(); HANDLEByReference phTokenDup = new HANDLEByReference(); HANDLEByReference pthreadHandle = new HANDLEByReference(); pthreadHandle.setValue(Kernel32.INSTANCE.GetCurrentThread()); // See if thread has a token. If not, must duplicate process token and set thread token using that. - if (!Advapi32.INSTANCE.OpenThreadToken(pthreadHandle.getValue(), + if (!Advapi32.INSTANCE.OpenThreadToken(pthreadHandle.getValue(), WinNT.TOKEN_IMPERSONATE | WinNT.TOKEN_QUERY, false, phToken)) { assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE, phToken)); - assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), + assertTrue(Advapi32.INSTANCE.DuplicateTokenEx(phToken.getValue(), WinNT.TOKEN_IMPERSONATE, null, WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, @@ -244,19 +262,19 @@ public void testSetThreadTokenThisThread() { if (phTokenDup.getValue() != null) assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); } - + public void testDuplicateToken() { HANDLEByReference phToken = new HANDLEByReference(); HANDLEByReference phTokenDup = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); - assertTrue(Advapi32.INSTANCE.DuplicateToken(phToken.getValue(), + assertTrue(Advapi32.INSTANCE.DuplicateToken(phToken.getValue(), WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, phTokenDup)); assertTrue(Kernel32.INSTANCE.CloseHandle(phTokenDup.getValue())); assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); } - + public void testDuplicateTokenEx() { HANDLEByReference hExistingToken = new HANDLEByReference(); HANDLEByReference phNewToken = new HANDLEByReference(); @@ -269,19 +287,19 @@ public void testDuplicateTokenEx() { assertTrue(Kernel32.INSTANCE.CloseHandle(phNewToken.getValue())); assertTrue(Kernel32.INSTANCE.CloseHandle(hExistingToken.getValue())); } - + public void testGetTokenOwnerInformation() { HANDLEByReference phToken = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); IntByReference tokenInformationLength = new IntByReference(); - assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, null, 0, tokenInformationLength)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); WinNT.TOKEN_OWNER owner = new WinNT.TOKEN_OWNER(tokenInformationLength.getValue()); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, owner, + assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenOwner, owner, tokenInformationLength.getValue(), tokenInformationLength)); assertTrue(tokenInformationLength.getValue() > 0); assertTrue(Advapi32.INSTANCE.IsValidSid(owner.Owner)); @@ -291,19 +309,19 @@ public void testGetTokenOwnerInformation() { // System.out.println(Advapi32Util.convertSidToStringSid(owner.Owner)); assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); } - + public void testGetTokenUserInformation() { HANDLEByReference phToken = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); IntByReference tokenInformationLength = new IntByReference(); - assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0, tokenInformationLength)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(tokenInformationLength.getValue()); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user, + assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user, tokenInformationLength.getValue(), tokenInformationLength)); assertTrue(tokenInformationLength.getValue() > 0); assertTrue(Advapi32.INSTANCE.IsValidSid(user.User.Sid)); @@ -312,20 +330,20 @@ public void testGetTokenUserInformation() { assertTrue(sidLength < tokenInformationLength.getValue()); // System.out.println(Advapi32Util.convertSidToStringSid(user.User.Sid)); assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); - } - + } + public void testGetTokenGroupsInformation() { HANDLEByReference phToken = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); - assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, + assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)); IntByReference tokenInformationLength = new IntByReference(); - assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + assertFalse(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, null, 0, tokenInformationLength)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); WinNT.TOKEN_GROUPS groups = new WinNT.TOKEN_GROUPS(tokenInformationLength.getValue()); - assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), - WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups, + assertTrue(Advapi32.INSTANCE.GetTokenInformation(phToken.getValue(), + WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups, tokenInformationLength.getValue(), tokenInformationLength)); assertTrue(tokenInformationLength.getValue() > 0); assertTrue(groups.GroupCount > 0); @@ -335,7 +353,7 @@ public void testGetTokenGroupsInformation() { } assertTrue(Kernel32.INSTANCE.CloseHandle(phToken.getValue())); } - + public void testImpersonateLoggedOnUser() { USER_INFO_1 userInfo = new USER_INFO_1(); userInfo.usri1_name = new WString("JNAAdvapi32TestImp"); @@ -349,29 +367,29 @@ public void testImpersonateLoggedOnUser() { HANDLEByReference phUser = new HANDLEByReference(); try { assertTrue(Advapi32.INSTANCE.LogonUser(userInfo.usri1_name.toString(), - null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, + null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phUser)); assertTrue(Advapi32.INSTANCE.ImpersonateLoggedOnUser(phUser.getValue())); assertTrue(Advapi32.INSTANCE.RevertToSelf()); } finally { if (phUser.getValue() != WinBase.INVALID_HANDLE_VALUE) { Kernel32.INSTANCE.CloseHandle(phUser.getValue()); - } + } } } finally { assertEquals(LMErr.NERR_Success, Netapi32.INSTANCE.NetUserDel( - null, userInfo.usri1_name.toString())); + null, userInfo.usri1_name.toString())); } } - + public void testRegOpenKeyEx() { HKEYByReference phKey = new HKEYByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegOpenKeyEx( WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft", 0, WinNT.KEY_READ, phKey)); assertTrue(WinBase.INVALID_HANDLE_VALUE != phKey.getValue()); - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegQueryValueEx() { HKEYByReference phKey = new HKEYByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegOpenKeyEx( @@ -384,15 +402,15 @@ public void testRegQueryValueEx() { assertTrue(lpcbData.getValue() > 0); char[] buffer = new char[lpcbData.getValue()]; assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegQueryValueEx( - phKey.getValue(), "User Agent", 0, lpType, buffer, lpcbData)); - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + phKey.getValue(), "User Agent", 0, lpType, buffer, lpcbData)); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegDeleteValue() { assertEquals(W32Errors.ERROR_FILE_NOT_FOUND, Advapi32.INSTANCE.RegDeleteValue( WinReg.HKEY_CURRENT_USER, "JNAAdvapi32TestDoesntExist")); } - + public void testRegSetValueEx_REG_SZ() { HKEYByReference phKey = new HKEYByReference(); // create parent key @@ -401,7 +419,7 @@ public void testRegSetValueEx_REG_SZ() { HKEYByReference phkTest = new HKEYByReference(); IntByReference lpdwDisposition = new IntByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCreateKeyEx( - phKey.getValue(), "JNAAdvapi32Test", 0, null, 0, WinNT.KEY_ALL_ACCESS, + phKey.getValue(), "JNAAdvapi32Test", 0, null, 0, WinNT.KEY_ALL_ACCESS, null, phkTest, lpdwDisposition)); // write a REG_SZ value char[] lpData = Native.toCharArray("Test"); @@ -416,16 +434,16 @@ public void testRegSetValueEx_REG_SZ() { assertTrue(lpcbData.getValue() > 0); char[] buffer = new char[lpcbData.getValue()]; assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegQueryValueEx( - phkTest.getValue(), "REG_SZ", 0, lpType, buffer, lpcbData)); + phkTest.getValue(), "REG_SZ", 0, lpType, buffer, lpcbData)); assertEquals("Test", Native.toString(buffer)); // delete the test key assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey( - phkTest.getValue())); + phkTest.getValue())); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegDeleteKey( phKey.getValue(), "JNAAdvapi32Test")); - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegSetValueEx_DWORD() { HKEYByReference phKey = new HKEYByReference(); // create parent key @@ -434,7 +452,7 @@ public void testRegSetValueEx_DWORD() { HKEYByReference phkTest = new HKEYByReference(); IntByReference lpdwDisposition = new IntByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCreateKeyEx( - phKey.getValue(), "JNAAdvapi32Test", 0, null, 0, WinNT.KEY_ALL_ACCESS, + phKey.getValue(), "JNAAdvapi32Test", 0, null, 0, WinNT.KEY_ALL_ACCESS, null, phkTest, lpdwDisposition)); // write a REG_DWORD value int value = 42145; @@ -444,7 +462,7 @@ public void testRegSetValueEx_DWORD() { data[2] = (byte)((value >> 16) & 0xff); data[3] = (byte)((value >> 24) & 0xff); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegSetValueEx( - phkTest.getValue(), "DWORD", 0, WinNT.REG_DWORD, data, 4)); + phkTest.getValue(), "DWORD", 0, WinNT.REG_DWORD, data, 4)); // re-read the REG_DWORD value IntByReference lpType = new IntByReference(); IntByReference lpcbData = new IntByReference(); @@ -458,12 +476,12 @@ public void testRegSetValueEx_DWORD() { assertEquals(value, valueRead.getValue()); // delete the test key assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey( - phkTest.getValue())); + phkTest.getValue())); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegDeleteKey( phKey.getValue(), "JNAAdvapi32Test")); - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegCreateKeyEx() { HKEYByReference phKey = new HKEYByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegOpenKeyEx( @@ -471,28 +489,28 @@ public void testRegCreateKeyEx() { HKEYByReference phkResult = new HKEYByReference(); IntByReference lpdwDisposition = new IntByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCreateKeyEx( - phKey.getValue(), "JNAAdvapi32Test", 0, null, 0, WinNT.KEY_ALL_ACCESS, + phKey.getValue(), "JNAAdvapi32Test", 0, null, 0, WinNT.KEY_ALL_ACCESS, null, phkResult, lpdwDisposition)); - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phkResult.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phkResult.getValue())); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegDeleteKey( phKey.getValue(), "JNAAdvapi32Test")); - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegDeleteKey() { assertEquals(W32Errors.ERROR_FILE_NOT_FOUND, Advapi32.INSTANCE.RegDeleteKey( WinReg.HKEY_CURRENT_USER, "JNAAdvapi32TestDoesntExist")); } - + public void testRegEnumKeyEx() { HKEYByReference phKey = new HKEYByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegOpenKeyEx( - WinReg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", + WinReg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, WinNT.KEY_READ, phKey)); IntByReference lpcSubKeys = new IntByReference(); IntByReference lpcMaxSubKeyLen = new IntByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegQueryInfoKey( - phKey.getValue(), null, null, null, lpcSubKeys, lpcMaxSubKeyLen, null, null, + phKey.getValue(), null, null, null, lpcSubKeys, lpcMaxSubKeyLen, null, null, null, null, null, null)); char[] name = new char[lpcMaxSubKeyLen.getValue() + 1]; for (int i = 0; i < lpcSubKeys.getValue(); i++) { @@ -501,31 +519,31 @@ public void testRegEnumKeyEx() { phKey.getValue(), i, name, lpcchValueName, null, null, null, null)); assertEquals(Native.toString(name).length(), lpcchValueName.getValue()); } - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegEnumValue() { HKEYByReference phKey = new HKEYByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegOpenKeyEx( - WinReg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", + WinReg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, WinNT.KEY_READ, phKey)); IntByReference lpcValues = new IntByReference(); IntByReference lpcMaxValueNameLen = new IntByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegQueryInfoKey( - phKey.getValue(), null, null, null, null, null, null, lpcValues, + phKey.getValue(), null, null, null, null, null, null, lpcValues, lpcMaxValueNameLen, null, null, null)); char[] name = new char[lpcMaxValueNameLen.getValue() + 1]; for (int i = 0; i < lpcValues.getValue(); i++) { IntByReference lpcchValueName = new IntByReference(lpcMaxValueNameLen.getValue() + 1); - IntByReference lpType = new IntByReference(); + IntByReference lpType = new IntByReference(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegEnumValue( - phKey.getValue(), i, name, lpcchValueName, null, + phKey.getValue(), i, name, lpcchValueName, null, lpType, null, null)); assertEquals(Native.toString(name).length(), lpcchValueName.getValue()); } - assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); + assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegCloseKey(phKey.getValue())); } - + public void testRegQueryInfoKey() { IntByReference lpcClass = new IntByReference(); IntByReference lpcSubKeys = new IntByReference(); @@ -537,29 +555,29 @@ public void testRegQueryInfoKey() { IntByReference lpcbSecurityDescriptor = new IntByReference(); FILETIME lpftLastWriteTime = new FILETIME(); assertEquals(W32Errors.ERROR_SUCCESS, Advapi32.INSTANCE.RegQueryInfoKey( - WinReg.HKEY_LOCAL_MACHINE, null, lpcClass, null, - lpcSubKeys, lpcMaxSubKeyLen, lpcMaxClassLen, lpcValues, - lpcMaxValueNameLen, lpcMaxValueLen, lpcbSecurityDescriptor, + WinReg.HKEY_LOCAL_MACHINE, null, lpcClass, null, + lpcSubKeys, lpcMaxSubKeyLen, lpcMaxClassLen, lpcValues, + lpcMaxValueNameLen, lpcMaxValueLen, lpcbSecurityDescriptor, lpftLastWriteTime)); assertTrue(lpcSubKeys.getValue() > 0); } - + public void testIsWellKnownSid() { String sidString = EVERYONE; PSIDByReference sid = new PSIDByReference(); assertTrue(Advapi32.INSTANCE.ConvertStringSidToSid(sidString, sid)); - assertTrue(Advapi32.INSTANCE.IsWellKnownSid(sid.getValue(), + assertTrue(Advapi32.INSTANCE.IsWellKnownSid(sid.getValue(), WELL_KNOWN_SID_TYPE.WinWorldSid)); - assertFalse(Advapi32.INSTANCE.IsWellKnownSid(sid.getValue(), + assertFalse(Advapi32.INSTANCE.IsWellKnownSid(sid.getValue(), WELL_KNOWN_SID_TYPE.WinAccountAdministratorSid)); } - + public void testCreateWellKnownSid() { PSID pSid = new PSID(WinNT.SECURITY_MAX_SID_SIZE); IntByReference cbSid = new IntByReference(WinNT.SECURITY_MAX_SID_SIZE); assertTrue(Advapi32.INSTANCE.CreateWellKnownSid(WELL_KNOWN_SID_TYPE.WinWorldSid, null, pSid, cbSid)); - assertTrue(Advapi32.INSTANCE.IsWellKnownSid(pSid, + assertTrue(Advapi32.INSTANCE.IsWellKnownSid(pSid, WELL_KNOWN_SID_TYPE.WinWorldSid)); assertTrue(cbSid.getValue() <= WinNT.SECURITY_MAX_SID_SIZE); PointerByReference convertedSidStringPtr = new PointerByReference(); @@ -568,14 +586,14 @@ public void testCreateWellKnownSid() { String convertedSidString = convertedSidStringPtr.getValue().getWideString(0); assertEquals(EVERYONE, convertedSidString); } - + public void testOpenEventLog() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); assertNotNull(h); assertFalse(h.equals(WinBase.INVALID_HANDLE_VALUE)); assertTrue(Advapi32.INSTANCE.CloseEventLog(h)); } - + public void testRegisterEventSource() { // the Security event log is reserved HANDLE h = Advapi32.INSTANCE.RegisterEventSource(null, "Security"); @@ -585,7 +603,7 @@ public void testRegisterEventSource() { public void testReportEvent() { String applicationEventLog = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"; - String jnaEventSource = "JNADevEventSource"; + String jnaEventSource = "JNADevEventSource"; String jnaEventSourceRegistryPath = applicationEventLog + "\\" + jnaEventSource; // ignore test if not able to create key (need to be administrator to do this). try { @@ -597,7 +615,7 @@ public void testReportEvent() { return; } - HANDLE h = Advapi32.INSTANCE.RegisterEventSource(null, jnaEventSource); + HANDLE h = Advapi32.INSTANCE.RegisterEventSource(null, jnaEventSource); IntByReference before = new IntByReference(); assertTrue(Advapi32.INSTANCE.GetNumberOfEventLogRecords(h, before)); assertNotNull(h); @@ -615,7 +633,7 @@ public void testReportEvent() { assertTrue(Advapi32.INSTANCE.DeregisterEventSource(h)); Advapi32Util.registryDeleteKey(WinReg.HKEY_LOCAL_MACHINE, jnaEventSourceRegistryPath); } - + public void testGetNumberOfEventLogRecords() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); assertFalse(h.equals(WinBase.INVALID_HANDLE_VALUE)); @@ -624,7 +642,7 @@ public void testGetNumberOfEventLogRecords() { assertTrue(n.getValue() >= 0); assertTrue(Advapi32.INSTANCE.CloseEventLog(h)); } - + /* public void testClearEventLog() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); @@ -636,64 +654,64 @@ public void testClearEventLog() { IntByReference after = new IntByReference(); assertTrue(Advapi32.INSTANCE.GetNumberOfEventLogRecords(h, after)); assertTrue(after.getValue() < before.getValue() || before.getValue() == 0); - assertTrue(Advapi32.INSTANCE.CloseEventLog(h)); + assertTrue(Advapi32.INSTANCE.CloseEventLog(h)); } */ - + public void testBackupEventLog() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); assertNotNull(h); - String backupFileName = Kernel32Util.getTempPath() + "\\JNADevEventLog.bak"; + String backupFileName = Kernel32Util.getTempPath() + "\\JNADevEventLog.bak"; File f = new File(backupFileName); if (f.exists()) { f.delete(); } - + assertTrue(Advapi32.INSTANCE.BackupEventLog(h, backupFileName)); HANDLE hBackup = Advapi32.INSTANCE.OpenBackupEventLog(null, backupFileName); assertNotNull(hBackup); - + IntByReference n = new IntByReference(); assertTrue(Advapi32.INSTANCE.GetNumberOfEventLogRecords(hBackup, n)); assertTrue(n.getValue() >= 0); - + assertTrue(Advapi32.INSTANCE.CloseEventLog(h)); assertTrue(Advapi32.INSTANCE.CloseEventLog(hBackup)); } - + public void testReadEventLog() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); IntByReference pnBytesRead = new IntByReference(); IntByReference pnMinNumberOfBytesNeeded = new IntByReference(); Memory buffer = new Memory(1); - assertFalse(Advapi32.INSTANCE.ReadEventLog(h, - WinNT.EVENTLOG_SEQUENTIAL_READ | WinNT.EVENTLOG_BACKWARDS_READ, + assertFalse(Advapi32.INSTANCE.ReadEventLog(h, + WinNT.EVENTLOG_SEQUENTIAL_READ | WinNT.EVENTLOG_BACKWARDS_READ, 0, buffer, (int) buffer.size(), pnBytesRead, pnMinNumberOfBytesNeeded)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); assertTrue(pnMinNumberOfBytesNeeded.getValue() > 0); assertTrue(Advapi32.INSTANCE.CloseEventLog(h)); } - + public void testReadEventLogEntries() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); IntByReference pnBytesRead = new IntByReference(); IntByReference pnMinNumberOfBytesNeeded = new IntByReference(); Memory buffer = new Memory(1024 * 64); // shorten test, avoid iterating through all events - int maxReads = 3; + int maxReads = 3; int rc = 0; while(true) { if (maxReads-- <= 0) - break; - if (! Advapi32.INSTANCE.ReadEventLog(h, - WinNT.EVENTLOG_SEQUENTIAL_READ | WinNT.EVENTLOG_FORWARDS_READ, + break; + if (! Advapi32.INSTANCE.ReadEventLog(h, + WinNT.EVENTLOG_SEQUENTIAL_READ | WinNT.EVENTLOG_FORWARDS_READ, 0, buffer, (int) buffer.size(), pnBytesRead, pnMinNumberOfBytesNeeded)) { rc = Kernel32.INSTANCE.GetLastError(); if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) { buffer = new Memory(pnMinNumberOfBytesNeeded.getValue()); rc = 0; continue; - } + } break; } int dwRead = pnBytesRead.getValue(); @@ -715,9 +733,9 @@ public void testReadEventLogEntries() { + new Win32Exception(rc), rc == W32Errors.ERROR_HANDLE_EOF || rc == 0); assertTrue("Error closing event log", - Advapi32.INSTANCE.CloseEventLog(h)); + Advapi32.INSTANCE.CloseEventLog(h)); } - + public void testGetOldestEventLogRecord() { HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, "Application"); IntByReference oldestRecord = new IntByReference(); @@ -727,7 +745,7 @@ public void testGetOldestEventLogRecord() { } public void testQueryServiceStatusEx() { - + SC_HANDLE scmHandle = Advapi32.INSTANCE.OpenSCManager(null, null, Winsvc.SC_MANAGER_CONNECT); assertNotNull(scmHandle); @@ -739,7 +757,7 @@ public void testQueryServiceStatusEx() { assertFalse(Advapi32.INSTANCE.QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, null, 0, pcbBytesNeeded)); assertEquals(W32Errors.ERROR_INSUFFICIENT_BUFFER, Kernel32.INSTANCE.GetLastError()); - + assertTrue(pcbBytesNeeded.getValue() > 0); SERVICE_STATUS_PROCESS status = new SERVICE_STATUS_PROCESS(pcbBytesNeeded.getValue()); @@ -747,14 +765,14 @@ public void testQueryServiceStatusEx() { assertTrue(Advapi32.INSTANCE.QueryServiceStatusEx(serviceHandle, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO, status, status.size(), pcbBytesNeeded)); - assertTrue(status.dwCurrentState == Winsvc.SERVICE_STOPPED || + assertTrue(status.dwCurrentState == Winsvc.SERVICE_STOPPED || status.dwCurrentState == Winsvc.SERVICE_RUNNING); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(serviceHandle)); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(scmHandle)); } - + public void testControlService() { SC_HANDLE scmHandle = Advapi32.INSTANCE.OpenSCManager(null, null, Winsvc.SC_MANAGER_CONNECT); assertNotNull(scmHandle); @@ -771,28 +789,28 @@ public void testControlService() { assertTrue(Advapi32.INSTANCE.CloseServiceHandle(serviceHandle)); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(scmHandle)); } - + public void testStartService() { SC_HANDLE scmHandle = Advapi32.INSTANCE.OpenSCManager(null, null, Winsvc.SC_MANAGER_CONNECT); assertNotNull(scmHandle); - + SC_HANDLE serviceHandle = Advapi32.INSTANCE.OpenService(scmHandle, "eventlog", Winsvc.SERVICE_QUERY_CONFIG); assertNotNull(serviceHandle); - + assertFalse(Advapi32.INSTANCE.StartService(serviceHandle, 0, null)); assertEquals(W32Errors.ERROR_ACCESS_DENIED, Kernel32.INSTANCE.GetLastError()); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(serviceHandle)); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(scmHandle)); } - + public void testOpenService() { assertNull(Advapi32.INSTANCE.OpenService(null, "eventlog", Winsvc.SERVICE_QUERY_CONFIG )); assertEquals(W32Errors.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); SC_HANDLE scmHandle = Advapi32.INSTANCE.OpenSCManager(null, null, Winsvc.SC_MANAGER_CONNECT); assertNotNull(scmHandle); - + SC_HANDLE serviceHandle = Advapi32.INSTANCE.OpenService(scmHandle, "eventlog", Winsvc.SERVICE_QUERY_CONFIG ); assertNotNull(serviceHandle); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(serviceHandle)); @@ -805,12 +823,12 @@ public void testOpenService() { assertTrue(Advapi32.INSTANCE.CloseServiceHandle(scmHandle)); } - + public void testOpenSCManager() { SC_HANDLE handle = Advapi32.INSTANCE.OpenSCManager(null, null, Winsvc.SC_MANAGER_CONNECT); assertNotNull(handle); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(handle)); - + assertNull(Advapi32.INSTANCE.OpenSCManager("invalidMachineName", null, Winsvc.SC_MANAGER_CONNECT)); int err = Kernel32.INSTANCE.GetLastError(); assertTrue("Unexpected error in OpenSCManager: " + err, @@ -820,94 +838,94 @@ public void testOpenSCManager() { assertNull(Advapi32.INSTANCE.OpenSCManager(null, "invalidDatabase", Winsvc.SC_MANAGER_CONNECT)); assertEquals(W32Errors.ERROR_INVALID_NAME, Kernel32.INSTANCE.GetLastError()); } - + public void testCloseServiceHandle() throws Exception { SC_HANDLE handle = Advapi32.INSTANCE.OpenSCManager(null, null, Winsvc.SC_MANAGER_CONNECT); assertNotNull(handle); assertTrue(Advapi32.INSTANCE.CloseServiceHandle(handle)); - + assertFalse(Advapi32.INSTANCE.CloseServiceHandle(null)); assertEquals(W32Errors.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); } - + public void testCreateProcessAsUser() { HANDLEByReference hToken = new HANDLEByReference(); HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess(); assertTrue(Advapi32.INSTANCE.OpenProcessToken(processHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, hToken)); - + assertFalse(Advapi32.INSTANCE.CreateProcessAsUser(hToken.getValue(), null, "InvalidCmdLine.jna", null, null, false, 0, null, null, new WinBase.STARTUPINFO(), new WinBase.PROCESS_INFORMATION())); assertEquals(W32Errors.ERROR_FILE_NOT_FOUND, Kernel32.INSTANCE.GetLastError()); assertTrue(Kernel32.INSTANCE.CloseHandle(hToken.getValue())); } - + /** * Tests both {@link Advapi32#LookupPrivilegeValue} and {@link Advapi32#LookupPrivilegeName} */ public void testLookupPrivilegeValueAndLookupPrivilegeName() { WinNT.LUID luid = new WinNT.LUID(); - + assertFalse(Advapi32.INSTANCE.LookupPrivilegeValue(null, "InvalidName", luid)); assertEquals(Kernel32.INSTANCE.GetLastError(), W32Errors.ERROR_NO_SUCH_PRIVILEGE); - + assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_BACKUP_NAME, luid)); assertTrue(luid.LowPart > 0 || luid.HighPart > 0); - + char[] lpName = new char[256]; IntByReference cchName = new IntByReference(lpName.length); assertTrue(Advapi32.INSTANCE.LookupPrivilegeName(null, luid, lpName, cchName)); assertEquals(WinNT.SE_BACKUP_NAME.length(), cchName.getValue()); assertEquals(WinNT.SE_BACKUP_NAME, Native.toString(lpName)); } - + public void testAdjustTokenPrivileges() { HANDLEByReference hToken = new HANDLEByReference(); assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES | WinNT.TOKEN_QUERY, hToken)); - + // Find an already enabled privilege TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES(1024); IntByReference returnLength = new IntByReference(); assertTrue(Advapi32.INSTANCE.GetTokenInformation(hToken.getValue(), WinNT.TOKEN_INFORMATION_CLASS.TokenPrivileges, tp, tp.size(), returnLength)); assertTrue(tp.PrivilegeCount.intValue() > 0); - + WinNT.LUID luid = null; for (int i=0; i 0) { luid = tp.Privileges[i].Luid; } } - assertTrue(luid != null); - + assertTrue(luid != null); + // Re-enable it. That should succeed. tp = new WinNT.TOKEN_PRIVILEGES(1); tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); - + assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(hToken.getValue(), false, tp, 0, null, null)); assertTrue(Kernel32.INSTANCE.CloseHandle(hToken.getValue())); } - + public void testImpersonateSelf() { assertTrue(Advapi32.INSTANCE.ImpersonateSelf(WinNT.SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous)); assertTrue(Advapi32.INSTANCE.RevertToSelf()); } - + public void testGetNamedSecurityInfoForFileNoSACL() throws Exception { // create a temp file File file = createTempFile(); - int infoType = OWNER_SECURITY_INFORMATION + int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; - + PointerByReference ppsidOwner = new PointerByReference(); PointerByReference ppsidGroup = new PointerByReference(); PointerByReference ppDacl = new PointerByReference(); PointerByReference ppSecurityDescriptor = new PointerByReference(); - + assertEquals(Advapi32.INSTANCE.GetNamedSecurityInfo( file.getAbsolutePath(), AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, @@ -921,7 +939,7 @@ public void testGetNamedSecurityInfoForFileNoSACL() throws Exception { Kernel32.INSTANCE.LocalFree(ppSecurityDescriptor.getValue()); file.delete(); } - + public void testGetNamedSecurityInfoForFileWithSACL() throws Exception { boolean impersontating = false; @@ -956,19 +974,19 @@ public void testGetNamedSecurityInfoForFileWithSACL() throws Exception { // Which token to adjust depends on whether we had to impersonate or not. HANDLE tokenAdjust = impersontating ? phTokenDuplicate.getValue() : phToken.getValue(); - + WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); // create a temp file File file = createTempFile(); - - int infoType = OWNER_SECURITY_INFORMATION + + int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION; - + PointerByReference ppsidOwner = new PointerByReference(); PointerByReference ppsidGroup = new PointerByReference(); PointerByReference ppDacl = new PointerByReference(); @@ -993,19 +1011,19 @@ public void testGetNamedSecurityInfoForFileWithSACL() throws Exception { } else { tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(0)); - Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null); + Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null); } if (phToken.getValue() != null) Kernel32.INSTANCE.CloseHandle(phToken.getValue()); if (phTokenDuplicate.getValue() != null) Kernel32.INSTANCE.CloseHandle(phTokenDuplicate.getValue()); } - + public void testSetNamedSecurityInfoForFileNoSACL() throws Exception { // create a temp file File file = createTempFile(); - int infoType = OWNER_SECURITY_INFORMATION + int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; @@ -1036,7 +1054,7 @@ public void testSetNamedSecurityInfoForFileNoSACL() throws Exception { Kernel32.INSTANCE.LocalFree(ppSecurityDescriptor.getValue()); file.delete(); } - + public void testSetNamedSecurityInfoForFileWithSACL() throws Exception { boolean impersontating = false; @@ -1049,10 +1067,10 @@ public void testSetNamedSecurityInfoForFileWithSACL() throws Exception { false, phToken)) { - assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); + assertEquals(W32Errors.ERROR_NO_TOKEN, Kernel32.INSTANCE.GetLastError()); // OpenThreadToken may fail with W32Errors.ERROR_NO_TOKEN if current thread is anonymous. When this happens, // we need to open the process token to duplicate it, then set our thread token. - assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), TOKEN_DUPLICATE, phToken)); + assertTrue(Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), TOKEN_DUPLICATE, phToken)); // Process token opened, now duplicate assertTrue(Advapi32.INSTANCE.DuplicateTokenEx( phToken.getValue(), @@ -1060,29 +1078,29 @@ public void testSetNamedSecurityInfoForFileWithSACL() throws Exception { null, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenImpersonation, - phTokenDuplicate)); + phTokenDuplicate)); // And set thread token. assertTrue(Advapi32.INSTANCE.SetThreadToken(null, phTokenDuplicate.getValue())); impersontating = true; } - + // Which token to adjust depends on whether we had to impersonate or not. HANDLE tokenAdjust = impersontating ? phTokenDuplicate.getValue() : phToken.getValue(); WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); WinNT.LUID pLuid = new WinNT.LUID(); - assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_SECURITY_NAME, pLuid)); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_SECURITY_NAME, pLuid)); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); assertTrue(Advapi32.INSTANCE.LookupPrivilegeValue(null, SE_RESTORE_NAME, pLuid)); - tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); + tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(WinNT.SE_PRIVILEGE_ENABLED)); assertTrue(Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null)); // create a temp file File file = createTempFile(); - int infoType = OWNER_SECURITY_INFORMATION + int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION; @@ -1121,18 +1139,18 @@ public void testSetNamedSecurityInfoForFileWithSACL() throws Exception { } else { tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(pLuid, new DWORD(0)); - Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null); + Advapi32.INSTANCE.AdjustTokenPrivileges(tokenAdjust, false, tp, 0, null, null); } if (phToken.getValue() != null) Kernel32.INSTANCE.CloseHandle(phToken.getValue()); if (phTokenDuplicate.getValue() != null) Kernel32.INSTANCE.CloseHandle(phTokenDuplicate.getValue()); } - + public void testGetSecurityDescriptorLength() throws Exception { // create a temp file - File file = createTempFile(); - int infoType = OWNER_SECURITY_INFORMATION + File file = createTempFile(); + int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; @@ -1156,12 +1174,12 @@ public void testGetSecurityDescriptorLength() throws Exception { public void testIsValidSecurityDescriptor() throws Exception { // create a temp file File file = createTempFile(); - int infoType = OWNER_SECURITY_INFORMATION + int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; PointerByReference ppSecurityDescriptor = new PointerByReference(); - + assertEquals(Advapi32.INSTANCE.GetNamedSecurityInfo( file.getAbsolutePath(), AccCtrl.SE_OBJECT_TYPE.SE_FILE_OBJECT, @@ -1442,12 +1460,12 @@ public DWORD callback(ByteByReference pbData, Pointer final IntByReference elementsReadWrapper = new IntByReference(0); FE_IMPORT_FUNC pfImportCallback = new FE_IMPORT_FUNC() { @Override - public DWORD callback(ByteByReference pbData, Pointer pvCallbackContext, + public DWORD callback(ByteByReference pbData, Pointer pvCallbackContext, ULONGByReference ulLength) { int elementsRead = elementsReadWrapper.getValue(); int remainingElements = outputStream.size() - elementsRead; int length = Math.min(remainingElements, ulLength.getValue().intValue()); - pbData.getPointer().write(0, outputStream.toByteArray(), elementsRead, + pbData.getPointer().write(0, outputStream.toByteArray(), elementsRead, length); elementsReadWrapper.setValue(elementsRead + length); ulLength.setValue(new ULONG(length)); @@ -1464,7 +1482,7 @@ public DWORD callback(ByteByReference pbData, Pointer pvCallbackContext, } private File createTempFile() throws Exception { - String filePath = System.getProperty("java.io.tmpdir") + System.nanoTime() + String filePath = System.getProperty("java.io.tmpdir") + System.nanoTime() + ".text"; File file = new File(filePath); file.createNewFile(); diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32DiskManagementFunctionsTest.java b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32DiskManagementFunctionsTest.java new file mode 100644 index 0000000000..b90931a226 --- /dev/null +++ b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32DiskManagementFunctionsTest.java @@ -0,0 +1,120 @@ +/* Copyright (c) 2007 Timothy Wall, All Rights Reserved + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + */ +package com.sun.jna.platform.win32; + +import java.io.File; +import java.util.List; + +import org.junit.Test; + +import com.sun.jna.platform.win32.WinDef.DWORD; +import com.sun.jna.platform.win32.WinDef.DWORDByReference; +import com.sun.jna.platform.win32.WinNT.LARGE_INTEGER; + +public class Kernel32DiskManagementFunctionsTest extends AbstractWin32TestSupport { + public Kernel32DiskManagementFunctionsTest() { + super(); + } + + @Test + public void testGetDiskFreeSpaceEx() { + List driveList = Kernel32Util.getLogicalDriveStrings(); + for (int index = (-1); index < driveList.size(); index++) { + String driveName = (index < 0) ? null : driveList.get(index); + if (driveName != null) { + // according to the documentation must end with a backslash + if (driveName.charAt(driveName.length() - 1) != File.separatorChar) { + driveName += File.separator; + } + + int driveType = Kernel32.INSTANCE.GetDriveType(driveName); + /* + * Don't try DVD or network drives since they may yield errors + * for the test - e.g., DEVICE_NOT_READY + */ + if (driveType != WinNT.DRIVE_FIXED) { + continue; + } + } + + testGetDiskFreeSpaceEx(driveName); + } + } + + private void testGetDiskFreeSpaceEx(String lpDirectoryName) { + LARGE_INTEGER.ByReference lpFreeBytesAvailable = new LARGE_INTEGER.ByReference(); + LARGE_INTEGER.ByReference lpTotalNumberOfBytes = new LARGE_INTEGER.ByReference(); + LARGE_INTEGER.ByReference lpTotalNumberOfFreeBytes = new LARGE_INTEGER.ByReference(); + assertCallSucceeded("GetDiskFreeSpaceEx(" + lpDirectoryName + ")", + Kernel32.INSTANCE.GetDiskFreeSpaceEx(lpDirectoryName, + lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes)); + +// System.out.append(getCurrentTestName()).append('[').append(lpDirectoryName).println(']'); +// System.out.append('\t').append("FreeBytesAvailable: ").println(lpFreeBytesAvailable); +// System.out.append('\t').append("TotalNumberOfBytes: ").println(lpTotalNumberOfBytes); +// System.out.append('\t').append("TotalNumberOfFreeBytes: ").println(lpTotalNumberOfFreeBytes); + + assertTrue("No free size for " + lpDirectoryName, lpTotalNumberOfFreeBytes.getValue() > 0L); + assertTrue("Free size (" + lpTotalNumberOfFreeBytes + ")" + + " not below total size (" + lpTotalNumberOfBytes + ")" + + " for " + lpDirectoryName, + lpTotalNumberOfFreeBytes.getValue() < lpTotalNumberOfBytes.getValue()); + } + + @Test + public void testGetDiskFreeSpace() { + List driveList = Kernel32Util.getLogicalDriveStrings(); + for (int index = (-1); index < driveList.size(); index++) { + String driveName = (index < 0) ? null : driveList.get(index); + if (driveName != null) { + // according to the documentation must end with a backslash + if (driveName.charAt(driveName.length() - 1) != File.separatorChar) { + driveName += File.separator; + } + + int driveType = Kernel32.INSTANCE.GetDriveType(driveName); + /* + * Don't try DVD or network drives since they may yield errors + * for the test - e.g., DEVICE_NOT_READY + */ + if (driveType != WinNT.DRIVE_FIXED) { + continue; + } + } + + testGetDiskFreeSpace(driveName); + } + } + + private void testGetDiskFreeSpace(String lpRootPathName) { + DWORDByReference lpSectorsPerCluster = new DWORDByReference(); + DWORDByReference lpBytesPerSector = new DWORDByReference(); + DWORDByReference lpNumberOfFreeClusters = new DWORDByReference(); + DWORDByReference lpTotalNumberOfClusters = new DWORDByReference(); + assertCallSucceeded("GetDiskFreeSpace(" + lpRootPathName + ")", + Kernel32.INSTANCE.GetDiskFreeSpace(lpRootPathName, + lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters)); + +// System.out.append(getCurrentTestName()).append('[').append(lpRootPathName).println(']'); +// System.out.append('\t').append("SectorsPerCluster: ").println(lpSectorsPerCluster.getValue()); +// System.out.append('\t').append("BytesPerSector: ").println(lpBytesPerSector.getValue()); +// System.out.append('\t').append("NumberOfFreeClusters: ").println(lpNumberOfFreeClusters.getValue()); +// System.out.append('\t').append("TotalNumberOfClusters: ").println(lpTotalNumberOfClusters.getValue()); + + DWORD freeSize = lpNumberOfFreeClusters.getValue(); + assertTrue("No free clusters for " + lpRootPathName, freeSize.longValue() > 0L); + + DWORD totalSize = lpTotalNumberOfClusters.getValue(); + assertTrue("Free clusters (" + freeSize + ") not below total (" + totalSize + ") for " + lpRootPathName, freeSize.longValue() < totalSize.longValue()); + } +} diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java index 8b3c51194f..38b5262478 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java @@ -12,7 +12,6 @@ */ package com.sun.jna.platform.win32; -import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -71,50 +70,48 @@ public void testNamedPipeServerAPI() { @Test public void testMultiThreadedNamedPipe() { - final String pipeName="\\\\.\\pipe\\" + getCurrentTestName(); - final Logger logger=Logger.getLogger(getClass().getName()); - final int MAX_BUFFER_SIZE=1024; - ExecutorService executors=Executors.newFixedThreadPool(2); + final String pipeName = "\\\\.\\pipe\\" + getCurrentTestName(); + final Logger logger = Logger.getLogger(getClass().getName()); + final int MAX_BUFFER_SIZE=1024; + ExecutorService executors = Executors.newFixedThreadPool(2); try { - Future server=executors.submit(new Runnable() { + Future server = executors.submit(new Runnable() { @Override public void run() { // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365588(v=vs.85).aspx - HANDLE hNamedPipe=Kernel32.INSTANCE.CreateNamedPipe(pipeName, + HANDLE hNamedPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateNamedPipe(pipeName, WinBase.PIPE_ACCESS_DUPLEX, // dwOpenMode WinBase.PIPE_TYPE_MESSAGE | WinBase.PIPE_READMODE_MESSAGE | WinBase.PIPE_WAIT, // dwPipeMode 1, // nMaxInstances, MAX_BUFFER_SIZE, // nOutBufferSize, MAX_BUFFER_SIZE, // nInBufferSize, (int) TimeUnit.SECONDS.toMillis(30L), // nDefaultTimeOut, - null); // lpSecurityAttributes - assertCallSucceeded("CreateNamedPipe", !WinBase.INVALID_HANDLE_VALUE.equals(hNamedPipe)); + null // lpSecurityAttributes + )); + try { logger.info("Await client connection"); assertCallSucceeded("ConnectNamedPipe", Kernel32.INSTANCE.ConnectNamedPipe(hNamedPipe, null)); logger.info("Client connected"); - - ByteBuffer readBuffer=ByteBuffer.allocate(MAX_BUFFER_SIZE); - IntByReference lpNumberOfBytesRead=new IntByReference(0); - assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hNamedPipe, readBuffer, MAX_BUFFER_SIZE, lpNumberOfBytesRead, null)); - - int readSize=lpNumberOfBytesRead.getValue(); + + byte[] readBuffer = new byte[MAX_BUFFER_SIZE]; + IntByReference lpNumberOfBytesRead = new IntByReference(0); + assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hNamedPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null)); + + int readSize = lpNumberOfBytesRead.getValue(); logger.info("Received client data - length=" + readSize); assertTrue("No data receieved from client", readSize > 0); - - byte[] writeBuffer=new byte[readSize]; - readBuffer.get(writeBuffer); - - IntByReference lpNumberOfBytesWritten=new IntByReference(0); - assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hNamedPipe, writeBuffer, readSize, lpNumberOfBytesWritten, null)); + + IntByReference lpNumberOfBytesWritten = new IntByReference(0); + assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hNamedPipe, readBuffer, readSize, lpNumberOfBytesWritten, null)); logger.info("Echoed client data - length=" + lpNumberOfBytesWritten.getValue()); assertEquals("Mismatched write buffer size", readSize, lpNumberOfBytesWritten.getValue()); - + // Flush the pipe to allow the client to read the pipe's contents before disconnecting assertCallSucceeded("FlushFileBuffers", Kernel32.INSTANCE.FlushFileBuffers(hNamedPipe)); - logger.info("Disconnecting"); - assertCallSucceeded("DisconnectNamedPipe", Kernel32.INSTANCE.DisconnectNamedPipe(hNamedPipe)); - logger.info("Disconnected"); + logger.info("Disconnecting"); + assertCallSucceeded("DisconnectNamedPipe", Kernel32.INSTANCE.DisconnectNamedPipe(hNamedPipe)); + logger.info("Disconnected"); } finally { // clean up assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hNamedPipe)); } @@ -122,43 +119,43 @@ public void run() { }); logger.info("Started server - handle=" + server); - Future client=executors.submit(new Runnable() { + Future client = executors.submit(new Runnable() { @Override public void run() { // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365592(v=vs.85).aspx assertCallSucceeded("WaitNamedPipe", Kernel32.INSTANCE.WaitNamedPipe(pipeName, (int) TimeUnit.SECONDS.toMillis(15L))); logger.info("Connected to server"); - HANDLE hPipe=Kernel32.INSTANCE.CreateFile(pipeName, - WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, - 0, // no sharing + HANDLE hPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateFile(pipeName, + WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, + 0, // no sharing null, // default security attributes - WinNT.OPEN_EXISTING, // opens existing pipe - 0, // default attributes - null); // no template file - assertCallSucceeded("CreateNamedPipe", !WinBase.INVALID_HANDLE_VALUE.equals(hPipe)); + WinNT.OPEN_EXISTING, // opens existing pipe + 0, // default attributes + null // no template file + )); + try { - IntByReference lpMode=new IntByReference(WinBase.PIPE_READMODE_MESSAGE); + IntByReference lpMode = new IntByReference(WinBase.PIPE_READMODE_MESSAGE); assertCallSucceeded("SetNamedPipeHandleState", Kernel32.INSTANCE.SetNamedPipeHandleState(hPipe, lpMode, null, null)); - - String expMessage=Thread.currentThread().getName() + " says hello"; - byte[] expData=expMessage.getBytes(); - IntByReference lpNumberOfBytesWritten=new IntByReference(0); + + String expMessage = Thread.currentThread().getName() + " says hello"; + byte[] expData = expMessage.getBytes(); + IntByReference lpNumberOfBytesWritten = new IntByReference(0); assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hPipe, expData, expData.length, lpNumberOfBytesWritten, null)); logger.info("Sent hello message"); assertEquals("Mismatched write buffer size", expData.length, lpNumberOfBytesWritten.getValue()); - - ByteBuffer readBuffer=ByteBuffer.allocate(MAX_BUFFER_SIZE); - IntByReference lpNumberOfBytesRead=new IntByReference(0); - assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hPipe, readBuffer, MAX_BUFFER_SIZE, lpNumberOfBytesRead, null)); - int readSize=lpNumberOfBytesRead.getValue(); + byte[] readBuffer = new byte[MAX_BUFFER_SIZE]; + IntByReference lpNumberOfBytesRead = new IntByReference(0); + assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null)); + + int readSize = lpNumberOfBytesRead.getValue(); logger.info("Received server data - length=" + readSize); assertTrue("No data receieved from server", readSize > 0); - byte[] actData=new byte[readSize]; - readBuffer.get(actData); - assertArrayEquals("Mismatched server data", expData, actData); + String actMessage = new String(readBuffer, 0, readSize); + assertEquals("Mismatched server data", expMessage, actMessage); } finally { // clean up assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hPipe)); } diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java index ed2173d650..97cb7e1407 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/Kernel32Test.java @@ -20,34 +20,32 @@ import java.io.IOException; import java.io.PrintWriter; import java.nio.ByteBuffer; -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; +import java.util.Collection; import java.util.Date; import java.util.List; -import java.util.Random; import java.util.TimeZone; -import junit.framework.TestCase; - -import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.NativeMappedConverter; import com.sun.jna.Platform; import com.sun.jna.Pointer; +import com.sun.jna.platform.win32.BaseTSD.SIZE_T; import com.sun.jna.platform.win32.WinBase.MEMORYSTATUSEX; import com.sun.jna.platform.win32.WinBase.SYSTEM_INFO; import com.sun.jna.platform.win32.WinDef.DWORD; import com.sun.jna.platform.win32.WinDef.HWND; -import com.sun.jna.platform.win32.BaseTSD.SIZE_T; import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.platform.win32.WinNT.HANDLEByReference; -import com.sun.jna.platform.win32.WinNT.LARGE_INTEGER; +import com.sun.jna.platform.win32.WinNT.MEMORY_BASIC_INFORMATION; import com.sun.jna.platform.win32.WinNT.OSVERSIONINFO; import com.sun.jna.platform.win32.WinNT.OSVERSIONINFOEX; -import com.sun.jna.platform.win32.WinNT.MEMORY_BASIC_INFORMATION; import com.sun.jna.ptr.IntByReference; +import junit.framework.TestCase; + public class Kernel32Test extends TestCase { public static void main(String[] args) { @@ -60,6 +58,21 @@ public static void main(String[] args) { junit.textui.TestRunner.run(Kernel32Test.class); } + // see https://github.com/twall/jna/issues/482 + public void testNoDuplicateMethodsNames() { + Collection dupSet = AbstractWin32TestSupport.detectDuplicateMethods(Kernel32.class); + if (dupSet.size() > 0) { + for (String name : new String[] { + // has 2 overloads by design since the API accepts both OSVERSIONINFO and OSVERSIONINFOEX + "GetVersionEx" + }) { + dupSet.remove(name); + } + } + + assertTrue("Duplicate methods found: " + dupSet, dupSet.isEmpty()); + } + public void testGetDriveType() { if (!Platform.isWindows()) return; @@ -145,7 +158,7 @@ private static boolean assertTimeSettingOperationSucceeded(String message, boole if (result) { return result; } - + int hr=Kernel32.INSTANCE.GetLastError(); /* * Check special error in case the user running the test isn't allowed @@ -158,13 +171,13 @@ private static boolean assertTimeSettingOperationSucceeded(String message, boole if (hr == WinError.ERROR_PRIVILEGE_NOT_HELD) { return false; // don't fail the test, but signal the failure } - + if (hr != WinError.ERROR_SUCCESS) { fail(message + " failed: hr=" + hr); } else { fail(message + " unknown failure reason code"); } - + return false; } @@ -236,10 +249,10 @@ public void testResetEvent() { // This should return successfully assertEquals(WinBase.WAIT_OBJECT_0, Kernel32.INSTANCE.WaitForSingleObject( handle, 1000)); - + // now reset it to not signaled Kernel32.INSTANCE.ResetEvent(handle); - + // handle runs into timeout since it is not triggered // WAIT_TIMEOUT = 0x00000102 assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject( @@ -399,16 +412,6 @@ public void testGlobalMemoryStatusEx() { assertEquals(0, lpBuffer.ullAvailExtendedVirtual.intValue()); } - public void testGetDiskFreeSpaceEx() { - LARGE_INTEGER.ByReference lpFreeBytesAvailable = new LARGE_INTEGER.ByReference(); - LARGE_INTEGER.ByReference lpTotalNumberOfBytes = new LARGE_INTEGER.ByReference(); - LARGE_INTEGER.ByReference lpTotalNumberOfFreeBytes = new LARGE_INTEGER.ByReference(); - assertTrue(Kernel32.INSTANCE.GetDiskFreeSpaceEx(null, - lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes)); - assertTrue(lpTotalNumberOfFreeBytes.getValue() > 0); - assertTrue(lpTotalNumberOfFreeBytes.getValue() < lpTotalNumberOfBytes.getValue()); - } - public void testDeleteFile() { String filename = Kernel32Util.getTempPath() + "\\FileDoesNotExist.jna"; assertFalse(Kernel32.INSTANCE.DeleteFile(filename)); @@ -421,21 +424,28 @@ public void testReadFile() throws IOException { tmp.deleteOnExit(); FileWriter fw = new FileWriter(tmp); - fw.append(expected); - fw.close(); + try { + fw.append(expected); + } finally { + fw.close(); + } HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); - assertFalse(hFile == WinBase.INVALID_HANDLE_VALUE); + assertFalse("Failed to create file handle: " + tmp, WinBase.INVALID_HANDLE_VALUE.equals(hFile)); - Memory m = new Memory(2048); - IntByReference lpNumberOfBytesRead = new IntByReference(0); - assertTrue(Kernel32.INSTANCE.ReadFile(hFile, m, (int) m.size(), lpNumberOfBytesRead, null)); - int read = lpNumberOfBytesRead.getValue(); - assertEquals(expected.length(), read); - assertEquals(expected, new String(m.getByteArray(0, read))); + try { + byte[] readBuffer=new byte[expected.length() + Byte.MAX_VALUE]; + IntByReference lpNumberOfBytesRead = new IntByReference(0); + assertTrue("Failed to read from file", Kernel32.INSTANCE.ReadFile(hFile, readBuffer, readBuffer.length, lpNumberOfBytesRead, null)); - assertTrue(Kernel32.INSTANCE.CloseHandle(hFile)); + int read = lpNumberOfBytesRead.getValue(); + assertEquals("Mismatched read size", expected.length(), read); + + assertEquals("Mismatched read content", expected, new String(readBuffer, 0, read)); + } finally { + assertTrue("Failed to close file", Kernel32.INSTANCE.CloseHandle(hFile)); + } } public void testSetHandleInformation() throws IOException { @@ -607,11 +617,11 @@ public final void testGetPrivateProfileString() throws IOException { writer.close(); final char[] buffer = new char[8]; - + DWORD len = Kernel32.INSTANCE.GetPrivateProfileString("Section", "existingKey", "DEF", buffer, new DWORD(buffer.length), tmp.getCanonicalPath()); assertEquals(3, len.intValue()); assertEquals("ABC", Native.toString(buffer)); - + len = Kernel32.INSTANCE.GetPrivateProfileString("Section", "missingKey", "DEF", buffer, new DWORD(buffer.length), tmp.getCanonicalPath()); assertEquals(3, len.intValue()); assertEquals("DEF", Native.toString(buffer)); @@ -637,7 +647,7 @@ public final void testWritePrivateProfileString() throws IOException { assertEquals(reader.readLine(), null); reader.close(); } - + public final void testGetPrivateProfileSection() throws IOException { final File tmp = File.createTempFile("testGetPrivateProfileSection", ".ini"); tmp.deleteOnExit(); @@ -704,47 +714,47 @@ public final void testCreateRemoteThread() throws IOException { assertNull(hThrd); assertEquals(Kernel32.INSTANCE.GetLastError(), WinError.ERROR_INVALID_HANDLE); } - + public void testWriteProcessMemory() { Kernel32 kernel = Kernel32.INSTANCE; - - boolean successWrite = kernel.WriteProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null); + + boolean successWrite = kernel.WriteProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null); assertFalse(successWrite); assertEquals(kernel.GetLastError(), WinError.ERROR_INVALID_HANDLE); - + ByteBuffer bufDest = ByteBuffer.allocateDirect(4); bufDest.put(new byte[]{0,1,2,3}); ByteBuffer bufSrc = ByteBuffer.allocateDirect(4); bufSrc.put(new byte[]{5,10,15,20}); Pointer ptrSrc = Native.getDirectBufferPointer(bufSrc); Pointer ptrDest = Native.getDirectBufferPointer(bufDest); - + HANDLE selfHandle = kernel.GetCurrentProcess(); kernel.WriteProcessMemory(selfHandle, ptrDest, ptrSrc, 3, null);//Write only the first three - + assertEquals(bufDest.get(0),5); assertEquals(bufDest.get(1),10); assertEquals(bufDest.get(2),15); assertEquals(bufDest.get(3),3); } - + public void testReadProcessMemory() { Kernel32 kernel = Kernel32.INSTANCE; - - boolean successRead = kernel.ReadProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null); + + boolean successRead = kernel.ReadProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null); assertFalse(successRead); assertEquals(kernel.GetLastError(), WinError.ERROR_INVALID_HANDLE); - + ByteBuffer bufSrc = ByteBuffer.allocateDirect(4); bufSrc.put(new byte[]{5,10,15,20}); ByteBuffer bufDest = ByteBuffer.allocateDirect(4); bufDest.put(new byte[]{0,1,2,3}); Pointer ptrSrc = Native.getDirectBufferPointer(bufSrc); Pointer ptrDest = Native.getDirectBufferPointer(bufDest); - + HANDLE selfHandle = kernel.GetCurrentProcess(); kernel.ReadProcessMemory(selfHandle, ptrSrc, ptrDest, 3, null);//Read only the first three - + assertEquals(bufDest.get(0),5); assertEquals(bufDest.get(1),10); assertEquals(bufDest.get(2),15); diff --git a/contrib/platform/test/com/sun/jna/platform/win32/User32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/User32Test.java index 89a8977a7e..5cdb26d452 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/User32Test.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/User32Test.java @@ -1,29 +1,24 @@ /* Copyright (c) 2010 Daniel Doubrovkine, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library 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 - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna.platform.win32; import static com.sun.jna.platform.win32.User32.INSTANCE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; +import java.util.Collection; import java.util.List; import org.junit.Ignore; @@ -53,17 +48,17 @@ /** * @author dblock[at]dblock[dot]org */ -public class User32Test { +public class User32Test extends AbstractWin32TestSupport { public static void main(String[] args) { JUnitCore.runClasses(User32Test.class); } - + /** * Iterates over all currently available Desktop windows and searches for * the window with the associated process whose full PE file path ends with * the specified string (case insensitive). - * + * * @param filePathEnd * The requested end of the process' full file path. * @return Either the found window or {@code null} if nothing was found. @@ -80,6 +75,25 @@ private static DesktopWindow getWindowByProcessPath(final String filePathEnd) { return null; } + @Test + public void testNoDuplicateMethodsNames() { + // see https://github.com/twall/jna/issues/482 + Collection dupSet = AbstractWin32TestSupport.detectDuplicateMethods(User32.class); + if (dupSet.size() > 0) { + for (String name : new String[] { + // has 2 overloads since the original API accepts both MONITORINFO and MONITORINFOEX + "GetMonitorInfo", + // has 2 overloads because of fact that in Windows HICON == HANDLE, whereas in Java they are not + // TODO consider using ONLY the HANDLE and remove any HICON reference + "GetIconInfo" + }) { + dupSet.remove(name); + } + } + + assertTrue("Duplicate methods found: " + dupSet, dupSet.isEmpty()); + } + @Test public void testGetSystemMetrics() { int cursorWidth = INSTANCE.GetSystemMetrics(WinUser.SM_CXCURSOR); @@ -157,10 +171,10 @@ public void testGetLastInputInfo() throws Exception { assertTrue(Kernel32.INSTANCE.GetTickCount() >= plii.dwTime); assertTrue(plii.dwTime > 0); } - + @Test public final void testRegisterWindowMessage() { - final int msg = User32.INSTANCE.RegisterWindowMessage("RM_UNITTEST"); + final int msg = User32.INSTANCE.RegisterWindowMessage("RM_UNITTEST"); assertTrue(msg >= 0xC000 && msg <= 0xFFFF); } @@ -208,7 +222,7 @@ public int apply(HMONITOR hMonitor, HDC hdc, RECT rect, LPARAM lparam) } }, new LPARAM(0)).booleanValue()); } - + @Test public final void testAdjustWindowRect() { RECT lpRect = new RECT(); @@ -216,27 +230,27 @@ public final void testAdjustWindowRect() { lpRect.top = 200; lpRect.bottom = 300; lpRect.right = 500; - + assertTrue(User32.INSTANCE.AdjustWindowRect(lpRect, new DWORD(WinUser.WS_THICKFRAME), new BOOL(1)).booleanValue()); - + assertTrue(lpRect.left < 100); assertTrue(lpRect.top < 200); assertTrue(lpRect.bottom > 300); assertTrue(lpRect.right > 500); } - + @Ignore("Locks the workstation") @Test public final void testLockWorkStation() { assertTrue(User32.INSTANCE.LockWorkStation().booleanValue()); } - + @Ignore("Shutsdown the workstation") @Test public final void testExitWindows() { assertTrue(User32.INSTANCE.ExitWindowsEx(new UINT(WinUser.EWX_LOGOFF), new DWORD(0x00030000)).booleanValue()); //This only tries to log off. } - + @Test public void testGetIconInfo() throws Exception { final ICONINFO iconInfo = new ICONINFO();