diff --git a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj index 635923e9..f7f633e7 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj +++ b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj @@ -61,6 +61,8 @@ + + diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs new file mode 100644 index 00000000..b669d43a --- /dev/null +++ b/src/AdvApi32.Desktop/AdvApi32Mockable.cs @@ -0,0 +1,194 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static AdvApi32; + [System.Runtime.CompilerServices.CompilerGenerated] + class AdvApi32Mockable : IAdvApi32 { + /// + /// Changes the optional configuration parameters of a service. + /// + /// + /// A handle to the service. + /// This handle is returned by the OpenService or CreateService function and + /// must have the access right. + /// + /// + /// The configuration information to be changed. + /// This parameter can be one value from . + /// + /// + /// A pointer to the new value to be set for the configuration information. + /// The format of this data depends on the value of the dwInfoLevel parameter. + /// If this value is NULL, the information remains unchanged. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool ChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo) + => ChangeServiceConfig2(hService, dwInfoLevel, lpInfo); + + /// + /// Creates a service object and adds it to the specified service control manager database. + /// + /// + /// A handle to the service control manager database. + /// This handle is returned by the OpenSCManager function and must have the access right. + /// + /// + /// The name of the service to install. + /// The maximum string length is 256 characters. + /// The service control manager database preserves the case of the characters, + /// but service name comparisons are always case insensitive. + /// Forward-slash (/) and backslash (\) are not valid service name characters. + /// + /// + /// The display name to be used by user interface programs to identify the service. + /// This string has a maximum length of 256 characters. + /// The name is case-preserved in the service control manager. + /// Display name comparisons are always case-insensitive. + /// + /// + /// The access to the service (). + /// Before granting the requested access, the system checks the access token of the calling process. + /// + /// + /// The service type (). + /// + /// + /// The service start options (). + /// + /// + /// The severity of the error (), and action taken, if this service fails to start. + /// + /// + /// The fully qualified path to the service binary file. If the path contains a space, it must be quoted so that it is correctly interpreted. For example, "d:\\my share\\myservice.exe" should be specified as "\"d:\\my share\\myservice.exe\"". + /// The path can also include arguments for an auto-start service.For example, "d:\\myshare\\myservice.exe arg1 arg2". These arguments are passed to the service entry point (typically the main function). + /// If you specify a path on another computer, the share must be accessible by the computer account of the local computer because this is the security context used in the remote call.However, this requirement allows any potential vulnerabilities in the remote computer to affect the local computer. Therefore, it is best to use a local file. + /// + /// + /// The names of the load ordering group of which this service is a member. Specify NULL or an empty string if the service does not belong to a group. + /// The startup program uses load ordering groups to load groups of services in a specified order with respect to the other groups. + /// The list of load ordering groups is contained in the following registry value: + /// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ServiceGroupOrder + /// + /// + /// A pointer to a variable that receives a tag value that is unique in the group specified in the lpLoadOrderGroup parameter. Specify NULL if you are not changing the existing tag. + /// You can use a tag for ordering service startup within a load ordering group by specifying a tag order vector in the following registry value: + /// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\GroupOrderList + /// Tags are only evaluated for driver services that have or start types. + /// + /// + /// A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify NULL or an empty string if the service has no dependencies. + /// Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. + /// You must prefix group names with SC_GROUP_IDENTIFIER so that they can be distinguished from a service name, because services and service groups share the same name space. + /// + /// + /// The name of the account under which the service should run. + /// If the service type is , use an account name in the form DomainName\UserName. + /// The service process will be logged on as this user. + /// If the account belongs to the built-in domain, you can specify .\UserName. + /// + /// + /// The password to the account name specified by the lpServiceStartName parameter. + /// Specify an empty string if the account has no password or if the service runs in the LocalService, NetworkService, or LocalSystem account. + /// If the account name specified by the lpServiceStartName parameter is the name of a managed service account or virtual account name, the lpPassword parameter must be NULL. + /// Passwords are ignored for driver services. + /// + /// + /// If the function succeeds, the return value is a handle to the service. + /// If the function fails, the return value is NULL + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeServiceHandle CreateService(SafeServiceHandle hSCManager, string lpServiceName, string lpDisplayName, ServiceAccess dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceErrorControl dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword) + => CreateService(hSCManager, lpServiceName, lpDisplayName, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, lpdwTagId, lpDependencies, lpServiceStartName, lpPassword); + + /// + /// Marks the specified service for deletion from the service control manager database. + /// + /// + /// A handle to the service. This handle is returned by the or function, and it must have the access right + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool DeleteService(SafeServiceHandle hService) + => DeleteService(hService); + + /// + /// Establishes a connection to the service control manager on the specified computer and opens the specified service control manager database. + /// + /// + /// The name of the target computer. + /// If the pointer is NULL or points to an empty string, + /// the function connects to the service control manager on the local computer. + /// + /// + /// The name of the service control manager database. + /// This parameter should be set to SERVICES_ACTIVE_DATABASE. + /// If it is NULL, the SERVICES_ACTIVE_DATABASE database is opened by default. + /// + /// + /// The access to the service control manager. For a list of access rights, see Service Security and Access Rights. + /// Before granting the requested access rights, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service control manager. + /// The access right is implicitly specified by calling this function. + /// + /// + /// If the function succeeds, the return value is a handle to the specified service control manager database. + /// If the function fails, the return value is NULL.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeServiceHandle OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess) + => OpenSCManager(lpMachineName, lpDatabaseName, dwDesiredAccess); + + /// + /// Opens an existing service. + /// + /// + /// A handle to the service control manager database. The function returns this handle. + /// + /// + /// The name of the service to be opened. This is the name specified by the lpServiceName parameter of the CreateService function when the service object was created, not the service display name that is shown by user interface applications to identify the service. + /// The maximum string length is 256 characters.The service control manager database preserves the case of the characters, but service name comparisons are always case insensitive.Forward-slash(/) and backslash(\) are invalid service name characters. + /// + /// + /// The access to the service (). + /// Before granting the requested access, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service object. + /// + /// + /// If the function succeeds, the return value is a handle to the service. + /// If the function fails, the return value is NULL. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeServiceHandle OpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess) + => OpenService(hSCManager, lpServiceName, dwDesiredAccess); + + /// + /// Starts a service. + /// + /// + /// A handle to the service. This handle is returned by the or function, and it must have the access right. + /// + /// + /// The number of strings in the lpServiceArgVectors array. If lpServiceArgVectors is NULL, this parameter can be zero. + /// + /// + /// The null-terminated strings to be passed to the ServiceMain function for the service as arguments. If there are no arguments, this parameter can be NULL. Otherwise, the first argument (lpServiceArgVectors[0]) is the name of the service, followed by any additional arguments (lpServiceArgVectors[1] through lpServiceArgVectors[dwNumServiceArgs-1]). + /// Driver services do not receive these arguments. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool StartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) + => StartService(hService, dwNumServiceArgs, lpServiceArgVectors); + } +} diff --git a/src/AdvApi32.Desktop/IAdvApi32.cs b/src/AdvApi32.Desktop/IAdvApi32.cs new file mode 100644 index 00000000..f05122d8 --- /dev/null +++ b/src/AdvApi32.Desktop/IAdvApi32.cs @@ -0,0 +1,188 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static AdvApi32; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IAdvApi32 { + /// + /// Changes the optional configuration parameters of a service. + /// + /// + /// A handle to the service. + /// This handle is returned by the OpenService or CreateService function and + /// must have the access right. + /// + /// + /// The configuration information to be changed. + /// This parameter can be one value from . + /// + /// + /// A pointer to the new value to be set for the configuration information. + /// The format of this data depends on the value of the dwInfoLevel parameter. + /// If this value is NULL, the information remains unchanged. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool ChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo); + + /// + /// Creates a service object and adds it to the specified service control manager database. + /// + /// + /// A handle to the service control manager database. + /// This handle is returned by the OpenSCManager function and must have the access right. + /// + /// + /// The name of the service to install. + /// The maximum string length is 256 characters. + /// The service control manager database preserves the case of the characters, + /// but service name comparisons are always case insensitive. + /// Forward-slash (/) and backslash (\) are not valid service name characters. + /// + /// + /// The display name to be used by user interface programs to identify the service. + /// This string has a maximum length of 256 characters. + /// The name is case-preserved in the service control manager. + /// Display name comparisons are always case-insensitive. + /// + /// + /// The access to the service (). + /// Before granting the requested access, the system checks the access token of the calling process. + /// + /// + /// The service type (). + /// + /// + /// The service start options (). + /// + /// + /// The severity of the error (), and action taken, if this service fails to start. + /// + /// + /// The fully qualified path to the service binary file. If the path contains a space, it must be quoted so that it is correctly interpreted. For example, "d:\\my share\\myservice.exe" should be specified as "\"d:\\my share\\myservice.exe\"". + /// The path can also include arguments for an auto-start service.For example, "d:\\myshare\\myservice.exe arg1 arg2". These arguments are passed to the service entry point (typically the main function). + /// If you specify a path on another computer, the share must be accessible by the computer account of the local computer because this is the security context used in the remote call.However, this requirement allows any potential vulnerabilities in the remote computer to affect the local computer. Therefore, it is best to use a local file. + /// + /// + /// The names of the load ordering group of which this service is a member. Specify NULL or an empty string if the service does not belong to a group. + /// The startup program uses load ordering groups to load groups of services in a specified order with respect to the other groups. + /// The list of load ordering groups is contained in the following registry value: + /// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ServiceGroupOrder + /// + /// + /// A pointer to a variable that receives a tag value that is unique in the group specified in the lpLoadOrderGroup parameter. Specify NULL if you are not changing the existing tag. + /// You can use a tag for ordering service startup within a load ordering group by specifying a tag order vector in the following registry value: + /// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\GroupOrderList + /// Tags are only evaluated for driver services that have or start types. + /// + /// + /// A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify NULL or an empty string if the service has no dependencies. + /// Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group. + /// You must prefix group names with SC_GROUP_IDENTIFIER so that they can be distinguished from a service name, because services and service groups share the same name space. + /// + /// + /// The name of the account under which the service should run. + /// If the service type is , use an account name in the form DomainName\UserName. + /// The service process will be logged on as this user. + /// If the account belongs to the built-in domain, you can specify .\UserName. + /// + /// + /// The password to the account name specified by the lpServiceStartName parameter. + /// Specify an empty string if the account has no password or if the service runs in the LocalService, NetworkService, or LocalSystem account. + /// If the account name specified by the lpServiceStartName parameter is the name of a managed service account or virtual account name, the lpPassword parameter must be NULL. + /// Passwords are ignored for driver services. + /// + /// + /// If the function succeeds, the return value is a handle to the service. + /// If the function fails, the return value is NULL + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeServiceHandle CreateService(SafeServiceHandle hSCManager, string lpServiceName, string lpDisplayName, ServiceAccess dwDesiredAccess, ServiceType dwServiceType, ServiceStartType dwStartType, ServiceErrorControl dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword); + + /// + /// Marks the specified service for deletion from the service control manager database. + /// + /// + /// A handle to the service. This handle is returned by the or function, and it must have the access right + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool DeleteService(SafeServiceHandle hService); + + /// + /// Establishes a connection to the service control manager on the specified computer and opens the specified service control manager database. + /// + /// + /// The name of the target computer. + /// If the pointer is NULL or points to an empty string, + /// the function connects to the service control manager on the local computer. + /// + /// + /// The name of the service control manager database. + /// This parameter should be set to SERVICES_ACTIVE_DATABASE. + /// If it is NULL, the SERVICES_ACTIVE_DATABASE database is opened by default. + /// + /// + /// The access to the service control manager. For a list of access rights, see Service Security and Access Rights. + /// Before granting the requested access rights, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service control manager. + /// The access right is implicitly specified by calling this function. + /// + /// + /// If the function succeeds, the return value is a handle to the specified service control manager database. + /// If the function fails, the return value is NULL.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeServiceHandle OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess); + + /// + /// Opens an existing service. + /// + /// + /// A handle to the service control manager database. The function returns this handle. + /// + /// + /// The name of the service to be opened. This is the name specified by the lpServiceName parameter of the CreateService function when the service object was created, not the service display name that is shown by user interface applications to identify the service. + /// The maximum string length is 256 characters.The service control manager database preserves the case of the characters, but service name comparisons are always case insensitive.Forward-slash(/) and backslash(\) are invalid service name characters. + /// + /// + /// The access to the service (). + /// Before granting the requested access, the system checks the access token of the calling process against the discretionary access-control list of the security descriptor associated with the service object. + /// + /// + /// If the function succeeds, the return value is a handle to the service. + /// If the function fails, the return value is NULL. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeServiceHandle OpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess); + + /// + /// Starts a service. + /// + /// + /// A handle to the service. This handle is returned by the or function, and it must have the access right. + /// + /// + /// The number of strings in the lpServiceArgVectors array. If lpServiceArgVectors is NULL, this parameter can be zero. + /// + /// + /// The null-terminated strings to be passed to the ServiceMain function for the service as arguments. If there are no arguments, this parameter can be NULL. Otherwise, the first argument (lpServiceArgVectors[0]) is the name of the service, followed by any additional arguments (lpServiceArgVectors[1] through lpServiceArgVectors[dwNumServiceArgs-1]). + /// Driver services do not receive these arguments. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool StartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); + } +} diff --git a/src/BCrypt/BCrypt.csproj b/src/BCrypt/BCrypt.csproj index ef0f928b..29621222 100644 --- a/src/BCrypt/BCrypt.csproj +++ b/src/BCrypt/BCrypt.csproj @@ -60,6 +60,8 @@ + + diff --git a/src/BCrypt/BCryptMockable.cs b/src/BCrypt/BCryptMockable.cs new file mode 100644 index 00000000..46b91609 --- /dev/null +++ b/src/BCrypt/BCryptMockable.cs @@ -0,0 +1,667 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Runtime.InteropServices; + using static BCrypt; + [System.Runtime.CompilerServices.CompilerGenerated] + class BCryptMockable : IBCrypt { /// + /// Loads and initializes a CNG provider. + /// + /// + /// A pointer to a BCRYPT_ALG_HANDLE variable that receives the CNG provider handle. + /// When you have finished using this handle, release it by passing it to the + /// BCryptCloseAlgorithmProvider function. + /// + /// + /// A pointer to a null-terminated Unicode string that identifies the requested + /// cryptographic algorithm. This can be one of the standard + /// CNG Algorithm Identifiers defined in + /// or the identifier for another registered algorithm. + /// + /// + /// + /// A pointer to a null-terminated Unicode string that identifies the specific provider + /// to load. This is the registered alias of the cryptographic primitive provider. + /// This parameter is optional and can be NULL if it is not needed. If this parameter + /// is NULL, the default provider for the specified algorithm will be loaded. + /// + /// + /// Note If the parameter value is NULL, CNG attempts to open each + /// registered provider, in order of priority, for the algorithm specified by the + /// parameter and returns the handle of the first provider that is successfully + /// opened.For the lifetime of the handle, any BCrypt*** cryptographic APIs will use the + /// provider that was successfully opened. + /// + /// + /// Options for the function. + /// + /// Returns a status code that indicates the success or failure of the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptOpenAlgorithmProvider( + out SafeAlgorithmHandle phAlgorithm, + string pszAlgId, + string pszImplementation, + BCryptOpenAlgorithmProviderFlags dwFlags) + => BCryptOpenAlgorithmProvider(out phAlgorithm, pszAlgId, pszImplementation, dwFlags); + + /// + /// Create a hash or Message Authentication Code (MAC) object. + /// + /// + /// The handle of an algorithm provider created by using the function. The algorithm that was specified when the provider was created must support the hash interface. + /// + /// + /// A pointer to a value that receives a handle that represents the hash or MAC object. This handle is used in subsequent hashing or MAC functions, such as the function. When you have finished using this handle, release it by passing it to the function. + /// + /// + /// A pointer to a buffer that receives the hash or MAC object. The parameter contains the size of this buffer. The required size of this buffer can be obtained by calling the function to get the property. This will provide the size of the hash or MAC object for the specified algorithm. + /// This memory can only be freed after the handle pointed to by the parameter is destroyed. + /// If the value of this parameter is NULL and the value of the parameter is zero, the memory for the hash object is allocated and freed by this function. + /// Windows 7: This memory management functionality is available beginning with Windows 7. + /// + /// + /// The size, in bytes, of the buffer. + /// If the value of this parameter is zero and the value of the parameter is NULL, the memory for the key object is allocated and freed by this function. + /// Windows 7: This memory management functionality is available beginning with Windows 7. + /// + /// + /// A pointer to a buffer that contains the key to use for the hash or MAC. The parameter contains the size of this buffer. This key only applies to hash algorithms opened by the BCryptOpenAlgorithmProvider function by using the flag. Otherwise, set this parameter to NULL. + /// + /// + /// The size, in bytes, of the buffer. If no key is used, set this parameter to zero. + /// + /// Flags that modify the behavior of the function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptCreateHash( + SafeAlgorithmHandle hAlgorithm, + out SafeHashHandle phHash, + byte[] pbHashObject, + int cbHashObject, + byte[] pbSecret, + int cbSecret, + BCryptCreateHashFlags dwFlags) + => BCryptCreateHash(hAlgorithm, out phHash, pbHashObject, cbHashObject, pbSecret, cbSecret, dwFlags); + + /// + /// Encrypts a block of data. + /// + /// + /// The handle of the key to use to encrypt the data. This handle is obtained from one of the key creation functions, such as , , or . + /// + /// + /// The address of a buffer that contains the plaintext to be encrypted. The cbInput parameter contains the size of the plaintext to encrypt. + /// + /// + /// The number of bytes in the pbInput buffer to encrypt. + /// + /// + /// A pointer to a structure that contains padding information. This parameter is only used with asymmetric keys and authenticated encryption modes. If an authenticated encryption mode is used, this parameter must point to a BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO structure. If asymmetric keys are used, the type of structure this parameter points to is determined by the value of the dwFlags parameter. Otherwise, the parameter must be set to NULL. + /// + /// + /// The address of a buffer that contains the initialization vector (IV) to use during encryption. The cbIV parameter contains the size of this buffer. This function will modify the contents of this buffer. If you need to reuse the IV later, make sure you make a copy of this buffer before calling this function. + /// This parameter is optional and can be NULL if no IV is used. + /// The required size of the IV can be obtained by calling the function to get the BCRYPT_BLOCK_LENGTH property.This will provide the size of a block for the algorithm, which is also the size of the IV. + /// + /// The size, in bytes, of the pbIV buffer. + /// + /// The address of the buffer that receives the ciphertext produced by this function. The parameter contains the size of this buffer. For more information, see Remarks. + /// If this parameter is NULL, the function calculates the size needed for the ciphertext of the data passed in the parameter. In this case, the location pointed to by the parameter contains this size, and the function returns .The parameter is not modified. + /// If the values of both the and parameters are NULL, an error is returned unless an authenticated encryption algorithm is in use.In the latter case, the call is treated as an authenticated encryption call with zero length data, and the authentication tag is returned in the parameter. + /// + /// + /// The size, in bytes, of the buffer. This parameter is ignored if the parameter is NULL. + /// + /// + /// A pointer to a ULONG variable that receives the number of bytes copied to the buffer. If is NULL, this receives the size, in bytes, required for the ciphertext. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the hKey parameter. + /// + /// Returns a status code that indicates the success or failure of the function. + /// + /// The and parameters can point to the same buffer. In this case, this function will perform the encryption in place. It is possible that the encrypted data size will be larger than the unencrypted data size, so the buffer must be large enough to hold the encrypted data. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptEncrypt( + SafeKeyHandle hKey, + byte[] pbInput, + int cbInput, + IntPtr pPaddingInfo, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbIV, + int cbIV, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 8)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptEncryptFlags dwFlags) + => BCryptEncrypt(hKey, pbInput, cbInput, pPaddingInfo, pbIV, cbIV, pbOutput, cbOutput, out pcbResult, dwFlags); + + /// + /// Decrypts a block of data. + /// + /// + /// The handle of the key to use to decrypt the data. This handle is obtained from one of the key creation functions, such as , , or . + /// + /// + /// The address of a buffer that contains the ciphertext to be decrypted. The parameter contains the size of the ciphertext to decrypt. For more information, see Remarks. + /// + /// + /// The number of bytes in the buffer to decrypt. + /// + /// + /// A pointer to a structure that contains padding information. This parameter is only used with asymmetric keys and authenticated encryption modes. If an authenticated encryption mode is used, this parameter must point to a BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO structure. If asymmetric keys are used, the type of structure this parameter points to is determined by the value of the parameter. Otherwise, the parameter must be set to NULL. + /// + /// + /// The address of a buffer that contains the initialization vector (IV) to use during decryption. The parameter contains the size of this buffer. This function will modify the contents of this buffer. If you need to reuse the IV later, make sure you make a copy of this buffer before calling this function. + /// This parameter is optional and can be NULL if no IV is used. + /// The required size of the IV can be obtained by calling the function to get the property. This will provide the size of a block for the algorithm, which is also the size of the IV. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// + /// The address of a buffer to receive the plaintext produced by this function. The cbOutput parameter contains the size of this buffer. For more information, see Remarks. + /// If this parameter is NULL, the function calculates the size required for the plaintext of the encrypted data passed in the parameter.In this case, the location pointed to by the parameter contains this size, and the function returns . + /// If the values of both the and parameters are NULL, an error is returned unless an authenticated encryption algorithm is in use.In the latter case, the call is treated as an authenticated encryption call with zero length data, and the authentication tag, passed in the parameter, is verified. + /// + /// + /// The size, in bytes, of the buffer. This parameter is ignored if the parameter is NULL. + /// + /// + /// A pointer to a ULONG variable to receive the number of bytes copied to the buffer. If is NULL, this receives the size, in bytes, required for the plaintext. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the parameter. + /// + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptDecrypt( + SafeKeyHandle hKey, + byte[] pbInput, + int cbInput, + IntPtr pPaddingInfo, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbIV, + int cbIV, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 8)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptEncryptFlags dwFlags) + => BCryptDecrypt(hKey, pbInput, cbInput, pPaddingInfo, pbIV, cbIV, pbOutput, cbOutput, out pcbResult, dwFlags); + + /// + /// Performs a one way hash or Message Authentication Code (MAC) on a data buffer. + /// + /// + /// The handle of the hash or MAC object to use to perform the operation. This handle is obtained by calling the function. + /// + /// + /// A pointer to a buffer that contains the data to process. The parameter contains the number of bytes in this buffer. This function does not modify the contents of this buffer. + /// + /// The number of bytes in the buffer. + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + /// + /// To combine more than one buffer into the hash or MAC, you can call this function multiple times, passing a different buffer each time. To obtain the hash or MAC value, call the function. + /// After the function has been called for a specified handle, that handle cannot be reused. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptHashData( + SafeHashHandle hHash, + byte[] pbInput, + int cbInput, + BCryptHashDataFlags dwFlags = BCryptHashDataFlags.None) + => BCryptHashData(hHash, pbInput, cbInput, dwFlags ); + + /// + /// Retrieves the hash or Message Authentication Code (MAC) value for the data accumulated from prior calls to . + /// + /// + /// The handle of the hash or MAC object to use to compute the hash or MAC. This handle is obtained by calling the function. After this function has been called, the hash handle passed to this function cannot be used again except in a call to . + /// + /// + /// A pointer to a buffer that receives the hash or MAC value. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. This size must exactly match the size of the hash or MAC value. + /// The size can be obtained by calling the function to get the property. This will provide the size of the hash or MAC value for the specified algorithm. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptFinishHash( + SafeHashHandle hHash, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbOutput, + int cbOutput, + BCryptFinishHashFlags dwFlags = BCryptFinishHashFlags.None) + => BCryptFinishHash(hHash, pbOutput, cbOutput, dwFlags ); + + /// + /// Creates a signature of a hash value. + /// + /// The handle of the key to use to sign the hash. + /// + /// A pointer to a structure that contains padding information. The actual type of structure this parameter points to depends on the value of the parameter. This parameter is only used with asymmetric keys and must be NULL otherwise. + /// + /// + /// A pointer to a buffer that contains the hash value to sign. The parameter contains the size of this buffer. + /// + /// + /// The number of bytes in the buffer to sign. + /// + /// + /// The address of a buffer to receive the signature produced by this function. The parameter contains the size of this buffer. + /// If this parameter is NULL, this function will calculate the size required for the signature and return the size in the location pointed to by the parameter. + /// + /// + /// The size, in bytes, of the buffer. This parameter is ignored if the parameter is NULL. + /// + /// + /// A pointer to a ULONG variable that receives the number of bytes copied to the buffer. + /// If is NULL, this receives the size, in bytes, required for the signature. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the parameter. + /// + /// Returns a status code that indicates the success or failure of the function. + /// + /// To later verify that the signature is valid, call the function with an identical key and an identical hash of the original data. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptSignHash( + SafeKeyHandle hKey, + IntPtr pPaddingInfo, + byte[] pbInput, + int cbInput, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptSignHashFlags dwFlags) + => BCryptSignHash(hKey, pPaddingInfo, pbInput, cbInput, pbOutput, cbOutput, out pcbResult, dwFlags); + + /// + /// Verifies that the specified signature matches the specified hash. + /// + /// + /// The handle of the key to use to decrypt the signature. This must be an identical key or the public key portion of the key pair used to sign the data with the function. + /// + /// + /// A pointer to a structure that contains padding information. The actual type of structure this parameter points to depends on the value of the parameter. This parameter is only used with asymmetric keys and must be NULL otherwise. + /// + /// + /// The address of a buffer that contains the hash of the data. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// + /// The address of a buffer that contains the signed hash of the data. The function is used to create the signature. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. The function is used to create the signature. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the hKey parameter. + /// If the key is a symmetric key, this parameter is not used and should be zero. + /// If the key is an asymmetric key, this can be one of the following values. + /// + /// + /// Returns a status code that indicates the success or failure of the function. + /// In particular, an invalid signature will produce a result. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptVerifySignature( + SafeKeyHandle hKey, + IntPtr pPaddingInfo, + byte[] pbHash, + int cbHash, + byte[] pbSignature, + int cbSignature, + BCryptSignHashFlags dwFlags = BCryptSignHashFlags.None) + => BCryptVerifySignature(hKey, pPaddingInfo, pbHash, cbHash, pbSignature, cbSignature, dwFlags ); + + /// + /// Creates an empty public/private key pair. + /// + /// The handle to the algorithm previously opened by + /// Receives a handle to the generated key pair. + /// The length of the key, in bits. + /// A set of flags that modify the behavior of this function. No flags are currently defined, so this parameter should be zero. + /// Returns a status code that indicates the success or failure of the function. + /// + /// After you create a key by using this function, you can use the BCryptSetProperty + /// function to set its properties; however, the key cannot be used until the + /// BCryptFinalizeKeyPair function is called. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptGenerateKeyPair( + SafeAlgorithmHandle hAlgorithm, + out SafeKeyHandle phKey, + int dwLength, + BCryptGenerateKeyPairFlags dwFlags = BCryptGenerateKeyPairFlags.None) + => BCryptGenerateKeyPair(hAlgorithm, out phKey, dwLength, dwFlags ); + + /// + /// Creates a key object for use with a symmetrical key encryption algorithm from a supplied key. + /// + /// + /// The handle of an algorithm provider created with the function. The algorithm specified when the provider was created must support symmetric key encryption. + /// + /// + /// Receives the of the generated key. + /// + /// + /// A pointer to a buffer that receives the key object. The parameter contains the size of this buffer. The required size of this buffer can be obtained by calling the function to get the BCRYPT_OBJECT_LENGTH property. This will provide the size of the key object for the specified algorithm. + /// This memory can only be freed after the key handle is destroyed. + /// If the value of this parameter is NULL and the value of the parameter is zero, the memory for the key object is allocated and freed by this function. + /// + /// + /// The size, in bytes, of the buffer. + /// If the value of this parameter is zero and the value of the parameter is NULL, the memory for the key object is allocated and freed by this function. + /// + /// + /// Pointer to a buffer that contains the key from which to create the key object. The parameter contains the size of this buffer. This is normally a hash of a password or some other reproducible data. If the data passed in exceeds the target key size, the data will be truncated and the excess will be ignored. + /// Note: We strongly recommended that applications pass in the exact number of bytes required by the target key. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// A set of flags that modify the behavior of this function. No flags are currently defined, so this parameter should be zero. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptGenerateSymmetricKey( + SafeAlgorithmHandle hAlgorithm, + out SafeKeyHandle phKey, + byte[] pbKeyObject, + int cbKeyObject, + byte[] pbSecret, + int cbSecret, + BCryptGenerateSymmetricKeyFlags flags = BCryptGenerateSymmetricKeyFlags.None) + => BCryptGenerateSymmetricKey(hAlgorithm, out phKey, pbKeyObject, cbKeyObject, pbSecret, cbSecret, flags ); + + /// + /// Completes a public/private key pair. + /// + /// The handle of the key to complete. This handle is obtained by calling the BCryptGenerateKeyPair function. + /// A set of flags that modify the behavior of this function. No flags are currently defined, so this parameter should be zero. + /// Returns a status code that indicates the success or failure of the function. + /// + /// The key cannot be used until this function has been called. + /// After this function has been called, the BCryptSetProperty function + /// can no longer be used for this key. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptFinalizeKeyPair( + SafeKeyHandle hKey, + BCryptFinalizeKeyPairFlags dwFlags = BCryptFinalizeKeyPairFlags.None) + => BCryptFinalizeKeyPair(hKey, dwFlags ); + + /// + /// Destroys a key. + /// + /// The handle of the key to destroy. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptDestroyKey( + IntPtr hKey) + => BCryptDestroyKey(hKey); + + /// + /// Destroys a secret agreement handle that was created by using the BCryptSecretAgreement function. + /// + /// The handle of the secret to destroy. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptDestroySecret( + IntPtr hSecret) + => BCryptDestroySecret(hSecret); + + /// + /// Imports a symmetric key from a key BLOB. The BCryptImportKeyPair function is used to import a public/private key pair. + /// + /// + /// The handle of the algorithm provider to import the key. This handle is obtained by calling the function. + /// + /// + /// The handle of the key encryption key needed to unwrap the key BLOB in the pbInput parameter. + /// Note The handle must be supplied by the same provider that supplied the key that is being imported. + /// + /// + /// An identifier that specifies the type of BLOB that is contained in the pbInput buffer. + /// This can be one of the values defined in . + /// + /// + /// A pointer to a BCRYPT_KEY_HANDLE that receives the handle of the imported key. This handle is used in subsequent functions that require a key, such as BCryptEncrypt. This handle must be released when it is no longer needed by passing it to the function. + /// + /// + /// A pointer to a buffer that receives the imported key object. + /// The parameter contains the size of this buffer. + /// The required size of this buffer can be obtained by calling the + /// function to get the BCRYPT_OBJECT_LENGTH property. This will provide the size of the + /// key object for the specified algorithm. + /// This memory can only be freed after the phKey key handle is destroyed. + /// + /// The size, in bytes, of the buffer. + /// + /// The address of a buffer that contains the key BLOB to import. + /// The parameter contains the size of this buffer. + /// The parameter specifies the type of key BLOB this buffer contains. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptImportKey( + SafeAlgorithmHandle hAlgorithm, + SafeKeyHandle hImportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + out SafeKeyHandle phKey, + byte[] pbKeyObject, + int cbKeyObject, + byte[] pbInput, + int cbInput, + BCryptImportKeyFlags dwFlags = BCryptImportKeyFlags.None) + => BCryptImportKey(hAlgorithm, hImportKey, pszBlobType, out phKey, pbKeyObject, cbKeyObject, pbInput, cbInput, dwFlags ); + + /// + /// Imports a public/private key pair from a key BLOB. + /// + /// The handle of the algorithm provider to import the key. This handle is obtained by calling the BCryptOpenAlgorithmProvider function. + /// This parameter is not currently used and should be NULL. + /// an identifier that specifies the type of BLOB that is contained in the buffer. + /// A pointer to a BCRYPT_KEY_HANDLE that receives the handle of the imported key. This handle is used in subsequent functions that require a key, such as BCryptSignHash. This handle must be released when it is no longer needed by passing it to the function. + /// The address of a buffer that contains the key BLOB to import. The cbInput parameter contains the size of this buffer. The parameter specifies the type of key BLOB this buffer contains. + /// The size, in bytes, of the buffer. + /// A set of flags that modify the behavior of this function. This can be zero or the following value: BCRYPT_NO_KEY_VALIDATION + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptImportKeyPair( + SafeAlgorithmHandle hAlgorithm, + SafeKeyHandle hImportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + out SafeKeyHandle phKey, + byte[] pbInput, + int cbInput, + BCryptImportKeyPairFlags dwFlags) + => BCryptImportKeyPair(hAlgorithm, hImportKey, pszBlobType, out phKey, pbInput, cbInput, dwFlags); + + /// + /// Exports a key to a memory BLOB that can be persisted for later use. + /// + /// The handle of the key to export. + /// + /// The handle of the key with which to wrap the exported key. Use this parameter when exporting BLOBs of type BCRYPT_AES_WRAP_KEY_BLOB; otherwise, set it to NULL. + /// Note: The handle must be supplied by the same provider that supplied the hKey handle, and hExportKey must be a handle to a symmetric key that can be used in the Advanced Encryption Standard(AES) key wrap algorithm.When the hKey handle is from the Microsoft provider, hExportKey must be an AES key handle. + /// + /// + /// An identifier that specifies the type of BLOB to export. This can be one of the values + /// defined in the or classes. + /// + /// + /// The address of a buffer that receives the key BLOB. + /// The parameter contains the size of this buffer. + /// If this parameter is NULL, this function will place the required size, in bytes, in the ULONG pointed to by the parameter. + /// + /// + /// Contains the size, in bytes, of the buffer. + /// + /// + /// A pointer to a ULONG that receives the number of bytes that were copied to the buffer. + /// If the pbOutput parameter is NULL, this function will place the required size, in bytes, + /// in the ULONG pointed to by this parameter. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptExportKey( + SafeKeyHandle hKey, + SafeKeyHandle hExportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptExportKeyFlags dwFlags = BCryptExportKeyFlags.None) + => BCryptExportKey(hKey, hExportKey, pszBlobType, pbOutput, cbOutput, out pcbResult, dwFlags ); + + /// + /// Creates a secret agreement value from a private and a public key. + /// + /// + /// The handle of the private key to use to create the secret agreement value. + /// This key and the hPubKey key must come from the same CNG cryptographic algorithm provider. + /// + /// + /// The handle of the public key to use to create the secret agreement value. + /// This key and the hPrivKey key must come from the same CNG cryptographic algorithm provider. + /// + /// + /// A pointer to a BCRYPT_SECRET_HANDLE that receives a handle that represents the + /// secret agreement value. This handle must be released by passing it to the + /// BCryptDestroySecret function when it is no longer needed. + /// + /// A set of flags that modify the behavior of this function. No flags are defined for this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptSecretAgreement( + SafeKeyHandle privateKey, + SafeKeyHandle publicKey, + out SafeSecretHandle secret, + BCryptSecretAgreementFlags flags = BCryptSecretAgreementFlags.None) + => BCryptSecretAgreement(privateKey, publicKey, out secret, flags ); + + /// + /// Derives a key from a secret agreement value. + /// + /// + /// The secret agreement handle to create the key from. + /// This handle is obtained from the BCryptSecretAgreement function. + /// + /// + /// The key derivation function. + /// May come from the constants defined on the class. + /// + /// + /// The address of a BCryptBufferDesc structure that contains the KDF parameters. + /// This parameter is optional and can be NULL if it is not needed. + /// + /// + /// The address of a buffer that receives the key. The cbDerivedKey parameter contains + /// the size of this buffer. If this parameter is NULL, this function will place the + /// required size, in bytes, in the ULONG pointed to by the pcbResult parameter. + /// + /// + /// The size, in bytes, of the pbDerivedKey buffer. + /// + /// + /// A pointer to a ULONG that receives the number of bytes that were copied to the + /// pbDerivedKey buffer. If the pbDerivedKey parameter is NULL, this function will + /// place the required size, in bytes, in the ULONG pointed to by this parameter. + /// + /// + /// A set of flags that modify the behavior of this function. + /// This can be zero or the following value. + /// + /// + /// Returns a status code that indicates the success or failure of the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptDeriveKey( + SafeSecretHandle sharedSecret, + string keyDerivationFunction, + [In] ref BCryptBufferDesc kdfParameters, + [Out, MarshalAs(UnmanagedType.LPArray)] byte[] derivedKey, + int derivedKeySize, + [Out] out int resultSize, + BCryptDeriveKeyFlags flags) + => BCryptDeriveKey(sharedSecret, keyDerivationFunction, ref kdfParameters, derivedKey, derivedKeySize, out resultSize, flags); + + /// + /// Sets the value of a named property for a CNG object. + /// + /// A handle that represents the CNG object to set the property value for. + /// + /// A pointer to a null-terminated Unicode string that contains the name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// The address of a buffer that contains the new property value. The parameter contains the size of this buffer. + /// The size, in bytes, of the buffer. + /// A set of flags that modify the behavior of this function. No flags are defined for this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptSetProperty( + SafeHandle hObject, + string property, + [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, + int inputSize, + BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) + => BCryptSetProperty(hObject, property, input, inputSize, flags ); + + /// + /// Retrieves the value of a named property for a CNG object. + /// + /// A handle that represents the CNG object to obtain the property value for. + /// A pointer to a null-terminated Unicode string that contains the name of the property to retrieve. This can be one of the predefined or a custom property identifier. + /// The address of a buffer that receives the property value. The parameter contains the size of this buffer. + /// The size, in bytes, of the buffer. + /// A pointer to a ULONG variable that receives the number of bytes that were copied to the pbOutput buffer. If the parameter is NULL, this function will place the required size, in bytes, in the location pointed to by this parameter. + /// A set of flags that modify the behavior of this function. No flags are defined for this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptGetProperty( + SafeHandle hObject, + string property, + [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, + int outputSize, + out int resultSize, + BCryptGetPropertyFlags flags = BCryptGetPropertyFlags.None) + => BCryptGetProperty(hObject, property, output, outputSize, out resultSize, flags ); + + /// + /// Generates a random number. + /// + /// + /// The handle of an algorithm provider created by using the function. The algorithm that was specified when the provider was created must support the random number generator interface. + /// + /// + /// The address of a buffer that receives the random number. The size of this buffer is specified by the parameter. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus BCryptGenRandom( + SafeAlgorithmHandle hAlgorithm, + byte[] pbBuffer, + int cbBuffer, + BCryptGenRandomFlags flags = BCryptGenRandomFlags.None) + => BCryptGenRandom(hAlgorithm, pbBuffer, cbBuffer, flags ); + } +} diff --git a/src/BCrypt/IBCrypt.cs b/src/BCrypt/IBCrypt.cs new file mode 100644 index 00000000..3b028d74 --- /dev/null +++ b/src/BCrypt/IBCrypt.cs @@ -0,0 +1,646 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Runtime.InteropServices; + using static BCrypt; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IBCrypt { /// + /// Loads and initializes a CNG provider. + /// + /// + /// A pointer to a BCRYPT_ALG_HANDLE variable that receives the CNG provider handle. + /// When you have finished using this handle, release it by passing it to the + /// BCryptCloseAlgorithmProvider function. + /// + /// + /// A pointer to a null-terminated Unicode string that identifies the requested + /// cryptographic algorithm. This can be one of the standard + /// CNG Algorithm Identifiers defined in + /// or the identifier for another registered algorithm. + /// + /// + /// + /// A pointer to a null-terminated Unicode string that identifies the specific provider + /// to load. This is the registered alias of the cryptographic primitive provider. + /// This parameter is optional and can be NULL if it is not needed. If this parameter + /// is NULL, the default provider for the specified algorithm will be loaded. + /// + /// + /// Note If the parameter value is NULL, CNG attempts to open each + /// registered provider, in order of priority, for the algorithm specified by the + /// parameter and returns the handle of the first provider that is successfully + /// opened.For the lifetime of the handle, any BCrypt*** cryptographic APIs will use the + /// provider that was successfully opened. + /// + /// + /// Options for the function. + /// + /// Returns a status code that indicates the success or failure of the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptOpenAlgorithmProvider( + out SafeAlgorithmHandle phAlgorithm, + string pszAlgId, + string pszImplementation, + BCryptOpenAlgorithmProviderFlags dwFlags); + + /// + /// Create a hash or Message Authentication Code (MAC) object. + /// + /// + /// The handle of an algorithm provider created by using the function. The algorithm that was specified when the provider was created must support the hash interface. + /// + /// + /// A pointer to a value that receives a handle that represents the hash or MAC object. This handle is used in subsequent hashing or MAC functions, such as the function. When you have finished using this handle, release it by passing it to the function. + /// + /// + /// A pointer to a buffer that receives the hash or MAC object. The parameter contains the size of this buffer. The required size of this buffer can be obtained by calling the function to get the property. This will provide the size of the hash or MAC object for the specified algorithm. + /// This memory can only be freed after the handle pointed to by the parameter is destroyed. + /// If the value of this parameter is NULL and the value of the parameter is zero, the memory for the hash object is allocated and freed by this function. + /// Windows 7: This memory management functionality is available beginning with Windows 7. + /// + /// + /// The size, in bytes, of the buffer. + /// If the value of this parameter is zero and the value of the parameter is NULL, the memory for the key object is allocated and freed by this function. + /// Windows 7: This memory management functionality is available beginning with Windows 7. + /// + /// + /// A pointer to a buffer that contains the key to use for the hash or MAC. The parameter contains the size of this buffer. This key only applies to hash algorithms opened by the BCryptOpenAlgorithmProvider function by using the flag. Otherwise, set this parameter to NULL. + /// + /// + /// The size, in bytes, of the buffer. If no key is used, set this parameter to zero. + /// + /// Flags that modify the behavior of the function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptCreateHash( + SafeAlgorithmHandle hAlgorithm, + out SafeHashHandle phHash, + byte[] pbHashObject, + int cbHashObject, + byte[] pbSecret, + int cbSecret, + BCryptCreateHashFlags dwFlags); + + /// + /// Encrypts a block of data. + /// + /// + /// The handle of the key to use to encrypt the data. This handle is obtained from one of the key creation functions, such as , , or . + /// + /// + /// The address of a buffer that contains the plaintext to be encrypted. The cbInput parameter contains the size of the plaintext to encrypt. + /// + /// + /// The number of bytes in the pbInput buffer to encrypt. + /// + /// + /// A pointer to a structure that contains padding information. This parameter is only used with asymmetric keys and authenticated encryption modes. If an authenticated encryption mode is used, this parameter must point to a BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO structure. If asymmetric keys are used, the type of structure this parameter points to is determined by the value of the dwFlags parameter. Otherwise, the parameter must be set to NULL. + /// + /// + /// The address of a buffer that contains the initialization vector (IV) to use during encryption. The cbIV parameter contains the size of this buffer. This function will modify the contents of this buffer. If you need to reuse the IV later, make sure you make a copy of this buffer before calling this function. + /// This parameter is optional and can be NULL if no IV is used. + /// The required size of the IV can be obtained by calling the function to get the BCRYPT_BLOCK_LENGTH property.This will provide the size of a block for the algorithm, which is also the size of the IV. + /// + /// The size, in bytes, of the pbIV buffer. + /// + /// The address of the buffer that receives the ciphertext produced by this function. The parameter contains the size of this buffer. For more information, see Remarks. + /// If this parameter is NULL, the function calculates the size needed for the ciphertext of the data passed in the parameter. In this case, the location pointed to by the parameter contains this size, and the function returns .The parameter is not modified. + /// If the values of both the and parameters are NULL, an error is returned unless an authenticated encryption algorithm is in use.In the latter case, the call is treated as an authenticated encryption call with zero length data, and the authentication tag is returned in the parameter. + /// + /// + /// The size, in bytes, of the buffer. This parameter is ignored if the parameter is NULL. + /// + /// + /// A pointer to a ULONG variable that receives the number of bytes copied to the buffer. If is NULL, this receives the size, in bytes, required for the ciphertext. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the hKey parameter. + /// + /// Returns a status code that indicates the success or failure of the function. + /// + /// The and parameters can point to the same buffer. In this case, this function will perform the encryption in place. It is possible that the encrypted data size will be larger than the unencrypted data size, so the buffer must be large enough to hold the encrypted data. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptEncrypt( + SafeKeyHandle hKey, + byte[] pbInput, + int cbInput, + IntPtr pPaddingInfo, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbIV, + int cbIV, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 8)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptEncryptFlags dwFlags); + + /// + /// Decrypts a block of data. + /// + /// + /// The handle of the key to use to decrypt the data. This handle is obtained from one of the key creation functions, such as , , or . + /// + /// + /// The address of a buffer that contains the ciphertext to be decrypted. The parameter contains the size of the ciphertext to decrypt. For more information, see Remarks. + /// + /// + /// The number of bytes in the buffer to decrypt. + /// + /// + /// A pointer to a structure that contains padding information. This parameter is only used with asymmetric keys and authenticated encryption modes. If an authenticated encryption mode is used, this parameter must point to a BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO structure. If asymmetric keys are used, the type of structure this parameter points to is determined by the value of the parameter. Otherwise, the parameter must be set to NULL. + /// + /// + /// The address of a buffer that contains the initialization vector (IV) to use during decryption. The parameter contains the size of this buffer. This function will modify the contents of this buffer. If you need to reuse the IV later, make sure you make a copy of this buffer before calling this function. + /// This parameter is optional and can be NULL if no IV is used. + /// The required size of the IV can be obtained by calling the function to get the property. This will provide the size of a block for the algorithm, which is also the size of the IV. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// + /// The address of a buffer to receive the plaintext produced by this function. The cbOutput parameter contains the size of this buffer. For more information, see Remarks. + /// If this parameter is NULL, the function calculates the size required for the plaintext of the encrypted data passed in the parameter.In this case, the location pointed to by the parameter contains this size, and the function returns . + /// If the values of both the and parameters are NULL, an error is returned unless an authenticated encryption algorithm is in use.In the latter case, the call is treated as an authenticated encryption call with zero length data, and the authentication tag, passed in the parameter, is verified. + /// + /// + /// The size, in bytes, of the buffer. This parameter is ignored if the parameter is NULL. + /// + /// + /// A pointer to a ULONG variable to receive the number of bytes copied to the buffer. If is NULL, this receives the size, in bytes, required for the plaintext. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the parameter. + /// + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptDecrypt( + SafeKeyHandle hKey, + byte[] pbInput, + int cbInput, + IntPtr pPaddingInfo, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbIV, + int cbIV, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 8)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptEncryptFlags dwFlags); + + /// + /// Performs a one way hash or Message Authentication Code (MAC) on a data buffer. + /// + /// + /// The handle of the hash or MAC object to use to perform the operation. This handle is obtained by calling the function. + /// + /// + /// A pointer to a buffer that contains the data to process. The parameter contains the number of bytes in this buffer. This function does not modify the contents of this buffer. + /// + /// The number of bytes in the buffer. + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + /// + /// To combine more than one buffer into the hash or MAC, you can call this function multiple times, passing a different buffer each time. To obtain the hash or MAC value, call the function. + /// After the function has been called for a specified handle, that handle cannot be reused. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptHashData( + SafeHashHandle hHash, + byte[] pbInput, + int cbInput, + BCryptHashDataFlags dwFlags = BCryptHashDataFlags.None); + + /// + /// Retrieves the hash or Message Authentication Code (MAC) value for the data accumulated from prior calls to . + /// + /// + /// The handle of the hash or MAC object to use to compute the hash or MAC. This handle is obtained by calling the function. After this function has been called, the hash handle passed to this function cannot be used again except in a call to . + /// + /// + /// A pointer to a buffer that receives the hash or MAC value. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. This size must exactly match the size of the hash or MAC value. + /// The size can be obtained by calling the function to get the property. This will provide the size of the hash or MAC value for the specified algorithm. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptFinishHash( + SafeHashHandle hHash, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbOutput, + int cbOutput, + BCryptFinishHashFlags dwFlags = BCryptFinishHashFlags.None); + + /// + /// Creates a signature of a hash value. + /// + /// The handle of the key to use to sign the hash. + /// + /// A pointer to a structure that contains padding information. The actual type of structure this parameter points to depends on the value of the parameter. This parameter is only used with asymmetric keys and must be NULL otherwise. + /// + /// + /// A pointer to a buffer that contains the hash value to sign. The parameter contains the size of this buffer. + /// + /// + /// The number of bytes in the buffer to sign. + /// + /// + /// The address of a buffer to receive the signature produced by this function. The parameter contains the size of this buffer. + /// If this parameter is NULL, this function will calculate the size required for the signature and return the size in the location pointed to by the parameter. + /// + /// + /// The size, in bytes, of the buffer. This parameter is ignored if the parameter is NULL. + /// + /// + /// A pointer to a ULONG variable that receives the number of bytes copied to the buffer. + /// If is NULL, this receives the size, in bytes, required for the signature. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the parameter. + /// + /// Returns a status code that indicates the success or failure of the function. + /// + /// To later verify that the signature is valid, call the function with an identical key and an identical hash of the original data. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptSignHash( + SafeKeyHandle hKey, + IntPtr pPaddingInfo, + byte[] pbInput, + int cbInput, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptSignHashFlags dwFlags); + + /// + /// Verifies that the specified signature matches the specified hash. + /// + /// + /// The handle of the key to use to decrypt the signature. This must be an identical key or the public key portion of the key pair used to sign the data with the function. + /// + /// + /// A pointer to a structure that contains padding information. The actual type of structure this parameter points to depends on the value of the parameter. This parameter is only used with asymmetric keys and must be NULL otherwise. + /// + /// + /// The address of a buffer that contains the hash of the data. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// + /// The address of a buffer that contains the signed hash of the data. The function is used to create the signature. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. The function is used to create the signature. + /// + /// + /// A set of flags that modify the behavior of this function. The allowed set of flags depends on the type of key specified by the hKey parameter. + /// If the key is a symmetric key, this parameter is not used and should be zero. + /// If the key is an asymmetric key, this can be one of the following values. + /// + /// + /// Returns a status code that indicates the success or failure of the function. + /// In particular, an invalid signature will produce a result. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptVerifySignature( + SafeKeyHandle hKey, + IntPtr pPaddingInfo, + byte[] pbHash, + int cbHash, + byte[] pbSignature, + int cbSignature, + BCryptSignHashFlags dwFlags = BCryptSignHashFlags.None); + + /// + /// Creates an empty public/private key pair. + /// + /// The handle to the algorithm previously opened by + /// Receives a handle to the generated key pair. + /// The length of the key, in bits. + /// A set of flags that modify the behavior of this function. No flags are currently defined, so this parameter should be zero. + /// Returns a status code that indicates the success or failure of the function. + /// + /// After you create a key by using this function, you can use the BCryptSetProperty + /// function to set its properties; however, the key cannot be used until the + /// BCryptFinalizeKeyPair function is called. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptGenerateKeyPair( + SafeAlgorithmHandle hAlgorithm, + out SafeKeyHandle phKey, + int dwLength, + BCryptGenerateKeyPairFlags dwFlags = BCryptGenerateKeyPairFlags.None); + + /// + /// Creates a key object for use with a symmetrical key encryption algorithm from a supplied key. + /// + /// + /// The handle of an algorithm provider created with the function. The algorithm specified when the provider was created must support symmetric key encryption. + /// + /// + /// Receives the of the generated key. + /// + /// + /// A pointer to a buffer that receives the key object. The parameter contains the size of this buffer. The required size of this buffer can be obtained by calling the function to get the BCRYPT_OBJECT_LENGTH property. This will provide the size of the key object for the specified algorithm. + /// This memory can only be freed after the key handle is destroyed. + /// If the value of this parameter is NULL and the value of the parameter is zero, the memory for the key object is allocated and freed by this function. + /// + /// + /// The size, in bytes, of the buffer. + /// If the value of this parameter is zero and the value of the parameter is NULL, the memory for the key object is allocated and freed by this function. + /// + /// + /// Pointer to a buffer that contains the key from which to create the key object. The parameter contains the size of this buffer. This is normally a hash of a password or some other reproducible data. If the data passed in exceeds the target key size, the data will be truncated and the excess will be ignored. + /// Note: We strongly recommended that applications pass in the exact number of bytes required by the target key. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// A set of flags that modify the behavior of this function. No flags are currently defined, so this parameter should be zero. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptGenerateSymmetricKey( + SafeAlgorithmHandle hAlgorithm, + out SafeKeyHandle phKey, + byte[] pbKeyObject, + int cbKeyObject, + byte[] pbSecret, + int cbSecret, + BCryptGenerateSymmetricKeyFlags flags = BCryptGenerateSymmetricKeyFlags.None); + + /// + /// Completes a public/private key pair. + /// + /// The handle of the key to complete. This handle is obtained by calling the BCryptGenerateKeyPair function. + /// A set of flags that modify the behavior of this function. No flags are currently defined, so this parameter should be zero. + /// Returns a status code that indicates the success or failure of the function. + /// + /// The key cannot be used until this function has been called. + /// After this function has been called, the BCryptSetProperty function + /// can no longer be used for this key. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptFinalizeKeyPair( + SafeKeyHandle hKey, + BCryptFinalizeKeyPairFlags dwFlags = BCryptFinalizeKeyPairFlags.None); + + /// + /// Destroys a key. + /// + /// The handle of the key to destroy. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptDestroyKey( + IntPtr hKey); + + /// + /// Destroys a secret agreement handle that was created by using the BCryptSecretAgreement function. + /// + /// The handle of the secret to destroy. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptDestroySecret( + IntPtr hSecret); + + /// + /// Imports a symmetric key from a key BLOB. The BCryptImportKeyPair function is used to import a public/private key pair. + /// + /// + /// The handle of the algorithm provider to import the key. This handle is obtained by calling the function. + /// + /// + /// The handle of the key encryption key needed to unwrap the key BLOB in the pbInput parameter. + /// Note The handle must be supplied by the same provider that supplied the key that is being imported. + /// + /// + /// An identifier that specifies the type of BLOB that is contained in the pbInput buffer. + /// This can be one of the values defined in . + /// + /// + /// A pointer to a BCRYPT_KEY_HANDLE that receives the handle of the imported key. This handle is used in subsequent functions that require a key, such as BCryptEncrypt. This handle must be released when it is no longer needed by passing it to the function. + /// + /// + /// A pointer to a buffer that receives the imported key object. + /// The parameter contains the size of this buffer. + /// The required size of this buffer can be obtained by calling the + /// function to get the BCRYPT_OBJECT_LENGTH property. This will provide the size of the + /// key object for the specified algorithm. + /// This memory can only be freed after the phKey key handle is destroyed. + /// + /// The size, in bytes, of the buffer. + /// + /// The address of a buffer that contains the key BLOB to import. + /// The parameter contains the size of this buffer. + /// The parameter specifies the type of key BLOB this buffer contains. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptImportKey( + SafeAlgorithmHandle hAlgorithm, + SafeKeyHandle hImportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + out SafeKeyHandle phKey, + byte[] pbKeyObject, + int cbKeyObject, + byte[] pbInput, + int cbInput, + BCryptImportKeyFlags dwFlags = BCryptImportKeyFlags.None); + + /// + /// Imports a public/private key pair from a key BLOB. + /// + /// The handle of the algorithm provider to import the key. This handle is obtained by calling the BCryptOpenAlgorithmProvider function. + /// This parameter is not currently used and should be NULL. + /// an identifier that specifies the type of BLOB that is contained in the buffer. + /// A pointer to a BCRYPT_KEY_HANDLE that receives the handle of the imported key. This handle is used in subsequent functions that require a key, such as BCryptSignHash. This handle must be released when it is no longer needed by passing it to the function. + /// The address of a buffer that contains the key BLOB to import. The cbInput parameter contains the size of this buffer. The parameter specifies the type of key BLOB this buffer contains. + /// The size, in bytes, of the buffer. + /// A set of flags that modify the behavior of this function. This can be zero or the following value: BCRYPT_NO_KEY_VALIDATION + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptImportKeyPair( + SafeAlgorithmHandle hAlgorithm, + SafeKeyHandle hImportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + out SafeKeyHandle phKey, + byte[] pbInput, + int cbInput, + BCryptImportKeyPairFlags dwFlags); + + /// + /// Exports a key to a memory BLOB that can be persisted for later use. + /// + /// The handle of the key to export. + /// + /// The handle of the key with which to wrap the exported key. Use this parameter when exporting BLOBs of type BCRYPT_AES_WRAP_KEY_BLOB; otherwise, set it to NULL. + /// Note: The handle must be supplied by the same provider that supplied the hKey handle, and hExportKey must be a handle to a symmetric key that can be used in the Advanced Encryption Standard(AES) key wrap algorithm.When the hKey handle is from the Microsoft provider, hExportKey must be an AES key handle. + /// + /// + /// An identifier that specifies the type of BLOB to export. This can be one of the values + /// defined in the or classes. + /// + /// + /// The address of a buffer that receives the key BLOB. + /// The parameter contains the size of this buffer. + /// If this parameter is NULL, this function will place the required size, in bytes, in the ULONG pointed to by the parameter. + /// + /// + /// Contains the size, in bytes, of the buffer. + /// + /// + /// A pointer to a ULONG that receives the number of bytes that were copied to the buffer. + /// If the pbOutput parameter is NULL, this function will place the required size, in bytes, + /// in the ULONG pointed to by this parameter. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptExportKey( + SafeKeyHandle hKey, + SafeKeyHandle hExportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + BCryptExportKeyFlags dwFlags = BCryptExportKeyFlags.None); + + /// + /// Creates a secret agreement value from a private and a public key. + /// + /// + /// The handle of the private key to use to create the secret agreement value. + /// This key and the hPubKey key must come from the same CNG cryptographic algorithm provider. + /// + /// + /// The handle of the public key to use to create the secret agreement value. + /// This key and the hPrivKey key must come from the same CNG cryptographic algorithm provider. + /// + /// + /// A pointer to a BCRYPT_SECRET_HANDLE that receives a handle that represents the + /// secret agreement value. This handle must be released by passing it to the + /// BCryptDestroySecret function when it is no longer needed. + /// + /// A set of flags that modify the behavior of this function. No flags are defined for this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptSecretAgreement( + SafeKeyHandle privateKey, + SafeKeyHandle publicKey, + out SafeSecretHandle secret, + BCryptSecretAgreementFlags flags = BCryptSecretAgreementFlags.None); + + /// + /// Derives a key from a secret agreement value. + /// + /// + /// The secret agreement handle to create the key from. + /// This handle is obtained from the BCryptSecretAgreement function. + /// + /// + /// The key derivation function. + /// May come from the constants defined on the class. + /// + /// + /// The address of a BCryptBufferDesc structure that contains the KDF parameters. + /// This parameter is optional and can be NULL if it is not needed. + /// + /// + /// The address of a buffer that receives the key. The cbDerivedKey parameter contains + /// the size of this buffer. If this parameter is NULL, this function will place the + /// required size, in bytes, in the ULONG pointed to by the pcbResult parameter. + /// + /// + /// The size, in bytes, of the pbDerivedKey buffer. + /// + /// + /// A pointer to a ULONG that receives the number of bytes that were copied to the + /// pbDerivedKey buffer. If the pbDerivedKey parameter is NULL, this function will + /// place the required size, in bytes, in the ULONG pointed to by this parameter. + /// + /// + /// A set of flags that modify the behavior of this function. + /// This can be zero or the following value. + /// + /// + /// Returns a status code that indicates the success or failure of the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptDeriveKey( + SafeSecretHandle sharedSecret, + string keyDerivationFunction, + [In] ref BCryptBufferDesc kdfParameters, + [Out, MarshalAs(UnmanagedType.LPArray)] byte[] derivedKey, + int derivedKeySize, + [Out] out int resultSize, + BCryptDeriveKeyFlags flags); + + /// + /// Sets the value of a named property for a CNG object. + /// + /// A handle that represents the CNG object to set the property value for. + /// + /// A pointer to a null-terminated Unicode string that contains the name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// The address of a buffer that contains the new property value. The parameter contains the size of this buffer. + /// The size, in bytes, of the buffer. + /// A set of flags that modify the behavior of this function. No flags are defined for this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptSetProperty( + SafeHandle hObject, + string property, + [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, + int inputSize, + BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None); + + /// + /// Retrieves the value of a named property for a CNG object. + /// + /// A handle that represents the CNG object to obtain the property value for. + /// A pointer to a null-terminated Unicode string that contains the name of the property to retrieve. This can be one of the predefined or a custom property identifier. + /// The address of a buffer that receives the property value. The parameter contains the size of this buffer. + /// The size, in bytes, of the buffer. + /// A pointer to a ULONG variable that receives the number of bytes that were copied to the pbOutput buffer. If the parameter is NULL, this function will place the required size, in bytes, in the location pointed to by this parameter. + /// A set of flags that modify the behavior of this function. No flags are defined for this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptGetProperty( + SafeHandle hObject, + string property, + [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, + int outputSize, + out int resultSize, + BCryptGetPropertyFlags flags = BCryptGetPropertyFlags.None); + + /// + /// Generates a random number. + /// + /// + /// The handle of an algorithm provider created by using the function. The algorithm that was specified when the provider was created must support the random number generator interface. + /// + /// + /// The address of a buffer that receives the random number. The size of this buffer is specified by the parameter. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus BCryptGenRandom( + SafeAlgorithmHandle hAlgorithm, + byte[] pbBuffer, + int cbBuffer, + BCryptGenRandomFlags flags = BCryptGenRandomFlags.None); + } +} diff --git a/src/Gdi32.Desktop/Gdi32.Desktop.csproj b/src/Gdi32.Desktop/Gdi32.Desktop.csproj index 02a0254c..d58904a0 100644 --- a/src/Gdi32.Desktop/Gdi32.Desktop.csproj +++ b/src/Gdi32.Desktop/Gdi32.Desktop.csproj @@ -23,6 +23,8 @@ + + diff --git a/src/Gdi32.Desktop/Gdi32Mockable.cs b/src/Gdi32.Desktop/Gdi32Mockable.cs new file mode 100644 index 00000000..ae07df4f --- /dev/null +++ b/src/Gdi32.Desktop/Gdi32Mockable.cs @@ -0,0 +1,14 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static Gdi32; + [System.Runtime.CompilerServices.CompilerGenerated] + class Gdi32Mockable : IGdi32 { [System.Runtime.CompilerServices.CompilerGenerated] + public bool DeleteObject(IntPtr hObject) + => DeleteObject(hObject); + } +} diff --git a/src/Gdi32.Desktop/IGdi32.cs b/src/Gdi32.Desktop/IGdi32.cs new file mode 100644 index 00000000..4d52674f --- /dev/null +++ b/src/Gdi32.Desktop/IGdi32.cs @@ -0,0 +1,13 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static Gdi32; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IGdi32 { [System.Runtime.CompilerServices.CompilerGenerated] + bool DeleteObject(IntPtr hObject); + } +} diff --git a/src/Hid.Desktop/Hid.Desktop.csproj b/src/Hid.Desktop/Hid.Desktop.csproj index eb1140af..6656d431 100644 --- a/src/Hid.Desktop/Hid.Desktop.csproj +++ b/src/Hid.Desktop/Hid.Desktop.csproj @@ -39,6 +39,8 @@ + + diff --git a/src/Hid.Desktop/HidMockable.cs b/src/Hid.Desktop/HidMockable.cs new file mode 100644 index 00000000..b0f2d55c --- /dev/null +++ b/src/Hid.Desktop/HidMockable.cs @@ -0,0 +1,166 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using static Kernel32; + using static Hid; + [System.Runtime.CompilerServices.CompilerGenerated] + class HidMockable : IHid { /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public void HidD_GetHidGuid(out Guid hidGuid) + => HidD_GetHidGuid(out hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes) + => HidD_GetAttributes(hidDeviceObject, ref attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetManufacturerString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetProductString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetSerialNumberString(hidDeviceObject, buffer, bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers) + => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle) + => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus HidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + => HidP_GetCaps(preparsedData, ref capabilities); + } +} \ No newline at end of file diff --git a/src/Hid.Desktop/IHid.cs b/src/Hid.Desktop/IHid.cs new file mode 100644 index 00000000..2a2ff521 --- /dev/null +++ b/src/Hid.Desktop/IHid.cs @@ -0,0 +1,158 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using static Kernel32; + using static Hid; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IHid { /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + void HidD_GetHidGuid(out Guid hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus HidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + } +} \ No newline at end of file diff --git a/src/Hid.Shared/HidMockable.cs b/src/Hid.Shared/HidMockable.cs new file mode 100644 index 00000000..4bfdb081 --- /dev/null +++ b/src/Hid.Shared/HidMockable.cs @@ -0,0 +1,301 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using static Kernel32; + public partial class Hid : IHidMockable { /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + public void InvokeHidD_GetHidGuid(out Guid hidGuid) + => HidD_GetHidGuid(hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + public bool InvokeHidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes) + => HidD_GetAttributes(hidDeviceObject, attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + public bool InvokeHidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetManufacturerString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + public bool InvokeHidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetProductString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + public bool InvokeHidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetSerialNumberString(hidDeviceObject, buffer, bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + public bool InvokeHidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers) + => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + public bool InvokeHidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle) + => HidD_GetPreparsedData(hidDeviceObject, preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + => HidP_GetCaps(preparsedData, capabilities); + /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + public void InvokeHidD_GetHidGuid(out Guid hidGuid) + => HidD_GetHidGuid(hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + public bool InvokeHidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes) + => HidD_GetAttributes(hidDeviceObject, attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + public bool InvokeHidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetManufacturerString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + public bool InvokeHidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetProductString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + public bool InvokeHidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetSerialNumberString(hidDeviceObject, buffer, bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + public bool InvokeHidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers) + => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + public bool InvokeHidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle) + => HidD_GetPreparsedData(hidDeviceObject, preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + => HidP_GetCaps(preparsedData, capabilities); + } +} \ No newline at end of file diff --git a/src/Hid.Shared/IHidMockable.cs b/src/Hid.Shared/IHidMockable.cs new file mode 100644 index 00000000..b8a5df3f --- /dev/null +++ b/src/Hid.Shared/IHidMockable.cs @@ -0,0 +1,285 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using static Kernel32; + public interface IHidMockable { /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + void InvokeHidD_GetHidGuid(out Guid hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + bool InvokeHidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + bool InvokeHidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + bool InvokeHidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + bool InvokeHidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + bool InvokeHidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + bool InvokeHidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + void InvokeHidD_GetHidGuid(out Guid hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + bool InvokeHidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + bool InvokeHidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + bool InvokeHidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + bool InvokeHidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + bool InvokeHidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + bool InvokeHidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + } +} \ No newline at end of file diff --git a/src/Hid/Hid.csproj b/src/Hid/Hid.csproj index 5bc198b2..9c5acff0 100644 --- a/src/Hid/Hid.csproj +++ b/src/Hid/Hid.csproj @@ -23,6 +23,8 @@ + + diff --git a/src/Hid/HidMockable.cs b/src/Hid/HidMockable.cs new file mode 100644 index 00000000..b0f2d55c --- /dev/null +++ b/src/Hid/HidMockable.cs @@ -0,0 +1,166 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using static Kernel32; + using static Hid; + [System.Runtime.CompilerServices.CompilerGenerated] + class HidMockable : IHid { /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public void HidD_GetHidGuid(out Guid hidGuid) + => HidD_GetHidGuid(out hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes) + => HidD_GetAttributes(hidDeviceObject, ref attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetManufacturerString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetProductString(hidDeviceObject, buffer, bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength) + => HidD_GetSerialNumberString(hidDeviceObject, buffer, bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers) + => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool HidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle) + => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus HidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + => HidP_GetCaps(preparsedData, ref capabilities); + } +} \ No newline at end of file diff --git a/src/Hid/IHid.cs b/src/Hid/IHid.cs new file mode 100644 index 00000000..2a2ff521 --- /dev/null +++ b/src/Hid/IHid.cs @@ -0,0 +1,158 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using static Kernel32; + using static Hid; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IHid { /// + /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. + /// + /// + /// Pointer to a caller-allocated GUID buffer that the routine uses to return the device interface GUID + /// for HIDClass devices. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + void HidD_GetHidGuid(out Guid hidGuid); + + /// + /// Returns the attributes of a specified top-level collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated structure that returns the + /// attributes of the collection specified by HidDeviceObject. + /// + /// TRUE if succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetAttributes( + SafeObjectHandle hidDeviceObject, + ref HiddAttributes attributes); + + /// + /// Returns a top-level collection's embedded string that identifies the manufacturer. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the collection's manufacturer + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// TRUE if it returns the entire NULL-terminated embedded string. Otherwise, the routine returns FALSE. + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetManufacturerString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the manufacturer's product. + /// + /// Specifies an open handle to a top-level collection. + /// Pointer to a caller-allocated buffer that the routine uses to return the requested product string. + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetProductString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Returns the embedded string of a top-level collection that identifies the serial number of the collection's physical + /// device. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return the requested serial number + /// string. + /// + /// + /// Specifies the length, in bytes, of a caller-allocated buffer provided at Buffer. If the + /// buffer is not large enough to return the entire NULL-terminated embedded string, the routine returns nothing in the + /// buffer. + /// + /// + /// TRUE if it successfully returns the entire NULL-terminated embedded string. Otherwise, the routine returns + /// FALSE. + /// + /// /// /// + /// + /// The maximum possible number of characters in an embedded string is device specific. For USB devices, the + /// maximum string length is 126 wide characters (not including the terminating NULL character). + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetSerialNumberString( + SafeObjectHandle hidDeviceObject, + StringBuilder buffer, + int bufferLength); + + /// + /// Sets the maximum number of input reports that the HID class driver ring buffer can hold for a specified top-level + /// collection. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Specifies the maximum number of buffers that the HID class driver should maintain for the + /// input reports generated by the HidDeviceObject collection. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_SetNumInputBuffers( + SafeObjectHandle hidDeviceObject, + uint numberBuffers); + + /// + /// Returns a top-level collection's preparsed data. + /// + /// Specifies an open handle to a top-level collection. + /// + /// Pointer to the address of a routine-allocated buffer that contains a collection's + /// preparsed data in a structure. + /// + /// TRUE if it succeeds; otherwise, it returns FALSE. + [System.Runtime.CompilerServices.CompilerGenerated] + bool HidD_GetPreparsedData( + SafeObjectHandle hidDeviceObject, + out SafePreparsedDataHandle preparsedDataHandle); + + /// + /// Returns a top-level collection's structure. + /// + /// Pointer to a top-level collection's preparsed data. + /// + /// Pointer to a caller-allocated buffer that the routine uses to return a collection's + /// structure. + /// + /// + /// on success or if rhe + /// specified preparsed data is invalid. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus HidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + } +} \ No newline at end of file diff --git a/src/ImageHlp/IImageHlp.cs b/src/ImageHlp/IImageHlp.cs new file mode 100644 index 00000000..c6aa6ed1 --- /dev/null +++ b/src/ImageHlp/IImageHlp.cs @@ -0,0 +1,45 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static DbgHelp; + using static ImageHlp; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IImageHlp { /// + /// Maps an image and preloads data from the mapped file. + /// + /// The file name of the image (executable file or DLL) that is loaded. + /// The path used to locate the image if the name provided cannot be found. If this parameter is NULL, then the search path rules set using the SearchPath function apply. + /// A pointer to a structure that receives information about the image after it is loaded. + /// The default extension to be used if the image name does not contain a file name extension. If the value is TRUE, a .DLL extension is used. If the value is FALSE, then an .EXE extension is used. + /// The access mode. If this value is TRUE, the file is mapped for read-access only. If the value is FALSE, the file is mapped for read and write access. + /// + /// If the function succeeds, the return value is TRUE. + /// If the function fails, the return value is FALSE. To retrieve extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool MapAndLoad( + string ImageName, + string DllPath, + out LOADED_IMAGE LoadedImage, + bool DotDll, + bool ReadOnly); + + /// + /// Deallocate all resources that are allocated by a previous call to the function. + /// + /// + /// A pointer to a structure. This structure is obtained through a call to the function. + /// + /// + /// If the function succeeds, the return value is TRUE. + /// If the function fails, the return value is FALSE. To retrieve extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool UnMapAndLoad( + ref LOADED_IMAGE LoadedImage); + } +} diff --git a/src/ImageHlp/ImageHlp.csproj b/src/ImageHlp/ImageHlp.csproj index 5937a174..60c6edec 100644 --- a/src/ImageHlp/ImageHlp.csproj +++ b/src/ImageHlp/ImageHlp.csproj @@ -38,8 +38,10 @@ + + diff --git a/src/ImageHlp/ImageHlpMockable.cs b/src/ImageHlp/ImageHlpMockable.cs new file mode 100644 index 00000000..50840366 --- /dev/null +++ b/src/ImageHlp/ImageHlpMockable.cs @@ -0,0 +1,47 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static DbgHelp; + using static ImageHlp; + [System.Runtime.CompilerServices.CompilerGenerated] + class ImageHlpMockable : IImageHlp { /// + /// Maps an image and preloads data from the mapped file. + /// + /// The file name of the image (executable file or DLL) that is loaded. + /// The path used to locate the image if the name provided cannot be found. If this parameter is NULL, then the search path rules set using the SearchPath function apply. + /// A pointer to a structure that receives information about the image after it is loaded. + /// The default extension to be used if the image name does not contain a file name extension. If the value is TRUE, a .DLL extension is used. If the value is FALSE, then an .EXE extension is used. + /// The access mode. If this value is TRUE, the file is mapped for read-access only. If the value is FALSE, the file is mapped for read and write access. + /// + /// If the function succeeds, the return value is TRUE. + /// If the function fails, the return value is FALSE. To retrieve extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool MapAndLoad( + string ImageName, + string DllPath, + out LOADED_IMAGE LoadedImage, + bool DotDll, + bool ReadOnly) + => MapAndLoad(ImageName, DllPath, out LoadedImage, DotDll, ReadOnly); + + /// + /// Deallocate all resources that are allocated by a previous call to the function. + /// + /// + /// A pointer to a structure. This structure is obtained through a call to the function. + /// + /// + /// If the function succeeds, the return value is TRUE. + /// If the function fails, the return value is FALSE. To retrieve extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool UnMapAndLoad( + ref LOADED_IMAGE LoadedImage) + => UnMapAndLoad(ref LoadedImage); + } +} diff --git a/src/Kernel32.Desktop/IKernel32.cs b/src/Kernel32.Desktop/IKernel32.cs new file mode 100644 index 00000000..95cf993e --- /dev/null +++ b/src/Kernel32.Desktop/IKernel32.cs @@ -0,0 +1,1079 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IKernel32 { + /// + /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. + /// For the most basic version of this function, see FindFirstFile. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). + /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// + /// The information level of the returned data. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the buffer that receives the file data. + /// The pointer type is determined by the level of information that is specified in the parameter. + /// + /// + /// The type of filtering to perform that is different from wildcard matching. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the search criteria if the specified needs structured search information. + /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. + /// + /// Specifies additional flags that control the search. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeFindFilesHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags); + + /// + /// 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. + /// + /// + /// The 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. + /// + /// + /// The location of the message definition. The type of this parameter depends upon the settings in the parameter. + /// If : A handle to the module that contains the message table to search. + /// If : Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. + /// If neither of these flags is set in dwFlags, then lpSource is ignored. + /// + /// + /// The message identifier for the requested message. This parameter is ignored if dwFlags includes . + /// + /// + /// The language identifier for the requested message. This parameter is ignored if dwFlags includes . + /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: + /// Language neutral + /// Thread LANGID, based on the thread's locale value + /// User default LANGID, based on the user's default locale value + /// System default LANGID, based on the system default locale value + /// US English + /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. + /// + /// + /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes , the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer. + /// This buffer cannot be larger than 64K bytes. + /// + /// + /// If the flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If is set, + /// this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// The output buffer cannot be larger than 64K bytes. + /// + /// + /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. + /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. + /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. + /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. + /// + /// + /// 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 . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments); + + /// + /// Retrieves the thread identifier of the calling thread. + /// + /// The thread identifier of the calling thread. + [System.Runtime.CompilerServices.CompilerGenerated] + uint GetCurrentThreadId(); + + /// Retrieves the process identifier of the calling process. + /// The process identifier of the calling process. + /// Until the process terminates, the process identifier uniquely identifies the process throughout the system. + [System.Runtime.CompilerServices.CompilerGenerated] + uint GetCurrentProcessId(); + + /// Retrieves a pseudo handle for the current process. + /// The return value is a pseudo handle to the current process. + /// + /// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For + /// compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this + /// constant value. The calling process can use a pseudo handle to specify its own process whenever a process handle is + /// required. Pseudo handles are not inherited by child processes. + /// This handle has the PROCESS_ALL_ACCESS access right to the process object. + /// + /// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of + /// the process to the primary token of the process. + /// + /// + /// A process can create a "real" handle to itself that is valid in the context of other processes, or that can + /// be inherited by other processes, by specifying the pseudo handle as the source handle in a call to the + /// DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself. + /// + /// + /// The pseudo handle need not be closed when it is no longer needed. Calling the + /// function with a pseudo handle has no effect.If the pseudo handle is duplicated by DuplicateHandle, the + /// duplicate handle must be closed. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle GetCurrentProcess(); + + /// + /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations + /// in the current process, regardless of which thread created the I/O operation. + /// + /// A handle to the file. + /// + /// A pointer to an data structure that contains the data used for asynchronous I/O. + /// If this parameter is NULL, all I/O requests for the hFile parameter are canceled. + /// + /// If this parameter is not NULL, only those specific I/O requests that were issued for the file with the + /// specified + /// overlapped structure are marked as canceled, meaning that you can cancel one + /// or more requests, while the CancelIo function cancels all outstanding requests on a file handle. + /// + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued + /// by the calling process for the specified file handle was successfully requested. The application must not free or + /// reuse the structure associated with the canceled I/O operations until they have + /// completed. The thread can use the GetOverlappedResult function to determine when the I/O operations themselves have + /// been completed. + /// + /// If the function fails, the return value is 0 (zero). To get extended error information, call the + /// function. + /// + /// + /// If this function cannot find a request to cancel, the return value is 0 (zero), and + /// + /// returns . + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool CancelIoEx( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped); + + /// + /// 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. + /// + /// + /// + /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, + /// socket, communications resource, mailslot, or pipe). + /// The hFile parameter must have been created with read access. + /// + /// For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag + /// by the CreateFile function, or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer that receives the data read from a file or device. + /// + /// This buffer must remain valid for the duration of the read operation. The caller must not use this buffer + /// until the read operation is completed. + /// + /// + /// The maximum number of bytes to be read. + /// + /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile + /// sets this value to zero before doing any work or error checking. Use for this parameter if + /// this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise it can be . + /// + /// If hFile is opened with FILE_FLAG_OVERLAPPED, the parameter must point to a + /// valid and unique structure, otherwise the function can incorrectly report that the + /// read operation is complete. + /// + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the read operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool ReadFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToRead, + NullableUInt32 lpNumberOfBytesRead, + OVERLAPPED* lpOverlapped); + + /// + /// Writes data to the specified file or input/output (I/O) device. + /// + /// This function is designed for both synchronous and asynchronous operation. For a similar function designed + /// solely for asynchronous operation, see WriteFileEx. + /// + /// + /// + /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape + /// drive, socket, communications resource, mailslot, or pipe). + /// + /// The hFile parameter must have been created with the write access. For more information, see Generic Access + /// Rights and File Security and Access Rights. + /// + /// + /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the + /// FILE_FLAG_OVERLAPPED flag or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer containing the data to be written to the file or device. + /// + /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer + /// until the write operation is completed. + /// + /// + /// + /// The number of bytes to be written to the file or device. + /// + /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the + /// underlying file system or communications technology. + /// + /// + /// + /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. + /// WriteFile sets this value to zero before doing any work or error checking. Use + /// for this parameter if this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be NULL only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL. + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start writing to the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// To write to the end of file, specify both the Offset and OffsetHigh members of the + /// structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open + /// hFile using FILE_APPEND_DATA access. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the write operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool WriteFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToWrite, + NullableUInt32 lpNumberOfBytesWritten, + OVERLAPPED* lpOverlapped); + + /// + /// Suspends the specified thread. + /// A 64-bit application can suspend a WOW64 thread using the function. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int SuspendThread(SafeObjectHandle hThread); + + /// + /// Suspends the specified WOW64 thread. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int Wow64SuspendThread(SafeObjectHandle hThread); + + /// + /// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. + /// + /// + /// A handle to the thread to be restarted. + /// This handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count. + /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int ResumeThread(SafeObjectHandle hThread); + + /// + /// Waits until the specified object is in the signaled state or the time-out interval elapses. + /// To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects. + /// + /// + /// A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. + /// If this handle is closed while the wait is still pending, the function's behavior is undefined. + /// The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. + /// + /// + /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. + /// See MSDN docs for more information. + /// + /// + /// If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + WaitForSingleObjectResult WaitForSingleObject( + SafeHandle hHandle, + uint dwMilliseconds); + + /// + /// Closes an open object handle. + /// + /// A valid handle to an open object. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool CloseHandle(IntPtr hObject); + /// + /// Creates a new process and its primary thread. The new process runs in the security context of the calling process. + /// If the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token. To run the new process in the security context of the user represented by the impersonation token, use the or CreateProcessWithLogonW function. + /// + /// + /// The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer. + /// The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed. + /// The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space–delimited token in the lpCommandLine string. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin; otherwise, the file name is ambiguous. For example, consider the string "c:\program files\sub dir\program name". This string can be interpreted in a number of ways. + /// See MSDN docs for more information. + /// + /// + /// The command line to be executed. The maximum length of this string is 32K characters. If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters. + /// The Unicode version of this function, CreateProcessAsUserW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation. + /// The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line. + /// If both lpApplicationName and lpCommandLine are non-NULL, *lpApplicationName specifies the module to execute, and *lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line. + /// If lpApplicationName is NULL, the first white space–delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. + /// See MSDN docs for more information. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new process object and determines whether child processes can inherit the returned handle to the process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller, in which case the process may not be opened again after it is run. The process handle is valid and will continue to have full access rights. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new thread object and determines whether child processes can inherit the returned handle to the thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller. + /// + /// + /// If this parameter is 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. + /// Terminal Services: You cannot inherit handles across sessions. Additionally, if this parameter is TRUE, you must create the process in the same session as the caller. + /// + /// + /// The flags that control the priority class and the creation of the process. For a list of values, see Process Creation Flags. + /// This parameter also controls the new process's priority class, which is used to determine the scheduling priorities of the process's threads. For a list of values, see GetPriorityClass. If none of the priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child process receives the default priority class of the calling process. + /// + /// + /// A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process. + /// An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form: + /// name=value\0 + /// Because the equal sign is used as a separator, it must not be used in the name of an environment variable. + /// An environment block can contain either Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. If this parameter is NULL and the environment block of the parent process contains Unicode characters, you must also ensure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. + /// The ANSI version of this function, CreateProcessAsUserA fails if the total size of the environment block for the process exceeds 32,767 characters. + /// Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block. + /// See MSDN docs for more information. + /// + /// + /// The full path to the current directory for the process. The string can also specify a UNC path. + /// If this parameter is NULL, the new process will have the same current drive and directory as the calling process. (This feature is provided primarily for shells that need to start an application and specify its initial drive and working directory.) + /// + /// + /// A pointer to a or structure. + /// The user must have full access to both the specified window station and desktop. If you want the process to be interactive, specify winsta0\default. If the lpDesktop member is NULL, the new process inherits the desktop and window station of its parent process. If this member is an empty string, "", the new process connects to a window station using the rules described in Process Connection to a Window Station. + /// To set extended attributes, use a structure and specify in the parameter. + /// Handles in or must be closed with CloseHandle when they are no longer needed. + /// Important The caller is responsible for ensuring that the standard handle fields in contain valid handle values. These fields are copied unchanged to the child process without validation, even when the dwFlags member specifies . Incorrect values can cause the child process to misbehave or crash. Use the Application Verifier runtime verification tool to detect invalid handles. + /// + /// + /// A pointer to a structure that receives identification information about the new process. + /// Handles in must be closed with CloseHandle when they are no longer needed. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool CreateProcess( + string lpApplicationName, + string lpCommandLine, + SECURITY_ATTRIBUTES lpProcessAttributes, + SECURITY_ATTRIBUTES lpThreadAttributes, + [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, + CreateProcessFlags dwCreationFlags, + IntPtr lpEnvironment, // IntPtr because it may point to unicode or ANSI characters, based on a flag. + string lpCurrentDirectory, + ref STARTUPINFO lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation); + + /// + /// Creates a new process and its primary thread. The new process runs in the security context of the user represented by the specified token. + /// Typically, the process that calls the CreateProcessAsUser function must have the SE_INCREASE_QUOTA_NAME privilege and may require the SE_ASSIGNPRIMARYTOKEN_NAME privilege if the token is not assignable. If this function fails with ERROR_PRIVILEGE_NOT_HELD (1314), use the CreateProcessWithLogonW function instead. CreateProcessWithLogonW requires no special privileges, but the specified user account must be allowed to log on interactively. Generally, it is best to use CreateProcessWithLogonW to create a process with alternate credentials. + /// + /// + /// A handle to the primary token that represents a user. The handle must have the TOKEN_QUERY, TOKEN_DUPLICATE, and TOKEN_ASSIGN_PRIMARY access rights. For more information, see Access Rights for Access-Token Objects. The user represented by the token must have read and execute access to the application specified by the or the parameter. + /// To get a primary token that represents the specified user, call the LogonUser function. Alternatively, you can call the DuplicateTokenEx function to convert an impersonation token into a primary token. This allows a server application that is impersonating a client to create a process that has the security context of the client. + /// If hToken is a restricted version of the caller's primary token, the SE_ASSIGNPRIMARYTOKEN_NAME privilege is not required. If the necessary privileges are not already enabled, CreateProcessAsUser enables them for the duration of the call. For more information, see Running with Special Privileges. + /// Terminal Services: The process is run in the session specified in the token. By default, this is the same session that called LogonUser. To change the session, use the SetTokenInformation function. + /// + /// + /// The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer. + /// The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed. + /// The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space–delimited token in the lpCommandLine string. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin; otherwise, the file name is ambiguous. For example, consider the string "c:\program files\sub dir\program name". This string can be interpreted in a number of ways. + /// See MSDN docs for more information. + /// + /// + /// The command line to be executed. The maximum length of this string is 32K characters. If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters. + /// The Unicode version of this function, CreateProcessAsUserW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation. + /// The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line. + /// If both lpApplicationName and lpCommandLine are non-NULL, *lpApplicationName specifies the module to execute, and *lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line. + /// If lpApplicationName is NULL, the first white space–delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. + /// See MSDN docs for more information. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new process object and determines whether child processes can inherit the returned handle to the process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller, in which case the process may not be opened again after it is run. The process handle is valid and will continue to have full access rights. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new thread object and determines whether child processes can inherit the returned handle to the thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller. + /// + /// + /// If this parameter is 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. + /// Terminal Services: You cannot inherit handles across sessions. Additionally, if this parameter is TRUE, you must create the process in the same session as the caller. + /// + /// + /// The flags that control the priority class and the creation of the process. For a list of values, see Process Creation Flags. + /// This parameter also controls the new process's priority class, which is used to determine the scheduling priorities of the process's threads. For a list of values, see GetPriorityClass. If none of the priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child process receives the default priority class of the calling process. + /// + /// + /// A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process. + /// An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form: + /// name=value\0 + /// Because the equal sign is used as a separator, it must not be used in the name of an environment variable. + /// An environment block can contain either Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. If this parameter is NULL and the environment block of the parent process contains Unicode characters, you must also ensure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. + /// The ANSI version of this function, CreateProcessAsUserA fails if the total size of the environment block for the process exceeds 32,767 characters. + /// Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block. + /// See MSDN docs for more information. + /// + /// + /// The full path to the current directory for the process. The string can also specify a UNC path. + /// If this parameter is NULL, the new process will have the same current drive and directory as the calling process. (This feature is provided primarily for shells that need to start an application and specify its initial drive and working directory.) + /// + /// + /// A pointer to a or structure. + /// The user must have full access to both the specified window station and desktop. If you want the process to be interactive, specify winsta0\default. If the lpDesktop member is NULL, the new process inherits the desktop and window station of its parent process. If this member is an empty string, "", the new process connects to a window station using the rules described in Process Connection to a Window Station. + /// To set extended attributes, use a structure and specify in the parameter. + /// Handles in or must be closed with CloseHandle when they are no longer needed. + /// Important The caller is responsible for ensuring that the standard handle fields in contain valid handle values. These fields are copied unchanged to the child process without validation, even when the dwFlags member specifies . Incorrect values can cause the child process to misbehave or crash. Use the Application Verifier runtime verification tool to detect invalid handles. + /// + /// + /// A pointer to a structure that receives identification information about the new process. + /// Handles in must be closed with CloseHandle when they are no longer needed. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool CreateProcessAsUser( + IntPtr hToken, + string lpApplicationName, + string lpCommandLine, + SECURITY_ATTRIBUTES lpProcessAttributes, + SECURITY_ATTRIBUTES lpThreadAttributes, + [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, + CreateProcessFlags dwCreationFlags, + IntPtr lpEnvironment, // IntPtr because it may point to unicode or ANSI characters, based on a flag. + string lpCurrentDirectory, + ref STARTUPINFO lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation); + + /// + /// Retrieves the contents of the structure that was specified when the calling process was created. + /// + /// + /// A pointer to a structure that receives the startup information. + /// + /// + /// This function does not return a value, and does not fail. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + void GetStartupInfo( + out STARTUPINFO lpStartupInfo); + + /// + /// Initializes the specified list of attributes for process and thread creation. + /// + /// + /// The attribute list. This parameter can be NULL to determine the buffer size required to support the specified number of attributes. + /// + /// + /// The count of attributes to be added to the list. + /// + /// + /// This parameter is reserved and must be zero. + /// + /// + /// If lpAttributeList is not NULL, this parameter specifies the size in bytes of the lpAttributeList buffer on input. On output, this parameter receives the size in bytes of the initialized attribute list. + /// If lpAttributeList is NULL, this parameter receives the required buffer size in bytes. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + /// + /// First, call this function with the parameter set to the maximum number of attributes you will be using and the lpAttributeList to NULL. The function returns the required buffer size in bytes in the lpSize parameter. Allocate enough space for the data in the lpAttributeList buffer and call the function again to initialize the buffer. + /// To add attributes to the list, call the function. To specify these attributes when creating a process, specify in the dwCreationFlag parameter and a structure in the lpStartupInfo parameter. Note that you can specify the same structure to multiple child processes. + /// When you have finished using the list, call the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool InitializeProcThreadAttributeList( + IntPtr lpAttributeList, + uint dwAttributeCount, + uint dwFlags, + ref IntPtr lpSize); + + /// + /// Updates the specified attribute in a list of attributes for process and thread creation. + /// + /// + /// A pointer to an attribute list created by the function. + /// + /// + /// This parameter is reserved and must be zero. + /// + /// + /// The attribute key to update in the attribute list. + /// + /// + /// A pointer to the attribute value. This value should persist until the attribute is destroyed using the function. + /// + /// + /// The size of the attribute value specified by the parameter. + /// + /// + /// This parameter is reserved and must be NULL. + /// + /// This parameter is reserved and must be NULL. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool UpdateProcThreadAttribute( + IntPtr lpAttributeList, + uint dwFlags, + ref uint Attribute, + IntPtr lpValue, + IntPtr cbSize, // SIZE_T varies by bitness + ref IntPtr lpPreviousValue, + ref IntPtr lpReturnSize); + + /// + /// Deletes the specified list of attributes for process and thread creation. + /// + /// + /// The attribute list. This list is created by the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + void DeleteProcThreadAttributeList( + IntPtr lpAttributeList); + + /// + /// Allocates a new console for the calling process. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool AllocConsole(); + + /// + /// Detaches the calling process from its console. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool FreeConsole(); + + /// + /// Attaches the calling process to the console of the specified process. + /// + /// + /// The identifier of the process whose console is to be used. This parameter can be one of the following values. + /// pid: Use the console of the specified process. + /// -1: Use the console of the parent of the current process. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool AttachConsole(uint dwProcessId); + + /// + /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified. + /// To perform this operation as a transacted operation, which results in a handle that can be used for transacted I/O, use the CreateFileTransacted function. + /// + /// + /// The name of the file or device to be created or opened. You may use either forward slashes (/) or backslashes (\) in this name. + /// In the ANSI version of this function, the name is limited to characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, Paths, and Namespaces. + /// For information on special device names, see Defining an MS-DOS Device Name. + /// To create a file stream, specify the name of the file, a colon, and then the name of the stream.For more information, see File Streams. + /// + /// + /// The requested access to the file or device, which can be summarized as read, write, both or neither zero). + /// The most commonly used values are , , or both( | ). For more information, see Generic Access Rights, File Security and Access Rights, File Access Rights Constants, and ACCESS_MASK. + /// If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without accessing that file or device, even if access would have been denied. + /// You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + /// For more information, see the Remarks section of this topic and Creating and Opening Files. + /// + /// + /// The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the following table). Access requests to attributes or extended attributes are not affected by this flag. + /// If this parameter is zero and succeeds, the file or device cannot be shared and cannot be opened again until the handle to the file or device is closed. For more information, see the Remarks section. + /// You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. would fail and the function would return ERROR_SHARING_VIOLATION. + /// To enable a process to share a file or device while another process has the file or device open, use a compatible combination of one or more of the following values. For more information about valid combinations of this parameter with the dwDesiredAccess parameter, see Creating and Opening Files. + /// + /// + /// A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes. + /// This parameter can be NULL. + /// If this parameter is NULL, the handle returned by CreateFile cannot be inherited by any child processes the application may create and the file or device associated with the returned handle gets a default security descriptor. + /// The member of the structure specifies a for a file or device. If this member is NULL, the file or device associated with the returned handle is assigned a default security descriptor. + /// CreateFile ignores the member when opening an existing file or device, but continues to use the member. + /// The member of the structure specifies whether the returned handle can be inherited. + /// + /// + /// An action to take on a file or device that exists or does not exist. + /// For devices other than files, this parameter is usually set to . + /// + /// + /// The file or device attributes and flags, being the most common default value for files. + /// This parameter can include any combination of the available file attributes (CreateFileFlags.*Attribute). All other file attributes override . + /// This parameter can also contain combinations of flags (CreateFileFlags.*Flag) for control of file or device caching behavior, access modes, and other special-purpose flags. These combine with any CreateFileFlags.*Attribute values. + /// This parameter can also contain Security Quality of Service (SQOS) information by specifying the SECURITY_SQOS_PRESENT flag. Additional SQOS-related flags information is presented in the table following the attributes and flags tables. + /// Note When CreateFile opens an existing file, it generally combines the file flags with the file attributes of the existing file, and ignores any file attributes supplied as part of dwFlagsAndAttributes. Special cases are detailed in Creating and Opening Files. + /// Some of the following file attributes and flags may only apply to files and not necessarily all other types of devices that CreateFile can open.For additional information, see the Remarks section of this topic and Creating and Opening Files. + /// For more advanced access to file attributes, see SetFileAttributes. For a complete list of all file attributes with their values and descriptions, see File Attribute Constants. + /// + /// + /// A valid handle to a template file with the access right. The template file supplies file attributes and extended attributes for the file that is being created. + /// This parameter can be NULL. + /// When opening an existing file, CreateFile ignores this parameter. + /// When opening a new encrypted file, the file inherits the discretionary access control list from its parent directory.For additional information, see File Encryption. + /// + /// + /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. + /// If the function fails, the return value is INVALID_HANDLE_VALUE.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle CreateFile( + string filename, + FileAccess access, + FileShare share, + SECURITY_ATTRIBUTES securityAttributes, + CreationDisposition creationDisposition, + CreateFileFlags flagsAndAttributes, + SafeObjectHandle templateFile); + + /// + /// Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used). + /// To specify additional attributes to use in a search, use the FindFirstFileEx function. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash(\). + /// If the string ends with a wildcard, period(.), or directory name, the user must have access permissions to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// A pointer to the WIN32_FIND_DATA structure that receives information about a found file or directory. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// If the function fails because no matching files can be found, the function returns ERROR_FILE_NOT_FOUND. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeFindFilesHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); + + /// + /// Continues a file search from a previous call to the , FindFirstFileEx, or FindFirstFileTransacted functions. + /// + /// The search handle returned by a previous call to the FindFirstFile or FindFirstFileEx function. + /// A pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. + /// + /// If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file or directory found. + /// If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate. To get extended error information, call the function. + /// If the function fails because no more matching files can be found, the function returns ERROR_NO_MORE_FILES. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool FindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData); + + /// + /// Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these + /// processes. + /// + /// The portions of the system to be included in the snapshot. + /// + /// The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate the + /// current process. This parameter is used when the , + /// , + /// , or + /// 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 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 . + /// + /// + /// + /// If the function succeeds, it returns an open handle to the specified snapshot. + /// + /// If the function fails, it returns . To get extended error information, call + /// . Possible error codes include + /// . + /// + /// + /// + /// The snapshot taken by this function is examined by the other tool help functions to provide their results.Access to the + /// snapshot is read only.The snapshot handle acts as an object handle and is subject to the same rules regarding which + /// processes and threads it is valid in. + /// + /// To enumerate the heap or module states for all processes, specify + /// and set to zero.Then, for + /// each additional process in the snapshot, call CreateToolhelp32Snapshot again, specifying its process identifier and the + /// or + /// value. + /// + /// + /// When taking snapshots that include heaps and modules for a process other than the current process, the + /// CreateToolhelp32Snapshot function can fail or return incorrect information for a variety of reasons. For example, if + /// the loader data table in the target process is corrupted or not initialized, or if the module list changes during the + /// function call as a result of DLLs being loaded or unloaded, the function might fail with + /// or other error code. Ensure that the target process was not started in a + /// suspended state, and try calling the function again. If the function fails with + /// when called with + /// or + /// , call the function again until it succeeds. + /// + /// + /// The and + /// flags do not retrieve handles for modules that were + /// loaded with the LOAD_LIBRARY_AS_DATAFILE or similar flags. For more information, see LoadLibraryEx. + /// + /// To destroy the snapshot, call on the returned handle. + /// + /// Note that you can use the + /// + /// function to retrieve the full name of an executable image for both 32- and 64-bit processes from a 32-bit process. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle CreateToolhelp32Snapshot( + CreateToolhelp32SnapshotFlags dwFlags, + uint th32ProcessID); + + /// Retrieves information about the first process encountered in a system snapshot. + /// + /// A handle to the snapshot returned from a previous call to the + /// function. + /// + /// + /// Contains process information such as the name of the executable file, the process identifier, and + /// the process identifier of the parent process. + /// + /// + /// Returns if the first entry of the process list has been copied to the buffer or + /// otherwise. The error value is returned by + /// the function if no processes exist or the snapshot does not contain process + /// information. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool Process32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); + + /// Retrieves information about the next process recorded in a system snapshot. + /// + /// A handle to the snapshot returned from a previous call to the + /// function. + /// + /// A structure. + /// + /// Returns if the next entry of the process list has been copied to the buffer or + /// otherwise. The error value is returned by + /// the function if no processes exist or the snapshot does not contain process + /// information. + /// + /// + /// To retrieve information about the first process recorded in a snapshot, use the + /// + /// function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool Process32Next( + SafeObjectHandle hSnapshot, + [In, Out] PROCESSENTRY32 lppe); + + /// Retrieves the full name of the executable image for the specified process. + /// + /// A handle to the process. This handle must be created with the + /// or + /// access right. + /// + /// One of the values. + /// The path to the executable image. If the function succeeds, this string is null-terminated. + /// + /// On input, specifies the size of the lpExeName buffer, in characters. On success, receives the + /// number of characters written to the buffer, not including the null-terminating character. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + /// Minimum OS: Windows Vista / Windows Server 2008. + [System.Runtime.CompilerServices.CompilerGenerated] + bool QueryFullProcessImageName( + SafeObjectHandle hProcess, + QueryFullProcessImageNameFlags dwFlags, + StringBuilder lpExeName, + ref uint lpdwSize); + + /// Opens an existing local process object. + /// + /// The access to the process object. This access right is checked against the security descriptor for the process. This + /// parameter can be one or more of the values. + /// + /// If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the + /// contents of the security descriptor. + /// + /// + /// + /// If this value is , processes created by this process will inherit + /// the handle. Otherwise, the processes do not inherit this handle. + /// + /// + /// The identifier of the local process to be opened. + /// + /// If the specified process is the System Process(0x00000000), the function fails and the last error code is + /// .If the specified process is the Idle process or one of the CSRSS + /// processes, this function fails and the last error code is because + /// their access restrictions prevent user-level code from opening them. + /// + /// + /// If you are using as an argument to this function, consider using + /// instead of OpenProcess, for improved performance. + /// + /// + /// If the function succeeds, the return value is an open handle to the specified process. + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle OpenProcess( + ProcessAccess dwDesiredAccess, + bool bInheritHandle, + uint dwProcessId); + + /// + /// Retrieves the results of an overlapped operation on the specified file, named pipe, or communications device. + /// To specify a timeout interval or wait on an alertable thread, use GetOverlappedResultEx. + /// + /// + /// A handle to the file, named pipe, or communications device. This is the same handle that was + /// specified when the overlapped operation was started by a call to the ReadFile, WriteFile, ConnectNamedPipe, + /// TransactNamedPipe, DeviceIoControl, or WaitCommEvent function. + /// + /// + /// A pointer to an structure that was specified when the overlapped + /// operation was started. + /// + /// + /// A pointer to a variable that receives the number of bytes that were actually + /// transferred by a read or write operation. For a TransactNamedPipe operation, this is the number of bytes that were read + /// from the pipe. For a DeviceIoControl operation, this is the number of bytes of output data returned by the device + /// driver. For a ConnectNamedPipe or WaitCommEvent operation, this value is undefined. + /// + /// + /// If this parameter is TRUE, and the Internal member of the lpOverlapped structure is STATUS_PENDING, + /// the function does not return until the operation has been completed. If this parameter is FALSE and the operation is + /// still pending, the function returns FALSE and the function returns + /// . + /// + /// + /// If the function succeeds, the return value is nonzero. + /// + /// If the function fails, the return value is zero.To get extended error information, call + /// . + /// + /// + /// + /// The results reported by the GetOverlappedResult function are those of the specified handle's last overlapped operation + /// to which the specified structure was provided, and for which the operation's results were + /// pending. A pending operation is indicated when the function that started the operation returns FALSE, and the + /// GetLastError function returns . When an I/O operation is pending, the + /// function that started the operation resets the hEvent member of the structure to the + /// nonsignaled state. Then when the pending operation has been completed, the system sets the event object to the signaled + /// state. + /// + /// If the bWait parameter is TRUE, GetOverlappedResult determines whether the pending operation has been completed + /// by waiting for the event object to be in the signaled state. + /// + /// + /// If the hEvent member of the structure is NULL, the system uses the state of the hFile + /// handle to signal when the operation has been completed. Use of file, named pipe, or communications-device handles for + /// this purpose is discouraged. It is safer to use an event object because of the confusion that can occur when multiple + /// simultaneous overlapped operations are performed on the same file, named pipe, or communications device. In this + /// situation, there is no way to know which operation caused the object's state to be signaled. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool GetOverlappedResult( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped, + out uint lpNumberOfBytesTransferred, + bool bWait); + + /// + /// Cancels all pending input and output (I/O) operations that are issued by the calling thread for the specified file. The + /// function does not cancel I/O operations that other threads issue for a file handle. + /// To cancel I/O operations from another thread, use the CancelIoEx function. + /// + /// + /// A handle to the file. + /// The function cancels all pending I/O operations for this file handle. + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued by + /// the calling thread for the specified file handle was successfully requested. The thread can use the + /// function to determine when the I/O operations themselves have been completed. + /// + /// If the function fails, the return value is zero (0). To get extended error information, call the + /// function. + /// + /// + /// + /// If there are any pending I/O operations in progress for the specified file handle, and they are issued by the calling + /// thread, the CancelIo function cancels them. CancelIo cancels only outstanding I/O on the handle, it does not change the + /// state of the handle; this means that you cannot rely on the state of the handle because you cannot know whether the + /// operation was completed successfully or canceled. + /// + /// The I/O operations must be issued as overlapped I/O. If they are not, the I/O operations do not return to allow + /// the thread to call the CancelIo function. Calling the CancelIo function with a file handle that is not opened with + /// FILE_FLAG_OVERLAPPED does nothing. + /// + /// + /// All I/O operations that are canceled complete with the error + /// , and all completion notifications for the I/O operations occur + /// normally. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool CancelIo(SafeObjectHandle hFile); + + /// + /// Determines whether the specified process is running under WOW64 (x86 emulator that allows 32-bit Windows-based + /// applications to run seamlessly on 64-bit Windows) + /// + /// + /// A handle to the process. The handle must have the or + /// access right. + /// + /// Windows Server 2003 and Windows XP: The handle must have the + /// access right. + /// + /// + /// + /// A pointer to a value that is set to if the process is running under + /// WOW64. If the process is running under 32-bit Windows, the value is set to . If the process is + /// a 64-bit application running under 64-bit Windows, the value is also set to . + /// + /// + /// If the function succeeds, the return value is a nonzero value. + /// + /// If the function fails, the return value is zero. To get extended error information, call + /// . + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool IsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process); + + /// + /// Creates an anonymous pipe, and returns handles to the read and write ends of the pipe. + /// + /// + /// A pointer to a variable that receives the read handle for the pipe. + /// + /// + /// A pointer to a variable that receives the write handle for the pipe. + /// + /// + /// A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If is NULL, the handle cannot be inherited. + /// The member of the structure specifies a security descriptor for the new pipe. If is NULL, the pipe gets a default security descriptor. The ACLs in the default security descriptor for a pipe come from the primary or impersonation token of the creator. + /// + /// + /// The size of the buffer for the pipe, in bytes. The size is only a suggestion; the system uses the value to calculate an appropriate buffering mechanism. If this parameter is zero, the system uses the default buffer size. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool CreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize); + } +} diff --git a/src/Kernel32.Desktop/Kernel32.Desktop.csproj b/src/Kernel32.Desktop/Kernel32.Desktop.csproj index 9421dae7..53225954 100644 --- a/src/Kernel32.Desktop/Kernel32.Desktop.csproj +++ b/src/Kernel32.Desktop/Kernel32.Desktop.csproj @@ -28,6 +28,7 @@ + @@ -47,6 +48,7 @@ + diff --git a/src/Kernel32.Desktop/Kernel32Mockable.cs b/src/Kernel32.Desktop/Kernel32Mockable.cs new file mode 100644 index 00000000..fa61b026 --- /dev/null +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -0,0 +1,1113 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; + [System.Runtime.CompilerServices.CompilerGenerated] + class Kernel32Mockable : IKernel32 { + /// + /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. + /// For the most basic version of this function, see FindFirstFile. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). + /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// + /// The information level of the returned data. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the buffer that receives the file data. + /// The pointer type is determined by the level of information that is specified in the parameter. + /// + /// + /// The type of filtering to perform that is different from wildcard matching. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the search criteria if the specified needs structured search information. + /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. + /// + /// Specifies additional flags that control the search. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeFindFilesHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags) + => FindFirstFileEx(lpFileName, fInfoLevelId, out lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags); + + /// + /// 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. + /// + /// + /// The 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. + /// + /// + /// The location of the message definition. The type of this parameter depends upon the settings in the parameter. + /// If : A handle to the module that contains the message table to search. + /// If : Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. + /// If neither of these flags is set in dwFlags, then lpSource is ignored. + /// + /// + /// The message identifier for the requested message. This parameter is ignored if dwFlags includes . + /// + /// + /// The language identifier for the requested message. This parameter is ignored if dwFlags includes . + /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: + /// Language neutral + /// Thread LANGID, based on the thread's locale value + /// User default LANGID, based on the user's default locale value + /// System default LANGID, based on the system default locale value + /// US English + /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. + /// + /// + /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes , the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer. + /// This buffer cannot be larger than 64K bytes. + /// + /// + /// If the flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If is set, + /// this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// The output buffer cannot be larger than 64K bytes. + /// + /// + /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. + /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. + /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. + /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. + /// + /// + /// 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 . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments) + => FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments); + + /// + /// Retrieves the thread identifier of the calling thread. + /// + /// The thread identifier of the calling thread. + [System.Runtime.CompilerServices.CompilerGenerated] + public uint GetCurrentThreadId() + => GetCurrentThreadId(); + + /// Retrieves the process identifier of the calling process. + /// The process identifier of the calling process. + /// Until the process terminates, the process identifier uniquely identifies the process throughout the system. + [System.Runtime.CompilerServices.CompilerGenerated] + public uint GetCurrentProcessId() + => GetCurrentProcessId(); + + /// Retrieves a pseudo handle for the current process. + /// The return value is a pseudo handle to the current process. + /// + /// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For + /// compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this + /// constant value. The calling process can use a pseudo handle to specify its own process whenever a process handle is + /// required. Pseudo handles are not inherited by child processes. + /// This handle has the PROCESS_ALL_ACCESS access right to the process object. + /// + /// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of + /// the process to the primary token of the process. + /// + /// + /// A process can create a "real" handle to itself that is valid in the context of other processes, or that can + /// be inherited by other processes, by specifying the pseudo handle as the source handle in a call to the + /// DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself. + /// + /// + /// The pseudo handle need not be closed when it is no longer needed. Calling the + /// function with a pseudo handle has no effect.If the pseudo handle is duplicated by DuplicateHandle, the + /// duplicate handle must be closed. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle GetCurrentProcess() + => GetCurrentProcess(); + + /// + /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations + /// in the current process, regardless of which thread created the I/O operation. + /// + /// A handle to the file. + /// + /// A pointer to an data structure that contains the data used for asynchronous I/O. + /// If this parameter is NULL, all I/O requests for the hFile parameter are canceled. + /// + /// If this parameter is not NULL, only those specific I/O requests that were issued for the file with the + /// specified + /// overlapped structure are marked as canceled, meaning that you can cancel one + /// or more requests, while the CancelIo function cancels all outstanding requests on a file handle. + /// + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued + /// by the calling process for the specified file handle was successfully requested. The application must not free or + /// reuse the structure associated with the canceled I/O operations until they have + /// completed. The thread can use the GetOverlappedResult function to determine when the I/O operations themselves have + /// been completed. + /// + /// If the function fails, the return value is 0 (zero). To get extended error information, call the + /// function. + /// + /// + /// If this function cannot find a request to cancel, the return value is 0 (zero), and + /// + /// returns . + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool CancelIoEx( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped) + => CancelIoEx(hFile, lpOverlapped); + + /// + /// 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. + /// + /// + /// + /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, + /// socket, communications resource, mailslot, or pipe). + /// The hFile parameter must have been created with read access. + /// + /// For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag + /// by the CreateFile function, or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer that receives the data read from a file or device. + /// + /// This buffer must remain valid for the duration of the read operation. The caller must not use this buffer + /// until the read operation is completed. + /// + /// + /// The maximum number of bytes to be read. + /// + /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile + /// sets this value to zero before doing any work or error checking. Use for this parameter if + /// this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise it can be . + /// + /// If hFile is opened with FILE_FLAG_OVERLAPPED, the parameter must point to a + /// valid and unique structure, otherwise the function can incorrectly report that the + /// read operation is complete. + /// + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the read operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool ReadFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToRead, + NullableUInt32 lpNumberOfBytesRead, + OVERLAPPED* lpOverlapped) + => ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); + + /// + /// Writes data to the specified file or input/output (I/O) device. + /// + /// This function is designed for both synchronous and asynchronous operation. For a similar function designed + /// solely for asynchronous operation, see WriteFileEx. + /// + /// + /// + /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape + /// drive, socket, communications resource, mailslot, or pipe). + /// + /// The hFile parameter must have been created with the write access. For more information, see Generic Access + /// Rights and File Security and Access Rights. + /// + /// + /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the + /// FILE_FLAG_OVERLAPPED flag or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer containing the data to be written to the file or device. + /// + /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer + /// until the write operation is completed. + /// + /// + /// + /// The number of bytes to be written to the file or device. + /// + /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the + /// underlying file system or communications technology. + /// + /// + /// + /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. + /// WriteFile sets this value to zero before doing any work or error checking. Use + /// for this parameter if this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be NULL only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL. + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start writing to the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// To write to the end of file, specify both the Offset and OffsetHigh members of the + /// structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open + /// hFile using FILE_APPEND_DATA access. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the write operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool WriteFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToWrite, + NullableUInt32 lpNumberOfBytesWritten, + OVERLAPPED* lpOverlapped) + => WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); + + /// + /// Suspends the specified thread. + /// A 64-bit application can suspend a WOW64 thread using the function. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int SuspendThread(SafeObjectHandle hThread) + => SuspendThread(hThread); + + /// + /// Suspends the specified WOW64 thread. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int Wow64SuspendThread(SafeObjectHandle hThread) + => Wow64SuspendThread(hThread); + + /// + /// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. + /// + /// + /// A handle to the thread to be restarted. + /// This handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count. + /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int ResumeThread(SafeObjectHandle hThread) + => ResumeThread(hThread); + + /// + /// Waits until the specified object is in the signaled state or the time-out interval elapses. + /// To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects. + /// + /// + /// A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. + /// If this handle is closed while the wait is still pending, the function's behavior is undefined. + /// The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. + /// + /// + /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. + /// See MSDN docs for more information. + /// + /// + /// If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public WaitForSingleObjectResult WaitForSingleObject( + SafeHandle hHandle, + uint dwMilliseconds) + => WaitForSingleObject(hHandle, dwMilliseconds); + + /// + /// Closes an open object handle. + /// + /// A valid handle to an open object. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool CloseHandle(IntPtr hObject) + => CloseHandle(hObject); + /// + /// Creates a new process and its primary thread. The new process runs in the security context of the calling process. + /// If the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token. To run the new process in the security context of the user represented by the impersonation token, use the or CreateProcessWithLogonW function. + /// + /// + /// The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer. + /// The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed. + /// The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space–delimited token in the lpCommandLine string. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin; otherwise, the file name is ambiguous. For example, consider the string "c:\program files\sub dir\program name". This string can be interpreted in a number of ways. + /// See MSDN docs for more information. + /// + /// + /// The command line to be executed. The maximum length of this string is 32K characters. If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters. + /// The Unicode version of this function, CreateProcessAsUserW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation. + /// The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line. + /// If both lpApplicationName and lpCommandLine are non-NULL, *lpApplicationName specifies the module to execute, and *lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line. + /// If lpApplicationName is NULL, the first white space–delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. + /// See MSDN docs for more information. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new process object and determines whether child processes can inherit the returned handle to the process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller, in which case the process may not be opened again after it is run. The process handle is valid and will continue to have full access rights. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new thread object and determines whether child processes can inherit the returned handle to the thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller. + /// + /// + /// If this parameter is 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. + /// Terminal Services: You cannot inherit handles across sessions. Additionally, if this parameter is TRUE, you must create the process in the same session as the caller. + /// + /// + /// The flags that control the priority class and the creation of the process. For a list of values, see Process Creation Flags. + /// This parameter also controls the new process's priority class, which is used to determine the scheduling priorities of the process's threads. For a list of values, see GetPriorityClass. If none of the priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child process receives the default priority class of the calling process. + /// + /// + /// A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process. + /// An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form: + /// name=value\0 + /// Because the equal sign is used as a separator, it must not be used in the name of an environment variable. + /// An environment block can contain either Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. If this parameter is NULL and the environment block of the parent process contains Unicode characters, you must also ensure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. + /// The ANSI version of this function, CreateProcessAsUserA fails if the total size of the environment block for the process exceeds 32,767 characters. + /// Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block. + /// See MSDN docs for more information. + /// + /// + /// The full path to the current directory for the process. The string can also specify a UNC path. + /// If this parameter is NULL, the new process will have the same current drive and directory as the calling process. (This feature is provided primarily for shells that need to start an application and specify its initial drive and working directory.) + /// + /// + /// A pointer to a or structure. + /// The user must have full access to both the specified window station and desktop. If you want the process to be interactive, specify winsta0\default. If the lpDesktop member is NULL, the new process inherits the desktop and window station of its parent process. If this member is an empty string, "", the new process connects to a window station using the rules described in Process Connection to a Window Station. + /// To set extended attributes, use a structure and specify in the parameter. + /// Handles in or must be closed with CloseHandle when they are no longer needed. + /// Important The caller is responsible for ensuring that the standard handle fields in contain valid handle values. These fields are copied unchanged to the child process without validation, even when the dwFlags member specifies . Incorrect values can cause the child process to misbehave or crash. Use the Application Verifier runtime verification tool to detect invalid handles. + /// + /// + /// A pointer to a structure that receives identification information about the new process. + /// Handles in must be closed with CloseHandle when they are no longer needed. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool CreateProcess( + string lpApplicationName, + string lpCommandLine, + SECURITY_ATTRIBUTES lpProcessAttributes, + SECURITY_ATTRIBUTES lpThreadAttributes, + [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, + CreateProcessFlags dwCreationFlags, + IntPtr lpEnvironment, // IntPtr because it may point to unicode or ANSI characters, based on a flag. + string lpCurrentDirectory, + ref STARTUPINFO lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation) + => CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out lpProcessInformation); + + /// + /// Creates a new process and its primary thread. The new process runs in the security context of the user represented by the specified token. + /// Typically, the process that calls the CreateProcessAsUser function must have the SE_INCREASE_QUOTA_NAME privilege and may require the SE_ASSIGNPRIMARYTOKEN_NAME privilege if the token is not assignable. If this function fails with ERROR_PRIVILEGE_NOT_HELD (1314), use the CreateProcessWithLogonW function instead. CreateProcessWithLogonW requires no special privileges, but the specified user account must be allowed to log on interactively. Generally, it is best to use CreateProcessWithLogonW to create a process with alternate credentials. + /// + /// + /// A handle to the primary token that represents a user. The handle must have the TOKEN_QUERY, TOKEN_DUPLICATE, and TOKEN_ASSIGN_PRIMARY access rights. For more information, see Access Rights for Access-Token Objects. The user represented by the token must have read and execute access to the application specified by the or the parameter. + /// To get a primary token that represents the specified user, call the LogonUser function. Alternatively, you can call the DuplicateTokenEx function to convert an impersonation token into a primary token. This allows a server application that is impersonating a client to create a process that has the security context of the client. + /// If hToken is a restricted version of the caller's primary token, the SE_ASSIGNPRIMARYTOKEN_NAME privilege is not required. If the necessary privileges are not already enabled, CreateProcessAsUser enables them for the duration of the call. For more information, see Running with Special Privileges. + /// Terminal Services: The process is run in the session specified in the token. By default, this is the same session that called LogonUser. To change the session, use the SetTokenInformation function. + /// + /// + /// The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer. + /// The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed. + /// The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space–delimited token in the lpCommandLine string. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin; otherwise, the file name is ambiguous. For example, consider the string "c:\program files\sub dir\program name". This string can be interpreted in a number of ways. + /// See MSDN docs for more information. + /// + /// + /// The command line to be executed. The maximum length of this string is 32K characters. If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to MAX_PATH characters. + /// The Unicode version of this function, CreateProcessAsUserW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation. + /// The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line. + /// If both lpApplicationName and lpCommandLine are non-NULL, *lpApplicationName specifies the module to execute, and *lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line. + /// If lpApplicationName is NULL, the first white space–delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. + /// See MSDN docs for more information. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new process object and determines whether child processes can inherit the returned handle to the process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller, in which case the process may not be opened again after it is run. The process handle is valid and will continue to have full access rights. + /// + /// + /// A pointer to a structure that specifies a security descriptor for the new thread object and determines whether child processes can inherit the returned handle to the thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread gets a default security descriptor and the handle cannot be inherited. The default security descriptor is that of the user referenced in the hToken parameter. This security descriptor may not allow access for the caller. + /// + /// + /// If this parameter is 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. + /// Terminal Services: You cannot inherit handles across sessions. Additionally, if this parameter is TRUE, you must create the process in the same session as the caller. + /// + /// + /// The flags that control the priority class and the creation of the process. For a list of values, see Process Creation Flags. + /// This parameter also controls the new process's priority class, which is used to determine the scheduling priorities of the process's threads. For a list of values, see GetPriorityClass. If none of the priority class flags is specified, the priority class defaults to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child process receives the default priority class of the calling process. + /// + /// + /// A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process. + /// An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form: + /// name=value\0 + /// Because the equal sign is used as a separator, it must not be used in the name of an environment variable. + /// An environment block can contain either Unicode or ANSI characters. If the environment block pointed to by lpEnvironment contains Unicode characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. If this parameter is NULL and the environment block of the parent process contains Unicode characters, you must also ensure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. + /// The ANSI version of this function, CreateProcessAsUserA fails if the total size of the environment block for the process exceeds 32,767 characters. + /// Note that an ANSI environment block is terminated by two zero bytes: one for the last string, one more to terminate the block. A Unicode environment block is terminated by four zero bytes: two for the last string, two more to terminate the block. + /// See MSDN docs for more information. + /// + /// + /// The full path to the current directory for the process. The string can also specify a UNC path. + /// If this parameter is NULL, the new process will have the same current drive and directory as the calling process. (This feature is provided primarily for shells that need to start an application and specify its initial drive and working directory.) + /// + /// + /// A pointer to a or structure. + /// The user must have full access to both the specified window station and desktop. If you want the process to be interactive, specify winsta0\default. If the lpDesktop member is NULL, the new process inherits the desktop and window station of its parent process. If this member is an empty string, "", the new process connects to a window station using the rules described in Process Connection to a Window Station. + /// To set extended attributes, use a structure and specify in the parameter. + /// Handles in or must be closed with CloseHandle when they are no longer needed. + /// Important The caller is responsible for ensuring that the standard handle fields in contain valid handle values. These fields are copied unchanged to the child process without validation, even when the dwFlags member specifies . Incorrect values can cause the child process to misbehave or crash. Use the Application Verifier runtime verification tool to detect invalid handles. + /// + /// + /// A pointer to a structure that receives identification information about the new process. + /// Handles in must be closed with CloseHandle when they are no longer needed. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool CreateProcessAsUser( + IntPtr hToken, + string lpApplicationName, + string lpCommandLine, + SECURITY_ATTRIBUTES lpProcessAttributes, + SECURITY_ATTRIBUTES lpThreadAttributes, + [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, + CreateProcessFlags dwCreationFlags, + IntPtr lpEnvironment, // IntPtr because it may point to unicode or ANSI characters, based on a flag. + string lpCurrentDirectory, + ref STARTUPINFO lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation) + => CreateProcessAsUser(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out lpProcessInformation); + + /// + /// Retrieves the contents of the structure that was specified when the calling process was created. + /// + /// + /// A pointer to a structure that receives the startup information. + /// + /// + /// This function does not return a value, and does not fail. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public void GetStartupInfo( + out STARTUPINFO lpStartupInfo) + => GetStartupInfo(out lpStartupInfo); + + /// + /// Initializes the specified list of attributes for process and thread creation. + /// + /// + /// The attribute list. This parameter can be NULL to determine the buffer size required to support the specified number of attributes. + /// + /// + /// The count of attributes to be added to the list. + /// + /// + /// This parameter is reserved and must be zero. + /// + /// + /// If lpAttributeList is not NULL, this parameter specifies the size in bytes of the lpAttributeList buffer on input. On output, this parameter receives the size in bytes of the initialized attribute list. + /// If lpAttributeList is NULL, this parameter receives the required buffer size in bytes. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + /// + /// First, call this function with the parameter set to the maximum number of attributes you will be using and the lpAttributeList to NULL. The function returns the required buffer size in bytes in the lpSize parameter. Allocate enough space for the data in the lpAttributeList buffer and call the function again to initialize the buffer. + /// To add attributes to the list, call the function. To specify these attributes when creating a process, specify in the dwCreationFlag parameter and a structure in the lpStartupInfo parameter. Note that you can specify the same structure to multiple child processes. + /// When you have finished using the list, call the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InitializeProcThreadAttributeList( + IntPtr lpAttributeList, + uint dwAttributeCount, + uint dwFlags, + ref IntPtr lpSize) + => InitializeProcThreadAttributeList(lpAttributeList, dwAttributeCount, dwFlags, ref lpSize); + + /// + /// Updates the specified attribute in a list of attributes for process and thread creation. + /// + /// + /// A pointer to an attribute list created by the function. + /// + /// + /// This parameter is reserved and must be zero. + /// + /// + /// The attribute key to update in the attribute list. + /// + /// + /// A pointer to the attribute value. This value should persist until the attribute is destroyed using the function. + /// + /// + /// The size of the attribute value specified by the parameter. + /// + /// + /// This parameter is reserved and must be NULL. + /// + /// This parameter is reserved and must be NULL. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool UpdateProcThreadAttribute( + IntPtr lpAttributeList, + uint dwFlags, + ref uint Attribute, + IntPtr lpValue, + IntPtr cbSize, // SIZE_T varies by bitness + ref IntPtr lpPreviousValue, + ref IntPtr lpReturnSize) + => UpdateProcThreadAttribute(lpAttributeList, dwFlags, ref Attribute, lpValue, cbSize, ref lpPreviousValue, ref lpReturnSize); + + /// + /// Deletes the specified list of attributes for process and thread creation. + /// + /// + /// The attribute list. This list is created by the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public void DeleteProcThreadAttributeList( + IntPtr lpAttributeList) + => DeleteProcThreadAttributeList(lpAttributeList); + + /// + /// Allocates a new console for the calling process. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool AllocConsole() + => AllocConsole(); + + /// + /// Detaches the calling process from its console. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool FreeConsole() + => FreeConsole(); + + /// + /// Attaches the calling process to the console of the specified process. + /// + /// + /// The identifier of the process whose console is to be used. This parameter can be one of the following values. + /// pid: Use the console of the specified process. + /// -1: Use the console of the parent of the current process. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool AttachConsole(uint dwProcessId) + => AttachConsole(dwProcessId); + + /// + /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified. + /// To perform this operation as a transacted operation, which results in a handle that can be used for transacted I/O, use the CreateFileTransacted function. + /// + /// + /// The name of the file or device to be created or opened. You may use either forward slashes (/) or backslashes (\) in this name. + /// In the ANSI version of this function, the name is limited to characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, Paths, and Namespaces. + /// For information on special device names, see Defining an MS-DOS Device Name. + /// To create a file stream, specify the name of the file, a colon, and then the name of the stream.For more information, see File Streams. + /// + /// + /// The requested access to the file or device, which can be summarized as read, write, both or neither zero). + /// The most commonly used values are , , or both( | ). For more information, see Generic Access Rights, File Security and Access Rights, File Access Rights Constants, and ACCESS_MASK. + /// If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without accessing that file or device, even if access would have been denied. + /// You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle. + /// For more information, see the Remarks section of this topic and Creating and Opening Files. + /// + /// + /// The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the following table). Access requests to attributes or extended attributes are not affected by this flag. + /// If this parameter is zero and succeeds, the file or device cannot be shared and cannot be opened again until the handle to the file or device is closed. For more information, see the Remarks section. + /// You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. would fail and the function would return ERROR_SHARING_VIOLATION. + /// To enable a process to share a file or device while another process has the file or device open, use a compatible combination of one or more of the following values. For more information about valid combinations of this parameter with the dwDesiredAccess parameter, see Creating and Opening Files. + /// + /// + /// A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes. + /// This parameter can be NULL. + /// If this parameter is NULL, the handle returned by CreateFile cannot be inherited by any child processes the application may create and the file or device associated with the returned handle gets a default security descriptor. + /// The member of the structure specifies a for a file or device. If this member is NULL, the file or device associated with the returned handle is assigned a default security descriptor. + /// CreateFile ignores the member when opening an existing file or device, but continues to use the member. + /// The member of the structure specifies whether the returned handle can be inherited. + /// + /// + /// An action to take on a file or device that exists or does not exist. + /// For devices other than files, this parameter is usually set to . + /// + /// + /// The file or device attributes and flags, being the most common default value for files. + /// This parameter can include any combination of the available file attributes (CreateFileFlags.*Attribute). All other file attributes override . + /// This parameter can also contain combinations of flags (CreateFileFlags.*Flag) for control of file or device caching behavior, access modes, and other special-purpose flags. These combine with any CreateFileFlags.*Attribute values. + /// This parameter can also contain Security Quality of Service (SQOS) information by specifying the SECURITY_SQOS_PRESENT flag. Additional SQOS-related flags information is presented in the table following the attributes and flags tables. + /// Note When CreateFile opens an existing file, it generally combines the file flags with the file attributes of the existing file, and ignores any file attributes supplied as part of dwFlagsAndAttributes. Special cases are detailed in Creating and Opening Files. + /// Some of the following file attributes and flags may only apply to files and not necessarily all other types of devices that CreateFile can open.For additional information, see the Remarks section of this topic and Creating and Opening Files. + /// For more advanced access to file attributes, see SetFileAttributes. For a complete list of all file attributes with their values and descriptions, see File Attribute Constants. + /// + /// + /// A valid handle to a template file with the access right. The template file supplies file attributes and extended attributes for the file that is being created. + /// This parameter can be NULL. + /// When opening an existing file, CreateFile ignores this parameter. + /// When opening a new encrypted file, the file inherits the discretionary access control list from its parent directory.For additional information, see File Encryption. + /// + /// + /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. + /// If the function fails, the return value is INVALID_HANDLE_VALUE.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle CreateFile( + string filename, + FileAccess access, + FileShare share, + SECURITY_ATTRIBUTES securityAttributes, + CreationDisposition creationDisposition, + CreateFileFlags flagsAndAttributes, + SafeObjectHandle templateFile) + => CreateFile(filename, access, share, securityAttributes, creationDisposition, flagsAndAttributes, templateFile); + + /// + /// Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used). + /// To specify additional attributes to use in a search, use the FindFirstFileEx function. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash(\). + /// If the string ends with a wildcard, period(.), or directory name, the user must have access permissions to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// A pointer to the WIN32_FIND_DATA structure that receives information about a found file or directory. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// If the function fails because no matching files can be found, the function returns ERROR_FILE_NOT_FOUND. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeFindFilesHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) + => FindFirstFile(lpFileName, out lpFindFileData); + + /// + /// Continues a file search from a previous call to the , FindFirstFileEx, or FindFirstFileTransacted functions. + /// + /// The search handle returned by a previous call to the FindFirstFile or FindFirstFileEx function. + /// A pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. + /// + /// If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file or directory found. + /// If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate. To get extended error information, call the function. + /// If the function fails because no more matching files can be found, the function returns ERROR_NO_MORE_FILES. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool FindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) + => FindNextFile(hFindFile, out lpFindFileData); + + /// + /// Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these + /// processes. + /// + /// The portions of the system to be included in the snapshot. + /// + /// The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate the + /// current process. This parameter is used when the , + /// , + /// , or + /// 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 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 . + /// + /// + /// + /// If the function succeeds, it returns an open handle to the specified snapshot. + /// + /// If the function fails, it returns . To get extended error information, call + /// . Possible error codes include + /// . + /// + /// + /// + /// The snapshot taken by this function is examined by the other tool help functions to provide their results.Access to the + /// snapshot is read only.The snapshot handle acts as an object handle and is subject to the same rules regarding which + /// processes and threads it is valid in. + /// + /// To enumerate the heap or module states for all processes, specify + /// and set to zero.Then, for + /// each additional process in the snapshot, call CreateToolhelp32Snapshot again, specifying its process identifier and the + /// or + /// value. + /// + /// + /// When taking snapshots that include heaps and modules for a process other than the current process, the + /// CreateToolhelp32Snapshot function can fail or return incorrect information for a variety of reasons. For example, if + /// the loader data table in the target process is corrupted or not initialized, or if the module list changes during the + /// function call as a result of DLLs being loaded or unloaded, the function might fail with + /// or other error code. Ensure that the target process was not started in a + /// suspended state, and try calling the function again. If the function fails with + /// when called with + /// or + /// , call the function again until it succeeds. + /// + /// + /// The and + /// flags do not retrieve handles for modules that were + /// loaded with the LOAD_LIBRARY_AS_DATAFILE or similar flags. For more information, see LoadLibraryEx. + /// + /// To destroy the snapshot, call on the returned handle. + /// + /// Note that you can use the + /// + /// function to retrieve the full name of an executable image for both 32- and 64-bit processes from a 32-bit process. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle CreateToolhelp32Snapshot( + CreateToolhelp32SnapshotFlags dwFlags, + uint th32ProcessID) + => CreateToolhelp32Snapshot(dwFlags, th32ProcessID); + + /// Retrieves information about the first process encountered in a system snapshot. + /// + /// A handle to the snapshot returned from a previous call to the + /// function. + /// + /// + /// Contains process information such as the name of the executable file, the process identifier, and + /// the process identifier of the parent process. + /// + /// + /// Returns if the first entry of the process list has been copied to the buffer or + /// otherwise. The error value is returned by + /// the function if no processes exist or the snapshot does not contain process + /// information. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool Process32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) + => Process32First(hSnapshot, lppe); + + /// Retrieves information about the next process recorded in a system snapshot. + /// + /// A handle to the snapshot returned from a previous call to the + /// function. + /// + /// A structure. + /// + /// Returns if the next entry of the process list has been copied to the buffer or + /// otherwise. The error value is returned by + /// the function if no processes exist or the snapshot does not contain process + /// information. + /// + /// + /// To retrieve information about the first process recorded in a snapshot, use the + /// + /// function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool Process32Next( + SafeObjectHandle hSnapshot, + [In, Out] PROCESSENTRY32 lppe) + => Process32Next(hSnapshot, lppe); + + /// Retrieves the full name of the executable image for the specified process. + /// + /// A handle to the process. This handle must be created with the + /// or + /// access right. + /// + /// One of the values. + /// The path to the executable image. If the function succeeds, this string is null-terminated. + /// + /// On input, specifies the size of the lpExeName buffer, in characters. On success, receives the + /// number of characters written to the buffer, not including the null-terminating character. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + /// Minimum OS: Windows Vista / Windows Server 2008. + [System.Runtime.CompilerServices.CompilerGenerated] + public bool QueryFullProcessImageName( + SafeObjectHandle hProcess, + QueryFullProcessImageNameFlags dwFlags, + StringBuilder lpExeName, + ref uint lpdwSize) + => QueryFullProcessImageName(hProcess, dwFlags, lpExeName, ref lpdwSize); + + /// Opens an existing local process object. + /// + /// The access to the process object. This access right is checked against the security descriptor for the process. This + /// parameter can be one or more of the values. + /// + /// If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the + /// contents of the security descriptor. + /// + /// + /// + /// If this value is , processes created by this process will inherit + /// the handle. Otherwise, the processes do not inherit this handle. + /// + /// + /// The identifier of the local process to be opened. + /// + /// If the specified process is the System Process(0x00000000), the function fails and the last error code is + /// .If the specified process is the Idle process or one of the CSRSS + /// processes, this function fails and the last error code is because + /// their access restrictions prevent user-level code from opening them. + /// + /// + /// If you are using as an argument to this function, consider using + /// instead of OpenProcess, for improved performance. + /// + /// + /// If the function succeeds, the return value is an open handle to the specified process. + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle OpenProcess( + ProcessAccess dwDesiredAccess, + bool bInheritHandle, + uint dwProcessId) + => OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); + + /// + /// Retrieves the results of an overlapped operation on the specified file, named pipe, or communications device. + /// To specify a timeout interval or wait on an alertable thread, use GetOverlappedResultEx. + /// + /// + /// A handle to the file, named pipe, or communications device. This is the same handle that was + /// specified when the overlapped operation was started by a call to the ReadFile, WriteFile, ConnectNamedPipe, + /// TransactNamedPipe, DeviceIoControl, or WaitCommEvent function. + /// + /// + /// A pointer to an structure that was specified when the overlapped + /// operation was started. + /// + /// + /// A pointer to a variable that receives the number of bytes that were actually + /// transferred by a read or write operation. For a TransactNamedPipe operation, this is the number of bytes that were read + /// from the pipe. For a DeviceIoControl operation, this is the number of bytes of output data returned by the device + /// driver. For a ConnectNamedPipe or WaitCommEvent operation, this value is undefined. + /// + /// + /// If this parameter is TRUE, and the Internal member of the lpOverlapped structure is STATUS_PENDING, + /// the function does not return until the operation has been completed. If this parameter is FALSE and the operation is + /// still pending, the function returns FALSE and the function returns + /// . + /// + /// + /// If the function succeeds, the return value is nonzero. + /// + /// If the function fails, the return value is zero.To get extended error information, call + /// . + /// + /// + /// + /// The results reported by the GetOverlappedResult function are those of the specified handle's last overlapped operation + /// to which the specified structure was provided, and for which the operation's results were + /// pending. A pending operation is indicated when the function that started the operation returns FALSE, and the + /// GetLastError function returns . When an I/O operation is pending, the + /// function that started the operation resets the hEvent member of the structure to the + /// nonsignaled state. Then when the pending operation has been completed, the system sets the event object to the signaled + /// state. + /// + /// If the bWait parameter is TRUE, GetOverlappedResult determines whether the pending operation has been completed + /// by waiting for the event object to be in the signaled state. + /// + /// + /// If the hEvent member of the structure is NULL, the system uses the state of the hFile + /// handle to signal when the operation has been completed. Use of file, named pipe, or communications-device handles for + /// this purpose is discouraged. It is safer to use an event object because of the confusion that can occur when multiple + /// simultaneous overlapped operations are performed on the same file, named pipe, or communications device. In this + /// situation, there is no way to know which operation caused the object's state to be signaled. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool GetOverlappedResult( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped, + out uint lpNumberOfBytesTransferred, + bool bWait) + => GetOverlappedResult(hFile, lpOverlapped, out lpNumberOfBytesTransferred, bWait); + + /// + /// Cancels all pending input and output (I/O) operations that are issued by the calling thread for the specified file. The + /// function does not cancel I/O operations that other threads issue for a file handle. + /// To cancel I/O operations from another thread, use the CancelIoEx function. + /// + /// + /// A handle to the file. + /// The function cancels all pending I/O operations for this file handle. + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued by + /// the calling thread for the specified file handle was successfully requested. The thread can use the + /// function to determine when the I/O operations themselves have been completed. + /// + /// If the function fails, the return value is zero (0). To get extended error information, call the + /// function. + /// + /// + /// + /// If there are any pending I/O operations in progress for the specified file handle, and they are issued by the calling + /// thread, the CancelIo function cancels them. CancelIo cancels only outstanding I/O on the handle, it does not change the + /// state of the handle; this means that you cannot rely on the state of the handle because you cannot know whether the + /// operation was completed successfully or canceled. + /// + /// The I/O operations must be issued as overlapped I/O. If they are not, the I/O operations do not return to allow + /// the thread to call the CancelIo function. Calling the CancelIo function with a file handle that is not opened with + /// FILE_FLAG_OVERLAPPED does nothing. + /// + /// + /// All I/O operations that are canceled complete with the error + /// , and all completion notifications for the I/O operations occur + /// normally. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool CancelIo(SafeObjectHandle hFile) + => CancelIo(hFile); + + /// + /// Determines whether the specified process is running under WOW64 (x86 emulator that allows 32-bit Windows-based + /// applications to run seamlessly on 64-bit Windows) + /// + /// + /// A handle to the process. The handle must have the or + /// access right. + /// + /// Windows Server 2003 and Windows XP: The handle must have the + /// access right. + /// + /// + /// + /// A pointer to a value that is set to if the process is running under + /// WOW64. If the process is running under 32-bit Windows, the value is set to . If the process is + /// a 64-bit application running under 64-bit Windows, the value is also set to . + /// + /// + /// If the function succeeds, the return value is a nonzero value. + /// + /// If the function fails, the return value is zero. To get extended error information, call + /// . + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool IsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) + => IsWow64Process(hProcess, out Wow64Process); + + /// + /// Creates an anonymous pipe, and returns handles to the read and write ends of the pipe. + /// + /// + /// A pointer to a variable that receives the read handle for the pipe. + /// + /// + /// A pointer to a variable that receives the write handle for the pipe. + /// + /// + /// A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If is NULL, the handle cannot be inherited. + /// The member of the structure specifies a security descriptor for the new pipe. If is NULL, the pipe gets a default security descriptor. The ACLs in the default security descriptor for a pipe come from the primary or impersonation token of the creator. + /// + /// + /// The size of the buffer for the pipe, in bytes. The size is only a suggestion; the system uses the value to calculate an appropriate buffering mechanism. If this parameter is zero, the system uses the default buffer size. + /// + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool CreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize) + => CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize); + } +} diff --git a/src/Kernel32.Shared/IKernel32Mockable.cs b/src/Kernel32.Shared/IKernel32Mockable.cs new file mode 100644 index 00000000..5c0c335c --- /dev/null +++ b/src/Kernel32.Shared/IKernel32Mockable.cs @@ -0,0 +1,372 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + public interface IKernel32Mockable { + /// + /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. + /// For the most basic version of this function, see FindFirstFile. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). + /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// + /// The information level of the returned data. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the buffer that receives the file data. + /// The pointer type is determined by the level of information that is specified in the parameter. + /// + /// + /// The type of filtering to perform that is different from wildcard matching. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the search criteria if the specified needs structured search information. + /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. + /// + /// Specifies additional flags that control the search. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// + SafeFindFilesHandle InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags); + + /// + /// 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. + /// + /// + /// The 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. + /// + /// + /// The location of the message definition. The type of this parameter depends upon the settings in the parameter. + /// If : A handle to the module that contains the message table to search. + /// If : Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. + /// If neither of these flags is set in dwFlags, then lpSource is ignored. + /// + /// + /// The message identifier for the requested message. This parameter is ignored if dwFlags includes . + /// + /// + /// The language identifier for the requested message. This parameter is ignored if dwFlags includes . + /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: + /// Language neutral + /// Thread LANGID, based on the thread's locale value + /// User default LANGID, based on the user's default locale value + /// System default LANGID, based on the system default locale value + /// US English + /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. + /// + /// + /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes , the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer. + /// This buffer cannot be larger than 64K bytes. + /// + /// + /// If the flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If is set, + /// this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// The output buffer cannot be larger than 64K bytes. + /// + /// + /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. + /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. + /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. + /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. + /// + /// + /// 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 . + /// + int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments); + + /// + /// Retrieves the thread identifier of the calling thread. + /// + /// The thread identifier of the calling thread. + uint InvokeGetCurrentThreadId(); + + /// Retrieves the process identifier of the calling process. + /// The process identifier of the calling process. + /// Until the process terminates, the process identifier uniquely identifies the process throughout the system. + uint InvokeGetCurrentProcessId(); + + /// Retrieves a pseudo handle for the current process. + /// The return value is a pseudo handle to the current process. + /// + /// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For + /// compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this + /// constant value. The calling process can use a pseudo handle to specify its own process whenever a process handle is + /// required. Pseudo handles are not inherited by child processes. + /// This handle has the PROCESS_ALL_ACCESS access right to the process object. + /// + /// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of + /// the process to the primary token of the process. + /// + /// + /// A process can create a "real" handle to itself that is valid in the context of other processes, or that can + /// be inherited by other processes, by specifying the pseudo handle as the source handle in a call to the + /// DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself. + /// + /// + /// The pseudo handle need not be closed when it is no longer needed. Calling the + /// function with a pseudo handle has no effect.If the pseudo handle is duplicated by DuplicateHandle, the + /// duplicate handle must be closed. + /// + /// + SafeObjectHandle InvokeGetCurrentProcess(); + + /// + /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations + /// in the current process, regardless of which thread created the I/O operation. + /// + /// A handle to the file. + /// + /// A pointer to an data structure that contains the data used for asynchronous I/O. + /// If this parameter is NULL, all I/O requests for the hFile parameter are canceled. + /// + /// If this parameter is not NULL, only those specific I/O requests that were issued for the file with the + /// specified + /// overlapped structure are marked as canceled, meaning that you can cancel one + /// or more requests, while the CancelIo function cancels all outstanding requests on a file handle. + /// + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued + /// by the calling process for the specified file handle was successfully requested. The application must not free or + /// reuse the structure associated with the canceled I/O operations until they have + /// completed. The thread can use the GetOverlappedResult function to determine when the I/O operations themselves have + /// been completed. + /// + /// If the function fails, the return value is 0 (zero). To get extended error information, call the + /// function. + /// + /// + /// If this function cannot find a request to cancel, the return value is 0 (zero), and + /// + /// returns . + /// + /// + bool InvokeCancelIoEx( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped); + + /// + /// 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. + /// + /// + /// + /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, + /// socket, communications resource, mailslot, or pipe). + /// The hFile parameter must have been created with read access. + /// + /// For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag + /// by the CreateFile function, or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer that receives the data read from a file or device. + /// + /// This buffer must remain valid for the duration of the read operation. The caller must not use this buffer + /// until the read operation is completed. + /// + /// + /// The maximum number of bytes to be read. + /// + /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile + /// sets this value to zero before doing any work or error checking. Use for this parameter if + /// this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise it can be . + /// + /// If hFile is opened with FILE_FLAG_OVERLAPPED, the parameter must point to a + /// valid and unique structure, otherwise the function can incorrectly report that the + /// read operation is complete. + /// + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the read operation is pending completion asynchronously. + /// + /// + bool InvokeReadFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToRead, + NullableUInt32 lpNumberOfBytesRead, + OVERLAPPED* lpOverlapped); + + /// + /// Writes data to the specified file or input/output (I/O) device. + /// + /// This function is designed for both synchronous and asynchronous operation. For a similar function designed + /// solely for asynchronous operation, see WriteFileEx. + /// + /// + /// + /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape + /// drive, socket, communications resource, mailslot, or pipe). + /// + /// The hFile parameter must have been created with the write access. For more information, see Generic Access + /// Rights and File Security and Access Rights. + /// + /// + /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the + /// FILE_FLAG_OVERLAPPED flag or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer containing the data to be written to the file or device. + /// + /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer + /// until the write operation is completed. + /// + /// + /// + /// The number of bytes to be written to the file or device. + /// + /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the + /// underlying file system or communications technology. + /// + /// + /// + /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. + /// WriteFile sets this value to zero before doing any work or error checking. Use + /// for this parameter if this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be NULL only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL. + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start writing to the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// To write to the end of file, specify both the Offset and OffsetHigh members of the + /// structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open + /// hFile using FILE_APPEND_DATA access. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the write operation is pending completion asynchronously. + /// + /// + bool InvokeWriteFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToWrite, + NullableUInt32 lpNumberOfBytesWritten, + OVERLAPPED* lpOverlapped); + + /// + /// Suspends the specified thread. + /// A 64-bit application can suspend a WOW64 thread using the function. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + int InvokeSuspendThread(SafeObjectHandle hThread); + + /// + /// Suspends the specified WOW64 thread. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + int InvokeWow64SuspendThread(SafeObjectHandle hThread); + + /// + /// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. + /// + /// + /// A handle to the thread to be restarted. + /// This handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count. + /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . + /// + int InvokeResumeThread(SafeObjectHandle hThread); + + /// + /// Waits until the specified object is in the signaled state or the time-out interval elapses. + /// To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects. + /// + /// + /// A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. + /// If this handle is closed while the wait is still pending, the function's behavior is undefined. + /// The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. + /// + /// + /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. + /// See MSDN docs for more information. + /// + /// + /// If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. + /// + WaitForSingleObjectResult InvokeWaitForSingleObject( + SafeHandle hHandle, + uint dwMilliseconds); + + /// + /// Closes an open object handle. + /// + /// A valid handle to an open object. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + bool InvokeCloseHandle(IntPtr hObject); + } +} diff --git a/src/Kernel32.Shared/Kernel32Mockable.cs b/src/Kernel32.Shared/Kernel32Mockable.cs new file mode 100644 index 00000000..fd033d3c --- /dev/null +++ b/src/Kernel32.Shared/Kernel32Mockable.cs @@ -0,0 +1,385 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable { + /// + /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. + /// For the most basic version of this function, see FindFirstFile. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). + /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// + /// The information level of the returned data. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the buffer that receives the file data. + /// The pointer type is determined by the level of information that is specified in the parameter. + /// + /// + /// The type of filtering to perform that is different from wildcard matching. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the search criteria if the specified needs structured search information. + /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. + /// + /// Specifies additional flags that control the search. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// + public SafeFindFilesHandle InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags) + => FindFirstFileEx(lpFileName, fInfoLevelId, lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags); + + /// + /// 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. + /// + /// + /// The 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. + /// + /// + /// The location of the message definition. The type of this parameter depends upon the settings in the parameter. + /// If : A handle to the module that contains the message table to search. + /// If : Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. + /// If neither of these flags is set in dwFlags, then lpSource is ignored. + /// + /// + /// The message identifier for the requested message. This parameter is ignored if dwFlags includes . + /// + /// + /// The language identifier for the requested message. This parameter is ignored if dwFlags includes . + /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: + /// Language neutral + /// Thread LANGID, based on the thread's locale value + /// User default LANGID, based on the user's default locale value + /// System default LANGID, based on the system default locale value + /// US English + /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. + /// + /// + /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes , the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer. + /// This buffer cannot be larger than 64K bytes. + /// + /// + /// If the flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If is set, + /// this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// The output buffer cannot be larger than 64K bytes. + /// + /// + /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. + /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. + /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. + /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. + /// + /// + /// 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 . + /// + public int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments) + => FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments); + + /// + /// Retrieves the thread identifier of the calling thread. + /// + /// The thread identifier of the calling thread. + public uint InvokeGetCurrentThreadId() + => GetCurrentThreadId(); + + /// Retrieves the process identifier of the calling process. + /// The process identifier of the calling process. + /// Until the process terminates, the process identifier uniquely identifies the process throughout the system. + public uint InvokeGetCurrentProcessId() + => GetCurrentProcessId(); + + /// Retrieves a pseudo handle for the current process. + /// The return value is a pseudo handle to the current process. + /// + /// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For + /// compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this + /// constant value. The calling process can use a pseudo handle to specify its own process whenever a process handle is + /// required. Pseudo handles are not inherited by child processes. + /// This handle has the PROCESS_ALL_ACCESS access right to the process object. + /// + /// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of + /// the process to the primary token of the process. + /// + /// + /// A process can create a "real" handle to itself that is valid in the context of other processes, or that can + /// be inherited by other processes, by specifying the pseudo handle as the source handle in a call to the + /// DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself. + /// + /// + /// The pseudo handle need not be closed when it is no longer needed. Calling the + /// function with a pseudo handle has no effect.If the pseudo handle is duplicated by DuplicateHandle, the + /// duplicate handle must be closed. + /// + /// + public SafeObjectHandle InvokeGetCurrentProcess() + => GetCurrentProcess(); + + /// + /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations + /// in the current process, regardless of which thread created the I/O operation. + /// + /// A handle to the file. + /// + /// A pointer to an data structure that contains the data used for asynchronous I/O. + /// If this parameter is NULL, all I/O requests for the hFile parameter are canceled. + /// + /// If this parameter is not NULL, only those specific I/O requests that were issued for the file with the + /// specified + /// overlapped structure are marked as canceled, meaning that you can cancel one + /// or more requests, while the CancelIo function cancels all outstanding requests on a file handle. + /// + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued + /// by the calling process for the specified file handle was successfully requested. The application must not free or + /// reuse the structure associated with the canceled I/O operations until they have + /// completed. The thread can use the GetOverlappedResult function to determine when the I/O operations themselves have + /// been completed. + /// + /// If the function fails, the return value is 0 (zero). To get extended error information, call the + /// function. + /// + /// + /// If this function cannot find a request to cancel, the return value is 0 (zero), and + /// + /// returns . + /// + /// + public bool InvokeCancelIoEx( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped) + => CancelIoEx(hFile, lpOverlapped); + + /// + /// 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. + /// + /// + /// + /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, + /// socket, communications resource, mailslot, or pipe). + /// The hFile parameter must have been created with read access. + /// + /// For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag + /// by the CreateFile function, or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer that receives the data read from a file or device. + /// + /// This buffer must remain valid for the duration of the read operation. The caller must not use this buffer + /// until the read operation is completed. + /// + /// + /// The maximum number of bytes to be read. + /// + /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile + /// sets this value to zero before doing any work or error checking. Use for this parameter if + /// this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise it can be . + /// + /// If hFile is opened with FILE_FLAG_OVERLAPPED, the parameter must point to a + /// valid and unique structure, otherwise the function can incorrectly report that the + /// read operation is complete. + /// + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the read operation is pending completion asynchronously. + /// + /// + public bool InvokeReadFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToRead, + NullableUInt32 lpNumberOfBytesRead, + OVERLAPPED* lpOverlapped) + => ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); + + /// + /// Writes data to the specified file or input/output (I/O) device. + /// + /// This function is designed for both synchronous and asynchronous operation. For a similar function designed + /// solely for asynchronous operation, see WriteFileEx. + /// + /// + /// + /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape + /// drive, socket, communications resource, mailslot, or pipe). + /// + /// The hFile parameter must have been created with the write access. For more information, see Generic Access + /// Rights and File Security and Access Rights. + /// + /// + /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the + /// FILE_FLAG_OVERLAPPED flag or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer containing the data to be written to the file or device. + /// + /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer + /// until the write operation is completed. + /// + /// + /// + /// The number of bytes to be written to the file or device. + /// + /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the + /// underlying file system or communications technology. + /// + /// + /// + /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. + /// WriteFile sets this value to zero before doing any work or error checking. Use + /// for this parameter if this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be NULL only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL. + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start writing to the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// To write to the end of file, specify both the Offset and OffsetHigh members of the + /// structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open + /// hFile using FILE_APPEND_DATA access. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the write operation is pending completion asynchronously. + /// + /// + public bool InvokeWriteFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToWrite, + NullableUInt32 lpNumberOfBytesWritten, + OVERLAPPED* lpOverlapped) + => WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); + + /// + /// Suspends the specified thread. + /// A 64-bit application can suspend a WOW64 thread using the function. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + public int InvokeSuspendThread(SafeObjectHandle hThread) + => SuspendThread(hThread); + + /// + /// Suspends the specified WOW64 thread. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + public int InvokeWow64SuspendThread(SafeObjectHandle hThread) + => Wow64SuspendThread(hThread); + + /// + /// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. + /// + /// + /// A handle to the thread to be restarted. + /// This handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count. + /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . + /// + public int InvokeResumeThread(SafeObjectHandle hThread) + => ResumeThread(hThread); + + /// + /// Waits until the specified object is in the signaled state or the time-out interval elapses. + /// To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects. + /// + /// + /// A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. + /// If this handle is closed while the wait is still pending, the function's behavior is undefined. + /// The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. + /// + /// + /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. + /// See MSDN docs for more information. + /// + /// + /// If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. + /// + public WaitForSingleObjectResult InvokeWaitForSingleObject( + SafeHandle hHandle, + uint dwMilliseconds) + => WaitForSingleObject(hHandle, dwMilliseconds); + + /// + /// Closes an open object handle. + /// + /// A valid handle to an open object. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + public bool InvokeCloseHandle(IntPtr hObject) + => CloseHandle(hObject); + } +} diff --git a/src/Kernel32/IKernel32.cs b/src/Kernel32/IKernel32.cs new file mode 100644 index 00000000..81ce35bb --- /dev/null +++ b/src/Kernel32/IKernel32.cs @@ -0,0 +1,387 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IKernel32 { + /// + /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. + /// For the most basic version of this function, see FindFirstFile. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). + /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// + /// The information level of the returned data. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the buffer that receives the file data. + /// The pointer type is determined by the level of information that is specified in the parameter. + /// + /// + /// The type of filtering to perform that is different from wildcard matching. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the search criteria if the specified needs structured search information. + /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. + /// + /// Specifies additional flags that control the search. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeFindFilesHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags); + + /// + /// 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. + /// + /// + /// The 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. + /// + /// + /// The location of the message definition. The type of this parameter depends upon the settings in the parameter. + /// If : A handle to the module that contains the message table to search. + /// If : Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. + /// If neither of these flags is set in dwFlags, then lpSource is ignored. + /// + /// + /// The message identifier for the requested message. This parameter is ignored if dwFlags includes . + /// + /// + /// The language identifier for the requested message. This parameter is ignored if dwFlags includes . + /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: + /// Language neutral + /// Thread LANGID, based on the thread's locale value + /// User default LANGID, based on the user's default locale value + /// System default LANGID, based on the system default locale value + /// US English + /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. + /// + /// + /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes , the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer. + /// This buffer cannot be larger than 64K bytes. + /// + /// + /// If the flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If is set, + /// this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// The output buffer cannot be larger than 64K bytes. + /// + /// + /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. + /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. + /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. + /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. + /// + /// + /// 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 . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments); + + /// + /// Retrieves the thread identifier of the calling thread. + /// + /// The thread identifier of the calling thread. + [System.Runtime.CompilerServices.CompilerGenerated] + uint GetCurrentThreadId(); + + /// Retrieves the process identifier of the calling process. + /// The process identifier of the calling process. + /// Until the process terminates, the process identifier uniquely identifies the process throughout the system. + [System.Runtime.CompilerServices.CompilerGenerated] + uint GetCurrentProcessId(); + + /// Retrieves a pseudo handle for the current process. + /// The return value is a pseudo handle to the current process. + /// + /// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For + /// compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this + /// constant value. The calling process can use a pseudo handle to specify its own process whenever a process handle is + /// required. Pseudo handles are not inherited by child processes. + /// This handle has the PROCESS_ALL_ACCESS access right to the process object. + /// + /// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of + /// the process to the primary token of the process. + /// + /// + /// A process can create a "real" handle to itself that is valid in the context of other processes, or that can + /// be inherited by other processes, by specifying the pseudo handle as the source handle in a call to the + /// DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself. + /// + /// + /// The pseudo handle need not be closed when it is no longer needed. Calling the + /// function with a pseudo handle has no effect.If the pseudo handle is duplicated by DuplicateHandle, the + /// duplicate handle must be closed. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle GetCurrentProcess(); + + /// + /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations + /// in the current process, regardless of which thread created the I/O operation. + /// + /// A handle to the file. + /// + /// A pointer to an data structure that contains the data used for asynchronous I/O. + /// If this parameter is NULL, all I/O requests for the hFile parameter are canceled. + /// + /// If this parameter is not NULL, only those specific I/O requests that were issued for the file with the + /// specified + /// overlapped structure are marked as canceled, meaning that you can cancel one + /// or more requests, while the CancelIo function cancels all outstanding requests on a file handle. + /// + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued + /// by the calling process for the specified file handle was successfully requested. The application must not free or + /// reuse the structure associated with the canceled I/O operations until they have + /// completed. The thread can use the GetOverlappedResult function to determine when the I/O operations themselves have + /// been completed. + /// + /// If the function fails, the return value is 0 (zero). To get extended error information, call the + /// function. + /// + /// + /// If this function cannot find a request to cancel, the return value is 0 (zero), and + /// + /// returns . + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool CancelIoEx( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped); + + /// + /// 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. + /// + /// + /// + /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, + /// socket, communications resource, mailslot, or pipe). + /// The hFile parameter must have been created with read access. + /// + /// For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag + /// by the CreateFile function, or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer that receives the data read from a file or device. + /// + /// This buffer must remain valid for the duration of the read operation. The caller must not use this buffer + /// until the read operation is completed. + /// + /// + /// The maximum number of bytes to be read. + /// + /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile + /// sets this value to zero before doing any work or error checking. Use for this parameter if + /// this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise it can be . + /// + /// If hFile is opened with FILE_FLAG_OVERLAPPED, the parameter must point to a + /// valid and unique structure, otherwise the function can incorrectly report that the + /// read operation is complete. + /// + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the read operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool ReadFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToRead, + NullableUInt32 lpNumberOfBytesRead, + OVERLAPPED* lpOverlapped); + + /// + /// Writes data to the specified file or input/output (I/O) device. + /// + /// This function is designed for both synchronous and asynchronous operation. For a similar function designed + /// solely for asynchronous operation, see WriteFileEx. + /// + /// + /// + /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape + /// drive, socket, communications resource, mailslot, or pipe). + /// + /// The hFile parameter must have been created with the write access. For more information, see Generic Access + /// Rights and File Security and Access Rights. + /// + /// + /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the + /// FILE_FLAG_OVERLAPPED flag or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer containing the data to be written to the file or device. + /// + /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer + /// until the write operation is completed. + /// + /// + /// + /// The number of bytes to be written to the file or device. + /// + /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the + /// underlying file system or communications technology. + /// + /// + /// + /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. + /// WriteFile sets this value to zero before doing any work or error checking. Use + /// for this parameter if this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be NULL only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL. + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start writing to the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// To write to the end of file, specify both the Offset and OffsetHigh members of the + /// structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open + /// hFile using FILE_APPEND_DATA access. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the write operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool WriteFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToWrite, + NullableUInt32 lpNumberOfBytesWritten, + OVERLAPPED* lpOverlapped); + + /// + /// Suspends the specified thread. + /// A 64-bit application can suspend a WOW64 thread using the function. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int SuspendThread(SafeObjectHandle hThread); + + /// + /// Suspends the specified WOW64 thread. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int Wow64SuspendThread(SafeObjectHandle hThread); + + /// + /// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. + /// + /// + /// A handle to the thread to be restarted. + /// This handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count. + /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + int ResumeThread(SafeObjectHandle hThread); + + /// + /// Waits until the specified object is in the signaled state or the time-out interval elapses. + /// To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects. + /// + /// + /// A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. + /// If this handle is closed while the wait is still pending, the function's behavior is undefined. + /// The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. + /// + /// + /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. + /// See MSDN docs for more information. + /// + /// + /// If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + WaitForSingleObjectResult WaitForSingleObject( + SafeHandle hHandle, + uint dwMilliseconds); + + /// + /// Closes an open object handle. + /// + /// A valid handle to an open object. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool CloseHandle(IntPtr hObject); + } +} diff --git a/src/Kernel32/Kernel32.csproj b/src/Kernel32/Kernel32.csproj index 9d0ffa06..117672ee 100644 --- a/src/Kernel32/Kernel32.csproj +++ b/src/Kernel32/Kernel32.csproj @@ -23,6 +23,8 @@ + + diff --git a/src/Kernel32/Kernel32Mockable.cs b/src/Kernel32/Kernel32Mockable.cs new file mode 100644 index 00000000..4dbef8d0 --- /dev/null +++ b/src/Kernel32/Kernel32Mockable.cs @@ -0,0 +1,400 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; + [System.Runtime.CompilerServices.CompilerGenerated] + class Kernel32Mockable : IKernel32 { + /// + /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. + /// For the most basic version of this function, see FindFirstFile. + /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. + /// + /// + /// The directory or path, and the file name, which can include wildcard characters, for example, an asterisk (*) or a question mark (?). + /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash (\). + /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on the path. + /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. + /// + /// + /// The information level of the returned data. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the buffer that receives the file data. + /// The pointer type is determined by the level of information that is specified in the parameter. + /// + /// + /// The type of filtering to perform that is different from wildcard matching. + /// This parameter is one of the enumeration values. + /// + /// + /// A pointer to the search criteria if the specified needs structured search information. + /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. + /// + /// Specifies additional flags that control the search. + /// + /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the lpFindFileData parameter contains information about the first file or directory found. + /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate.To get extended error information, call the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeFindFilesHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags) + => FindFirstFileEx(lpFileName, fInfoLevelId, out lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags); + + /// + /// 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. + /// + /// + /// The 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. + /// + /// + /// The location of the message definition. The type of this parameter depends upon the settings in the parameter. + /// If : A handle to the module that contains the message table to search. + /// If : Pointer to a string that consists of unformatted message text. It will be scanned for inserts and formatted accordingly. + /// If neither of these flags is set in dwFlags, then lpSource is ignored. + /// + /// + /// The message identifier for the requested message. This parameter is ignored if dwFlags includes . + /// + /// + /// The language identifier for the requested message. This parameter is ignored if dwFlags includes . + /// If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only.If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND.If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: + /// Language neutral + /// Thread LANGID, based on the thread's locale value + /// User default LANGID, based on the user's default locale value + /// System default LANGID, based on the system default locale value + /// US English + /// If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present.If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND. + /// + /// + /// A pointer to a buffer that receives the null-terminated string that specifies the formatted message. If dwFlags includes , the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in lpBuffer. + /// This buffer cannot be larger than 64K bytes. + /// + /// + /// If the flag is not set, this parameter specifies the size of the output buffer, in TCHARs. If is set, + /// this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// The output buffer cannot be larger than 64K bytes. + /// + /// + /// An array of values that are used as insert values in the formatted message. A %1 in the format string indicates the first value in the Arguments array; a %2 indicates the second argument; and so on. + /// The interpretation of each value depends on the formatting information associated with the insert in the message definition.The default is to treat each value as a pointer to a null-terminated string. + /// By default, the Arguments parameter is of type va_list*, which is a language- and implementation-specific data type for describing a variable number of arguments.The state of the va_list argument is undefined upon return from the function.To use the va_list again, destroy the variable argument list pointer using va_end and reinitialize it with va_start. + /// If you do not have a pointer of type va_list*, then specify the FORMAT_MESSAGE_ARGUMENT_ARRAY flag and pass a pointer to an array of DWORD_PTR values; those values are input to the message formatted as the insert values.Each insert must have a corresponding element in the array. + /// + /// + /// 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 . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments) + => FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments); + + /// + /// Retrieves the thread identifier of the calling thread. + /// + /// The thread identifier of the calling thread. + [System.Runtime.CompilerServices.CompilerGenerated] + public uint GetCurrentThreadId() + => GetCurrentThreadId(); + + /// Retrieves the process identifier of the calling process. + /// The process identifier of the calling process. + /// Until the process terminates, the process identifier uniquely identifies the process throughout the system. + [System.Runtime.CompilerServices.CompilerGenerated] + public uint GetCurrentProcessId() + => GetCurrentProcessId(); + + /// Retrieves a pseudo handle for the current process. + /// The return value is a pseudo handle to the current process. + /// + /// A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the current process handle. For + /// compatibility with future operating systems, it is best to call GetCurrentProcess instead of hard-coding this + /// constant value. The calling process can use a pseudo handle to specify its own process whenever a process handle is + /// required. Pseudo handles are not inherited by child processes. + /// This handle has the PROCESS_ALL_ACCESS access right to the process object. + /// + /// Windows Server 2003 and Windows XP: This handle has the maximum access allowed by the security descriptor of + /// the process to the primary token of the process. + /// + /// + /// A process can create a "real" handle to itself that is valid in the context of other processes, or that can + /// be inherited by other processes, by specifying the pseudo handle as the source handle in a call to the + /// DuplicateHandle function. A process can also use the OpenProcess function to open a real handle to itself. + /// + /// + /// The pseudo handle need not be closed when it is no longer needed. Calling the + /// function with a pseudo handle has no effect.If the pseudo handle is duplicated by DuplicateHandle, the + /// duplicate handle must be closed. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle GetCurrentProcess() + => GetCurrentProcess(); + + /// + /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations + /// in the current process, regardless of which thread created the I/O operation. + /// + /// A handle to the file. + /// + /// A pointer to an data structure that contains the data used for asynchronous I/O. + /// If this parameter is NULL, all I/O requests for the hFile parameter are canceled. + /// + /// If this parameter is not NULL, only those specific I/O requests that were issued for the file with the + /// specified + /// overlapped structure are marked as canceled, meaning that you can cancel one + /// or more requests, while the CancelIo function cancels all outstanding requests on a file handle. + /// + /// + /// + /// If the function succeeds, the return value is nonzero. The cancel operation for all pending I/O operations issued + /// by the calling process for the specified file handle was successfully requested. The application must not free or + /// reuse the structure associated with the canceled I/O operations until they have + /// completed. The thread can use the GetOverlappedResult function to determine when the I/O operations themselves have + /// been completed. + /// + /// If the function fails, the return value is 0 (zero). To get extended error information, call the + /// function. + /// + /// + /// If this function cannot find a request to cancel, the return value is 0 (zero), and + /// + /// returns . + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool CancelIoEx( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped) + => CancelIoEx(hFile, lpOverlapped); + + /// + /// 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. + /// + /// + /// + /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, + /// socket, communications resource, mailslot, or pipe). + /// The hFile parameter must have been created with read access. + /// + /// For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag + /// by the CreateFile function, or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer that receives the data read from a file or device. + /// + /// This buffer must remain valid for the duration of the read operation. The caller must not use this buffer + /// until the read operation is completed. + /// + /// + /// The maximum number of bytes to be read. + /// + /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile + /// sets this value to zero before doing any work or error checking. Use for this parameter if + /// this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise it can be . + /// + /// If hFile is opened with FILE_FLAG_OVERLAPPED, the parameter must point to a + /// valid and unique structure, otherwise the function can incorrectly report that the + /// read operation is complete. + /// + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start reading from the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the read operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool ReadFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToRead, + NullableUInt32 lpNumberOfBytesRead, + OVERLAPPED* lpOverlapped) + => ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); + + /// + /// Writes data to the specified file or input/output (I/O) device. + /// + /// This function is designed for both synchronous and asynchronous operation. For a similar function designed + /// solely for asynchronous operation, see WriteFileEx. + /// + /// + /// + /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape + /// drive, socket, communications resource, mailslot, or pipe). + /// + /// The hFile parameter must have been created with the write access. For more information, see Generic Access + /// Rights and File Security and Access Rights. + /// + /// + /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the + /// FILE_FLAG_OVERLAPPED flag or a socket handle returned by the socket or accept function. + /// + /// + /// + /// A pointer to the buffer containing the data to be written to the file or device. + /// + /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer + /// until the write operation is completed. + /// + /// + /// + /// The number of bytes to be written to the file or device. + /// + /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the + /// underlying file system or communications technology. + /// + /// + /// + /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. + /// WriteFile sets this value to zero before doing any work or error checking. Use + /// for this parameter if this is an asynchronous operation to avoid potentially erroneous results. + /// + /// This parameter can be NULL only when the parameter is not + /// . + /// + /// + /// + /// A pointer to an structure is required if the hFile parameter was opened with + /// FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL. + /// + /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to + /// start writing to the file or device. This offset is specified by setting the Offset and OffsetHigh members of + /// the structure. For an hFile that does not support byte offsets, Offset and OffsetHigh + /// are ignored. + /// + /// + /// To write to the end of file, specify both the Offset and OffsetHigh members of the + /// structure as 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open + /// hFile using FILE_APPEND_DATA access. + /// + /// + /// + /// If the function succeeds, the return value is . + /// + /// If the function fails, or is completing asynchronously, the return value is . To get + /// extended error information, call the GetLastError function. + /// + /// + /// Note: The code is not a failure; + /// it designates the write operation is pending completion asynchronously. + /// + /// + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool WriteFile( + SafeObjectHandle hFile, + void* lpBuffer, + uint nNumberOfBytesToWrite, + NullableUInt32 lpNumberOfBytesWritten, + OVERLAPPED* lpOverlapped) + => WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); + + /// + /// Suspends the specified thread. + /// A 64-bit application can suspend a WOW64 thread using the function. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int SuspendThread(SafeObjectHandle hThread) + => SuspendThread(hThread); + + /// + /// Suspends the specified WOW64 thread. + /// + /// + /// A handle to the thread that is to be suspended. + /// The handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count; otherwise, it is (DWORD) -1. To get extended error information, use the function. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int Wow64SuspendThread(SafeObjectHandle hThread) + => Wow64SuspendThread(hThread); + + /// + /// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. + /// + /// + /// A handle to the thread to be restarted. + /// This handle must have the THREAD_SUSPEND_RESUME access right. For more information, see Thread Security and Access Rights. + /// + /// + /// If the function succeeds, the return value is the thread's previous suspend count. + /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public int ResumeThread(SafeObjectHandle hThread) + => ResumeThread(hThread); + + /// + /// Waits until the specified object is in the signaled state or the time-out interval elapses. + /// To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use WaitForMultipleObjects. + /// + /// + /// A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. + /// If this handle is closed while the wait is still pending, the function's behavior is undefined. + /// The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. + /// + /// + /// The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. + /// See MSDN docs for more information. + /// + /// + /// If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public WaitForSingleObjectResult WaitForSingleObject( + SafeHandle hHandle, + uint dwMilliseconds) + => WaitForSingleObject(hHandle, dwMilliseconds); + + /// + /// Closes an open object handle. + /// + /// A valid handle to an open object. + /// + /// If the function succeeds, the return value is nonzero. + /// If the function fails, the return value is zero.To get extended error information, call . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool CloseHandle(IntPtr hObject) + => CloseHandle(hObject); + } +} diff --git a/src/MockGenerator/App.config b/src/MockGenerator/App.config new file mode 100644 index 00000000..8324aa6f --- /dev/null +++ b/src/MockGenerator/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/MockGenerator/MockGenerator.csproj b/src/MockGenerator/MockGenerator.csproj new file mode 100644 index 00000000..afeea15a --- /dev/null +++ b/src/MockGenerator/MockGenerator.csproj @@ -0,0 +1,123 @@ + + + + + Debug + AnyCPU + {4FCA4D69-3E4F-43F1-B93B-05920B88A116} + Exe + Properties + MockGenerator + MockGenerator + v4.6 + 512 + true + + + AnyCPU + true + full + false + ..\..\bin\Debug\Tools\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + ..\..\bin\Release\Tools\ + DEBUG;TRACE + prompt + 4 + false + false + + + + ..\..\packages\Microsoft.CodeAnalysis.Common.1.0.0\lib\net45\Microsoft.CodeAnalysis.dll + True + + + ..\..\packages\Microsoft.CodeAnalysis.CSharp.1.0.0\lib\net45\Microsoft.CodeAnalysis.CSharp.dll + True + + + False + ..\..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.1.0.0\lib\net45\Microsoft.CodeAnalysis.CSharp.Workspaces.dll + True + + + False + ..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.0.0\lib\net45\Microsoft.CodeAnalysis.Workspaces.dll + True + + + False + ..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.0.0\lib\net45\Microsoft.CodeAnalysis.Workspaces.Desktop.dll + True + + + + ..\..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + True + + + False + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll + True + + + False + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll + True + + + False + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll + True + + + False + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll + True + + + False + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.TypedParts.dll + True + + + + ..\..\packages\System.Reflection.Metadata.1.0.21\lib\portable-net45+win8\System.Reflection.Metadata.dll + True + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs new file mode 100644 index 00000000..aef35dfe --- /dev/null +++ b/src/MockGenerator/Program.cs @@ -0,0 +1,440 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MockGenerator +{ + using System.Diagnostics; + using System.IO; + using System.Threading; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.CSharp.Syntax; + using Microsoft.CodeAnalysis.MSBuild; + + class Program + { + static readonly SyntaxTrivia WhitespaceCharacter = SyntaxFactory.Whitespace(" "); + static readonly SyntaxTrivia TabCharacter = SyntaxFactory.Whitespace("\t"); + static readonly SyntaxTrivia NewLineCharacter = SyntaxFactory.Whitespace("\n"); + + private static readonly IDictionary ClassCache; + private static readonly IDictionary InterfaceCache; + + static Program() + { + ClassCache = new Dictionary(); + InterfaceCache = new Dictionary(); + } + + private static void Main() + { + Run(); + } + + private static void Run() + { + Console.WriteLine("Loading solution"); + + var currentDirectory = Environment.CurrentDirectory; + + var workspace = MSBuildWorkspace.Create(); + + var solutionRoot = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(currentDirectory))), "src"); + var solution = workspace.OpenSolutionAsync(Path.Combine(solutionRoot, "PInvoke.sln")).Result; + var projects = GetProjectsFromSolution(solution); + for (var i = 0; i < projects.Length; i++) + { + var project = projects[i]; + Console.WriteLine($"Processing project {project.Name}"); + + var documents = project.Documents + .Where(x => x.FilePath.EndsWith(".cs")) + .ToArray(); + for (int index = 0; index < documents.Length; index++) + { + var document = documents[index]; + + Console.WriteLine($"\tProcessing {Path.GetFileName(document.FilePath)}"); + ProcessSourceCodes(ref solution, ref project, ref document); + } + + projects = GetProjectsFromSolution(solution); + } + + if (!workspace.TryApplyChanges(solution)) + { + Console.Error.WriteLine("Solution save failed."); + } + else + { + Console.WriteLine("Solution save succeeded!"); + } + + Console.ReadLine(); + } + + private static Project[] GetProjectsFromSolution(Solution solution) + { + return solution.Projects + .OrderBy(x => x.Name) + .ToArray(); + } + + private static void ProcessSourceCodes(ref Solution solution, ref Project project, ref Document document) + { + var compilationUnit = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax; + if (compilationUnit == null || compilationUnit.Members.Count == 0) return; + + var namespaceDeclarations = compilationUnit.Members.OfType(); + foreach (var namespaceDeclaration in namespaceDeclarations) + { + if (namespaceDeclaration == null || namespaceDeclaration.Name.ToString() != "PInvoke") return; + + var classDeclarations = namespaceDeclaration.Members + .OfType() + .ToArray(); + foreach (var classDeclaration in classDeclarations) + { + var className = classDeclaration.Identifier.Text; + if (className.EndsWith("Mockable") || className.EndsWith("Extensions")) + { + Console.WriteLine($"\tSkipping class {className} because it is a mockable or an extension method."); + continue; + } + + var methodDeclarations = classDeclaration.Members + .OfType() + .Where(a => a.AttributeLists.Any( + b => b.Attributes.Any( + c => c.Name.ToString() == "DllImport")) + && IsPublicStaticExternMethod(a)) + .ToArray(); + if (methodDeclarations.Length <= 0) + { + Console.WriteLine($"\tSkipping class {className} because it has no public static extern methods with DllImport attributes."); + continue; + } + + var newInterfaceModifier = + SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}"); + var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}Mockable"); + + PrepareClassCacheEntry(newClassModifier, classDeclaration, newInterfaceModifier); + PrepareInterfaceCacheEntry(newInterfaceModifier); + + var newClassDeclaration = ClassCache[newClassModifier.Identifier.Text]; + var newInterfaceDeclaration = InterfaceCache[newInterfaceModifier.Identifier.Text]; + + foreach (var methodDeclaration in methodDeclarations) + { + var invokeMethodIdentifier = + SyntaxFactory.IdentifierName($"{methodDeclaration.Identifier.Text}"); + + newClassDeclaration = DecorateClassWithWrapperFunction( + methodDeclaration, + invokeMethodIdentifier, + newClassDeclaration); + ClassCache[newClassModifier.Identifier.Text] = newClassDeclaration; + + newInterfaceDeclaration = DecorateInterfaceWithWrapperFunction( + methodDeclaration, + invokeMethodIdentifier, + newInterfaceDeclaration); + InterfaceCache[newInterfaceModifier.Identifier.Text] = newInterfaceDeclaration; + + string fileDirectory; + var baseFileName = GetBaseFileName(document.FilePath, out fileDirectory); + + var usings = new[] + { + SyntaxFactory.UsingDirective( + SyntaxFactory.Token(SyntaxKind.StaticKeyword) + .WithLeadingTrivia(WhitespaceCharacter), + null, + SyntaxFactory.IdentifierName(classDeclaration.Identifier + .WithLeadingTrivia() + .WithTrailingTrivia()) + .WithLeadingTrivia(WhitespaceCharacter)) + .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter) + }; + + AddPathToProject(ref solution, ref project, $"{baseFileName}Mockable.cs", + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) + .AddMembers(newClassDeclaration) + .ToFullString()); + AddPathToProject(ref solution, ref project, $"I{baseFileName}.cs", + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) + .AddMembers(newInterfaceDeclaration) + .ToFullString()); + } + } + } + } + + private static Document GetExistingDocument(Project project, string path) + { + return project.Documents.FirstOrDefault(x => x.Name == Path.GetFileName(path)); + } + + private static void AddPathToProject(ref Solution solution, ref Project project, string fileName, string contents) + { + var document = GetExistingDocument(project, fileName); + if (document != null) + { + project = project.RemoveDocument(document.Id); + solution = project.Solution; + } + + Console.WriteLine($"\t - Adding {fileName} to project"); + document = project.AddDocument(fileName, + contents, + null, + Path.Combine(Path.GetDirectoryName(project.FilePath), fileName)); + project = document.Project; + solution = project.Solution; + } + + private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) + { + if (!InterfaceCache.ContainsKey(newInterfaceModifier.Identifier.Text)) + { + InterfaceCache.Add(newInterfaceModifier.Identifier.Text, + SyntaxFactory.InterfaceDeclaration( + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + }), + SyntaxFactory.TokenList( + SyntaxFactory + .Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + newInterfaceModifier + .Identifier + .WithTrailingTrivia(WhitespaceCharacter) + .WithLeadingTrivia(WhitespaceCharacter), + null, + null, + SyntaxFactory.List(), + SyntaxFactory.List()) + .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter)); + } + } + + private static void PrepareClassCacheEntry(IdentifierNameSyntax newClassModifier, + ClassDeclarationSyntax classDeclaration, + IdentifierNameSyntax newInterfaceModifier) + { + if (!ClassCache.ContainsKey(newClassModifier.Identifier.Text)) + { + var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); + ClassCache.Add(newClassModifier.Identifier.Text, + SyntaxFactory.ClassDeclaration( + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + }), + SyntaxFactory.TokenList(), + newClassModifier.Identifier + .WithTrailingTrivia(WhitespaceCharacter) + .WithLeadingTrivia(WhitespaceCharacter), + null, + baseList.AddTypes( + SyntaxFactory.SimpleBaseType( + newInterfaceModifier + .WithLeadingTrivia(WhitespaceCharacter) + .WithTrailingTrivia(WhitespaceCharacter))), + SyntaxFactory.List(), + SyntaxFactory.List()) + .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter)); + } + } + + private static NamespaceDeclarationSyntax CreateNewEmptyNamespaceDeclaration( + NamespaceDeclarationSyntax namespaceDeclaration, + IEnumerable usings = null) + { + var namespaceUsings = namespaceDeclaration.Usings; + if (usings != null) + { + namespaceUsings = namespaceUsings.AddRange(usings); + } + + var newNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( + namespaceDeclaration.NamespaceKeyword, + namespaceDeclaration.Name, + namespaceDeclaration.OpenBraceToken, + namespaceDeclaration.Externs, + namespaceUsings, + SyntaxFactory.List(), + namespaceDeclaration.CloseBraceToken, + namespaceDeclaration.SemicolonToken); + return newNamespaceDeclaration; + } + + private static bool IsPublicStaticExternMethod(MethodDeclarationSyntax methodDeclaration) + { + var externMethodKeyword = methodDeclaration.Modifiers + .SingleOrDefault(x => x.IsKind(SyntaxKind.ExternKeyword)); + var staticMethodKeyword = methodDeclaration.Modifiers + .SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); + var publicMethodKeyword = methodDeclaration.Modifiers + .SingleOrDefault(x => x.IsKind(SyntaxKind.PublicKeyword)); + return externMethodKeyword != default(SyntaxToken) && staticMethodKeyword != default(SyntaxToken) && publicMethodKeyword != default(SyntaxToken); + } + + private static string GetBaseFileName(string file, out string fileDirectory) + { + var baseFileName = Path.GetFileNameWithoutExtension(file); + + fileDirectory = Path.GetDirectoryName(file); + Debug.Assert(fileDirectory != null, "fileDirectory != null"); + return baseFileName; + } + + private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( + MethodDeclarationSyntax methodDeclaration, + IdentifierNameSyntax invokeMethodIdentifier, + InterfaceDeclarationSyntax interfaceDeclaration) + { + if (interfaceDeclaration.Members + .OfType() + .Any(x => x.Identifier.Text == invokeMethodIdentifier.Identifier.Text)) + { + return interfaceDeclaration; + } + + var dllImport = methodDeclaration.AttributeLists + .First(x => x.OpenBracketToken.HasLeadingTrivia); + var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + }), + GetModifiersForWrapperFunction(methodDeclaration), + methodDeclaration.ReturnType, + default(ExplicitInterfaceSpecifierSyntax), + invokeMethodIdentifier.Identifier, + methodDeclaration.TypeParameterList, + methodDeclaration.ParameterList, + methodDeclaration.ConstraintClauses, + default(BlockSyntax), + SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + + interfaceDeclaration = interfaceDeclaration + .AddMembers( + interfaceMethodDeclaration + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + .WithLeadingTrivia(dllImport.OpenBracketToken.LeadingTrivia)); + return interfaceDeclaration; + } + + private static SyntaxTokenList GetModifiersForWrapperFunction(MethodDeclarationSyntax methodDeclaration) + { + var unsafeModifier = methodDeclaration.Modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.UnsafeKeyword)); + + var modifiers = SyntaxFactory.TokenList(); + if (unsafeModifier != default(SyntaxToken)) + { + modifiers = modifiers.Add(unsafeModifier); + } + return modifiers; + } + + private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDeclarationSyntax methodDeclaration, + IdentifierNameSyntax invokeMethodIdentifier, + ClassDeclarationSyntax classDeclaration) + { + if (classDeclaration.Members + .OfType() + .Any(x => x.Identifier.Text == invokeMethodIdentifier.Identifier.Text)) + { + return classDeclaration; + } + + var dllImport = methodDeclaration.AttributeLists + .First(x => x.OpenBracketToken.HasLeadingTrivia); + var arguments = methodDeclaration.ParameterList + .Parameters + .Select((x, i) => + { + var identifierName = SyntaxFactory.Argument( + null, + x.Modifiers + .FirstOrDefault(z => z.IsKind(SyntaxKind.RefKeyword) || z.IsKind(SyntaxKind.OutKeyword)) + .WithLeadingTrivia(), + SyntaxFactory.IdentifierName(x.Identifier)); + if (i > 0) + { + identifierName = identifierName.WithLeadingTrivia(WhitespaceCharacter); + } + + return identifierName; + }); + + var arrowBody = SyntaxFactory.ArrowExpressionClause( + SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken) + .WithLeadingTrivia( + NewLineCharacter, + TabCharacter, + TabCharacter, + TabCharacter) + .WithTrailingTrivia(WhitespaceCharacter), + SyntaxFactory.InvocationExpression( + SyntaxFactory.IdentifierName(methodDeclaration.Identifier), + SyntaxFactory.ArgumentList( + SyntaxFactory.SeparatedList(arguments)))); + + var wrapperMethodDeclaration = SyntaxFactory.MethodDeclaration( + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter, + TabCharacter) + }), + GetModifiersForWrapperFunction(methodDeclaration) + .Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + methodDeclaration.ReturnType, + default(ExplicitInterfaceSpecifierSyntax), + invokeMethodIdentifier.Identifier, + methodDeclaration.TypeParameterList, + methodDeclaration.ParameterList, + methodDeclaration.ConstraintClauses, + default(BlockSyntax), + arrowBody, + SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + + classDeclaration = classDeclaration + .AddMembers( + wrapperMethodDeclaration + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + .WithLeadingTrivia(dllImport.OpenBracketToken.LeadingTrivia)); + return classDeclaration; + } + + private static AttributeListSyntax GetCompilerGeneratedAttribute() + { + return SyntaxFactory.AttributeList( + SyntaxFactory.SeparatedList(new[] { + SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("System.Runtime.CompilerServices.CompilerGenerated")) + })); + } + } +} diff --git a/src/MockGenerator/Properties/AssemblyInfo.cs b/src/MockGenerator/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..595a9fbb --- /dev/null +++ b/src/MockGenerator/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MockGenerator")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MockGenerator")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4fca4d69-3e4f-43f1-b93b-05920b88a116")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/MockGenerator/packages.config b/src/MockGenerator/packages.config new file mode 100644 index 00000000..621ff548 --- /dev/null +++ b/src/MockGenerator/packages.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/NCrypt/INCrypt.cs b/src/NCrypt/INCrypt.cs new file mode 100644 index 00000000..1ade8118 --- /dev/null +++ b/src/NCrypt/INCrypt.cs @@ -0,0 +1,125 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static NCrypt; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface INCrypt { /// + /// Loads and initializes a CNG key storage provider. + /// + /// + /// A pointer to a variable that receives the provider handle. When you have finished using this handle, release it by passing it to the function. + /// + /// + /// A pointer to a null-terminated Unicode string that identifies the key storage provider to load. This is the registered alias of the key storage provider. This parameter is optional and can be NULL. If this parameter is NULL, the default key storage provider is loaded. The class identifies the built-in key storage providers. + /// + /// Flags that modify the behavior of the function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS NCryptOpenStorageProvider( + out SafeProviderHandle phProvider, + string pszProviderName, + NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None); + + /// + /// Creates a new key and stores it in the specified key storage provider. After you create a key by using this function, you can use the NCryptSetProperty function to set its properties; however, the key cannot be used until the NCryptFinalizeKey function is called. + /// + /// + /// The handle of the key storage provider to create the key in. This handle is obtained by using the function. + /// + /// + /// The address of an variable that receives the handle of the key. When you have finished using this handle, release it by disposing it. + /// + /// + /// A null-terminated Unicode string that contains the identifier of the cryptographic algorithm to create the key. This can be one of the standard CNG Algorithm Identifiers defined in or the identifier for another registered algorithm. + /// + /// + /// A pointer to a null-terminated Unicode string that contains the name of the key. If this parameter is NULL, this function will create an ephemeral key that is not persisted. + /// + /// + /// A legacy identifier that specifies the type of key. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS NCryptCreatePersistedKey( + SafeProviderHandle hProvider, + out SafeKeyHandle phKey, + string pszAlgId, + string pszKeyName = null, + LegacyKeySpec dwLegacyKeySpec = LegacyKeySpec.None, + NCryptCreatePersistedKeyFlags dwFlags = NCryptCreatePersistedKeyFlags.None); + + /// + /// Completes a CNG key storage key. The key cannot be used until this function has been called. + /// + /// + /// The handle of the key to complete. This handle is obtained by calling the function. + /// + /// + /// Flags that modify function behavior. + /// + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS NCryptFinalizeKey( + SafeKeyHandle hKey, + NCryptFinalizeKeyFlags dwFlags = NCryptFinalizeKeyFlags.None); + + /// + /// Retrieves the value of a named property for a key storage object. + /// + /// + /// The handle of the object to get the property for. This can be a provider handle () or a key handle (). + /// + /// + /// A pointer to a null-terminated Unicode string that contains the name of the property to retrieve. This can be one of the predefined or a custom property identifier. + /// + /// + /// The address of a buffer that receives the property value. The parameter contains the size of this buffer. + /// To calculate the size required for the buffer, set this parameter to NULL. The size, in bytes, required is returned in the location pointed to by the parameter. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// + /// A pointer to a DWORD variable that receives the number of bytes that were copied to the buffer. + /// If the parameter is NULL, the size, in bytes, required for the buffer is placed in the location pointed to by this parameter. + /// + /// Flags that modify function behavior. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS NCryptGetProperty( + SafeHandle hObject, + string pszProperty, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + NCryptGetPropertyFlags dwFlags); + + /// + /// Sets the value for a named property for a CNG key storage object. + /// + /// The handle of the key storage object to set the property for. + /// + /// A pointer to a null-terminated Unicode string that contains the name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// + /// The address of a buffer that contains the new property value. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// Flags that modify function behavior. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS NCryptSetProperty( + SafeHandle hObject, + string pszProperty, + byte[] pbInput, + int cbInput, + NCryptSetPropertyFlags dwFlags); + } +} diff --git a/src/NCrypt/NCrypt.csproj b/src/NCrypt/NCrypt.csproj index 02126362..381dffb7 100644 --- a/src/NCrypt/NCrypt.csproj +++ b/src/NCrypt/NCrypt.csproj @@ -23,6 +23,7 @@ + @@ -37,6 +38,7 @@ + diff --git a/src/NCrypt/NCryptMockable.cs b/src/NCrypt/NCryptMockable.cs new file mode 100644 index 00000000..512a0fef --- /dev/null +++ b/src/NCrypt/NCryptMockable.cs @@ -0,0 +1,130 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static NCrypt; + [System.Runtime.CompilerServices.CompilerGenerated] + class NCryptMockable : INCrypt { /// + /// Loads and initializes a CNG key storage provider. + /// + /// + /// A pointer to a variable that receives the provider handle. When you have finished using this handle, release it by passing it to the function. + /// + /// + /// A pointer to a null-terminated Unicode string that identifies the key storage provider to load. This is the registered alias of the key storage provider. This parameter is optional and can be NULL. If this parameter is NULL, the default key storage provider is loaded. The class identifies the built-in key storage providers. + /// + /// Flags that modify the behavior of the function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS NCryptOpenStorageProvider( + out SafeProviderHandle phProvider, + string pszProviderName, + NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None) + => NCryptOpenStorageProvider(out phProvider, pszProviderName, dwFlags ); + + /// + /// Creates a new key and stores it in the specified key storage provider. After you create a key by using this function, you can use the NCryptSetProperty function to set its properties; however, the key cannot be used until the NCryptFinalizeKey function is called. + /// + /// + /// The handle of the key storage provider to create the key in. This handle is obtained by using the function. + /// + /// + /// The address of an variable that receives the handle of the key. When you have finished using this handle, release it by disposing it. + /// + /// + /// A null-terminated Unicode string that contains the identifier of the cryptographic algorithm to create the key. This can be one of the standard CNG Algorithm Identifiers defined in or the identifier for another registered algorithm. + /// + /// + /// A pointer to a null-terminated Unicode string that contains the name of the key. If this parameter is NULL, this function will create an ephemeral key that is not persisted. + /// + /// + /// A legacy identifier that specifies the type of key. + /// + /// A set of flags that modify the behavior of this function. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS NCryptCreatePersistedKey( + SafeProviderHandle hProvider, + out SafeKeyHandle phKey, + string pszAlgId, + string pszKeyName = null, + LegacyKeySpec dwLegacyKeySpec = LegacyKeySpec.None, + NCryptCreatePersistedKeyFlags dwFlags = NCryptCreatePersistedKeyFlags.None) + => NCryptCreatePersistedKey(hProvider, out phKey, pszAlgId, pszKeyName , dwLegacyKeySpec , dwFlags ); + + /// + /// Completes a CNG key storage key. The key cannot be used until this function has been called. + /// + /// + /// The handle of the key to complete. This handle is obtained by calling the function. + /// + /// + /// Flags that modify function behavior. + /// + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS NCryptFinalizeKey( + SafeKeyHandle hKey, + NCryptFinalizeKeyFlags dwFlags = NCryptFinalizeKeyFlags.None) + => NCryptFinalizeKey(hKey, dwFlags ); + + /// + /// Retrieves the value of a named property for a key storage object. + /// + /// + /// The handle of the object to get the property for. This can be a provider handle () or a key handle (). + /// + /// + /// A pointer to a null-terminated Unicode string that contains the name of the property to retrieve. This can be one of the predefined or a custom property identifier. + /// + /// + /// The address of a buffer that receives the property value. The parameter contains the size of this buffer. + /// To calculate the size required for the buffer, set this parameter to NULL. The size, in bytes, required is returned in the location pointed to by the parameter. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// + /// A pointer to a DWORD variable that receives the number of bytes that were copied to the buffer. + /// If the parameter is NULL, the size, in bytes, required for the buffer is placed in the location pointed to by this parameter. + /// + /// Flags that modify function behavior. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS NCryptGetProperty( + SafeHandle hObject, + string pszProperty, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + NCryptGetPropertyFlags dwFlags) + => NCryptGetProperty(hObject, pszProperty, pbOutput, cbOutput, out pcbResult, dwFlags); + + /// + /// Sets the value for a named property for a CNG key storage object. + /// + /// The handle of the key storage object to set the property for. + /// + /// A pointer to a null-terminated Unicode string that contains the name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// + /// The address of a buffer that contains the new property value. The parameter contains the size of this buffer. + /// + /// + /// The size, in bytes, of the buffer. + /// + /// Flags that modify function behavior. + /// Returns a status code that indicates the success or failure of the function. + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS NCryptSetProperty( + SafeHandle hObject, + string pszProperty, + byte[] pbInput, + int cbInput, + NCryptSetPropertyFlags dwFlags) + => NCryptSetProperty(hObject, pszProperty, pbInput, cbInput, dwFlags); + } +} diff --git a/src/PInvoke.sln b/src/PInvoke.sln index a6293b50..bee3552f 100644 --- a/src/PInvoke.sln +++ b/src/PInvoke.sln @@ -100,6 +100,10 @@ Project("{FF286327-C783-4F7A-AB73-9BCBAD0D4460}") = "DbgHelp.NuGet", "DbgHelp.Nu EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbgHelp.Tests", "DbgHelp.Tests\DbgHelp.Tests.csproj", "{9EC79974-4353-411E-A04F-598474D9CE58}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{0D9ABEF6-1EC7-4E6B-A9A2-377D8E892332}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MockGenerator", "MockGenerator\MockGenerator.csproj", "{4FCA4D69-3E4F-43F1-B93B-05920B88A116}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution Kernel32.Tests.Shared\Kernel32.Tests.Shared.projitems*{f37b9b20-0d43-49db-bf85-519a525c64d8}*SharedItemsImports = 13 @@ -253,8 +257,15 @@ Global {9EC79974-4353-411E-A04F-598474D9CE58}.Debug|Any CPU.Build.0 = Debug|Any CPU {9EC79974-4353-411E-A04F-598474D9CE58}.Release|Any CPU.ActiveCfg = Release|Any CPU {9EC79974-4353-411E-A04F-598474D9CE58}.Release|Any CPU.Build.0 = Release|Any CPU + {4FCA4D69-3E4F-43F1-B93B-05920B88A116}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4FCA4D69-3E4F-43F1-B93B-05920B88A116}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4FCA4D69-3E4F-43F1-B93B-05920B88A116}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4FCA4D69-3E4F-43F1-B93B-05920B88A116}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {4FCA4D69-3E4F-43F1-B93B-05920B88A116} = {0D9ABEF6-1EC7-4E6B-A9A2-377D8E892332} + EndGlobalSection EndGlobal diff --git a/src/SetupApi.Desktop/ISetupApi.cs b/src/SetupApi.Desktop/ISetupApi.cs new file mode 100644 index 00000000..70cfff1d --- /dev/null +++ b/src/SetupApi.Desktop/ISetupApi.cs @@ -0,0 +1,176 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static SetupApi; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface ISetupApi { /// + /// The SetupDiGetClassDevs function returns a handle to a device information set + /// that contains requested device information elements for a local computer. + /// + /// + /// A pointer to the GUID for a device setup class or a device interface class. This pointer is + /// optional and can be . For more information about how to set ClassGuid, see the following Remarks + /// section. + /// + /// + /// A pointer to a NULL-terminated string that specifies: + /// + /// + /// + /// An identifier(ID) of a Plug and Play(PnP) enumerator.This ID can either be the value's globally + /// unique identifier (GUID) or symbolic name. For example, "PCI" can be used to specify the PCI PnP value. Other + /// examples of symbolic names for PnP values include "USB," "PCMCIA," and "SCSI". + /// + /// + /// + /// + /// A PnP device instance ID.When specifying a PnP device instance ID, DIGCF_DEVICEINTERFACE must be + /// set in the Flags parameter. + /// + /// + /// + /// This pointer is optional and can be .If an enumeration value is not used to select devices, set + /// Enumerator to . + /// + /// + /// A handle to the top-level window to be used for a user interface that is associated with + /// installing a device instance in the device information set. This handle is optional and can be . + /// + /// + /// A variable of type DWORD that specifies control options that filter the device information elements + /// that are added to the device information set. This parameter can be a bitwise OR of zero or more of the flags. + /// + /// + /// If the operation succeeds, SetupDiGetClassDevs returns a handle to a device information set that contains all + /// installed devices that matched the supplied parameters. If the operation fails, the function returns an invalid handle. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + SafeDeviceInfoSetHandle SetupDiGetClassDevs( + NullableGuid classGuid, + string enumerator, + IntPtr hwndParent, + GetClassDevsFlags flags); + + /// + /// Enumerates the device interfaces that are contained in a device information set. + /// + /// + /// A pointer to a device information set that contains the device interfaces for which to + /// return information. This handle is typically returned by . + /// + /// + /// A pointer to an structure that specifies a device + /// information element in DeviceInfoSet. This parameter is optional and can be . If this parameter + /// is specified, SetupDiEnumDeviceInterfaces constrains the enumeration to the interfaces that are supported by the + /// specified device. If this parameter is , repeated calls to SetupDiEnumDeviceInterfaces return + /// information about the interfaces that are associated with all the device information elements in DeviceInfoSet. This + /// pointer is typically returned by . + /// + /// + /// A pointer to a that specifies the device interface class for the + /// requested interface. + /// + /// + /// A zero-based index into the list of interfaces in the device information set. The caller + /// should call this function first with MemberIndex set to zero to obtain the first interface. Then, repeatedly increment + /// MemberIndex and retrieve an interface until this function fails and returns + /// . + /// + /// + /// A pointer to a caller-allocated buffer that contains, on successful return, a + /// completed structure that identifies an interface that meets the search parameters. + /// The caller + /// must set before calling this function either manually or via + /// . + /// + /// + /// Returns if the function completed without error. If the function completed with an + /// error, is returned and the error code for the failure can be retrieved by calling + /// . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool SetupDiEnumDeviceInterfaces( + SafeDeviceInfoSetHandle deviceInfoSet, + DeviceInfoData deviceInfoData, + ref Guid interfaceClassGuid, + uint memberIndex, + ref DeviceInterfaceData deviceInterfaceData); + + /// + /// Returns details about a device interface. + /// + /// + /// A pointer to a device information set that contains the device interfaces for which to + /// return information. This handle is typically returned by . + /// + /// + /// A pointer to an structure that specifies the + /// interface in DeviceInfoSet for which to retrieve details. A pointer of this type is typically returned by + /// . + /// + /// + /// A pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA structure to receive + /// information about the specified interface. This parameter is optional and can be . This + /// parameter must be if is zero. If this parameter is specified, the + /// caller must set .cbSize to sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) before calling this + /// function. The cbSize member always contains the size of the fixed part of the data structure, not a size reflecting the + /// variable-length string at the end. + /// + /// + /// The size of the buffer. + /// This parameter must be zero if is . + /// + /// + /// A pointer to a variable of type that receives the required size of the + /// DeviceInterfaceDetailData buffer. This size includes the size of the fixed part of the structure plus the number of + /// bytes required for the variable-length device path string. This parameter is optional and can be + /// . + /// + /// + /// A pointer to a buffer that receives information about the device that supports the requested interface. The caller + /// must set before calling this function. + /// This parameter is optional and can be . + /// + /// + /// Returns if the function completed without error. If the function completed with an + /// error, is returned and the error code for the failure can be retrieved by calling + /// . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool SetupDiGetDeviceInterfaceDetail( + SafeDeviceInfoSetHandle deviceInfoSet, + ref DeviceInterfaceData deviceInterfaceData, + IntPtr deviceInterfaceDetailData, + uint deviceInterfaceDetailDataSize, + NullableUInt32 requiredSize, + DeviceInfoData deviceInfoData); + + /// + /// Returns a structure that specifies a device information element in a device information + /// set. + /// + /// + /// A handle to the device information set for which to return an + /// structure that represents a device information element. + /// + /// A zero-based index of the device information element to retrieve. + /// + /// A pointer to an structure to receive information about an enumerated + /// device information element. The caller must set before calling this function. + /// + /// + /// Returns if the function completed without error. If the function completed with an + /// error, is returned and the error code for the failure can be retrieved by calling + /// . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + bool SetupDiEnumDeviceInfo( + SafeDeviceInfoSetHandle deviceInfoSet, + uint memberIndex, + DeviceInfoData deviceInfoData); + } +} \ No newline at end of file diff --git a/src/SetupApi.Desktop/SetupApi.Desktop.csproj b/src/SetupApi.Desktop/SetupApi.Desktop.csproj index fcc8f4f4..1dbedf75 100644 --- a/src/SetupApi.Desktop/SetupApi.Desktop.csproj +++ b/src/SetupApi.Desktop/SetupApi.Desktop.csproj @@ -38,6 +38,7 @@ + @@ -46,6 +47,7 @@ + diff --git a/src/SetupApi.Desktop/SetupApiMockable.cs b/src/SetupApi.Desktop/SetupApiMockable.cs new file mode 100644 index 00000000..f0c3bbf6 --- /dev/null +++ b/src/SetupApi.Desktop/SetupApiMockable.cs @@ -0,0 +1,180 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static SetupApi; + [System.Runtime.CompilerServices.CompilerGenerated] + class SetupApiMockable : ISetupApi { /// + /// The SetupDiGetClassDevs function returns a handle to a device information set + /// that contains requested device information elements for a local computer. + /// + /// + /// A pointer to the GUID for a device setup class or a device interface class. This pointer is + /// optional and can be . For more information about how to set ClassGuid, see the following Remarks + /// section. + /// + /// + /// A pointer to a NULL-terminated string that specifies: + /// + /// + /// + /// An identifier(ID) of a Plug and Play(PnP) enumerator.This ID can either be the value's globally + /// unique identifier (GUID) or symbolic name. For example, "PCI" can be used to specify the PCI PnP value. Other + /// examples of symbolic names for PnP values include "USB," "PCMCIA," and "SCSI". + /// + /// + /// + /// + /// A PnP device instance ID.When specifying a PnP device instance ID, DIGCF_DEVICEINTERFACE must be + /// set in the Flags parameter. + /// + /// + /// + /// This pointer is optional and can be .If an enumeration value is not used to select devices, set + /// Enumerator to . + /// + /// + /// A handle to the top-level window to be used for a user interface that is associated with + /// installing a device instance in the device information set. This handle is optional and can be . + /// + /// + /// A variable of type DWORD that specifies control options that filter the device information elements + /// that are added to the device information set. This parameter can be a bitwise OR of zero or more of the flags. + /// + /// + /// If the operation succeeds, SetupDiGetClassDevs returns a handle to a device information set that contains all + /// installed devices that matched the supplied parameters. If the operation fails, the function returns an invalid handle. + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeDeviceInfoSetHandle SetupDiGetClassDevs( + NullableGuid classGuid, + string enumerator, + IntPtr hwndParent, + GetClassDevsFlags flags) + => SetupDiGetClassDevs(classGuid, enumerator, hwndParent, flags); + + /// + /// Enumerates the device interfaces that are contained in a device information set. + /// + /// + /// A pointer to a device information set that contains the device interfaces for which to + /// return information. This handle is typically returned by . + /// + /// + /// A pointer to an structure that specifies a device + /// information element in DeviceInfoSet. This parameter is optional and can be . If this parameter + /// is specified, SetupDiEnumDeviceInterfaces constrains the enumeration to the interfaces that are supported by the + /// specified device. If this parameter is , repeated calls to SetupDiEnumDeviceInterfaces return + /// information about the interfaces that are associated with all the device information elements in DeviceInfoSet. This + /// pointer is typically returned by . + /// + /// + /// A pointer to a that specifies the device interface class for the + /// requested interface. + /// + /// + /// A zero-based index into the list of interfaces in the device information set. The caller + /// should call this function first with MemberIndex set to zero to obtain the first interface. Then, repeatedly increment + /// MemberIndex and retrieve an interface until this function fails and returns + /// . + /// + /// + /// A pointer to a caller-allocated buffer that contains, on successful return, a + /// completed structure that identifies an interface that meets the search parameters. + /// The caller + /// must set before calling this function either manually or via + /// . + /// + /// + /// Returns if the function completed without error. If the function completed with an + /// error, is returned and the error code for the failure can be retrieved by calling + /// . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool SetupDiEnumDeviceInterfaces( + SafeDeviceInfoSetHandle deviceInfoSet, + DeviceInfoData deviceInfoData, + ref Guid interfaceClassGuid, + uint memberIndex, + ref DeviceInterfaceData deviceInterfaceData) + => SetupDiEnumDeviceInterfaces(deviceInfoSet, deviceInfoData, ref interfaceClassGuid, memberIndex, ref deviceInterfaceData); + + /// + /// Returns details about a device interface. + /// + /// + /// A pointer to a device information set that contains the device interfaces for which to + /// return information. This handle is typically returned by . + /// + /// + /// A pointer to an structure that specifies the + /// interface in DeviceInfoSet for which to retrieve details. A pointer of this type is typically returned by + /// . + /// + /// + /// A pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA structure to receive + /// information about the specified interface. This parameter is optional and can be . This + /// parameter must be if is zero. If this parameter is specified, the + /// caller must set .cbSize to sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) before calling this + /// function. The cbSize member always contains the size of the fixed part of the data structure, not a size reflecting the + /// variable-length string at the end. + /// + /// + /// The size of the buffer. + /// This parameter must be zero if is . + /// + /// + /// A pointer to a variable of type that receives the required size of the + /// DeviceInterfaceDetailData buffer. This size includes the size of the fixed part of the structure plus the number of + /// bytes required for the variable-length device path string. This parameter is optional and can be + /// . + /// + /// + /// A pointer to a buffer that receives information about the device that supports the requested interface. The caller + /// must set before calling this function. + /// This parameter is optional and can be . + /// + /// + /// Returns if the function completed without error. If the function completed with an + /// error, is returned and the error code for the failure can be retrieved by calling + /// . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool SetupDiGetDeviceInterfaceDetail( + SafeDeviceInfoSetHandle deviceInfoSet, + ref DeviceInterfaceData deviceInterfaceData, + IntPtr deviceInterfaceDetailData, + uint deviceInterfaceDetailDataSize, + NullableUInt32 requiredSize, + DeviceInfoData deviceInfoData) + => SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, deviceInterfaceDetailData, deviceInterfaceDetailDataSize, requiredSize, deviceInfoData); + + /// + /// Returns a structure that specifies a device information element in a device information + /// set. + /// + /// + /// A handle to the device information set for which to return an + /// structure that represents a device information element. + /// + /// A zero-based index of the device information element to retrieve. + /// + /// A pointer to an structure to receive information about an enumerated + /// device information element. The caller must set before calling this function. + /// + /// + /// Returns if the function completed without error. If the function completed with an + /// error, is returned and the error code for the failure can be retrieved by calling + /// . + /// + [System.Runtime.CompilerServices.CompilerGenerated] + public bool SetupDiEnumDeviceInfo( + SafeDeviceInfoSetHandle deviceInfoSet, + uint memberIndex, + DeviceInfoData deviceInfoData) + => SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, deviceInfoData); + } +} \ No newline at end of file diff --git a/src/User32.Desktop/IUser32.cs b/src/User32.Desktop/IUser32.cs new file mode 100644 index 00000000..02f1eed8 --- /dev/null +++ b/src/User32.Desktop/IUser32.cs @@ -0,0 +1,45 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static User32; + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IUser32 { [System.Runtime.CompilerServices.CompilerGenerated] + int SetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); + + [System.Runtime.CompilerServices.CompilerGenerated] + int GetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); + + [System.Runtime.CompilerServices.CompilerGenerated] + bool SetWindowPos( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int X, + int Y, + int cx, + int cy, + SetWindowPosFlags uFlags); + + [System.Runtime.CompilerServices.CompilerGenerated] + IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); + + [System.Runtime.CompilerServices.CompilerGenerated] + IntPtr FindWindowEx( + IntPtr parentHandle, + IntPtr childAfter, + string className, + string windowTitle); + + [System.Runtime.CompilerServices.CompilerGenerated] + bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); + + [System.Runtime.CompilerServices.CompilerGenerated] + IntPtr GetForegroundWindow(); + + [System.Runtime.CompilerServices.CompilerGenerated] + int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); + } +} diff --git a/src/User32.Desktop/User32.Desktop.csproj b/src/User32.Desktop/User32.Desktop.csproj index ade71ad1..832d115a 100644 --- a/src/User32.Desktop/User32.Desktop.csproj +++ b/src/User32.Desktop/User32.Desktop.csproj @@ -21,6 +21,7 @@ + @@ -28,6 +29,7 @@ + diff --git a/src/User32.Desktop/User32Mockable.cs b/src/User32.Desktop/User32Mockable.cs new file mode 100644 index 00000000..cedf25b4 --- /dev/null +++ b/src/User32.Desktop/User32Mockable.cs @@ -0,0 +1,53 @@ +// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. + +namespace PInvoke +{ + using System; + using System.Runtime.InteropServices; + using static User32; + [System.Runtime.CompilerServices.CompilerGenerated] + class User32Mockable : IUser32 { [System.Runtime.CompilerServices.CompilerGenerated] + public int SetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) + => SetWindowLong(hWnd, nIndex, dwNewLong); + + [System.Runtime.CompilerServices.CompilerGenerated] + public int GetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) + => GetWindowLong(hWnd, nIndex); + + [System.Runtime.CompilerServices.CompilerGenerated] + public bool SetWindowPos( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int X, + int Y, + int cx, + int cy, + SetWindowPosFlags uFlags) + => SetWindowPos(hWnd, hWndInsertAfter, X, Y, cx, cy, uFlags); + + [System.Runtime.CompilerServices.CompilerGenerated] + public IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent) + => SetParent(hWndChild, hWndNewParent); + + [System.Runtime.CompilerServices.CompilerGenerated] + public IntPtr FindWindowEx( + IntPtr parentHandle, + IntPtr childAfter, + string className, + string windowTitle) + => FindWindowEx(parentHandle, childAfter, className, windowTitle); + + [System.Runtime.CompilerServices.CompilerGenerated] + public bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) + => ShowWindow(hWnd, nCmdShow); + + [System.Runtime.CompilerServices.CompilerGenerated] + public IntPtr GetForegroundWindow() + => GetForegroundWindow(); + + [System.Runtime.CompilerServices.CompilerGenerated] + public int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) + => SendMessage(hWnd, wMsg, wParam, lParam); + } +}