From 39fc4fc0656b576a9129274b43c2a913e6c9f248 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Mon, 16 Nov 2015 19:17:26 +0100 Subject: [PATCH 01/46] first step towards automatic code generation of mockables. --- src/AdvApi32.Desktop/AdvApi32.cs | 2 +- src/MockGenerator/App.config | 6 ++ src/MockGenerator/MockGenerator.csproj | 83 ++++++++++++++++++++ src/MockGenerator/Program.cs | 79 +++++++++++++++++++ src/MockGenerator/Properties/AssemblyInfo.cs | 36 +++++++++ src/MockGenerator/packages.config | 8 ++ src/PInvoke.sln | 11 +++ 7 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 src/MockGenerator/App.config create mode 100644 src/MockGenerator/MockGenerator.csproj create mode 100644 src/MockGenerator/Program.cs create mode 100644 src/MockGenerator/Properties/AssemblyInfo.cs create mode 100644 src/MockGenerator/packages.config diff --git a/src/AdvApi32.Desktop/AdvApi32.cs b/src/AdvApi32.Desktop/AdvApi32.cs index 55b17ecd..59fc0d44 100644 --- a/src/AdvApi32.Desktop/AdvApi32.cs +++ b/src/AdvApi32.Desktop/AdvApi32.cs @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the AdvApi32.dll Windows library /// that are available to Desktop apps only. /// - public static partial class AdvApi32 + public static partial class AdvApi32 : IFoobar { /// /// Used to prefix group names so that they can be distinguished from a service name, 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..9cffa6b8 --- /dev/null +++ b/src/MockGenerator/MockGenerator.csproj @@ -0,0 +1,83 @@ + + + + + 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 + + + + ..\..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.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..4b68f936 --- /dev/null +++ b/src/MockGenerator/Program.cs @@ -0,0 +1,79 @@ +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 Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.CSharp.Syntax; + + class Program + { + static void Main(string[] args) + { + var currentDirectory = Environment.CurrentDirectory; + + var solutionRoot = Path.Combine(currentDirectory, "..", "..", ".."); + foreach (var file in Directory.GetFiles(solutionRoot, "*.cs", SearchOption.AllDirectories)) + { + ProcessSourceCodes(file); + } + } + + private static void ProcessSourceCodes(string file) + { + var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(file)); + + var compilationUnit = syntaxTree.GetRoot() 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(); + for (var index = 0; index < classDeclarations.Length; index++) + { + var classDeclaration = classDeclarations[index]; + + var modifiers = classDeclaration.Modifiers; + var staticKeyword = modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); + if (staticKeyword != default(SyntaxToken)) + { + modifiers.Remove(staticKeyword); + } + + var interfaceName = SyntaxFactory + .IdentifierName($"I{classDeclaration.Identifier.Text}Mockable") + .WithLeadingTrivia(SyntaxFactory.Whitespace(" ")) + .WithTrailingTrivia(SyntaxFactory.Whitespace(" ")); + + var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); + baseList = baseList.AddTypes( + SyntaxFactory.SimpleBaseType(interfaceName)); + + var newClassDeclaration = SyntaxFactory.ClassDeclaration( + classDeclaration.AttributeLists, + modifiers, + classDeclaration.Identifier, + classDeclaration.TypeParameterList, + baseList, + classDeclaration.ConstraintClauses, + classDeclaration.Members); + compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); + classDeclaration = newClassDeclaration; + + + } + } + } + } +} 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..fa91bc8a --- /dev/null +++ b/src/MockGenerator/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file 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 From 37995f02e4513dbba0c3d45ebe3b3f81b7a9e92c Mon Sep 17 00:00:00 2001 From: ffMathy Date: Mon, 16 Nov 2015 21:17:28 +0100 Subject: [PATCH 02/46] new changes to generation. --- src/MockGenerator/Program.cs | 135 +++++++++++++++++++++++++++++++++-- 1 file changed, 130 insertions(+), 5 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 4b68f936..51b0f023 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -14,6 +14,9 @@ namespace MockGenerator class Program { + static readonly SyntaxTrivia WhitespaceCharacter = SyntaxFactory.Whitespace(" "); + static readonly SyntaxTrivia NewLineCharacter = SyntaxFactory.Whitespace("\n"); + static void Main(string[] args) { var currentDirectory = Environment.CurrentDirectory; @@ -51,14 +54,14 @@ private static void ProcessSourceCodes(string file) modifiers.Remove(staticKeyword); } - var interfaceName = SyntaxFactory - .IdentifierName($"I{classDeclaration.Identifier.Text}Mockable") - .WithLeadingTrivia(SyntaxFactory.Whitespace(" ")) - .WithTrailingTrivia(SyntaxFactory.Whitespace(" ")); + var interfaceIdentifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); baseList = baseList.AddTypes( - SyntaxFactory.SimpleBaseType(interfaceName)); + SyntaxFactory.SimpleBaseType( + interfaceIdentifier + .WithLeadingTrivia(WhitespaceCharacter) + .WithTrailingTrivia(WhitespaceCharacter))); var newClassDeclaration = SyntaxFactory.ClassDeclaration( classDeclaration.AttributeLists, @@ -71,9 +74,131 @@ private static void ProcessSourceCodes(string file) compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); classDeclaration = newClassDeclaration; + var interfaceDeclaration = SyntaxFactory.InterfaceDeclaration( + SyntaxFactory.List(), + SyntaxFactory.TokenList( + SyntaxFactory + .Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + interfaceIdentifier + .Identifier + .WithTrailingTrivia(WhitespaceCharacter) + .WithLeadingTrivia(WhitespaceCharacter), + null, + null, + SyntaxFactory.List(), + SyntaxFactory.List()); + + var methodDeclarations = classDeclaration.Members + .OfType() + .ToArray(); + for (int i = 0; i < methodDeclarations.Length; i++) + { + var methodDeclaration = methodDeclarations[i]; + var externMethodKeyword = methodDeclaration.Modifiers + .SingleOrDefault(x => x.IsKind(SyntaxKind.ExternKeyword)); + var staticMethodKeyword = methodDeclaration.Modifiers + .SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); + if (externMethodKeyword == default(SyntaxToken) || staticMethodKeyword == default(SyntaxToken)) + { + continue; + } + + var invokeMethodIdentifier = + SyntaxFactory.IdentifierName($"Invoke{methodDeclaration.Identifier.Text}"); + + classDeclaration = DecorateClassWithWrapperFunction(methodDeclaration, invokeMethodIdentifier, classDeclaration); + + interfaceDeclaration = DecorateInterfaceWithWrapperFunction(methodDeclaration, invokeMethodIdentifier, interfaceDeclaration); + } + if (interfaceDeclaration.Members.Count > 0) + { + WriteInterfaceToFile(file, interfaceDeclaration); + } + if (classDeclaration.Members.Count > 0) + { + File.WriteAllText( + file, + classDeclaration.ToFullString()); + } } } } + + private static void WriteInterfaceToFile(string file, InterfaceDeclarationSyntax interfaceDeclaration) + { + var baseFileName = Path.GetFileNameWithoutExtension(file); + + var fileDirectory = Path.GetDirectoryName(file); + Debug.Assert(fileDirectory != null, "fileDirectory != null"); + + File.WriteAllText( + Path.Combine( + fileDirectory, + $"I{baseFileName}Mockable.cs"), + interfaceDeclaration.ToFullString()); + } + + private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( + MethodDeclarationSyntax methodDeclaration, + IdentifierNameSyntax invokeMethodIdentifier, + InterfaceDeclarationSyntax interfaceDeclaration) + { + var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( + SyntaxFactory.List(), + SyntaxFactory.TokenList(), + methodDeclaration.ReturnType, + default(ExplicitInterfaceSpecifierSyntax), + invokeMethodIdentifier.Identifier, + methodDeclaration.TypeParameterList, + methodDeclaration.ParameterList, + methodDeclaration.ConstraintClauses, + default(BlockSyntax), + SyntaxFactory.Token(SyntaxKind.SemicolonToken)); + + interfaceDeclaration = interfaceDeclaration + .AddMembers( + interfaceMethodDeclaration + .WithTrailingTrivia(NewLineCharacter) + .WithLeadingTrivia(NewLineCharacter)); + return interfaceDeclaration; + } + + private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDeclarationSyntax methodDeclaration, + IdentifierNameSyntax invokeMethodIdentifier, + ClassDeclarationSyntax classDeclaration) + { + var arguments = methodDeclaration.ParameterList + .Parameters + .Select(x => SyntaxFactory.Argument( + SyntaxFactory.IdentifierName(x.Identifier))); + + var arrowBody = SyntaxFactory.ArrowExpressionClause( + SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken), + SyntaxFactory.InvocationExpression( + SyntaxFactory.IdentifierName(methodDeclaration.Identifier), + SyntaxFactory.ArgumentList( + SyntaxFactory.SeparatedList(arguments)))); + + var wrapperMethodDeclaration = SyntaxFactory.MethodDeclaration( + SyntaxFactory.List(), + SyntaxFactory.TokenList(), + methodDeclaration.ReturnType, + default(ExplicitInterfaceSpecifierSyntax), + invokeMethodIdentifier.Identifier, + methodDeclaration.TypeParameterList, + methodDeclaration.ParameterList, + methodDeclaration.ConstraintClauses, + default(BlockSyntax), + arrowBody); + + classDeclaration = classDeclaration + .AddMembers( + wrapperMethodDeclaration + .WithTrailingTrivia(NewLineCharacter) + .WithLeadingTrivia(NewLineCharacter)); + return classDeclaration; + } } } From fc7df65632a488ba5ffe8bbea8165f6b7be0f696 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Mon, 16 Nov 2015 21:18:43 +0100 Subject: [PATCH 03/46] changed back faulty class. --- src/AdvApi32.Desktop/AdvApi32.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AdvApi32.Desktop/AdvApi32.cs b/src/AdvApi32.Desktop/AdvApi32.cs index 59fc0d44..55b17ecd 100644 --- a/src/AdvApi32.Desktop/AdvApi32.cs +++ b/src/AdvApi32.Desktop/AdvApi32.cs @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the AdvApi32.dll Windows library /// that are available to Desktop apps only. /// - public static partial class AdvApi32 : IFoobar + public static partial class AdvApi32 { /// /// Used to prefix group names so that they can be distinguished from a service name, From 82598fbf1d930cf6b95f7486f3600a99914ae801 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Mon, 16 Nov 2015 21:21:22 +0100 Subject: [PATCH 04/46] better generation. --- src/MockGenerator/Program.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 51b0f023..7119520f 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -51,7 +51,7 @@ private static void ProcessSourceCodes(string file) var staticKeyword = modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); if (staticKeyword != default(SyntaxToken)) { - modifiers.Remove(staticKeyword); + modifiers = modifiers.Remove(staticKeyword); } var interfaceIdentifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); @@ -66,7 +66,8 @@ private static void ProcessSourceCodes(string file) var newClassDeclaration = SyntaxFactory.ClassDeclaration( classDeclaration.AttributeLists, modifiers, - classDeclaration.Identifier, + classDeclaration.Identifier + .WithLeadingTrivia(WhitespaceCharacter), classDeclaration.TypeParameterList, baseList, classDeclaration.ConstraintClauses, From a2e1110b7040e72540b7859ee54338d7aa394541 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:10:36 +0100 Subject: [PATCH 05/46] further changes to generation by wrapping interface declarations in namespace. --- src/MockGenerator/Program.cs | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 7119520f..508460f3 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -36,11 +36,11 @@ private static void ProcessSourceCodes(string file) if (compilationUnit == null || compilationUnit.Members.Count == 0) return; var namespaceDeclarations = compilationUnit.Members.OfType(); - foreach (var namespaceDeclaration in namespaceDeclarations) + foreach (var classNamespaceDeclaration in namespaceDeclarations) { - if (namespaceDeclaration == null || namespaceDeclaration.Name.ToString() != "PInvoke") return; + if (classNamespaceDeclaration == null || classNamespaceDeclaration.Name.ToString() != "PInvoke") return; - var classDeclarations = namespaceDeclaration.Members + var classDeclarations = classNamespaceDeclaration.Members .OfType() .ToArray(); for (var index = 0; index < classDeclarations.Length; index++) @@ -74,6 +74,16 @@ private static void ProcessSourceCodes(string file) classDeclaration.Members); compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); classDeclaration = newClassDeclaration; + + var interfaceNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( + classNamespaceDeclaration.NamespaceKeyword, + classNamespaceDeclaration.Name, + classNamespaceDeclaration.OpenBraceToken, + classNamespaceDeclaration.Externs, + classNamespaceDeclaration.Usings, + SyntaxFactory.List(), + classNamespaceDeclaration.CloseBraceToken, + classNamespaceDeclaration.SemicolonToken); var interfaceDeclaration = SyntaxFactory.InterfaceDeclaration( SyntaxFactory.List(), @@ -96,6 +106,7 @@ private static void ProcessSourceCodes(string file) for (int i = 0; i < methodDeclarations.Length; i++) { var methodDeclaration = methodDeclarations[i]; + var externMethodKeyword = methodDeclaration.Modifiers .SingleOrDefault(x => x.IsKind(SyntaxKind.ExternKeyword)); var staticMethodKeyword = methodDeclaration.Modifiers @@ -108,26 +119,33 @@ private static void ProcessSourceCodes(string file) var invokeMethodIdentifier = SyntaxFactory.IdentifierName($"Invoke{methodDeclaration.Identifier.Text}"); - classDeclaration = DecorateClassWithWrapperFunction(methodDeclaration, invokeMethodIdentifier, classDeclaration); + classDeclaration = DecorateClassWithWrapperFunction( + methodDeclaration, + invokeMethodIdentifier, + classDeclaration); - interfaceDeclaration = DecorateInterfaceWithWrapperFunction(methodDeclaration, invokeMethodIdentifier, interfaceDeclaration); + interfaceNamespaceDeclaration.Members.Add( + DecorateInterfaceWithWrapperFunction( + methodDeclaration, + invokeMethodIdentifier, + interfaceDeclaration)); } if (interfaceDeclaration.Members.Count > 0) { - WriteInterfaceToFile(file, interfaceDeclaration); + WriteInterfaceToFile(file, interfaceNamespaceDeclaration); } if (classDeclaration.Members.Count > 0) { File.WriteAllText( file, - classDeclaration.ToFullString()); + compilationUnit.ToFullString()); } } } } - private static void WriteInterfaceToFile(string file, InterfaceDeclarationSyntax interfaceDeclaration) + private static void WriteInterfaceToFile(string file, NamespaceDeclarationSyntax interfaceNamespaceDeclaration) { var baseFileName = Path.GetFileNameWithoutExtension(file); @@ -138,7 +156,7 @@ private static void WriteInterfaceToFile(string file, InterfaceDeclarationSyntax Path.Combine( fileDirectory, $"I{baseFileName}Mockable.cs"), - interfaceDeclaration.ToFullString()); + interfaceNamespaceDeclaration.ToFullString()); } private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( From ba3bfa4d4bbec4924dee0cde9aecccb735f4040a Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:15:59 +0100 Subject: [PATCH 06/46] yet another attempt. --- src/MockGenerator/Program.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 508460f3..31547b10 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -124,11 +124,11 @@ private static void ProcessSourceCodes(string file) invokeMethodIdentifier, classDeclaration); - interfaceNamespaceDeclaration.Members.Add( - DecorateInterfaceWithWrapperFunction( - methodDeclaration, - invokeMethodIdentifier, - interfaceDeclaration)); + interfaceDeclaration = DecorateInterfaceWithWrapperFunction( + methodDeclaration, + invokeMethodIdentifier, + interfaceDeclaration); + interfaceNamespaceDeclaration.Members.Add(interfaceDeclaration); } if (interfaceDeclaration.Members.Count > 0) From c2bf4e66d43bc96d07e7c4b951eee0e2b6e88779 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:19:46 +0100 Subject: [PATCH 07/46] more stuff. --- src/MockGenerator/Program.cs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 31547b10..b8ee405c 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -62,18 +62,6 @@ private static void ProcessSourceCodes(string file) interfaceIdentifier .WithLeadingTrivia(WhitespaceCharacter) .WithTrailingTrivia(WhitespaceCharacter))); - - var newClassDeclaration = SyntaxFactory.ClassDeclaration( - classDeclaration.AttributeLists, - modifiers, - classDeclaration.Identifier - .WithLeadingTrivia(WhitespaceCharacter), - classDeclaration.TypeParameterList, - baseList, - classDeclaration.ConstraintClauses, - classDeclaration.Members); - compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); - classDeclaration = newClassDeclaration; var interfaceNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( classNamespaceDeclaration.NamespaceKeyword, @@ -130,6 +118,18 @@ private static void ProcessSourceCodes(string file) interfaceDeclaration); interfaceNamespaceDeclaration.Members.Add(interfaceDeclaration); } + + var newClassDeclaration = SyntaxFactory.ClassDeclaration( + classDeclaration.AttributeLists, + modifiers, + classDeclaration.Identifier + .WithLeadingTrivia(WhitespaceCharacter), + classDeclaration.TypeParameterList, + baseList, + classDeclaration.ConstraintClauses, + classDeclaration.Members); + compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); + classDeclaration = newClassDeclaration; if (interfaceDeclaration.Members.Count > 0) { From 27a5788f37302d8144d612813ffe1cdc2d0f5011 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:26:47 +0100 Subject: [PATCH 08/46] further progress. --- src/MockGenerator/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index b8ee405c..eb2a0e21 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -46,6 +46,7 @@ private static void ProcessSourceCodes(string file) for (var index = 0; index < classDeclarations.Length; index++) { var classDeclaration = classDeclarations[index]; + var previousClassMemberCount = classDeclaration.Members.Count; var modifiers = classDeclaration.Modifiers; var staticKeyword = modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); @@ -135,7 +136,7 @@ private static void ProcessSourceCodes(string file) { WriteInterfaceToFile(file, interfaceNamespaceDeclaration); } - if (classDeclaration.Members.Count > 0) + if (classDeclaration.Members.Count > previousClassMemberCount) { File.WriteAllText( file, From 543a237e2c55afc62277f2ad8835c86c9b8adf9e Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:32:45 +0100 Subject: [PATCH 09/46] class fix. --- src/MockGenerator/Program.cs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index eb2a0e21..126addcd 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -46,18 +46,19 @@ private static void ProcessSourceCodes(string file) for (var index = 0; index < classDeclarations.Length; index++) { var classDeclaration = classDeclarations[index]; - var previousClassMemberCount = classDeclaration.Members.Count; + var newClassDeclaration = classDeclaration; + var previousClassMemberCount = newClassDeclaration.Members.Count; - var modifiers = classDeclaration.Modifiers; + var modifiers = newClassDeclaration.Modifiers; var staticKeyword = modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); if (staticKeyword != default(SyntaxToken)) { modifiers = modifiers.Remove(staticKeyword); } - var interfaceIdentifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); + var interfaceIdentifier = SyntaxFactory.IdentifierName($"I{newClassDeclaration.Identifier.Text}Mockable"); - var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); + var baseList = newClassDeclaration.BaseList ?? SyntaxFactory.BaseList(); baseList = baseList.AddTypes( SyntaxFactory.SimpleBaseType( interfaceIdentifier @@ -89,7 +90,7 @@ private static void ProcessSourceCodes(string file) SyntaxFactory.List(), SyntaxFactory.List()); - var methodDeclarations = classDeclaration.Members + var methodDeclarations = newClassDeclaration.Members .OfType() .ToArray(); for (int i = 0; i < methodDeclarations.Length; i++) @@ -108,10 +109,10 @@ private static void ProcessSourceCodes(string file) var invokeMethodIdentifier = SyntaxFactory.IdentifierName($"Invoke{methodDeclaration.Identifier.Text}"); - classDeclaration = DecorateClassWithWrapperFunction( + newClassDeclaration = DecorateClassWithWrapperFunction( methodDeclaration, invokeMethodIdentifier, - classDeclaration); + newClassDeclaration); interfaceDeclaration = DecorateInterfaceWithWrapperFunction( methodDeclaration, @@ -120,23 +121,22 @@ private static void ProcessSourceCodes(string file) interfaceNamespaceDeclaration.Members.Add(interfaceDeclaration); } - var newClassDeclaration = SyntaxFactory.ClassDeclaration( - classDeclaration.AttributeLists, + newClassDeclaration = SyntaxFactory.ClassDeclaration( + newClassDeclaration.AttributeLists, modifiers, - classDeclaration.Identifier + newClassDeclaration.Identifier .WithLeadingTrivia(WhitespaceCharacter), - classDeclaration.TypeParameterList, + newClassDeclaration.TypeParameterList, baseList, - classDeclaration.ConstraintClauses, - classDeclaration.Members); + newClassDeclaration.ConstraintClauses, + newClassDeclaration.Members); compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); - classDeclaration = newClassDeclaration; if (interfaceDeclaration.Members.Count > 0) { WriteInterfaceToFile(file, interfaceNamespaceDeclaration); } - if (classDeclaration.Members.Count > previousClassMemberCount) + if (newClassDeclaration.Members.Count > previousClassMemberCount) { File.WriteAllText( file, From 847d7f5ae920a9cdccab6af5870aa12a8ada27b9 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:38:44 +0100 Subject: [PATCH 10/46] more fixes. --- src/MockGenerator/Program.cs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 126addcd..d8604fbc 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -15,6 +15,7 @@ namespace MockGenerator class Program { static readonly SyntaxTrivia WhitespaceCharacter = SyntaxFactory.Whitespace(" "); + static readonly SyntaxTrivia TabCharacter = SyntaxFactory.Whitespace("\t"); static readonly SyntaxTrivia NewLineCharacter = SyntaxFactory.Whitespace("\n"); static void Main(string[] args) @@ -97,11 +98,7 @@ private static void ProcessSourceCodes(string file) { var methodDeclaration = methodDeclarations[i]; - var externMethodKeyword = methodDeclaration.Modifiers - .SingleOrDefault(x => x.IsKind(SyntaxKind.ExternKeyword)); - var staticMethodKeyword = methodDeclaration.Modifiers - .SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); - if (externMethodKeyword == default(SyntaxToken) || staticMethodKeyword == default(SyntaxToken)) + if (IsPublicStaticExternMethod(methodDeclaration)) { continue; } @@ -146,6 +143,17 @@ private static void ProcessSourceCodes(string file) } } + 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 void WriteInterfaceToFile(string file, NamespaceDeclarationSyntax interfaceNamespaceDeclaration) { var baseFileName = Path.GetFileNameWithoutExtension(file); @@ -195,7 +203,8 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec SyntaxFactory.IdentifierName(x.Identifier))); var arrowBody = SyntaxFactory.ArrowExpressionClause( - SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken), + SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken) + .WithTrailingTrivia(NewLineCharacter, TabCharacter), SyntaxFactory.InvocationExpression( SyntaxFactory.IdentifierName(methodDeclaration.Identifier), SyntaxFactory.ArgumentList( @@ -203,7 +212,9 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec var wrapperMethodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.List(), - SyntaxFactory.TokenList(), + SyntaxFactory.TokenList( + SyntaxFactory.Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), methodDeclaration.ReturnType, default(ExplicitInterfaceSpecifierSyntax), invokeMethodIdentifier.Identifier, From e064da1844b47a2fea57b04cd34591596ecad435 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:43:24 +0100 Subject: [PATCH 11/46] fixes. --- src/MockGenerator/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index d8604fbc..adf3302e 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -204,7 +204,7 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec var arrowBody = SyntaxFactory.ArrowExpressionClause( SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken) - .WithTrailingTrivia(NewLineCharacter, TabCharacter), + .WithLeadingTrivia(NewLineCharacter, TabCharacter), SyntaxFactory.InvocationExpression( SyntaxFactory.IdentifierName(methodDeclaration.Identifier), SyntaxFactory.ArgumentList( From 1d90d106764b6b7300466f023b29f5943de6fe1a Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 07:46:23 +0100 Subject: [PATCH 12/46] awesomeness. --- src/MockGenerator/Program.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index adf3302e..1dca3ab4 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -204,7 +204,8 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec var arrowBody = SyntaxFactory.ArrowExpressionClause( SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken) - .WithLeadingTrivia(NewLineCharacter, TabCharacter), + .WithLeadingTrivia(NewLineCharacter, TabCharacter) + .WithTrailingTrivia(WhitespaceCharacter), SyntaxFactory.InvocationExpression( SyntaxFactory.IdentifierName(methodDeclaration.Identifier), SyntaxFactory.ArgumentList( @@ -222,7 +223,8 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec methodDeclaration.ParameterList, methodDeclaration.ConstraintClauses, default(BlockSyntax), - arrowBody); + arrowBody, + SyntaxFactory.Token(SyntaxKind.SemicolonToken)); classDeclaration = classDeclaration .AddMembers( From 17ca24d3f00c182e66a4a36eaf9104500fd0337a Mon Sep 17 00:00:00 2001 From: ffMathy Date: Tue, 17 Nov 2015 08:18:40 +0100 Subject: [PATCH 13/46] foo. --- src/MockGenerator/Program.cs | 118 ++++++++++++++++++++--------------- 1 file changed, 67 insertions(+), 51 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 1dca3ab4..afc05d7c 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -37,52 +37,61 @@ private static void ProcessSourceCodes(string file) if (compilationUnit == null || compilationUnit.Members.Count == 0) return; var namespaceDeclarations = compilationUnit.Members.OfType(); - foreach (var classNamespaceDeclaration in namespaceDeclarations) + foreach (var namespaceDeclaration in namespaceDeclarations) { - if (classNamespaceDeclaration == null || classNamespaceDeclaration.Name.ToString() != "PInvoke") return; + if (namespaceDeclaration == null || namespaceDeclaration.Name.ToString() != "PInvoke") return; - var classDeclarations = classNamespaceDeclaration.Members + var classDeclarations = namespaceDeclaration.Members .OfType() .ToArray(); for (var index = 0; index < classDeclarations.Length; index++) { var classDeclaration = classDeclarations[index]; - var newClassDeclaration = classDeclaration; - var previousClassMemberCount = newClassDeclaration.Members.Count; - var modifiers = newClassDeclaration.Modifiers; - var staticKeyword = modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); - if (staticKeyword != default(SyntaxToken)) - { - modifiers = modifiers.Remove(staticKeyword); - } - - var interfaceIdentifier = SyntaxFactory.IdentifierName($"I{newClassDeclaration.Identifier.Text}Mockable"); + var newInterfaceModifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); + var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}Mockable"); - var baseList = newClassDeclaration.BaseList ?? SyntaxFactory.BaseList(); + var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); baseList = baseList.AddTypes( SyntaxFactory.SimpleBaseType( - interfaceIdentifier + newInterfaceModifier .WithLeadingTrivia(WhitespaceCharacter) .WithTrailingTrivia(WhitespaceCharacter))); - var interfaceNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( - classNamespaceDeclaration.NamespaceKeyword, - classNamespaceDeclaration.Name, - classNamespaceDeclaration.OpenBraceToken, - classNamespaceDeclaration.Externs, - classNamespaceDeclaration.Usings, + var newNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( + namespaceDeclaration.NamespaceKeyword, + namespaceDeclaration.Name, + namespaceDeclaration.OpenBraceToken, + namespaceDeclaration.Externs, + namespaceDeclaration.Usings, SyntaxFactory.List(), - classNamespaceDeclaration.CloseBraceToken, - classNamespaceDeclaration.SemicolonToken); + namespaceDeclaration.CloseBraceToken, + namespaceDeclaration.SemicolonToken); - var interfaceDeclaration = SyntaxFactory.InterfaceDeclaration( + var newClassNamespaceDeclaration = newNamespaceDeclaration; + var newInterfaceNamespaceDeclaration = newNamespaceDeclaration; + + var newClassDeclaration = SyntaxFactory.ClassDeclaration( + SyntaxFactory.List(), + SyntaxFactory.TokenList( + SyntaxFactory + .Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + newClassModifier + .Identifier + .WithTrailingTrivia(WhitespaceCharacter) + .WithLeadingTrivia(WhitespaceCharacter), + null, + null, + SyntaxFactory.List(), + SyntaxFactory.List()); + var newInterfaceDeclaration = SyntaxFactory.InterfaceDeclaration( SyntaxFactory.List(), SyntaxFactory.TokenList( SyntaxFactory .Token(SyntaxKind.PublicKeyword) .WithTrailingTrivia(WhitespaceCharacter)), - interfaceIdentifier + newInterfaceModifier .Identifier .WithTrailingTrivia(WhitespaceCharacter) .WithLeadingTrivia(WhitespaceCharacter), @@ -91,7 +100,7 @@ private static void ProcessSourceCodes(string file) SyntaxFactory.List(), SyntaxFactory.List()); - var methodDeclarations = newClassDeclaration.Members + var methodDeclarations = classDeclaration.Members .OfType() .ToArray(); for (int i = 0; i < methodDeclarations.Length; i++) @@ -108,36 +117,24 @@ private static void ProcessSourceCodes(string file) newClassDeclaration = DecorateClassWithWrapperFunction( methodDeclaration, - invokeMethodIdentifier, + invokeMethodIdentifier, newClassDeclaration); + newClassNamespaceDeclaration.Members.Add(classDeclaration); - interfaceDeclaration = DecorateInterfaceWithWrapperFunction( + newInterfaceDeclaration = DecorateInterfaceWithWrapperFunction( methodDeclaration, invokeMethodIdentifier, - interfaceDeclaration); - interfaceNamespaceDeclaration.Members.Add(interfaceDeclaration); + newInterfaceDeclaration); + newInterfaceNamespaceDeclaration.Members.Add(newInterfaceDeclaration); } - - newClassDeclaration = SyntaxFactory.ClassDeclaration( - newClassDeclaration.AttributeLists, - modifiers, - newClassDeclaration.Identifier - .WithLeadingTrivia(WhitespaceCharacter), - newClassDeclaration.TypeParameterList, - baseList, - newClassDeclaration.ConstraintClauses, - newClassDeclaration.Members); - compilationUnit = compilationUnit.ReplaceNode(classDeclaration, newClassDeclaration); - if (interfaceDeclaration.Members.Count > 0) + if (newInterfaceDeclaration.Members.Count > 0) { - WriteInterfaceToFile(file, interfaceNamespaceDeclaration); + WriteInterfaceToFile(file, newInterfaceNamespaceDeclaration); } - if (newClassDeclaration.Members.Count > previousClassMemberCount) + if (classDeclaration.Members.Count > 0) { - File.WriteAllText( - file, - compilationUnit.ToFullString()); + WriteClassToFile(file, newClassNamespaceDeclaration); } } } @@ -156,10 +153,8 @@ private static bool IsPublicStaticExternMethod(MethodDeclarationSyntax methodDec private static void WriteInterfaceToFile(string file, NamespaceDeclarationSyntax interfaceNamespaceDeclaration) { - var baseFileName = Path.GetFileNameWithoutExtension(file); - - var fileDirectory = Path.GetDirectoryName(file); - Debug.Assert(fileDirectory != null, "fileDirectory != null"); + string fileDirectory; + var baseFileName = GetBaseFileName(file, out fileDirectory); File.WriteAllText( Path.Combine( @@ -168,6 +163,27 @@ private static void WriteInterfaceToFile(string file, NamespaceDeclarationSyntax interfaceNamespaceDeclaration.ToFullString()); } + private static void WriteClassToFile(string file, NamespaceDeclarationSyntax classNamespaceDeclaration) + { + string fileDirectory; + var baseFileName = GetBaseFileName(file, out fileDirectory); + + File.WriteAllText( + Path.Combine( + fileDirectory, + $"{baseFileName}Mockable.cs"), + classNamespaceDeclaration.ToFullString()); + } + + 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, From f2aac5d08a566f9676b9416fcbc95b411acc6d88 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sat, 21 Nov 2015 21:09:20 +0100 Subject: [PATCH 14/46] finalized program. --- src/MockGenerator/Program.cs | 225 ++++++++++++++++++++--------------- 1 file changed, 128 insertions(+), 97 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index afc05d7c..d9b7cf5d 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -18,6 +18,15 @@ class Program 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(); + } + static void Main(string[] args) { var currentDirectory = Environment.CurrentDirectory; @@ -44,69 +53,69 @@ private static void ProcessSourceCodes(string file) var classDeclarations = namespaceDeclaration.Members .OfType() .ToArray(); - for (var index = 0; index < classDeclarations.Length; index++) + foreach (var classDeclaration in classDeclarations) { - var classDeclaration = classDeclarations[index]; + if (classDeclaration.Identifier.Text.EndsWith("Mockable")) continue; var newInterfaceModifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); - var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}Mockable"); - - var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); - baseList = baseList.AddTypes( - SyntaxFactory.SimpleBaseType( - newInterfaceModifier - .WithLeadingTrivia(WhitespaceCharacter) - .WithTrailingTrivia(WhitespaceCharacter))); - - var newNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( - namespaceDeclaration.NamespaceKeyword, - namespaceDeclaration.Name, - namespaceDeclaration.OpenBraceToken, - namespaceDeclaration.Externs, - namespaceDeclaration.Usings, - SyntaxFactory.List(), - namespaceDeclaration.CloseBraceToken, - namespaceDeclaration.SemicolonToken); - - var newClassNamespaceDeclaration = newNamespaceDeclaration; - var newInterfaceNamespaceDeclaration = newNamespaceDeclaration; - - var newClassDeclaration = SyntaxFactory.ClassDeclaration( - SyntaxFactory.List(), - SyntaxFactory.TokenList( - SyntaxFactory - .Token(SyntaxKind.PublicKeyword) - .WithTrailingTrivia(WhitespaceCharacter)), - newClassModifier - .Identifier - .WithTrailingTrivia(WhitespaceCharacter) - .WithLeadingTrivia(WhitespaceCharacter), - null, - null, - SyntaxFactory.List(), - SyntaxFactory.List()); - var newInterfaceDeclaration = SyntaxFactory.InterfaceDeclaration( - SyntaxFactory.List(), - SyntaxFactory.TokenList( - SyntaxFactory - .Token(SyntaxKind.PublicKeyword) - .WithTrailingTrivia(WhitespaceCharacter)), - newInterfaceModifier - .Identifier - .WithTrailingTrivia(WhitespaceCharacter) - .WithLeadingTrivia(WhitespaceCharacter), - null, - null, - SyntaxFactory.List(), - SyntaxFactory.List()); + var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}"); + + if (!ClassCache.ContainsKey(newClassModifier.Identifier.Text)) + { + var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); + ClassCache.Add(newClassModifier.Identifier.Text, + SyntaxFactory.ClassDeclaration( + SyntaxFactory.List(), + SyntaxFactory.TokenList( + SyntaxFactory + .Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter), + SyntaxFactory + .Token(SyntaxKind.PartialKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + newClassModifier.Identifier + .WithTrailingTrivia(WhitespaceCharacter) + .WithLeadingTrivia(WhitespaceCharacter), + null, + baseList.AddTypes( + SyntaxFactory.SimpleBaseType( + newInterfaceModifier + .WithLeadingTrivia(WhitespaceCharacter) + .WithTrailingTrivia(WhitespaceCharacter))), + SyntaxFactory.List(), + SyntaxFactory.List()) + .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter)); + } + if (!InterfaceCache.ContainsKey(newInterfaceModifier.Identifier.Text)) + { + InterfaceCache.Add(newInterfaceModifier.Identifier.Text, + SyntaxFactory.InterfaceDeclaration( + SyntaxFactory.List(), + SyntaxFactory.TokenList( + SyntaxFactory + .Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + newInterfaceModifier + .Identifier + .WithTrailingTrivia(WhitespaceCharacter) + .WithLeadingTrivia(WhitespaceCharacter), + null, + null, + SyntaxFactory.List(), + SyntaxFactory.List()) + .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter)); + } + + var newClassDeclaration = ClassCache[newClassModifier.Identifier.Text]; + var newInterfaceDeclaration = InterfaceCache[newInterfaceModifier.Identifier.Text]; var methodDeclarations = classDeclaration.Members .OfType() .ToArray(); - for (int i = 0; i < methodDeclarations.Length; i++) + foreach (var methodDeclaration in methodDeclarations) { - var methodDeclaration = methodDeclarations[i]; - if (IsPublicStaticExternMethod(methodDeclaration)) { continue; @@ -116,30 +125,55 @@ private static void ProcessSourceCodes(string file) SyntaxFactory.IdentifierName($"Invoke{methodDeclaration.Identifier.Text}"); newClassDeclaration = DecorateClassWithWrapperFunction( - methodDeclaration, + methodDeclaration, invokeMethodIdentifier, newClassDeclaration); - newClassNamespaceDeclaration.Members.Add(classDeclaration); + ClassCache[newClassModifier.Identifier.Text] = newClassDeclaration; newInterfaceDeclaration = DecorateInterfaceWithWrapperFunction( methodDeclaration, invokeMethodIdentifier, newInterfaceDeclaration); - newInterfaceNamespaceDeclaration.Members.Add(newInterfaceDeclaration); - } + InterfaceCache[newInterfaceModifier.Identifier.Text] = newInterfaceDeclaration; - if (newInterfaceDeclaration.Members.Count > 0) - { - WriteInterfaceToFile(file, newInterfaceNamespaceDeclaration); - } - if (classDeclaration.Members.Count > 0) - { - WriteClassToFile(file, newClassNamespaceDeclaration); + string fileDirectory; + var baseFileName = GetBaseFileName(file, out fileDirectory); + + File.WriteAllText( + Path.Combine( + fileDirectory, + $"I{baseFileName}Mockable.cs"), + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) + .AddMembers(newInterfaceDeclaration) + .ToFullString()); + + File.WriteAllText( + Path.Combine( + fileDirectory, + $"{baseFileName}Mockable.cs"), + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) + .AddMembers(newClassDeclaration) + .ToFullString()); } } } } + private static NamespaceDeclarationSyntax CreateNewEmptyNamespaceDeclaration( + NamespaceDeclarationSyntax namespaceDeclaration) + { + var newNamespaceDeclaration = SyntaxFactory.NamespaceDeclaration( + namespaceDeclaration.NamespaceKeyword, + namespaceDeclaration.Name, + namespaceDeclaration.OpenBraceToken, + namespaceDeclaration.Externs, + namespaceDeclaration.Usings, + SyntaxFactory.List(), + namespaceDeclaration.CloseBraceToken, + namespaceDeclaration.SemicolonToken); + return newNamespaceDeclaration; + } + private static bool IsPublicStaticExternMethod(MethodDeclarationSyntax methodDeclaration) { var externMethodKeyword = methodDeclaration.Modifiers @@ -151,30 +185,6 @@ private static bool IsPublicStaticExternMethod(MethodDeclarationSyntax methodDec return externMethodKeyword == default(SyntaxToken) || staticMethodKeyword == default(SyntaxToken) || publicMethodKeyword == default(SyntaxToken); } - private static void WriteInterfaceToFile(string file, NamespaceDeclarationSyntax interfaceNamespaceDeclaration) - { - string fileDirectory; - var baseFileName = GetBaseFileName(file, out fileDirectory); - - File.WriteAllText( - Path.Combine( - fileDirectory, - $"I{baseFileName}Mockable.cs"), - interfaceNamespaceDeclaration.ToFullString()); - } - - private static void WriteClassToFile(string file, NamespaceDeclarationSyntax classNamespaceDeclaration) - { - string fileDirectory; - var baseFileName = GetBaseFileName(file, out fileDirectory); - - File.WriteAllText( - Path.Combine( - fileDirectory, - $"{baseFileName}Mockable.cs"), - classNamespaceDeclaration.ToFullString()); - } - private static string GetBaseFileName(string file, out string fileDirectory) { var baseFileName = Path.GetFileNameWithoutExtension(file); @@ -189,6 +199,8 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( IdentifierNameSyntax invokeMethodIdentifier, InterfaceDeclarationSyntax interfaceDeclaration) { + var dllImport = methodDeclaration.AttributeLists + .First(x => x.OpenBracketToken.HasLeadingTrivia); var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.List(), SyntaxFactory.TokenList(), @@ -204,8 +216,10 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( interfaceDeclaration = interfaceDeclaration .AddMembers( interfaceMethodDeclaration - .WithTrailingTrivia(NewLineCharacter) - .WithLeadingTrivia(NewLineCharacter)); + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + .WithLeadingTrivia(dllImport.OpenBracketToken.LeadingTrivia)); return interfaceDeclaration; } @@ -213,14 +227,29 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec IdentifierNameSyntax invokeMethodIdentifier, ClassDeclarationSyntax classDeclaration) { + var dllImport = methodDeclaration.AttributeLists + .First(x => x.OpenBracketToken.HasLeadingTrivia); var arguments = methodDeclaration.ParameterList .Parameters - .Select(x => SyntaxFactory.Argument( - SyntaxFactory.IdentifierName(x.Identifier))); + .Select((x, i) => + { + var identifierName = SyntaxFactory.Argument( + SyntaxFactory.IdentifierName(x.Identifier)); + if (i > 0) + { + identifierName = identifierName.WithLeadingTrivia(WhitespaceCharacter); + } + + return identifierName; + }); var arrowBody = SyntaxFactory.ArrowExpressionClause( SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken) - .WithLeadingTrivia(NewLineCharacter, TabCharacter) + .WithLeadingTrivia( + NewLineCharacter, + TabCharacter, + TabCharacter, + TabCharacter) .WithTrailingTrivia(WhitespaceCharacter), SyntaxFactory.InvocationExpression( SyntaxFactory.IdentifierName(methodDeclaration.Identifier), @@ -245,8 +274,10 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec classDeclaration = classDeclaration .AddMembers( wrapperMethodDeclaration - .WithTrailingTrivia(NewLineCharacter) - .WithLeadingTrivia(NewLineCharacter)); + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + .WithLeadingTrivia(dllImport.OpenBracketToken.LeadingTrivia)); return classDeclaration; } } From 91cb6e7e751f5906d58b0fd3fa30c77a85abfb62 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 01:05:49 +0100 Subject: [PATCH 15/46] static conversion. --- src/AdvApi32.Desktop/AdvApi32.cs | 4 +- src/BCrypt/BCrypt.cs | 4 +- src/Gdi32.Desktop/Gdi32.cs | 4 +- src/Hid.Shared/Hid.cs | 4 +- src/ImageHlp/ImageHlp.cs | 4 +- src/Kernel32.Desktop/Kernel32.cs | 4 +- src/Kernel32.Shared/Kernel32.cs | 4 +- src/MockGenerator/Program.cs | 128 +++++++++++++++++++------------ src/NCrypt/NCrypt.cs | 4 +- src/SetupApi.Desktop/SetupApi.cs | 4 +- src/User32.Desktop/User32.cs | 4 +- 11 files changed, 98 insertions(+), 70 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32.cs b/src/AdvApi32.Desktop/AdvApi32.cs index 55b17ecd..e035db72 100644 --- a/src/AdvApi32.Desktop/AdvApi32.cs +++ b/src/AdvApi32.Desktop/AdvApi32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the AdvApi32.dll Windows library /// that are available to Desktop apps only. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Used to prefix group names so that they can be distinguished from a service name, diff --git a/src/BCrypt/BCrypt.cs b/src/BCrypt/BCrypt.cs index 29ce6b04..fd0ef43b 100644 --- a/src/BCrypt/BCrypt.cs +++ b/src/BCrypt/BCrypt.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// /// Exported functions from the BCrypt.dll Windows library. /// - public static partial class BCrypt + public partial class BCrypt { /// /// Loads and initializes a CNG provider. diff --git a/src/Gdi32.Desktop/Gdi32.cs b/src/Gdi32.Desktop/Gdi32.cs index 8747d074..8e9b8502 100644 --- a/src/Gdi32.Desktop/Gdi32.cs +++ b/src/Gdi32.Desktop/Gdi32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Exported functions from the Gdi32.dll Windows library. /// - public static partial class Gdi32 + public partial class Gdi32 { [DllImport(nameof(Gdi32))] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/src/Hid.Shared/Hid.cs b/src/Hid.Shared/Hid.cs index 50ae0072..1b7580bb 100644 --- a/src/Hid.Shared/Hid.cs +++ b/src/Hid.Shared/Hid.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -12,7 +12,7 @@ namespace PInvoke /// Exported functions from the Hid.dll Windows library /// that are available to Desktop and Store apps. /// - public static partial class Hid + public partial class Hid { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. diff --git a/src/ImageHlp/ImageHlp.cs b/src/ImageHlp/ImageHlp.cs index 61d11032..08d7c1ee 100644 --- a/src/ImageHlp/ImageHlp.cs +++ b/src/ImageHlp/ImageHlp.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// Exported functions from the ImageHlp.dll Windows library /// that are available to Desktop and Store apps. /// - public static partial class ImageHlp + public partial class ImageHlp { /// /// Maps an image and preloads data from the mapped file. diff --git a/src/Kernel32.Desktop/Kernel32.cs b/src/Kernel32.Desktop/Kernel32.cs index 7ffde6e7..c2f3c6fb 100644 --- a/src/Kernel32.Desktop/Kernel32.cs +++ b/src/Kernel32.Desktop/Kernel32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// /// Exported functions from the Kernel32.dll Windows library. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// Creates a new process and its primary thread. The new process runs in the security context of the calling process. diff --git a/src/Kernel32.Shared/Kernel32.cs b/src/Kernel32.Shared/Kernel32.cs index 15464c1a..caaf329a 100644 --- a/src/Kernel32.Shared/Kernel32.cs +++ b/src/Kernel32.Shared/Kernel32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// /// Exported functions from the Kernel32.dll Windows library. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// The maximum length of file paths for most Win32 functions. diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index d9b7cf5d..eaecdb91 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -53,66 +53,27 @@ private static void ProcessSourceCodes(string file) var classDeclarations = namespaceDeclaration.Members .OfType() .ToArray(); - foreach (var classDeclaration in classDeclarations) + for (int index = 0; index < classDeclarations.Length; index++) { - if (classDeclaration.Identifier.Text.EndsWith("Mockable")) continue; + var classDeclaration = classDeclarations[index]; + if (classDeclaration.Identifier.Text.EndsWith("Mockable")) + { + continue; + } - var newInterfaceModifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); + var newInterfaceModifier = + SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}"); - if (!ClassCache.ContainsKey(newClassModifier.Identifier.Text)) - { - var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); - ClassCache.Add(newClassModifier.Identifier.Text, - SyntaxFactory.ClassDeclaration( - SyntaxFactory.List(), - SyntaxFactory.TokenList( - SyntaxFactory - .Token(SyntaxKind.PublicKeyword) - .WithTrailingTrivia(WhitespaceCharacter), - SyntaxFactory - .Token(SyntaxKind.PartialKeyword) - .WithTrailingTrivia(WhitespaceCharacter)), - newClassModifier.Identifier - .WithTrailingTrivia(WhitespaceCharacter) - .WithLeadingTrivia(WhitespaceCharacter), - null, - baseList.AddTypes( - SyntaxFactory.SimpleBaseType( - newInterfaceModifier - .WithLeadingTrivia(WhitespaceCharacter) - .WithTrailingTrivia(WhitespaceCharacter))), - SyntaxFactory.List(), - SyntaxFactory.List()) - .WithLeadingTrivia(TabCharacter) - .WithTrailingTrivia(NewLineCharacter)); - } - if (!InterfaceCache.ContainsKey(newInterfaceModifier.Identifier.Text)) - { - InterfaceCache.Add(newInterfaceModifier.Identifier.Text, - SyntaxFactory.InterfaceDeclaration( - SyntaxFactory.List(), - SyntaxFactory.TokenList( - SyntaxFactory - .Token(SyntaxKind.PublicKeyword) - .WithTrailingTrivia(WhitespaceCharacter)), - newInterfaceModifier - .Identifier - .WithTrailingTrivia(WhitespaceCharacter) - .WithLeadingTrivia(WhitespaceCharacter), - null, - null, - SyntaxFactory.List(), - SyntaxFactory.List()) - .WithLeadingTrivia(TabCharacter) - .WithTrailingTrivia(NewLineCharacter)); - } + PrepareClassCacheEntry(newClassModifier, classDeclaration, newInterfaceModifier); + PrepareInterfaceCacheEntry(newInterfaceModifier); var newClassDeclaration = ClassCache[newClassModifier.Identifier.Text]; var newInterfaceDeclaration = InterfaceCache[newInterfaceModifier.Identifier.Text]; var methodDeclarations = classDeclaration.Members .OfType() + .Where(a => a.AttributeLists.Any(b => b.Attributes.Any(c => c.Name.ToString() == "DllImport"))) .ToArray(); foreach (var methodDeclaration in methodDeclarations) { @@ -155,10 +116,77 @@ private static void ProcessSourceCodes(string file) .AddMembers(newClassDeclaration) .ToFullString()); } + + if (methodDeclarations.Length > 0) + { + var staticModifier = classDeclaration.Modifiers.Single(x => x.IsKind(SyntaxKind.StaticKeyword)); + compilationUnit = compilationUnit.ReplaceNode( + classDeclaration, + classDeclaration.WithModifiers( + classDeclaration.Modifiers.Remove(staticModifier))); + File.WriteAllText(file, compilationUnit.ToFullString()); + } } } } + private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) + { + if (!InterfaceCache.ContainsKey(newInterfaceModifier.Identifier.Text)) + { + InterfaceCache.Add(newInterfaceModifier.Identifier.Text, + SyntaxFactory.InterfaceDeclaration( + SyntaxFactory.List(), + 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(), + SyntaxFactory.TokenList( + SyntaxFactory + .Token(SyntaxKind.PublicKeyword) + .WithTrailingTrivia(WhitespaceCharacter), + SyntaxFactory + .Token(SyntaxKind.PartialKeyword) + .WithTrailingTrivia(WhitespaceCharacter)), + 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) { diff --git a/src/NCrypt/NCrypt.cs b/src/NCrypt/NCrypt.cs index b92c67b7..348fc612 100644 --- a/src/NCrypt/NCrypt.cs +++ b/src/NCrypt/NCrypt.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the NCrypt.dll Windows library /// that are available to Desktop and Store apps. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Loads and initializes a CNG key storage provider. diff --git a/src/SetupApi.Desktop/SetupApi.cs b/src/SetupApi.Desktop/SetupApi.cs index 88cf9f30..e8e44627 100644 --- a/src/SetupApi.Desktop/SetupApi.cs +++ b/src/SetupApi.Desktop/SetupApi.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the SetupApi.dll Windows library /// that are available to Desktop apps only. /// - public static partial class SetupApi + public partial class SetupApi { /// /// The SetupDiGetClassDevs function returns a handle to a device information set diff --git a/src/User32.Desktop/User32.cs b/src/User32.Desktop/User32.cs index 4ae899e2..d2122cc1 100644 --- a/src/User32.Desktop/User32.cs +++ b/src/User32.Desktop/User32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Exported functions from the User32.dll Windows library. /// - public static partial class User32 + public partial class User32 { [DllImport(nameof(User32))] public static extern int SetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); From 50223d726c00aa555b47fc3b0af75beaa1527ac8 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 01:21:28 +0100 Subject: [PATCH 16/46] updates. --- src/MockGenerator/Program.cs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index eaecdb91..f46d40e5 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -53,9 +53,8 @@ private static void ProcessSourceCodes(string file) var classDeclarations = namespaceDeclaration.Members .OfType() .ToArray(); - for (int index = 0; index < classDeclarations.Length; index++) + foreach (var classDeclaration in classDeclarations) { - var classDeclaration = classDeclarations[index]; if (classDeclaration.Identifier.Text.EndsWith("Mockable")) { continue; @@ -117,15 +116,22 @@ private static void ProcessSourceCodes(string file) .ToFullString()); } - if (methodDeclarations.Length > 0) + if (methodDeclarations.Length <= 0) { - var staticModifier = classDeclaration.Modifiers.Single(x => x.IsKind(SyntaxKind.StaticKeyword)); - compilationUnit = compilationUnit.ReplaceNode( - classDeclaration, - classDeclaration.WithModifiers( - classDeclaration.Modifiers.Remove(staticModifier))); - File.WriteAllText(file, compilationUnit.ToFullString()); + continue; + } + + var staticModifier = classDeclaration.Modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); + if (staticModifier == default(SyntaxToken)) + { + continue; } + + compilationUnit = compilationUnit.ReplaceNode( + classDeclaration, + classDeclaration.WithModifiers( + classDeclaration.Modifiers.Remove(staticModifier))); + File.WriteAllText(file, compilationUnit.ToFullString()); } } } From 109afa059cfc2615e22940bb82f574a4c2c13b84 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 01:23:52 +0100 Subject: [PATCH 17/46] new changes. --- src/MockGenerator/MockGenerator.csproj | 40 ++++++++++++++++++++++++++ src/MockGenerator/packages.config | 6 ++++ 2 files changed, 46 insertions(+) diff --git a/src/MockGenerator/MockGenerator.csproj b/src/MockGenerator/MockGenerator.csproj index 9cffa6b8..e0e3cdbf 100644 --- a/src/MockGenerator/MockGenerator.csproj +++ b/src/MockGenerator/MockGenerator.csproj @@ -43,11 +43,51 @@ ..\..\packages\Microsoft.CodeAnalysis.CSharp.1.0.0\lib\net45\Microsoft.CodeAnalysis.CSharp.dll True + + ..\..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.1.0.0\lib\net45\Microsoft.CodeAnalysis.CSharp.Workspaces.dll + True + + + ..\..\packages\Microsoft.CodeAnalysis.VisualBasic.1.0.0\lib\net45\Microsoft.CodeAnalysis.VisualBasic.dll + True + + + ..\..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.1.0.0\lib\net45\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll + True + + + ..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.0.0\lib\net45\Microsoft.CodeAnalysis.Workspaces.dll + True + + + ..\..\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 + + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll + True + + + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll + True + + + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll + True + + + ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll + True + + + ..\..\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 diff --git a/src/MockGenerator/packages.config b/src/MockGenerator/packages.config index fa91bc8a..9da500ec 100644 --- a/src/MockGenerator/packages.config +++ b/src/MockGenerator/packages.config @@ -1,8 +1,14 @@  + + + + + + \ No newline at end of file From c95ebba53dc0a6dc050eac4f5e76b53906779222 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 02:25:20 +0100 Subject: [PATCH 18/46] new program stuff. --- src/MockGenerator/Program.cs | 65 ++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 11 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index f46d40e5..07f19ef2 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -11,6 +11,7 @@ namespace MockGenerator using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; + using Microsoft.CodeAnalysis.MSBuild; class Program { @@ -27,18 +28,35 @@ static Program() InterfaceCache = new Dictionary(); } - static void Main(string[] args) + private static void Main() + { + Run(); + } + + private static void Run() { var currentDirectory = Environment.CurrentDirectory; - var solutionRoot = Path.Combine(currentDirectory, "..", "..", ".."); - foreach (var file in Directory.GetFiles(solutionRoot, "*.cs", SearchOption.AllDirectories)) + 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 = solution.Projects.ToArray(); + for (var i = 0; i < projects.Length; i++) { - ProcessSourceCodes(file); + var project = projects[i]; + foreach (var file in project.Documents + .Select(x => x.FilePath) + .Where(x => x.EndsWith(".cs"))) + { + ProcessSourceCodes(ref solution, ref project, file); + } } + + workspace.TryApplyChanges(solution); } - private static void ProcessSourceCodes(string file) + private static void ProcessSourceCodes(ref Solution solution, ref Project project, string file) { var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(file)); @@ -99,21 +117,27 @@ private static void ProcessSourceCodes(string file) string fileDirectory; var baseFileName = GetBaseFileName(file, out fileDirectory); - File.WriteAllText( - Path.Combine( + var mockableInterfacePath = Path.Combine( fileDirectory, - $"I{baseFileName}Mockable.cs"), + $"I{baseFileName}Mockable.cs"); + File.WriteAllText( + mockableInterfacePath, CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) .AddMembers(newInterfaceDeclaration) .ToFullString()); - File.WriteAllText( - Path.Combine( + var mockableClassPath = Path.Combine( fileDirectory, - $"{baseFileName}Mockable.cs"), + $"{baseFileName}Mockable.cs"); + File.WriteAllText( + mockableClassPath, CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) .AddMembers(newClassDeclaration) .ToFullString()); + + project = project.AddDocument(Path.GetFileName(mockableClassPath), File.ReadAllText(mockableClassPath)).Project; + project = project.AddDocument(Path.GetFileName(mockableInterfacePath), File.ReadAllText(mockableInterfacePath)).Project; + solution = project.Solution; } if (methodDeclarations.Length <= 0) @@ -136,6 +160,25 @@ private static void ProcessSourceCodes(string file) } } + private static string GetProjectFile(string file) + { + var folder = Path.GetDirectoryName(file); + var projectFile = (string)null; + while (folder != null) + { + var projectFiles = Directory.GetFiles(folder, "*.csproj"); + if (projectFiles.Any()) + { + projectFile = projectFiles.Single(); + break; + } + + folder = Path.GetDirectoryName(folder); + } + + return projectFile; + } + private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) { if (!InterfaceCache.ContainsKey(newInterfaceModifier.Identifier.Text)) From ad34bea88769a1afd19864180579e06f3217e038 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 02:42:29 +0100 Subject: [PATCH 19/46] added mockables. --- src/AdvApi32.Desktop/AdvApi32Mockable.cs | 186 +++ src/AdvApi32.Desktop/IAdvApi32Mockable.cs | 180 +++ src/BCrypt/BCryptMockable.cs | 663 ++++++++++ src/BCrypt/IBCryptMockable.cs | 641 +++++++++ src/Gdi32.Desktop/Gdi32Mockable.cs | 11 + src/Gdi32.Desktop/IGdi32Mockable.cs | 10 + src/Hid.Shared/HidMockable.cs | 301 +++++ src/Hid.Shared/IHidMockable.cs | 285 ++++ src/ImageHlp/IImageHlpMockable.cs | 41 + src/ImageHlp/ImageHlpMockable.cs | 43 + src/Kernel32.Desktop/IKernel32Mockable.cs | 1042 +++++++++++++++ src/Kernel32.Desktop/Kernel32Mockable.cs | 1076 +++++++++++++++ src/Kernel32.Shared/IKernel32Mockable.cs | 1404 ++++++++++++++++++++ src/Kernel32.Shared/Kernel32Mockable.cs | 1451 +++++++++++++++++++++ src/Kernel32/IKernel32Mockable.cs | 45 + src/Kernel32/Kernel32.csproj | 2 + src/Kernel32/Kernel32Mockable.cs | 46 + src/MockGenerator/Program.cs | 44 +- src/NCrypt/INCryptMockable.cs | 118 ++ src/NCrypt/NCryptMockable.cs | 123 ++ src/SetupApi.Desktop/ISetupApiMockable.cs | 170 +++ src/SetupApi.Desktop/SetupApiMockable.cs | 174 +++ src/User32.Desktop/IUser32Mockable.cs | 35 + src/User32.Desktop/User32Mockable.cs | 43 + 24 files changed, 8115 insertions(+), 19 deletions(-) create mode 100644 src/AdvApi32.Desktop/AdvApi32Mockable.cs create mode 100644 src/AdvApi32.Desktop/IAdvApi32Mockable.cs create mode 100644 src/BCrypt/BCryptMockable.cs create mode 100644 src/BCrypt/IBCryptMockable.cs create mode 100644 src/Gdi32.Desktop/Gdi32Mockable.cs create mode 100644 src/Gdi32.Desktop/IGdi32Mockable.cs create mode 100644 src/Hid.Shared/HidMockable.cs create mode 100644 src/Hid.Shared/IHidMockable.cs create mode 100644 src/ImageHlp/IImageHlpMockable.cs create mode 100644 src/ImageHlp/ImageHlpMockable.cs create mode 100644 src/Kernel32.Desktop/IKernel32Mockable.cs create mode 100644 src/Kernel32.Desktop/Kernel32Mockable.cs create mode 100644 src/Kernel32.Shared/IKernel32Mockable.cs create mode 100644 src/Kernel32.Shared/Kernel32Mockable.cs create mode 100644 src/Kernel32/IKernel32Mockable.cs create mode 100644 src/Kernel32/Kernel32Mockable.cs create mode 100644 src/NCrypt/INCryptMockable.cs create mode 100644 src/NCrypt/NCryptMockable.cs create mode 100644 src/SetupApi.Desktop/ISetupApiMockable.cs create mode 100644 src/SetupApi.Desktop/SetupApiMockable.cs create mode 100644 src/User32.Desktop/IUser32Mockable.cs create mode 100644 src/User32.Desktop/User32Mockable.cs diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs new file mode 100644 index 00000000..292aebf2 --- /dev/null +++ b/src/AdvApi32.Desktop/AdvApi32Mockable.cs @@ -0,0 +1,186 @@ +// 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; + public partial class AdvApi32 : IAdvApi32Mockable { + /// + /// 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 + /// + public bool InvokeChangeServiceConfig2(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 + /// + public SafeServiceHandle InvokeCreateService(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 + /// + public bool InvokeDeleteService(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 . + /// + public SafeServiceHandle InvokeOpenSCManager(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. + /// + public SafeServiceHandle InvokeOpenService(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. + /// + public bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) + => StartService(hService, dwNumServiceArgs, lpServiceArgVectors); + } +} diff --git a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs new file mode 100644 index 00000000..4f21a887 --- /dev/null +++ b/src/AdvApi32.Desktop/IAdvApi32Mockable.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; + public interface IAdvApi32Mockable { + /// + /// 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 + /// + bool InvokeChangeServiceConfig2(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 + /// + SafeServiceHandle InvokeCreateService(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 + /// + bool InvokeDeleteService(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 . + /// + SafeServiceHandle InvokeOpenSCManager(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. + /// + SafeServiceHandle InvokeOpenService(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. + /// + bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); + } +} diff --git a/src/BCrypt/BCryptMockable.cs b/src/BCrypt/BCryptMockable.cs new file mode 100644 index 00000000..79cbf4ba --- /dev/null +++ b/src/BCrypt/BCryptMockable.cs @@ -0,0 +1,663 @@ +// 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; + public partial class BCrypt : IBCryptMockable { /// + /// 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. + /// + public NTStatus InvokeBCryptOpenAlgorithmProvider( + out SafeAlgorithmHandle phAlgorithm, + string pszAlgId, + string pszImplementation, + BCryptOpenAlgorithmProviderFlags dwFlags) + => BCryptOpenAlgorithmProvider(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. + public NTStatus InvokeBCryptCreateHash( + SafeAlgorithmHandle hAlgorithm, + out SafeHashHandle phHash, + byte[] pbHashObject, + int cbHashObject, + byte[] pbSecret, + int cbSecret, + BCryptCreateHashFlags dwFlags) + => BCryptCreateHash(hAlgorithm, 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. + /// + public NTStatus InvokeBCryptEncrypt( + 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, 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. + public NTStatus InvokeBCryptDecrypt( + 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, 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. + /// + public NTStatus InvokeBCryptHashData( + 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. + public NTStatus InvokeBCryptFinishHash( + 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. + /// + public NTStatus InvokeBCryptSignHash( + 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, 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. + /// + public NTStatus InvokeBCryptVerifySignature( + 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. + /// + public NTStatus InvokeBCryptGenerateKeyPair( + SafeAlgorithmHandle hAlgorithm, + out SafeKeyHandle phKey, + int dwLength, + BCryptGenerateKeyPairFlags dwFlags = BCryptGenerateKeyPairFlags.None) + => BCryptGenerateKeyPair(hAlgorithm, 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. + public NTStatus InvokeBCryptGenerateSymmetricKey( + SafeAlgorithmHandle hAlgorithm, + out SafeKeyHandle phKey, + byte[] pbKeyObject, + int cbKeyObject, + byte[] pbSecret, + int cbSecret, + BCryptGenerateSymmetricKeyFlags flags = BCryptGenerateSymmetricKeyFlags.None) + => BCryptGenerateSymmetricKey(hAlgorithm, 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. + /// + public NTStatus InvokeBCryptFinalizeKeyPair( + 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. + public NTStatus InvokeBCryptDestroyKey( + 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. + public NTStatus InvokeBCryptDestroySecret( + 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. + public NTStatus InvokeBCryptImportKey( + 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, 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. + public NTStatus InvokeBCryptImportKeyPair( + SafeAlgorithmHandle hAlgorithm, + SafeKeyHandle hImportKey, + [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, + out SafeKeyHandle phKey, + byte[] pbInput, + int cbInput, + BCryptImportKeyPairFlags dwFlags) + => BCryptImportKeyPair(hAlgorithm, hImportKey, pszBlobType, 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. + public NTStatus InvokeBCryptExportKey( + 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, 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. + public NTStatus InvokeBCryptSecretAgreement( + SafeKeyHandle privateKey, + SafeKeyHandle publicKey, + out SafeSecretHandle secret, + BCryptSecretAgreementFlags flags = BCryptSecretAgreementFlags.None) + => BCryptSecretAgreement(privateKey, publicKey, 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. + /// + public NTStatus InvokeBCryptDeriveKey( + 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, kdfParameters, derivedKey, derivedKeySize, 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. + public NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, + int inputSize, + BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) + => BCryptSetProperty(hObject, property, input, inputSize, 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. + /// + /// The name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// 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. + public NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + string 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. + public NTStatus InvokeBCryptGetProperty( + SafeHandle hObject, + string property, + [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, + int outputSize, + out int resultSize, + BCryptGetPropertyFlags flags = BCryptGetPropertyFlags.None) + => BCryptGetProperty(hObject, property, output, outputSize, 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. + public NTStatus InvokeBCryptGenRandom( + SafeAlgorithmHandle hAlgorithm, + byte[] pbBuffer, + int cbBuffer, + BCryptGenRandomFlags flags = BCryptGenRandomFlags.None) + => BCryptGenRandom(hAlgorithm, pbBuffer, cbBuffer, flags ); + } +} diff --git a/src/BCrypt/IBCryptMockable.cs b/src/BCrypt/IBCryptMockable.cs new file mode 100644 index 00000000..6e5b51bc --- /dev/null +++ b/src/BCrypt/IBCryptMockable.cs @@ -0,0 +1,641 @@ +// 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; + public interface IBCryptMockable { /// + /// 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. + /// + NTStatus InvokeBCryptOpenAlgorithmProvider( + 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. + NTStatus InvokeBCryptCreateHash( + 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. + /// + NTStatus InvokeBCryptEncrypt( + 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. + NTStatus InvokeBCryptDecrypt( + 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. + /// + NTStatus InvokeBCryptHashData( + 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. + NTStatus InvokeBCryptFinishHash( + 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. + /// + NTStatus InvokeBCryptSignHash( + 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. + /// + NTStatus InvokeBCryptVerifySignature( + 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. + /// + NTStatus InvokeBCryptGenerateKeyPair( + 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. + NTStatus InvokeBCryptGenerateSymmetricKey( + 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. + /// + NTStatus InvokeBCryptFinalizeKeyPair( + 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. + NTStatus InvokeBCryptDestroyKey( + 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. + NTStatus InvokeBCryptDestroySecret( + 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. + NTStatus InvokeBCryptImportKey( + 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. + NTStatus InvokeBCryptImportKeyPair( + 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. + NTStatus InvokeBCryptExportKey( + 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. + NTStatus InvokeBCryptSecretAgreement( + 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. + /// + NTStatus InvokeBCryptDeriveKey( + 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. + NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, + int inputSize, + BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None); + + /// + /// Sets the value of a named property for a CNG object. + /// + /// A handle that represents the CNG object to set the property value for. + /// + /// The name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// 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. + NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + string 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. + NTStatus InvokeBCryptGetProperty( + 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. + NTStatus InvokeBCryptGenRandom( + SafeAlgorithmHandle hAlgorithm, + byte[] pbBuffer, + int cbBuffer, + BCryptGenRandomFlags flags = BCryptGenRandomFlags.None); + } +} diff --git a/src/Gdi32.Desktop/Gdi32Mockable.cs b/src/Gdi32.Desktop/Gdi32Mockable.cs new file mode 100644 index 00000000..f20495af --- /dev/null +++ b/src/Gdi32.Desktop/Gdi32Mockable.cs @@ -0,0 +1,11 @@ +// 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; + public partial class Gdi32 : IGdi32Mockable { public bool InvokeDeleteObject(IntPtr hObject) + => DeleteObject(hObject); + } +} diff --git a/src/Gdi32.Desktop/IGdi32Mockable.cs b/src/Gdi32.Desktop/IGdi32Mockable.cs new file mode 100644 index 00000000..20d9b40b --- /dev/null +++ b/src/Gdi32.Desktop/IGdi32Mockable.cs @@ -0,0 +1,10 @@ +// 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; + public interface IGdi32Mockable { bool InvokeDeleteObject(IntPtr hObject); + } +} 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/ImageHlp/IImageHlpMockable.cs b/src/ImageHlp/IImageHlpMockable.cs new file mode 100644 index 00000000..3a8e2877 --- /dev/null +++ b/src/ImageHlp/IImageHlpMockable.cs @@ -0,0 +1,41 @@ +// 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; + public interface IImageHlpMockable { /// + /// 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 . + /// + bool InvokeMapAndLoad( + 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 . + /// + bool InvokeUnMapAndLoad( + ref LOADED_IMAGE LoadedImage); + } +} diff --git a/src/ImageHlp/ImageHlpMockable.cs b/src/ImageHlp/ImageHlpMockable.cs new file mode 100644 index 00000000..ecfa97e0 --- /dev/null +++ b/src/ImageHlp/ImageHlpMockable.cs @@ -0,0 +1,43 @@ +// 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; + public partial class ImageHlp : IImageHlpMockable { /// + /// 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 . + /// + public bool InvokeMapAndLoad( + string ImageName, + string DllPath, + out LOADED_IMAGE LoadedImage, + bool DotDll, + bool ReadOnly) + => MapAndLoad(ImageName, DllPath, 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 . + /// + public bool InvokeUnMapAndLoad( + ref LOADED_IMAGE LoadedImage) + => UnMapAndLoad(LoadedImage); + } +} diff --git a/src/Kernel32.Desktop/IKernel32Mockable.cs b/src/Kernel32.Desktop/IKernel32Mockable.cs new file mode 100644 index 00000000..df85509e --- /dev/null +++ b/src/Kernel32.Desktop/IKernel32Mockable.cs @@ -0,0 +1,1042 @@ +// 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; + 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); + /// + /// 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 . + /// + bool InvokeCreateProcess( + 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 . + /// + bool InvokeCreateProcessAsUser( + 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. + /// + void InvokeGetStartupInfo( + 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. + /// + bool InvokeInitializeProcThreadAttributeList( + 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 . + /// + bool InvokeUpdateProcThreadAttribute( + 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. + /// + void InvokeDeleteProcThreadAttributeList( + 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 . + /// + bool InvokeAllocConsole(); + + /// + /// 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 . + /// + bool InvokeFreeConsole(); + + /// + /// 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 . + /// + bool InvokeAttachConsole(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 . + /// + SafeObjectHandle InvokeCreateFile( + 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. + /// + SafeFindFilesHandle InvokeFindFirstFile(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. + /// + bool InvokeFindNextFile(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. + /// + /// + SafeObjectHandle InvokeCreateToolhelp32Snapshot( + 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. + /// + bool InvokeProcess32First(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. + /// + bool InvokeProcess32Next( + 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. + bool InvokeQueryFullProcessImageName( + 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. + SafeObjectHandle InvokeOpenProcess( + 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. + /// + /// + bool InvokeGetOverlappedResult( + 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. + /// + /// + bool InvokeCancelIo(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 + /// . + /// + /// + bool InvokeIsWow64Process(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 . + /// + bool InvokeCreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize); + } +} diff --git a/src/Kernel32.Desktop/Kernel32Mockable.cs b/src/Kernel32.Desktop/Kernel32Mockable.cs new file mode 100644 index 00000000..5da04cc1 --- /dev/null +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -0,0 +1,1076 @@ +// 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; + public partial class Kernel32 : 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); + /// + /// 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 . + /// + public bool InvokeCreateProcess( + 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, lpStartupInfo, 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 . + /// + public bool InvokeCreateProcessAsUser( + 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, lpStartupInfo, 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. + /// + public void InvokeGetStartupInfo( + out STARTUPINFO lpStartupInfo) + => GetStartupInfo(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. + /// + public bool InvokeInitializeProcThreadAttributeList( + IntPtr lpAttributeList, + uint dwAttributeCount, + uint dwFlags, + ref IntPtr lpSize) + => InitializeProcThreadAttributeList(lpAttributeList, dwAttributeCount, dwFlags, 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 . + /// + public bool InvokeUpdateProcThreadAttribute( + 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, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize); + + /// + /// Deletes the specified list of attributes for process and thread creation. + /// + /// + /// The attribute list. This list is created by the function. + /// + public void InvokeDeleteProcThreadAttributeList( + 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 . + /// + public bool InvokeAllocConsole() + => 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 . + /// + public bool InvokeFreeConsole() + => 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 . + /// + public bool InvokeAttachConsole(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 . + /// + public SafeObjectHandle InvokeCreateFile( + 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. + /// + public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) + => FindFirstFile(lpFileName, 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. + /// + public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) + => FindNextFile(hFindFile, 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. + /// + /// + public SafeObjectHandle InvokeCreateToolhelp32Snapshot( + 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. + /// + public bool InvokeProcess32First(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. + /// + public bool InvokeProcess32Next( + 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. + public bool InvokeQueryFullProcessImageName( + SafeObjectHandle hProcess, + QueryFullProcessImageNameFlags dwFlags, + StringBuilder lpExeName, + ref uint lpdwSize) + => QueryFullProcessImageName(hProcess, dwFlags, lpExeName, 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. + public SafeObjectHandle InvokeOpenProcess( + 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. + /// + /// + public bool InvokeGetOverlappedResult( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped, + out uint lpNumberOfBytesTransferred, + bool bWait) + => GetOverlappedResult(hFile, lpOverlapped, 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. + /// + /// + public bool InvokeCancelIo(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 + /// . + /// + /// + public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) + => IsWow64Process(hProcess, 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 . + /// + public bool InvokeCreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize) + => CreatePipe(hReadPipe, hWritePipe, lpPipeAttributes, nSize); + } +} diff --git a/src/Kernel32.Shared/IKernel32Mockable.cs b/src/Kernel32.Shared/IKernel32Mockable.cs new file mode 100644 index 00000000..e2d899c2 --- /dev/null +++ b/src/Kernel32.Shared/IKernel32Mockable.cs @@ -0,0 +1,1404 @@ +// 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); + /// + /// 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 . + /// + bool InvokeCreateProcess( + 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 . + /// + bool InvokeCreateProcessAsUser( + 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. + /// + void InvokeGetStartupInfo( + 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. + /// + bool InvokeInitializeProcThreadAttributeList( + 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 . + /// + bool InvokeUpdateProcThreadAttribute( + 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. + /// + void InvokeDeleteProcThreadAttributeList( + 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 . + /// + bool InvokeAllocConsole(); + + /// + /// 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 . + /// + bool InvokeFreeConsole(); + + /// + /// 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 . + /// + bool InvokeAttachConsole(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 . + /// + SafeObjectHandle InvokeCreateFile( + 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. + /// + SafeFindFilesHandle InvokeFindFirstFile(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. + /// + bool InvokeFindNextFile(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. + /// + /// + SafeObjectHandle InvokeCreateToolhelp32Snapshot( + 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. + /// + bool InvokeProcess32First(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. + /// + bool InvokeProcess32Next( + 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. + bool InvokeQueryFullProcessImageName( + 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. + SafeObjectHandle InvokeOpenProcess( + 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. + /// + /// + bool InvokeGetOverlappedResult( + 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. + /// + /// + bool InvokeCancelIo(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 + /// . + /// + /// + bool InvokeIsWow64Process(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 . + /// + bool InvokeCreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize); + + /// + /// 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..22235fba --- /dev/null +++ b/src/Kernel32.Shared/Kernel32Mockable.cs @@ -0,0 +1,1451 @@ +// 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 { + /// + /// 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); + /// + /// 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 . + /// + public bool InvokeCreateProcess( + 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, lpStartupInfo, 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 . + /// + public bool InvokeCreateProcessAsUser( + 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, lpStartupInfo, 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. + /// + public void InvokeGetStartupInfo( + out STARTUPINFO lpStartupInfo) + => GetStartupInfo(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. + /// + public bool InvokeInitializeProcThreadAttributeList( + IntPtr lpAttributeList, + uint dwAttributeCount, + uint dwFlags, + ref IntPtr lpSize) + => InitializeProcThreadAttributeList(lpAttributeList, dwAttributeCount, dwFlags, 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 . + /// + public bool InvokeUpdateProcThreadAttribute( + 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, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize); + + /// + /// Deletes the specified list of attributes for process and thread creation. + /// + /// + /// The attribute list. This list is created by the function. + /// + public void InvokeDeleteProcThreadAttributeList( + 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 . + /// + public bool InvokeAllocConsole() + => 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 . + /// + public bool InvokeFreeConsole() + => 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 . + /// + public bool InvokeAttachConsole(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 . + /// + public SafeObjectHandle InvokeCreateFile( + 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. + /// + public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) + => FindFirstFile(lpFileName, 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. + /// + public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) + => FindNextFile(hFindFile, 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. + /// + /// + public SafeObjectHandle InvokeCreateToolhelp32Snapshot( + 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. + /// + public bool InvokeProcess32First(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. + /// + public bool InvokeProcess32Next( + 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. + public bool InvokeQueryFullProcessImageName( + SafeObjectHandle hProcess, + QueryFullProcessImageNameFlags dwFlags, + StringBuilder lpExeName, + ref uint lpdwSize) + => QueryFullProcessImageName(hProcess, dwFlags, lpExeName, 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. + public SafeObjectHandle InvokeOpenProcess( + 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. + /// + /// + public bool InvokeGetOverlappedResult( + SafeObjectHandle hFile, + OVERLAPPED* lpOverlapped, + out uint lpNumberOfBytesTransferred, + bool bWait) + => GetOverlappedResult(hFile, lpOverlapped, 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. + /// + /// + public bool InvokeCancelIo(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 + /// . + /// + /// + public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) + => IsWow64Process(hProcess, 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 . + /// + public bool InvokeCreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize) + => CreatePipe(hReadPipe, hWritePipe, lpPipeAttributes, nSize); + + /// + /// 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/IKernel32Mockable.cs b/src/Kernel32/IKernel32Mockable.cs new file mode 100644 index 00000000..3e85a1f1 --- /dev/null +++ b/src/Kernel32/IKernel32Mockable.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 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); + } +} diff --git a/src/Kernel32/Kernel32.csproj b/src/Kernel32/Kernel32.csproj index 9d0ffa06..43c30b0a 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..6dbeccba --- /dev/null +++ b/src/Kernel32/Kernel32Mockable.cs @@ -0,0 +1,46 @@ +// 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 { + /// + /// 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); + } +} diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 07f19ef2..3e87d84d 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -45,15 +45,18 @@ private static void Run() for (var i = 0; i < projects.Length; i++) { var project = projects[i]; + Console.WriteLine($"Processing project {project.Name}"); + foreach (var file in project.Documents .Select(x => x.FilePath) .Where(x => x.EndsWith(".cs"))) { + Console.WriteLine($"\tProcessing {Path.GetFileName(file)}"); ProcessSourceCodes(ref solution, ref project, file); } - } - workspace.TryApplyChanges(solution); + workspace.TryApplyChanges(solution); + } } private static void ProcessSourceCodes(ref Solution solution, ref Project project, string file) @@ -135,8 +138,16 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec .AddMembers(newClassDeclaration) .ToFullString()); - project = project.AddDocument(Path.GetFileName(mockableClassPath), File.ReadAllText(mockableClassPath)).Project; - project = project.AddDocument(Path.GetFileName(mockableInterfacePath), File.ReadAllText(mockableInterfacePath)).Project; + if (!DoesProjectContainFile(project, mockableClassPath)) + { + AddPathToProject(ref project, mockableClassPath); + } + + if (!DoesProjectContainFile(project, mockableInterfacePath)) + { + AddPathToProject(ref project, mockableInterfacePath); + } + solution = project.Solution; } @@ -160,23 +171,18 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec } } - private static string GetProjectFile(string file) + private static bool DoesProjectContainFile(Project project, string path) { - var folder = Path.GetDirectoryName(file); - var projectFile = (string)null; - while (folder != null) - { - var projectFiles = Directory.GetFiles(folder, "*.csproj"); - if (projectFiles.Any()) - { - projectFile = projectFiles.Single(); - break; - } - - folder = Path.GetDirectoryName(folder); - } + return project.Documents.Any(x => x.Name == Path.GetFileName(path)); + } - return projectFile; + private static void AddPathToProject(ref Project project, string mockableClassPath) + { + project = + project.AddDocument(Path.GetFileName(mockableClassPath), + File.ReadAllText(mockableClassPath), + null, + mockableClassPath).Project; } private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) diff --git a/src/NCrypt/INCryptMockable.cs b/src/NCrypt/INCryptMockable.cs new file mode 100644 index 00000000..b272d0c7 --- /dev/null +++ b/src/NCrypt/INCryptMockable.cs @@ -0,0 +1,118 @@ +// 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; + public interface INCryptMockable { /// + /// 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. + SECURITY_STATUS InvokeNCryptOpenStorageProvider( + 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. + SECURITY_STATUS InvokeNCryptCreatePersistedKey( + 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. + SECURITY_STATUS InvokeNCryptFinalizeKey( + 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. + SECURITY_STATUS InvokeNCryptGetProperty( + 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. + SECURITY_STATUS InvokeNCryptSetProperty( + SafeHandle hObject, + string pszProperty, + byte[] pbInput, + int cbInput, + NCryptSetPropertyFlags dwFlags); + } +} diff --git a/src/NCrypt/NCryptMockable.cs b/src/NCrypt/NCryptMockable.cs new file mode 100644 index 00000000..f8df1460 --- /dev/null +++ b/src/NCrypt/NCryptMockable.cs @@ -0,0 +1,123 @@ +// 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; + public partial class NCrypt : INCryptMockable { /// + /// 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. + public SECURITY_STATUS InvokeNCryptOpenStorageProvider( + out SafeProviderHandle phProvider, + string pszProviderName, + NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None) + => NCryptOpenStorageProvider(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. + public SECURITY_STATUS InvokeNCryptCreatePersistedKey( + SafeProviderHandle hProvider, + out SafeKeyHandle phKey, + string pszAlgId, + string pszKeyName = null, + LegacyKeySpec dwLegacyKeySpec = LegacyKeySpec.None, + NCryptCreatePersistedKeyFlags dwFlags = NCryptCreatePersistedKeyFlags.None) + => NCryptCreatePersistedKey(hProvider, 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. + public SECURITY_STATUS InvokeNCryptFinalizeKey( + 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. + public SECURITY_STATUS InvokeNCryptGetProperty( + SafeHandle hObject, + string pszProperty, + [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, + int cbOutput, + out int pcbResult, + NCryptGetPropertyFlags dwFlags) + => NCryptGetProperty(hObject, pszProperty, pbOutput, cbOutput, 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. + public SECURITY_STATUS InvokeNCryptSetProperty( + SafeHandle hObject, + string pszProperty, + byte[] pbInput, + int cbInput, + NCryptSetPropertyFlags dwFlags) + => NCryptSetProperty(hObject, pszProperty, pbInput, cbInput, dwFlags); + } +} diff --git a/src/SetupApi.Desktop/ISetupApiMockable.cs b/src/SetupApi.Desktop/ISetupApiMockable.cs new file mode 100644 index 00000000..de249cbe --- /dev/null +++ b/src/SetupApi.Desktop/ISetupApiMockable.cs @@ -0,0 +1,170 @@ +// 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; + public interface ISetupApiMockable { /// + /// 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. + /// + SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( + 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 + /// . + /// + bool InvokeSetupDiEnumDeviceInterfaces( + 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 + /// . + /// + bool InvokeSetupDiGetDeviceInterfaceDetail( + 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 + /// . + /// + bool InvokeSetupDiEnumDeviceInfo( + SafeDeviceInfoSetHandle deviceInfoSet, + uint memberIndex, + DeviceInfoData deviceInfoData); + } +} \ No newline at end of file diff --git a/src/SetupApi.Desktop/SetupApiMockable.cs b/src/SetupApi.Desktop/SetupApiMockable.cs new file mode 100644 index 00000000..de290f56 --- /dev/null +++ b/src/SetupApi.Desktop/SetupApiMockable.cs @@ -0,0 +1,174 @@ +// 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; + public partial class SetupApi : ISetupApiMockable { /// + /// 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. + /// + public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( + 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 + /// . + /// + public bool InvokeSetupDiEnumDeviceInterfaces( + SafeDeviceInfoSetHandle deviceInfoSet, + DeviceInfoData deviceInfoData, + ref Guid interfaceClassGuid, + uint memberIndex, + ref DeviceInterfaceData deviceInterfaceData) + => SetupDiEnumDeviceInterfaces(deviceInfoSet, deviceInfoData, interfaceClassGuid, memberIndex, 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 + /// . + /// + public bool InvokeSetupDiGetDeviceInterfaceDetail( + SafeDeviceInfoSetHandle deviceInfoSet, + ref DeviceInterfaceData deviceInterfaceData, + IntPtr deviceInterfaceDetailData, + uint deviceInterfaceDetailDataSize, + NullableUInt32 requiredSize, + DeviceInfoData deviceInfoData) + => SetupDiGetDeviceInterfaceDetail(deviceInfoSet, 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 + /// . + /// + public bool InvokeSetupDiEnumDeviceInfo( + SafeDeviceInfoSetHandle deviceInfoSet, + uint memberIndex, + DeviceInfoData deviceInfoData) + => SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, deviceInfoData); + } +} \ No newline at end of file diff --git a/src/User32.Desktop/IUser32Mockable.cs b/src/User32.Desktop/IUser32Mockable.cs new file mode 100644 index 00000000..dbbf3180 --- /dev/null +++ b/src/User32.Desktop/IUser32Mockable.cs @@ -0,0 +1,35 @@ +// 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; + public interface IUser32Mockable { int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); + + int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); + + bool InvokeSetWindowPos( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int X, + int Y, + int cx, + int cy, + SetWindowPosFlags uFlags); + + IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent); + + IntPtr InvokeFindWindowEx( + IntPtr parentHandle, + IntPtr childAfter, + string className, + string windowTitle); + + bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); + + IntPtr InvokeGetForegroundWindow(); + + int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); + } +} diff --git a/src/User32.Desktop/User32Mockable.cs b/src/User32.Desktop/User32Mockable.cs new file mode 100644 index 00000000..f471a712 --- /dev/null +++ b/src/User32.Desktop/User32Mockable.cs @@ -0,0 +1,43 @@ +// 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; + public partial class User32 : IUser32Mockable { public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) + => SetWindowLong(hWnd, nIndex, dwNewLong); + + public int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) + => GetWindowLong(hWnd, nIndex); + + public bool InvokeSetWindowPos( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int X, + int Y, + int cx, + int cy, + SetWindowPosFlags uFlags) + => SetWindowPos(hWnd, hWndInsertAfter, X, Y, cx, cy, uFlags); + + public IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent) + => SetParent(hWndChild, hWndNewParent); + + public IntPtr InvokeFindWindowEx( + IntPtr parentHandle, + IntPtr childAfter, + string className, + string windowTitle) + => FindWindowEx(parentHandle, childAfter, className, windowTitle); + + public bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) + => ShowWindow(hWnd, nCmdShow); + + public IntPtr InvokeGetForegroundWindow() + => GetForegroundWindow(); + + public int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) + => SendMessage(hWnd, wMsg, wParam, lParam); + } +} From 4172584ab17180e4603a6b62c3962d6bd2afff74 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 02:45:24 +0100 Subject: [PATCH 20/46] more updates. --- src/BCrypt/BCrypt.csproj | 2 ++ src/Kernel32.Desktop/Kernel32Mockable.cs | 2 +- src/Kernel32.Shared/Kernel32Mockable.cs | 2 +- src/MockGenerator/Program.cs | 39 +++++++++++------------- 4 files changed, 21 insertions(+), 24 deletions(-) diff --git a/src/BCrypt/BCrypt.csproj b/src/BCrypt/BCrypt.csproj index ef0f928b..e9923540 100644 --- a/src/BCrypt/BCrypt.csproj +++ b/src/BCrypt/BCrypt.csproj @@ -60,6 +60,8 @@ + + diff --git a/src/Kernel32.Desktop/Kernel32Mockable.cs b/src/Kernel32.Desktop/Kernel32Mockable.cs index 5da04cc1..22ba9cd8 100644 --- a/src/Kernel32.Desktop/Kernel32Mockable.cs +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -6,7 +6,7 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using System.Text; - public partial class Kernel32 : IKernel32Mockable { + 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. diff --git a/src/Kernel32.Shared/Kernel32Mockable.cs b/src/Kernel32.Shared/Kernel32Mockable.cs index 22235fba..50fc1d77 100644 --- a/src/Kernel32.Shared/Kernel32Mockable.cs +++ b/src/Kernel32.Shared/Kernel32Mockable.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; - public partial class Kernel32 : IKernel32Mockable { + 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. diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 3e87d84d..25685dfb 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -52,14 +52,12 @@ private static void Run() .Where(x => x.EndsWith(".cs"))) { Console.WriteLine($"\tProcessing {Path.GetFileName(file)}"); - ProcessSourceCodes(ref solution, ref project, file); + ProcessSourceCodes(workspace, ref solution, ref project, file); } - - workspace.TryApplyChanges(solution); } } - private static void ProcessSourceCodes(ref Solution solution, ref Project project, string file) + private static void ProcessSourceCodes(Workspace workspace, ref Solution solution, ref Project project, string file) { var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(file)); @@ -138,17 +136,11 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec .AddMembers(newClassDeclaration) .ToFullString()); - if (!DoesProjectContainFile(project, mockableClassPath)) - { - AddPathToProject(ref project, mockableClassPath); - } - - if (!DoesProjectContainFile(project, mockableInterfacePath)) - { - AddPathToProject(ref project, mockableInterfacePath); - } + AddPathToProject(ref project, mockableClassPath); + AddPathToProject(ref project, mockableInterfacePath); solution = project.Solution; + workspace.TryApplyChanges(solution); } if (methodDeclarations.Length <= 0) @@ -178,11 +170,14 @@ private static bool DoesProjectContainFile(Project project, string path) private static void AddPathToProject(ref Project project, string mockableClassPath) { - project = - project.AddDocument(Path.GetFileName(mockableClassPath), - File.ReadAllText(mockableClassPath), - null, - mockableClassPath).Project; + if (!DoesProjectContainFile(project, mockableClassPath)) + { + project = + project.AddDocument(Path.GetFileName(mockableClassPath), + File.ReadAllText(mockableClassPath), + null, + mockableClassPath).Project; + } } private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) @@ -329,9 +324,9 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec var arrowBody = SyntaxFactory.ArrowExpressionClause( SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken) .WithLeadingTrivia( - NewLineCharacter, - TabCharacter, - TabCharacter, + NewLineCharacter, + TabCharacter, + TabCharacter, TabCharacter) .WithTrailingTrivia(WhitespaceCharacter), SyntaxFactory.InvocationExpression( @@ -358,7 +353,7 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec .AddMembers( wrapperMethodDeclaration .WithTrailingTrivia( - NewLineCharacter, + NewLineCharacter, TabCharacter) .WithLeadingTrivia(dllImport.OpenBracketToken.LeadingTrivia)); return classDeclaration; From a31d0a65376ae9ae81178f0d0bba286de474798d Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 02:55:04 +0100 Subject: [PATCH 21/46] foo changes. --- src/BCrypt/BCryptMockable.cs | 427 --------- src/BCrypt/IBCryptMockable.cs | 411 --------- src/Kernel32.Shared/IKernel32Mockable.cs | 1032 --------------------- src/Kernel32.Shared/Kernel32Mockable.cs | 1066 ---------------------- src/Kernel32/Kernel32Mockable.cs | 2 +- src/MockGenerator/Program.cs | 43 +- 6 files changed, 16 insertions(+), 2965 deletions(-) diff --git a/src/BCrypt/BCryptMockable.cs b/src/BCrypt/BCryptMockable.cs index 79cbf4ba..2dce78d4 100644 --- a/src/BCrypt/BCryptMockable.cs +++ b/src/BCrypt/BCryptMockable.cs @@ -232,432 +232,5 @@ public NTStatus InvokeBCryptFinishHash( 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. - /// - public NTStatus InvokeBCryptSignHash( - 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, 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. - /// - public NTStatus InvokeBCryptVerifySignature( - 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. - /// - public NTStatus InvokeBCryptGenerateKeyPair( - SafeAlgorithmHandle hAlgorithm, - out SafeKeyHandle phKey, - int dwLength, - BCryptGenerateKeyPairFlags dwFlags = BCryptGenerateKeyPairFlags.None) - => BCryptGenerateKeyPair(hAlgorithm, 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. - public NTStatus InvokeBCryptGenerateSymmetricKey( - SafeAlgorithmHandle hAlgorithm, - out SafeKeyHandle phKey, - byte[] pbKeyObject, - int cbKeyObject, - byte[] pbSecret, - int cbSecret, - BCryptGenerateSymmetricKeyFlags flags = BCryptGenerateSymmetricKeyFlags.None) - => BCryptGenerateSymmetricKey(hAlgorithm, 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. - /// - public NTStatus InvokeBCryptFinalizeKeyPair( - 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. - public NTStatus InvokeBCryptDestroyKey( - 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. - public NTStatus InvokeBCryptDestroySecret( - 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. - public NTStatus InvokeBCryptImportKey( - 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, 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. - public NTStatus InvokeBCryptImportKeyPair( - SafeAlgorithmHandle hAlgorithm, - SafeKeyHandle hImportKey, - [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, - out SafeKeyHandle phKey, - byte[] pbInput, - int cbInput, - BCryptImportKeyPairFlags dwFlags) - => BCryptImportKeyPair(hAlgorithm, hImportKey, pszBlobType, 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. - public NTStatus InvokeBCryptExportKey( - 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, 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. - public NTStatus InvokeBCryptSecretAgreement( - SafeKeyHandle privateKey, - SafeKeyHandle publicKey, - out SafeSecretHandle secret, - BCryptSecretAgreementFlags flags = BCryptSecretAgreementFlags.None) - => BCryptSecretAgreement(privateKey, publicKey, 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. - /// - public NTStatus InvokeBCryptDeriveKey( - 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, kdfParameters, derivedKey, derivedKeySize, 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. - public NTStatus InvokeBCryptSetProperty( - SafeHandle hObject, - string property, - [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, - int inputSize, - BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) - => BCryptSetProperty(hObject, property, input, inputSize, 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. - /// - /// The name of the property to set. This can be one of the predefined or a custom property identifier. - /// - /// 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. - public NTStatus InvokeBCryptSetProperty( - SafeHandle hObject, - string property, - string 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. - public NTStatus InvokeBCryptGetProperty( - SafeHandle hObject, - string property, - [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, - int outputSize, - out int resultSize, - BCryptGetPropertyFlags flags = BCryptGetPropertyFlags.None) - => BCryptGetProperty(hObject, property, output, outputSize, 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. - public NTStatus InvokeBCryptGenRandom( - SafeAlgorithmHandle hAlgorithm, - byte[] pbBuffer, - int cbBuffer, - BCryptGenRandomFlags flags = BCryptGenRandomFlags.None) - => BCryptGenRandom(hAlgorithm, pbBuffer, cbBuffer, flags ); } } diff --git a/src/BCrypt/IBCryptMockable.cs b/src/BCrypt/IBCryptMockable.cs index 6e5b51bc..30c70a8a 100644 --- a/src/BCrypt/IBCryptMockable.cs +++ b/src/BCrypt/IBCryptMockable.cs @@ -226,416 +226,5 @@ NTStatus InvokeBCryptFinishHash( [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. - /// - NTStatus InvokeBCryptSignHash( - 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. - /// - NTStatus InvokeBCryptVerifySignature( - 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. - /// - NTStatus InvokeBCryptGenerateKeyPair( - 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. - NTStatus InvokeBCryptGenerateSymmetricKey( - 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. - /// - NTStatus InvokeBCryptFinalizeKeyPair( - 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. - NTStatus InvokeBCryptDestroyKey( - 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. - NTStatus InvokeBCryptDestroySecret( - 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. - NTStatus InvokeBCryptImportKey( - 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. - NTStatus InvokeBCryptImportKeyPair( - 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. - NTStatus InvokeBCryptExportKey( - 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. - NTStatus InvokeBCryptSecretAgreement( - 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. - /// - NTStatus InvokeBCryptDeriveKey( - 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. - NTStatus InvokeBCryptSetProperty( - SafeHandle hObject, - string property, - [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, - int inputSize, - BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None); - - /// - /// Sets the value of a named property for a CNG object. - /// - /// A handle that represents the CNG object to set the property value for. - /// - /// The name of the property to set. This can be one of the predefined or a custom property identifier. - /// - /// 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. - NTStatus InvokeBCryptSetProperty( - SafeHandle hObject, - string property, - string 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. - NTStatus InvokeBCryptGetProperty( - 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. - NTStatus InvokeBCryptGenRandom( - SafeAlgorithmHandle hAlgorithm, - byte[] pbBuffer, - int cbBuffer, - BCryptGenRandomFlags flags = BCryptGenRandomFlags.None); } } diff --git a/src/Kernel32.Shared/IKernel32Mockable.cs b/src/Kernel32.Shared/IKernel32Mockable.cs index e2d899c2..5c0c335c 100644 --- a/src/Kernel32.Shared/IKernel32Mockable.cs +++ b/src/Kernel32.Shared/IKernel32Mockable.cs @@ -339,1038 +339,6 @@ bool InvokeWriteFile( /// 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); - /// - /// 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 . - /// - bool InvokeCreateProcess( - 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 . - /// - bool InvokeCreateProcessAsUser( - 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. - /// - void InvokeGetStartupInfo( - 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. - /// - bool InvokeInitializeProcThreadAttributeList( - 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 . - /// - bool InvokeUpdateProcThreadAttribute( - 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. - /// - void InvokeDeleteProcThreadAttributeList( - 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 . - /// - bool InvokeAllocConsole(); - - /// - /// 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 . - /// - bool InvokeFreeConsole(); - - /// - /// 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 . - /// - bool InvokeAttachConsole(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 . - /// - SafeObjectHandle InvokeCreateFile( - 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. - /// - SafeFindFilesHandle InvokeFindFirstFile(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. - /// - bool InvokeFindNextFile(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. - /// - /// - SafeObjectHandle InvokeCreateToolhelp32Snapshot( - 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. - /// - bool InvokeProcess32First(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. - /// - bool InvokeProcess32Next( - 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. - bool InvokeQueryFullProcessImageName( - 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. - SafeObjectHandle InvokeOpenProcess( - 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. - /// - /// - bool InvokeGetOverlappedResult( - 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. - /// - /// - bool InvokeCancelIo(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 - /// . - /// - /// - bool InvokeIsWow64Process(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 . - /// - bool InvokeCreatePipe( - out SafeObjectHandle hReadPipe, - out SafeObjectHandle hWritePipe, - SECURITY_ATTRIBUTES lpPipeAttributes, - uint nSize); - - /// - /// 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. diff --git a/src/Kernel32.Shared/Kernel32Mockable.cs b/src/Kernel32.Shared/Kernel32Mockable.cs index 50fc1d77..fd033d3c 100644 --- a/src/Kernel32.Shared/Kernel32Mockable.cs +++ b/src/Kernel32.Shared/Kernel32Mockable.cs @@ -371,1072 +371,6 @@ public WaitForSingleObjectResult InvokeWaitForSingleObject( 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); - /// - /// 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 . - /// - public bool InvokeCreateProcess( - 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, lpStartupInfo, 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 . - /// - public bool InvokeCreateProcessAsUser( - 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, lpStartupInfo, 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. - /// - public void InvokeGetStartupInfo( - out STARTUPINFO lpStartupInfo) - => GetStartupInfo(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. - /// - public bool InvokeInitializeProcThreadAttributeList( - IntPtr lpAttributeList, - uint dwAttributeCount, - uint dwFlags, - ref IntPtr lpSize) - => InitializeProcThreadAttributeList(lpAttributeList, dwAttributeCount, dwFlags, 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 . - /// - public bool InvokeUpdateProcThreadAttribute( - 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, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize); - - /// - /// Deletes the specified list of attributes for process and thread creation. - /// - /// - /// The attribute list. This list is created by the function. - /// - public void InvokeDeleteProcThreadAttributeList( - 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 . - /// - public bool InvokeAllocConsole() - => 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 . - /// - public bool InvokeFreeConsole() - => 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 . - /// - public bool InvokeAttachConsole(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 . - /// - public SafeObjectHandle InvokeCreateFile( - 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. - /// - public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) - => FindFirstFile(lpFileName, 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. - /// - public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) - => FindNextFile(hFindFile, 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. - /// - /// - public SafeObjectHandle InvokeCreateToolhelp32Snapshot( - 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. - /// - public bool InvokeProcess32First(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. - /// - public bool InvokeProcess32Next( - 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. - public bool InvokeQueryFullProcessImageName( - SafeObjectHandle hProcess, - QueryFullProcessImageNameFlags dwFlags, - StringBuilder lpExeName, - ref uint lpdwSize) - => QueryFullProcessImageName(hProcess, dwFlags, lpExeName, 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. - public SafeObjectHandle InvokeOpenProcess( - 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. - /// - /// - public bool InvokeGetOverlappedResult( - SafeObjectHandle hFile, - OVERLAPPED* lpOverlapped, - out uint lpNumberOfBytesTransferred, - bool bWait) - => GetOverlappedResult(hFile, lpOverlapped, 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. - /// - /// - public bool InvokeCancelIo(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 - /// . - /// - /// - public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) - => IsWow64Process(hProcess, 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 . - /// - public bool InvokeCreatePipe( - out SafeObjectHandle hReadPipe, - out SafeObjectHandle hWritePipe, - SECURITY_ATTRIBUTES lpPipeAttributes, - uint nSize) - => CreatePipe(hReadPipe, hWritePipe, lpPipeAttributes, nSize); - - /// - /// 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. /// diff --git a/src/Kernel32/Kernel32Mockable.cs b/src/Kernel32/Kernel32Mockable.cs index 6dbeccba..737d3599 100644 --- a/src/Kernel32/Kernel32Mockable.cs +++ b/src/Kernel32/Kernel32Mockable.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; - public partial class Kernel32 : IKernel32Mockable { + 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. diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 25685dfb..bda0b100 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -118,29 +118,14 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio string fileDirectory; var baseFileName = GetBaseFileName(file, out fileDirectory); - var mockableInterfacePath = Path.Combine( - fileDirectory, - $"I{baseFileName}Mockable.cs"); - File.WriteAllText( - mockableInterfacePath, + AddPathToProject(workspace, ref solution, ref project, $"{baseFileName}Mockable.cs", CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) - .AddMembers(newInterfaceDeclaration) + .AddMembers(newClassDeclaration) .ToFullString()); - - var mockableClassPath = Path.Combine( - fileDirectory, - $"{baseFileName}Mockable.cs"); - File.WriteAllText( - mockableClassPath, + AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) - .AddMembers(newClassDeclaration) + .AddMembers(newInterfaceDeclaration) .ToFullString()); - - AddPathToProject(ref project, mockableClassPath); - AddPathToProject(ref project, mockableInterfacePath); - - solution = project.Solution; - workspace.TryApplyChanges(solution); } if (methodDeclarations.Length <= 0) @@ -163,21 +148,23 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio } } - private static bool DoesProjectContainFile(Project project, string path) + private static Document GetExistingDocument(Project project, string path) { - return project.Documents.Any(x => x.Name == Path.GetFileName(path)); + return project.Documents.FirstOrDefault(x => x.Name == Path.GetFileName(path)); } - private static void AddPathToProject(ref Project project, string mockableClassPath) + private static void AddPathToProject(Workspace workspace, ref Solution solution, ref Project project, string fileName, string contents) { - if (!DoesProjectContainFile(project, mockableClassPath)) + var document = GetExistingDocument(project, fileName); + if (document != null) { - project = - project.AddDocument(Path.GetFileName(mockableClassPath), - File.ReadAllText(mockableClassPath), - null, - mockableClassPath).Project; + project = project.RemoveDocument(document.Id); } + + document = project.AddDocument(fileName, contents); + project = document.Project; + solution = project.Solution; + workspace.TryApplyChanges(solution); } private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) From 5c9556e3b09b8acd0a73cb0c99f1123b27b30b90 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:02:06 +0100 Subject: [PATCH 22/46] new stuff. --- src/AdvApi32.Desktop/AdvApi32.Desktop.csproj | 1 + src/AdvApi32.Desktop/AdvApi32Mockable.cs | 155 +------------------ src/Kernel32/Kernel32Mockable.cs | 2 +- src/MockGenerator/Program.cs | 11 +- 4 files changed, 13 insertions(+), 156 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj index 635923e9..8d13b5cd 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj +++ b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj @@ -61,6 +61,7 @@ + diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs index 292aebf2..a6338509 100644 --- a/src/AdvApi32.Desktop/AdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/AdvApi32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -29,158 +29,5 @@ public partial class AdvApi32 : IAdvApi32Mockable { /// public bool InvokeChangeServiceConfig2(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 - /// - public SafeServiceHandle InvokeCreateService(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 - /// - public bool InvokeDeleteService(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 . - /// - public SafeServiceHandle InvokeOpenSCManager(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. - /// - public SafeServiceHandle InvokeOpenService(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. - /// - public bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) - => StartService(hService, dwNumServiceArgs, lpServiceArgVectors); } } diff --git a/src/Kernel32/Kernel32Mockable.cs b/src/Kernel32/Kernel32Mockable.cs index 737d3599..b9f5c05e 100644 --- a/src/Kernel32/Kernel32Mockable.cs +++ b/src/Kernel32/Kernel32Mockable.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; - public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable { + public partial class Kernel32 : IKernel32Mockable , 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. diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index bda0b100..0b321b26 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -41,7 +41,7 @@ private static void Run() var solutionRoot = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(currentDirectory))), "src"); var solution = workspace.OpenSolutionAsync(Path.Combine(solutionRoot, "PInvoke.sln")).Result; - var projects = solution.Projects.ToArray(); + var projects = GetProjectsFromSolution(solution); for (var i = 0; i < projects.Length; i++) { var project = projects[i]; @@ -54,9 +54,18 @@ private static void Run() Console.WriteLine($"\tProcessing {Path.GetFileName(file)}"); ProcessSourceCodes(workspace, ref solution, ref project, file); } + + projects = GetProjectsFromSolution(solution); } } + private static Project[] GetProjectsFromSolution(Solution solution) + { + return solution.Projects + .OrderBy(x => x.Name) + .ToArray(); + } + private static void ProcessSourceCodes(Workspace workspace, ref Solution solution, ref Project project, string file) { var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(file)); From cc8e5b6ddec20176b0ec469b509757fa41e98336 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:16:42 +0100 Subject: [PATCH 23/46] updated. --- src/AdvApi32.Desktop/AdvApi32.Desktop.csproj | 1 + src/AdvApi32.Desktop/IAdvApi32Mockable.cs | 150 +------------------ src/Gdi32.Desktop/Gdi32.Desktop.csproj | 2 + src/Gdi32.Desktop/Gdi32Mockable.cs | 2 +- src/Gdi32.Desktop/IGdi32Mockable.cs | 2 +- src/MockGenerator/Program.cs | 19 ++- 6 files changed, 18 insertions(+), 158 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj index 8d13b5cd..c52fa31b 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj +++ b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj @@ -62,6 +62,7 @@ + diff --git a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs index 4f21a887..c16f3504 100644 --- a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -28,153 +28,5 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is zero /// bool InvokeChangeServiceConfig2(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 - /// - SafeServiceHandle InvokeCreateService(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 - /// - bool InvokeDeleteService(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 . - /// - SafeServiceHandle InvokeOpenSCManager(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. - /// - SafeServiceHandle InvokeOpenService(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. - /// - bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); } } diff --git a/src/Gdi32.Desktop/Gdi32.Desktop.csproj b/src/Gdi32.Desktop/Gdi32.Desktop.csproj index 02a0254c..0fc2e679 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 index f20495af..145e9b84 100644 --- a/src/Gdi32.Desktop/Gdi32Mockable.cs +++ b/src/Gdi32.Desktop/Gdi32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 diff --git a/src/Gdi32.Desktop/IGdi32Mockable.cs b/src/Gdi32.Desktop/IGdi32Mockable.cs index 20d9b40b..f07917c6 100644 --- a/src/Gdi32.Desktop/IGdi32Mockable.cs +++ b/src/Gdi32.Desktop/IGdi32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 0b321b26..327ef661 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -57,6 +57,9 @@ private static void Run() projects = GetProjectsFromSolution(solution); } + + Console.WriteLine("Done!"); + Console.ReadLine(); } private static Project[] GetProjectsFromSolution(Solution solution) @@ -165,15 +168,17 @@ private static Document GetExistingDocument(Project project, string path) private static void AddPathToProject(Workspace workspace, ref Solution solution, ref Project project, string fileName, string contents) { var document = GetExistingDocument(project, fileName); - if (document != null) + if (document == null) { - project = project.RemoveDocument(document.Id); + 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; + workspace.TryApplyChanges(solution); } - - document = project.AddDocument(fileName, contents); - project = document.Project; - solution = project.Solution; - workspace.TryApplyChanges(solution); } private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterfaceModifier) From 032d0a1bfee630a53a7df12a6101e92dfee29bac Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:24:45 +0100 Subject: [PATCH 24/46] added stuff. --- src/Hid.Desktop/Hid.Desktop.csproj | 2 + src/Hid/Hid.csproj | 2 + src/ImageHlp/IImageHlpMockable.cs | 15 +- src/ImageHlp/ImageHlp.csproj | 2 + src/ImageHlp/ImageHlpMockable.cs | 16 +- src/Kernel32.Desktop/IKernel32Mockable.cs | 601 +----------------- src/Kernel32.Desktop/Kernel32.Desktop.csproj | 2 + src/Kernel32.Desktop/Kernel32Mockable.cs | 623 +------------------ src/MockGenerator/Program.cs | 12 +- src/NCrypt/INCryptMockable.cs | 96 +-- src/NCrypt/NCrypt.csproj | 2 + src/NCrypt/NCryptMockable.cs | 100 +-- src/SetupApi.Desktop/ISetupApiMockable.cs | 117 +--- src/SetupApi.Desktop/SetupApi.Desktop.csproj | 2 + src/SetupApi.Desktop/SetupApiMockable.cs | 120 +--- src/User32.Desktop/IUser32Mockable.cs | 27 +- src/User32.Desktop/User32.Desktop.csproj | 2 + src/User32.Desktop/User32Mockable.cs | 34 +- 18 files changed, 35 insertions(+), 1740 deletions(-) diff --git a/src/Hid.Desktop/Hid.Desktop.csproj b/src/Hid.Desktop/Hid.Desktop.csproj index eb1140af..edae0fe3 100644 --- a/src/Hid.Desktop/Hid.Desktop.csproj +++ b/src/Hid.Desktop/Hid.Desktop.csproj @@ -39,6 +39,8 @@ + + diff --git a/src/Hid/Hid.csproj b/src/Hid/Hid.csproj index 5bc198b2..e2b8e981 100644 --- a/src/Hid/Hid.csproj +++ b/src/Hid/Hid.csproj @@ -23,6 +23,8 @@ + + diff --git a/src/ImageHlp/IImageHlpMockable.cs b/src/ImageHlp/IImageHlpMockable.cs index 3a8e2877..5ccfcd66 100644 --- a/src/ImageHlp/IImageHlpMockable.cs +++ b/src/ImageHlp/IImageHlpMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -24,18 +24,5 @@ bool InvokeMapAndLoad( 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 . - /// - bool InvokeUnMapAndLoad( - ref LOADED_IMAGE LoadedImage); } } diff --git a/src/ImageHlp/ImageHlp.csproj b/src/ImageHlp/ImageHlp.csproj index 5937a174..907da4e9 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 index ecfa97e0..3f2dc493 100644 --- a/src/ImageHlp/ImageHlpMockable.cs +++ b/src/ImageHlp/ImageHlpMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -25,19 +25,5 @@ public bool InvokeMapAndLoad( bool DotDll, bool ReadOnly) => MapAndLoad(ImageName, DllPath, 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 . - /// - public bool InvokeUnMapAndLoad( - ref LOADED_IMAGE LoadedImage) - => UnMapAndLoad(LoadedImage); } } diff --git a/src/Kernel32.Desktop/IKernel32Mockable.cs b/src/Kernel32.Desktop/IKernel32Mockable.cs index df85509e..29a294a3 100644 --- a/src/Kernel32.Desktop/IKernel32Mockable.cs +++ b/src/Kernel32.Desktop/IKernel32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -439,604 +439,5 @@ bool InvokeCreateProcess( 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 . - /// - bool InvokeCreateProcessAsUser( - 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. - /// - void InvokeGetStartupInfo( - 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. - /// - bool InvokeInitializeProcThreadAttributeList( - 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 . - /// - bool InvokeUpdateProcThreadAttribute( - 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. - /// - void InvokeDeleteProcThreadAttributeList( - 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 . - /// - bool InvokeAllocConsole(); - - /// - /// 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 . - /// - bool InvokeFreeConsole(); - - /// - /// 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 . - /// - bool InvokeAttachConsole(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 . - /// - SafeObjectHandle InvokeCreateFile( - 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. - /// - SafeFindFilesHandle InvokeFindFirstFile(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. - /// - bool InvokeFindNextFile(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. - /// - /// - SafeObjectHandle InvokeCreateToolhelp32Snapshot( - 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. - /// - bool InvokeProcess32First(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. - /// - bool InvokeProcess32Next( - 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. - bool InvokeQueryFullProcessImageName( - 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. - SafeObjectHandle InvokeOpenProcess( - 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. - /// - /// - bool InvokeGetOverlappedResult( - 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. - /// - /// - bool InvokeCancelIo(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 - /// . - /// - /// - bool InvokeIsWow64Process(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 . - /// - bool InvokeCreatePipe( - 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..8360c4fd 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 index 22ba9cd8..32ef45eb 100644 --- a/src/Kernel32.Desktop/Kernel32Mockable.cs +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using System.Text; - public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable { + public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable , 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. @@ -453,624 +453,5 @@ public bool InvokeCreateProcess( ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation) => CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, 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 . - /// - public bool InvokeCreateProcessAsUser( - 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, lpStartupInfo, 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. - /// - public void InvokeGetStartupInfo( - out STARTUPINFO lpStartupInfo) - => GetStartupInfo(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. - /// - public bool InvokeInitializeProcThreadAttributeList( - IntPtr lpAttributeList, - uint dwAttributeCount, - uint dwFlags, - ref IntPtr lpSize) - => InitializeProcThreadAttributeList(lpAttributeList, dwAttributeCount, dwFlags, 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 . - /// - public bool InvokeUpdateProcThreadAttribute( - 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, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize); - - /// - /// Deletes the specified list of attributes for process and thread creation. - /// - /// - /// The attribute list. This list is created by the function. - /// - public void InvokeDeleteProcThreadAttributeList( - 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 . - /// - public bool InvokeAllocConsole() - => 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 . - /// - public bool InvokeFreeConsole() - => 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 . - /// - public bool InvokeAttachConsole(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 . - /// - public SafeObjectHandle InvokeCreateFile( - 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. - /// - public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) - => FindFirstFile(lpFileName, 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. - /// - public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) - => FindNextFile(hFindFile, 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. - /// - /// - public SafeObjectHandle InvokeCreateToolhelp32Snapshot( - 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. - /// - public bool InvokeProcess32First(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. - /// - public bool InvokeProcess32Next( - 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. - public bool InvokeQueryFullProcessImageName( - SafeObjectHandle hProcess, - QueryFullProcessImageNameFlags dwFlags, - StringBuilder lpExeName, - ref uint lpdwSize) - => QueryFullProcessImageName(hProcess, dwFlags, lpExeName, 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. - public SafeObjectHandle InvokeOpenProcess( - 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. - /// - /// - public bool InvokeGetOverlappedResult( - SafeObjectHandle hFile, - OVERLAPPED* lpOverlapped, - out uint lpNumberOfBytesTransferred, - bool bWait) - => GetOverlappedResult(hFile, lpOverlapped, 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. - /// - /// - public bool InvokeCancelIo(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 - /// . - /// - /// - public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) - => IsWow64Process(hProcess, 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 . - /// - public bool InvokeCreatePipe( - out SafeObjectHandle hReadPipe, - out SafeObjectHandle hWritePipe, - SECURITY_ATTRIBUTES lpPipeAttributes, - uint nSize) - => CreatePipe(hReadPipe, hWritePipe, lpPipeAttributes, nSize); } } diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 327ef661..b671d5ac 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -8,6 +8,7 @@ namespace MockGenerator { using System.Diagnostics; using System.IO; + using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -58,7 +59,15 @@ private static void Run() projects = GetProjectsFromSolution(solution); } - Console.WriteLine("Done!"); + if (!workspace.TryApplyChanges(solution)) + { + Console.Error.WriteLine("Solution save failed."); + } + else + { + Console.WriteLine("Solution save succeeded!"); + } + Console.ReadLine(); } @@ -177,7 +186,6 @@ private static void AddPathToProject(Workspace workspace, ref Solution solution, Path.Combine(Path.GetDirectoryName(project.FilePath), fileName)); project = document.Project; solution = project.Solution; - workspace.TryApplyChanges(solution); } } diff --git a/src/NCrypt/INCryptMockable.cs b/src/NCrypt/INCryptMockable.cs index b272d0c7..c4357396 100644 --- a/src/NCrypt/INCryptMockable.cs +++ b/src/NCrypt/INCryptMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -20,99 +20,5 @@ SECURITY_STATUS InvokeNCryptOpenStorageProvider( 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. - SECURITY_STATUS InvokeNCryptCreatePersistedKey( - 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. - SECURITY_STATUS InvokeNCryptFinalizeKey( - 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. - SECURITY_STATUS InvokeNCryptGetProperty( - 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. - SECURITY_STATUS InvokeNCryptSetProperty( - SafeHandle hObject, - string pszProperty, - byte[] pbInput, - int cbInput, - NCryptSetPropertyFlags dwFlags); } } diff --git a/src/NCrypt/NCrypt.csproj b/src/NCrypt/NCrypt.csproj index 02126362..4ff0bd16 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 index f8df1460..be0c3c60 100644 --- a/src/NCrypt/NCryptMockable.cs +++ b/src/NCrypt/NCryptMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -21,103 +21,5 @@ public SECURITY_STATUS InvokeNCryptOpenStorageProvider( string pszProviderName, NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None) => NCryptOpenStorageProvider(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. - public SECURITY_STATUS InvokeNCryptCreatePersistedKey( - SafeProviderHandle hProvider, - out SafeKeyHandle phKey, - string pszAlgId, - string pszKeyName = null, - LegacyKeySpec dwLegacyKeySpec = LegacyKeySpec.None, - NCryptCreatePersistedKeyFlags dwFlags = NCryptCreatePersistedKeyFlags.None) - => NCryptCreatePersistedKey(hProvider, 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. - public SECURITY_STATUS InvokeNCryptFinalizeKey( - 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. - public SECURITY_STATUS InvokeNCryptGetProperty( - SafeHandle hObject, - string pszProperty, - [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, - int cbOutput, - out int pcbResult, - NCryptGetPropertyFlags dwFlags) - => NCryptGetProperty(hObject, pszProperty, pbOutput, cbOutput, 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. - public SECURITY_STATUS InvokeNCryptSetProperty( - SafeHandle hObject, - string pszProperty, - byte[] pbInput, - int cbInput, - NCryptSetPropertyFlags dwFlags) - => NCryptSetProperty(hObject, pszProperty, pbInput, cbInput, dwFlags); } } diff --git a/src/SetupApi.Desktop/ISetupApiMockable.cs b/src/SetupApi.Desktop/ISetupApiMockable.cs index de249cbe..c561ddfe 100644 --- a/src/SetupApi.Desktop/ISetupApiMockable.cs +++ b/src/SetupApi.Desktop/ISetupApiMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -51,120 +51,5 @@ SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( 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 - /// . - /// - bool InvokeSetupDiEnumDeviceInterfaces( - 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 - /// . - /// - bool InvokeSetupDiGetDeviceInterfaceDetail( - 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 - /// . - /// - bool InvokeSetupDiEnumDeviceInfo( - 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..1a42774e 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 index de290f56..ae0da9fc 100644 --- a/src/SetupApi.Desktop/SetupApiMockable.cs +++ b/src/SetupApi.Desktop/SetupApiMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -52,123 +52,5 @@ public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( 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 - /// . - /// - public bool InvokeSetupDiEnumDeviceInterfaces( - SafeDeviceInfoSetHandle deviceInfoSet, - DeviceInfoData deviceInfoData, - ref Guid interfaceClassGuid, - uint memberIndex, - ref DeviceInterfaceData deviceInterfaceData) - => SetupDiEnumDeviceInterfaces(deviceInfoSet, deviceInfoData, interfaceClassGuid, memberIndex, 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 - /// . - /// - public bool InvokeSetupDiGetDeviceInterfaceDetail( - SafeDeviceInfoSetHandle deviceInfoSet, - ref DeviceInterfaceData deviceInterfaceData, - IntPtr deviceInterfaceDetailData, - uint deviceInterfaceDetailDataSize, - NullableUInt32 requiredSize, - DeviceInfoData deviceInfoData) - => SetupDiGetDeviceInterfaceDetail(deviceInfoSet, 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 - /// . - /// - public bool InvokeSetupDiEnumDeviceInfo( - SafeDeviceInfoSetHandle deviceInfoSet, - uint memberIndex, - DeviceInfoData deviceInfoData) - => SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, deviceInfoData); } } \ No newline at end of file diff --git a/src/User32.Desktop/IUser32Mockable.cs b/src/User32.Desktop/IUser32Mockable.cs index dbbf3180..00f12d57 100644 --- a/src/User32.Desktop/IUser32Mockable.cs +++ b/src/User32.Desktop/IUser32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,30 +6,5 @@ namespace PInvoke using System; using System.Runtime.InteropServices; public interface IUser32Mockable { int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); - - int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); - - bool InvokeSetWindowPos( - IntPtr hWnd, - IntPtr hWndInsertAfter, - int X, - int Y, - int cx, - int cy, - SetWindowPosFlags uFlags); - - IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent); - - IntPtr InvokeFindWindowEx( - IntPtr parentHandle, - IntPtr childAfter, - string className, - string windowTitle); - - bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); - - IntPtr InvokeGetForegroundWindow(); - - int InvokeSendMessage(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..a10d221e 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 index f471a712..8fc4d1ef 100644 --- a/src/User32.Desktop/User32Mockable.cs +++ b/src/User32.Desktop/User32Mockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -7,37 +7,5 @@ namespace PInvoke using System.Runtime.InteropServices; public partial class User32 : IUser32Mockable { public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) => SetWindowLong(hWnd, nIndex, dwNewLong); - - public int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) - => GetWindowLong(hWnd, nIndex); - - public bool InvokeSetWindowPos( - IntPtr hWnd, - IntPtr hWndInsertAfter, - int X, - int Y, - int cx, - int cy, - SetWindowPosFlags uFlags) - => SetWindowPos(hWnd, hWndInsertAfter, X, Y, cx, cy, uFlags); - - public IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent) - => SetParent(hWndChild, hWndNewParent); - - public IntPtr InvokeFindWindowEx( - IntPtr parentHandle, - IntPtr childAfter, - string className, - string windowTitle) - => FindWindowEx(parentHandle, childAfter, className, windowTitle); - - public bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) - => ShowWindow(hWnd, nCmdShow); - - public IntPtr InvokeGetForegroundWindow() - => GetForegroundWindow(); - - public int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) - => SendMessage(hWnd, wMsg, wParam, lParam); } } From 616d4b28a9dae9bbab002f15fa4d81a6145f9d7a Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:26:28 +0100 Subject: [PATCH 25/46] better program. --- src/MockGenerator/Program.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index b671d5ac..de23e83a 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -114,6 +114,11 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .OfType() .Where(a => a.AttributeLists.Any(b => b.Attributes.Any(c => c.Name.ToString() == "DllImport"))) .ToArray(); + if (methodDeclarations.Length <= 0) + { + continue; + } + foreach (var methodDeclaration in methodDeclarations) { if (IsPublicStaticExternMethod(methodDeclaration)) @@ -149,11 +154,6 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .ToFullString()); } - if (methodDeclarations.Length <= 0) - { - continue; - } - var staticModifier = classDeclaration.Modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); if (staticModifier == default(SyntaxToken)) { From a5816820f7732c72e790a4003df404730aef1243 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:30:26 +0100 Subject: [PATCH 26/46] new stuff. --- src/Hid.Desktop/Hid.Desktop.csproj | 2 -- src/Hid/Hid.csproj | 2 -- src/MockGenerator/Program.cs | 18 +++++++++--------- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/Hid.Desktop/Hid.Desktop.csproj b/src/Hid.Desktop/Hid.Desktop.csproj index edae0fe3..eb1140af 100644 --- a/src/Hid.Desktop/Hid.Desktop.csproj +++ b/src/Hid.Desktop/Hid.Desktop.csproj @@ -39,8 +39,6 @@ - - diff --git a/src/Hid/Hid.csproj b/src/Hid/Hid.csproj index e2b8e981..5bc198b2 100644 --- a/src/Hid/Hid.csproj +++ b/src/Hid/Hid.csproj @@ -23,8 +23,6 @@ - - diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index de23e83a..131add41 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -100,6 +100,15 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio continue; } + var methodDeclarations = classDeclaration.Members + .OfType() + .Where(a => a.AttributeLists.Any(b => b.Attributes.Any(c => c.Name.ToString() == "DllImport"))) + .ToArray(); + if (methodDeclarations.Length <= 0) + { + continue; + } + var newInterfaceModifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}"); @@ -110,15 +119,6 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio var newClassDeclaration = ClassCache[newClassModifier.Identifier.Text]; var newInterfaceDeclaration = InterfaceCache[newInterfaceModifier.Identifier.Text]; - var methodDeclarations = classDeclaration.Members - .OfType() - .Where(a => a.AttributeLists.Any(b => b.Attributes.Any(c => c.Name.ToString() == "DllImport"))) - .ToArray(); - if (methodDeclarations.Length <= 0) - { - continue; - } - foreach (var methodDeclaration in methodDeclarations) { if (IsPublicStaticExternMethod(methodDeclaration)) From 3a66854b983401285671472f35423dcd390c067f Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:31:20 +0100 Subject: [PATCH 27/46] new hid files. --- src/Hid.Desktop/Hid.Desktop.csproj | 2 + src/Hid.Desktop/HidMockable.cs | 165 +++++++++++++++++++++++++++++ src/Hid.Desktop/IHidMockable.cs | 156 +++++++++++++++++++++++++++ src/Hid/Hid.csproj | 2 + src/Hid/HidMockable.cs | 20 ++++ src/Hid/IHidMockable.cs | 19 ++++ 6 files changed, 364 insertions(+) create mode 100644 src/Hid.Desktop/HidMockable.cs create mode 100644 src/Hid.Desktop/IHidMockable.cs create mode 100644 src/Hid/HidMockable.cs create mode 100644 src/Hid/IHidMockable.cs diff --git a/src/Hid.Desktop/Hid.Desktop.csproj b/src/Hid.Desktop/Hid.Desktop.csproj index eb1140af..edae0fe3 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..fef52b19 --- /dev/null +++ b/src/Hid.Desktop/HidMockable.cs @@ -0,0 +1,165 @@ +// 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); + } +} \ No newline at end of file diff --git a/src/Hid.Desktop/IHidMockable.cs b/src/Hid.Desktop/IHidMockable.cs new file mode 100644 index 00000000..fca05093 --- /dev/null +++ b/src/Hid.Desktop/IHidMockable.cs @@ -0,0 +1,156 @@ +// 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); + } +} \ No newline at end of file diff --git a/src/Hid/Hid.csproj b/src/Hid/Hid.csproj index 5bc198b2..e2b8e981 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..361ff375 --- /dev/null +++ b/src/Hid/HidMockable.cs @@ -0,0 +1,20 @@ +// 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); + } +} \ No newline at end of file diff --git a/src/Hid/IHidMockable.cs b/src/Hid/IHidMockable.cs new file mode 100644 index 00000000..adb0fdd5 --- /dev/null +++ b/src/Hid/IHidMockable.cs @@ -0,0 +1,19 @@ +// 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); + } +} \ No newline at end of file From f540802319beb20aca718e29bb33c33828c5e84e Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:33:29 +0100 Subject: [PATCH 28/46] class fixes. --- .../AdvApi32+ServiceControlAction.cs | 4 ++-- .../AdvApi32+ServiceControlActionType.cs | 4 ++-- .../AdvApi32+ServiceDelayedAutoStartInfo.cs | 4 ++-- .../AdvApi32+ServiceDescription.cs | 4 ++-- .../AdvApi32+ServiceFailureActions.cs | 4 ++-- .../AdvApi32+ServiceInfoLevel.cs | 4 ++-- .../AdvApi32+ServiceLaunchProtected.cs | 4 ++-- .../AdvApi32+ServiceLaunchProtectedInfo.cs | 4 ++-- .../AdvApi32+ServicePreferredNodeInfo.cs | 4 ++-- .../AdvApi32+ServicePreshutdownInfo.cs | 4 ++-- .../AdvApi32+ServiceRequiredPrivilegesInfo.cs | 4 ++-- .../AdvApi32+ServiceSidInfo.cs | 4 ++-- .../AdvApi32+ServiceSidType.cs | 4 ++-- .../AdvApi32+ServiceTrigger.cs | 4 ++-- .../AdvApi32+ServiceTriggerAction.cs | 4 ++-- .../AdvApi32+ServiceTriggerInfo.cs | 4 ++-- .../AdvApi32+ServiceTriggerType.cs | 4 ++-- src/AdvApi32.Desktop/AdvApi32.Helpers.cs | 4 ++-- src/BCrypt/BCrypt+AlgorithmIdentifiers.cs | 4 ++-- src/BCrypt/BCrypt+BCryptBuffer.cs | 4 ++-- src/BCrypt/BCrypt+BCryptBufferDesc.cs | 4 ++-- src/BCrypt/BCrypt+SafeAlgorithmHandle.cs | 4 ++-- src/BCrypt/BCrypt+SafeHashHandle.cs | 4 ++-- src/BCrypt/BCrypt+SafeKeyHandle.cs | 4 ++-- src/BCrypt/BCrypt+SafeSecretHandle.cs | 4 ++-- src/BCrypt/BCrypt.Helpers.cs | 4 ++-- src/DbgHelp/DbgHelp+Characteristics.cs | 4 ++-- src/DbgHelp/DbgHelp+LOADED_IMAGE.cs | 4 ++-- src/DbgHelp/DbgHelp.Helpers.cs | 4 ++-- src/DbgHelp/DbgHelp.cs | 4 ++-- src/Gdi32.Desktop/Gdi32.Helpers.cs | 4 ++-- src/Hid.Desktop/Hid.cs | 4 ++-- src/Hid.Shared/Hid+HiddAttributes.cs | 2 +- src/Hid.Shared/Hid+HidpCaps.cs | 4 ++-- src/Hid.Shared/Hid+SafePreparsedDataHandle.cs | 2 +- src/Hid.Shared/Hid.Helpers.cs | 4 ++-- src/ImageHlp/ImageHlp.Helpers.cs | 4 ++-- src/Kernel32.Desktop/Kernel32.Helpers.cs | 4 ++-- src/Kernel32.Shared/Kernel32+FileAttribute.cs | 4 ++-- .../Kernel32+SafeFindFilesHandle.cs | 4 ++-- .../Kernel32+SafeObjectHandle.cs | 4 ++-- .../Kernel32+WaitForSingleObjectResult.cs | 4 ++-- src/Kernel32.Shared/Kernel32.Helpers.cs | 4 ++-- src/Kernel32.Shared/Kernel32Extensions.cs | 4 ++-- src/MockGenerator/Program.cs | 22 +++++++++---------- .../NCrypt+KeyStorageImplementationType.cs | 4 ++-- .../NCrypt+KeyStoragePropertyIdentifiers.cs | 4 ++-- .../NCrypt+NCryptCreatePersistedKeyFlags.cs | 4 ++-- src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs | 4 ++-- src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs | 4 ++-- src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs | 4 ++-- src/NCrypt/NCrypt+SafeKeyHandle.cs | 4 ++-- src/NCrypt/NCrypt+SafeProviderHandle.cs | 4 ++-- src/NCrypt/NCrypt.Helpers.cs | 4 ++-- src/SetupApi.Desktop/SetupApi.Helpers.cs | 4 ++-- src/User32.Desktop/User32.Helpers.cs | 4 ++-- src/Windows.Core/Constants.cs | 4 ++-- src/Windows.Core/NTStatusFacilities.cs | 4 ++-- src/Windows.Core/NTStatusSeverity.cs | 4 ++-- src/Windows.Core/PInvokeExtensions.cs | 4 ++-- 60 files changed, 126 insertions(+), 128 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs index ed3ab67d..282a31ea 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Represents an action that the service control manager can perform. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs index 2545c165..00a68352 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Specifies action levels for the Type member of the struct. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs index e7fe955a..c802cd1e 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Contains the delayed auto-start setting of an auto-start service. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs index 2c6501a0..00459e85 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Contains a service description. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs index ad3cde28..74bc4861 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct ServiceFailureActions diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs index 4b491b50..7ad3fedc 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Describes the configuration information to be changed. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs index 6be06861..267374ca 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// The protection type of the service diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs index 1770546f..9bb0c9f5 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Indicates a service protection type. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs index 1e6d697a..44c16649 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Represents the preferred node on which to run a service. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs index 4d806f78..da9d0cd6 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Contains preshutdown settings diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs index ff0fdb69..c95b1ac6 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Represents the required privileges for a service. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs index abab4e42..913a1b1d 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Represents a service security identifier (SID). diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs index 68b63fd8..de950c08 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Represents a service security identifier (SID). diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs index 6cc4cbda..7fbde13c 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Represents a service trigger event. This structure is used by the structure. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs index 2668c64e..f5176507 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public static partial class AdvApi32 + public partial class AdvApi32 { public enum ServiceTriggerAction { diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs index 757b17ed..a5f0ab67 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public static partial class AdvApi32 + public partial class AdvApi32 { /// /// Contains trigger event information for a service. This structure is used by the and QueryServiceConfig2 functions. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs index b2576bad..31b65d53 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public static partial class AdvApi32 + public partial class AdvApi32 { public enum ServiceTriggerType { diff --git a/src/AdvApi32.Desktop/AdvApi32.Helpers.cs b/src/AdvApi32.Desktop/AdvApi32.Helpers.cs index 5db926e5..43b3063a 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Helpers.cs +++ b/src/AdvApi32.Desktop/AdvApi32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class AdvApi32 + public partial class AdvApi32 { public static void InstallService(string servicePath, string serviceName, string serviceDisplayName, string serviceDescription, string userName, string password) { diff --git a/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs b/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs index 406bd009..6ce26759 100644 --- a/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs +++ b/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// The identifiers for the algorithms defined within BCrypt itself. diff --git a/src/BCrypt/BCrypt+BCryptBuffer.cs b/src/BCrypt/BCrypt+BCryptBuffer.cs index 8ce6809d..8e63b24c 100644 --- a/src/BCrypt/BCrypt+BCryptBuffer.cs +++ b/src/BCrypt/BCrypt+BCryptBuffer.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// Used to represent a generic CNG buffer. diff --git a/src/BCrypt/BCrypt+BCryptBufferDesc.cs b/src/BCrypt/BCrypt+BCryptBufferDesc.cs index 928bccd4..408f3b98 100644 --- a/src/BCrypt/BCrypt+BCryptBufferDesc.cs +++ b/src/BCrypt/BCrypt+BCryptBufferDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// Used to contain a set of generic CNG buffers. diff --git a/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs b/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs index caf74047..fea9c41a 100644 --- a/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs +++ b/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// A BCrypt algorithm handle. diff --git a/src/BCrypt/BCrypt+SafeHashHandle.cs b/src/BCrypt/BCrypt+SafeHashHandle.cs index 419e282a..ac104836 100644 --- a/src/BCrypt/BCrypt+SafeHashHandle.cs +++ b/src/BCrypt/BCrypt+SafeHashHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// A BCrypt cryptographic hash handle. diff --git a/src/BCrypt/BCrypt+SafeKeyHandle.cs b/src/BCrypt/BCrypt+SafeKeyHandle.cs index 924e951a..a1dfdf64 100644 --- a/src/BCrypt/BCrypt+SafeKeyHandle.cs +++ b/src/BCrypt/BCrypt+SafeKeyHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// A BCrypt cryptographic key handle. diff --git a/src/BCrypt/BCrypt+SafeSecretHandle.cs b/src/BCrypt/BCrypt+SafeSecretHandle.cs index b56c7d09..bb558e5c 100644 --- a/src/BCrypt/BCrypt+SafeSecretHandle.cs +++ b/src/BCrypt/BCrypt+SafeSecretHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public static partial class BCrypt + public partial class BCrypt { /// /// A safe handle for BCrypt secrets. diff --git a/src/BCrypt/BCrypt.Helpers.cs b/src/BCrypt/BCrypt.Helpers.cs index 6cbaa6d8..4535999f 100644 --- a/src/BCrypt/BCrypt.Helpers.cs +++ b/src/BCrypt/BCrypt.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class BCrypt + public partial class BCrypt { /// /// Loads and initializes a CNG provider. diff --git a/src/DbgHelp/DbgHelp+Characteristics.cs b/src/DbgHelp/DbgHelp+Characteristics.cs index a476693e..6f2d8807 100644 --- a/src/DbgHelp/DbgHelp+Characteristics.cs +++ b/src/DbgHelp/DbgHelp+Characteristics.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class DbgHelp + public partial class DbgHelp { /// /// Describes a native binary image. diff --git a/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs b/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs index 9022d67f..d8abee40 100644 --- a/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs +++ b/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class DbgHelp + public partial class DbgHelp { /// /// Contains information about the loaded image. diff --git a/src/DbgHelp/DbgHelp.Helpers.cs b/src/DbgHelp/DbgHelp.Helpers.cs index e66326e8..67de8ebf 100644 --- a/src/DbgHelp/DbgHelp.Helpers.cs +++ b/src/DbgHelp/DbgHelp.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class DbgHelp + public partial class DbgHelp { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/DbgHelp/DbgHelp.cs b/src/DbgHelp/DbgHelp.cs index f8ed233a..1e4c8923 100644 --- a/src/DbgHelp/DbgHelp.cs +++ b/src/DbgHelp/DbgHelp.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the DbgHelp.dll Windows library /// that are available to Desktop and Store apps. /// - public static partial class DbgHelp + public partial class DbgHelp { } } diff --git a/src/Gdi32.Desktop/Gdi32.Helpers.cs b/src/Gdi32.Desktop/Gdi32.Helpers.cs index 73e8ea46..3d15aff5 100644 --- a/src/Gdi32.Desktop/Gdi32.Helpers.cs +++ b/src/Gdi32.Desktop/Gdi32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class Gdi32 + public partial class Gdi32 { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/Hid.Desktop/Hid.cs b/src/Hid.Desktop/Hid.cs index 25184d7b..d28e734c 100644 --- a/src/Hid.Desktop/Hid.cs +++ b/src/Hid.Desktop/Hid.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -7,7 +7,7 @@ namespace PInvoke /// Exported functions from the Hid.dll Windows library /// that are available to Desktop apps only. /// - public static partial class Hid + public partial class Hid { } } diff --git a/src/Hid.Shared/Hid+HiddAttributes.cs b/src/Hid.Shared/Hid+HiddAttributes.cs index af239b70..d589f0cf 100644 --- a/src/Hid.Shared/Hid+HiddAttributes.cs +++ b/src/Hid.Shared/Hid+HiddAttributes.cs @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class Hid + public partial class Hid { /// /// The HIDD_ATTRIBUTES structure contains vendor information about a HIDClass device. diff --git a/src/Hid.Shared/Hid+HidpCaps.cs b/src/Hid.Shared/Hid+HidpCaps.cs index fde9f540..a419ee5d 100644 --- a/src/Hid.Shared/Hid+HidpCaps.cs +++ b/src/Hid.Shared/Hid+HidpCaps.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class Hid + public partial class Hid { /// /// The HIDP_CAPS structure contains information about a top-level collection's capability. diff --git a/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs b/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs index 40f8dcbd..4ca758c3 100644 --- a/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs +++ b/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs @@ -10,7 +10,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class Hid + public partial class Hid { /// /// Represents a preparsed data handle created by diff --git a/src/Hid.Shared/Hid.Helpers.cs b/src/Hid.Shared/Hid.Helpers.cs index 84ebf7c0..8962b234 100644 --- a/src/Hid.Shared/Hid.Helpers.cs +++ b/src/Hid.Shared/Hid.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -13,7 +13,7 @@ namespace PInvoke /// a slightly higher level of functionality to ease calling into native code. /// [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Functions are named like their native counterparts")] - public static partial class Hid + public partial class Hid { public static Guid HidD_GetHidGuid() { diff --git a/src/ImageHlp/ImageHlp.Helpers.cs b/src/ImageHlp/ImageHlp.Helpers.cs index 6fb9f678..ca87666b 100644 --- a/src/ImageHlp/ImageHlp.Helpers.cs +++ b/src/ImageHlp/ImageHlp.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class ImageHlp + public partial class ImageHlp { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/Kernel32.Desktop/Kernel32.Helpers.cs b/src/Kernel32.Desktop/Kernel32.Helpers.cs index 8c572a45..49290528 100644 --- a/src/Kernel32.Desktop/Kernel32.Helpers.cs +++ b/src/Kernel32.Desktop/Kernel32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class Kernel32 + public partial class Kernel32 { /// Retrieves information about the first process encountered in a system snapshot. /// diff --git a/src/Kernel32.Shared/Kernel32+FileAttribute.cs b/src/Kernel32.Shared/Kernel32+FileAttribute.cs index c28da2b3..d41bf28b 100644 --- a/src/Kernel32.Shared/Kernel32+FileAttribute.cs +++ b/src/Kernel32.Shared/Kernel32+FileAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// Defines the Win32 FileAttributes enum. diff --git a/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs b/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs index 3ca67dff..0291a255 100644 --- a/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs +++ b/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// Represents a Win32 handle that can be closed with . diff --git a/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs b/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs index 4387eb74..0c3baf0c 100644 --- a/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs +++ b/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// Represents a Win32 handle that can be closed with . diff --git a/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs b/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs index 7835cab5..f411ffe7 100644 --- a/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs +++ b/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// Values that may be returned from the function. diff --git a/src/Kernel32.Shared/Kernel32.Helpers.cs b/src/Kernel32.Shared/Kernel32.Helpers.cs index 0da4ba81..0705e1cf 100644 --- a/src/Kernel32.Shared/Kernel32.Helpers.cs +++ b/src/Kernel32.Shared/Kernel32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class Kernel32 + public partial class Kernel32 { /// /// Returns the error code returned by the last unmanaged function that was called using platform invoke that has diff --git a/src/Kernel32.Shared/Kernel32Extensions.cs b/src/Kernel32.Shared/Kernel32Extensions.cs index aaca6cb9..b9adb731 100644 --- a/src/Kernel32.Shared/Kernel32Extensions.cs +++ b/src/Kernel32.Shared/Kernel32Extensions.cs @@ -1,9 +1,9 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 { - public static class Kernel32Extensions + public class Kernel32Extensions { /// /// Throws an exception if a P/Invoke failed. diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 131add41..abd6e275 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -100,6 +100,16 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio continue; } + var staticModifier = classDeclaration.Modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); + if (staticModifier != default(SyntaxToken)) + { + compilationUnit = compilationUnit.ReplaceNode( + classDeclaration, + classDeclaration.WithModifiers( + classDeclaration.Modifiers.Remove(staticModifier))); + File.WriteAllText(file, compilationUnit.ToFullString()); + } + var methodDeclarations = classDeclaration.Members .OfType() .Where(a => a.AttributeLists.Any(b => b.Attributes.Any(c => c.Name.ToString() == "DllImport"))) @@ -153,18 +163,6 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .AddMembers(newInterfaceDeclaration) .ToFullString()); } - - var staticModifier = classDeclaration.Modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); - if (staticModifier == default(SyntaxToken)) - { - continue; - } - - compilationUnit = compilationUnit.ReplaceNode( - classDeclaration, - classDeclaration.WithModifiers( - classDeclaration.Modifiers.Remove(staticModifier))); - File.WriteAllText(file, compilationUnit.ToFullString()); } } } diff --git a/src/NCrypt/NCrypt+KeyStorageImplementationType.cs b/src/NCrypt/NCrypt+KeyStorageImplementationType.cs index 09e5ad13..66a804ff 100644 --- a/src/NCrypt/NCrypt+KeyStorageImplementationType.cs +++ b/src/NCrypt/NCrypt+KeyStorageImplementationType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Describes the key storage implementation types that may be returned by the diff --git a/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs b/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs index 22f630dc..9073c8d0 100644 --- a/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs +++ b/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Defines the names of the built-in key storage property identifiers diff --git a/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs b/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs index dfee143f..749adf24 100644 --- a/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Flags that may be passed to the method. diff --git a/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs b/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs index d3854c2d..d87198b7 100644 --- a/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Flags that may be passed to the function. diff --git a/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs b/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs index 9723b2ae..7a06637d 100644 --- a/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Flags that may be supplied to the function. diff --git a/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs b/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs index d4f19b07..ec42fc15 100644 --- a/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Flags that may be supplied to the function. diff --git a/src/NCrypt/NCrypt+SafeKeyHandle.cs b/src/NCrypt/NCrypt+SafeKeyHandle.cs index 46a4845a..ee863375 100644 --- a/src/NCrypt/NCrypt+SafeKeyHandle.cs +++ b/src/NCrypt/NCrypt+SafeKeyHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class NCrypt + public partial class NCrypt { /// /// An NCrypt key handle. diff --git a/src/NCrypt/NCrypt+SafeProviderHandle.cs b/src/NCrypt/NCrypt+SafeProviderHandle.cs index 09decaf3..6a210b43 100644 --- a/src/NCrypt/NCrypt+SafeProviderHandle.cs +++ b/src/NCrypt/NCrypt+SafeProviderHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public static partial class NCrypt + public partial class NCrypt { /// /// An NCrypt open storage provider handle. diff --git a/src/NCrypt/NCrypt.Helpers.cs b/src/NCrypt/NCrypt.Helpers.cs index 4e3108b4..55fe0182 100644 --- a/src/NCrypt/NCrypt.Helpers.cs +++ b/src/NCrypt/NCrypt.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class NCrypt + public partial class NCrypt { /// /// Loads and initializes a CNG key storage provider. diff --git a/src/SetupApi.Desktop/SetupApi.Helpers.cs b/src/SetupApi.Desktop/SetupApi.Helpers.cs index 80fad4fd..dd58394f 100644 --- a/src/SetupApi.Desktop/SetupApi.Helpers.cs +++ b/src/SetupApi.Desktop/SetupApi.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -12,7 +12,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class SetupApi + public partial class SetupApi { private static readonly Lazy DeviceInterfaceDetailDataSize = new Lazy(() => { diff --git a/src/User32.Desktop/User32.Helpers.cs b/src/User32.Desktop/User32.Helpers.cs index e4a3666c..4dac6efe 100644 --- a/src/User32.Desktop/User32.Helpers.cs +++ b/src/User32.Desktop/User32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public static partial class User32 + public partial class User32 { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/Windows.Core/Constants.cs b/src/Windows.Core/Constants.cs index 904637c2..955a134f 100644 --- a/src/Windows.Core/Constants.cs +++ b/src/Windows.Core/Constants.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Constants defined by common C or Windows headers. /// - public static partial class Constants + public partial class Constants { /// /// An infinite timeout. diff --git a/src/Windows.Core/NTStatusFacilities.cs b/src/Windows.Core/NTStatusFacilities.cs index cc3cbd55..2efb43b5 100644 --- a/src/Windows.Core/NTStatusFacilities.cs +++ b/src/Windows.Core/NTStatusFacilities.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Represent the 16 facility bits in enumeration. /// - internal static class NTStatusFacilities + internal class NTStatusFacilities { internal const uint HidErrorCode = (uint)0x11 << 16; } diff --git a/src/Windows.Core/NTStatusSeverity.cs b/src/Windows.Core/NTStatusSeverity.cs index 491baa28..f1293d44 100644 --- a/src/Windows.Core/NTStatusSeverity.cs +++ b/src/Windows.Core/NTStatusSeverity.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Represent the 4 high bits of a enumeration : Severity (2 bits), Customer code (1 bit) and Reserved (1 bit). /// - internal static class NTStatusSeverity + internal class NTStatusSeverity { internal const uint Success = (uint)0x0 << 28; internal const uint Informational = (uint)0x4 << 28; diff --git a/src/Windows.Core/PInvokeExtensions.cs b/src/Windows.Core/PInvokeExtensions.cs index af36e519..3ef10c17 100644 --- a/src/Windows.Core/PInvokeExtensions.cs +++ b/src/Windows.Core/PInvokeExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Extension methods for commonly defined types. /// - public static class PInvokeExtensions + public class PInvokeExtensions { /// /// Converts an HRESULT to From a2cd48321ee24b523b14221b1d01c10949a10327 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:42:09 +0100 Subject: [PATCH 29/46] fixed extension stuff. --- src/MockGenerator/Program.cs | 5 ++++- src/Windows.Core/PInvokeExtensions.cs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index abd6e275..73a4b6ce 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -95,7 +95,8 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .ToArray(); foreach (var classDeclaration in classDeclarations) { - if (classDeclaration.Identifier.Text.EndsWith("Mockable")) + var className = classDeclaration.Identifier.Text; + if (className.EndsWith("Mockable") || className.EndsWith("Extensions")) { continue; } @@ -319,6 +320,8 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec .Select((x, i) => { var identifierName = SyntaxFactory.Argument( + null, + x.Modifiers.FirstOrDefault(z => z.IsKind(SyntaxKind.RefKeyword) || z.IsKind(SyntaxKind.OutKeyword)), SyntaxFactory.IdentifierName(x.Identifier)); if (i > 0) { diff --git a/src/Windows.Core/PInvokeExtensions.cs b/src/Windows.Core/PInvokeExtensions.cs index 3ef10c17..cd35d308 100644 --- a/src/Windows.Core/PInvokeExtensions.cs +++ b/src/Windows.Core/PInvokeExtensions.cs @@ -8,7 +8,7 @@ namespace PInvoke /// /// Extension methods for commonly defined types. /// - public class PInvokeExtensions + public static class PInvokeExtensions { /// /// Converts an HRESULT to From fc65cc82bf1e724823d1fced4bfaa54db9cecd94 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:46:01 +0100 Subject: [PATCH 30/46] reverted to compiled solution. --- .../AdvApi32+ServiceControlAction.cs | 4 +- .../AdvApi32+ServiceControlActionType.cs | 4 +- .../AdvApi32+ServiceDelayedAutoStartInfo.cs | 4 +- .../AdvApi32+ServiceDescription.cs | 4 +- .../AdvApi32+ServiceFailureActions.cs | 4 +- .../AdvApi32+ServiceInfoLevel.cs | 4 +- .../AdvApi32+ServiceLaunchProtected.cs | 4 +- .../AdvApi32+ServiceLaunchProtectedInfo.cs | 4 +- .../AdvApi32+ServicePreferredNodeInfo.cs | 4 +- .../AdvApi32+ServicePreshutdownInfo.cs | 4 +- .../AdvApi32+ServiceRequiredPrivilegesInfo.cs | 4 +- .../AdvApi32+ServiceSidInfo.cs | 4 +- .../AdvApi32+ServiceSidType.cs | 4 +- .../AdvApi32+ServiceTrigger.cs | 4 +- .../AdvApi32+ServiceTriggerAction.cs | 4 +- .../AdvApi32+ServiceTriggerInfo.cs | 4 +- .../AdvApi32+ServiceTriggerType.cs | 4 +- src/AdvApi32.Desktop/AdvApi32.Desktop.csproj | 2 - src/AdvApi32.Desktop/AdvApi32.Helpers.cs | 4 +- src/AdvApi32.Desktop/AdvApi32.cs | 4 +- src/BCrypt/BCrypt+AlgorithmIdentifiers.cs | 4 +- src/BCrypt/BCrypt+BCryptBuffer.cs | 4 +- src/BCrypt/BCrypt+BCryptBufferDesc.cs | 4 +- src/BCrypt/BCrypt+SafeAlgorithmHandle.cs | 4 +- src/BCrypt/BCrypt+SafeHashHandle.cs | 4 +- src/BCrypt/BCrypt+SafeKeyHandle.cs | 4 +- src/BCrypt/BCrypt+SafeSecretHandle.cs | 4 +- src/BCrypt/BCrypt.Helpers.cs | 4 +- src/BCrypt/BCrypt.cs | 4 +- src/BCrypt/BCrypt.csproj | 2 - src/DbgHelp/DbgHelp+Characteristics.cs | 4 +- src/DbgHelp/DbgHelp+LOADED_IMAGE.cs | 4 +- src/DbgHelp/DbgHelp.Helpers.cs | 4 +- src/DbgHelp/DbgHelp.cs | 4 +- src/Gdi32.Desktop/Gdi32.Desktop.csproj | 2 - src/Gdi32.Desktop/Gdi32.Helpers.cs | 4 +- src/Gdi32.Desktop/Gdi32.cs | 4 +- src/Hid.Desktop/Hid.Desktop.csproj | 2 - src/Hid.Desktop/Hid.cs | 4 +- src/Hid.Shared/Hid+HiddAttributes.cs | 2 +- src/Hid.Shared/Hid+HidpCaps.cs | 4 +- src/Hid.Shared/Hid+SafePreparsedDataHandle.cs | 2 +- src/Hid.Shared/Hid.Helpers.cs | 4 +- src/Hid.Shared/Hid.cs | 4 +- src/Hid/Hid.csproj | 2 - src/ImageHlp/ImageHlp.Helpers.cs | 4 +- src/ImageHlp/ImageHlp.cs | 4 +- src/ImageHlp/ImageHlp.csproj | 2 - src/Kernel32.Desktop/Kernel32.Desktop.csproj | 2 - src/Kernel32.Desktop/Kernel32.Helpers.cs | 4 +- src/Kernel32.Desktop/Kernel32.cs | 4 +- src/Kernel32.Shared/Kernel32+FileAttribute.cs | 4 +- .../Kernel32+SafeFindFilesHandle.cs | 4 +- .../Kernel32+SafeObjectHandle.cs | 4 +- .../Kernel32+WaitForSingleObjectResult.cs | 4 +- src/Kernel32.Shared/Kernel32.Helpers.cs | 4 +- src/Kernel32.Shared/Kernel32.cs | 4 +- src/Kernel32.Shared/Kernel32Extensions.cs | 4 +- src/Kernel32/Kernel32.csproj | 2 - src/MockGenerator/MockGenerator.csproj | 40 ------------------- src/MockGenerator/Program.cs | 4 +- src/MockGenerator/packages.config | 6 --- .../NCrypt+KeyStorageImplementationType.cs | 4 +- .../NCrypt+KeyStoragePropertyIdentifiers.cs | 4 +- .../NCrypt+NCryptCreatePersistedKeyFlags.cs | 4 +- src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs | 4 +- src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs | 4 +- src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs | 4 +- src/NCrypt/NCrypt+SafeKeyHandle.cs | 4 +- src/NCrypt/NCrypt+SafeProviderHandle.cs | 4 +- src/NCrypt/NCrypt.Helpers.cs | 4 +- src/NCrypt/NCrypt.cs | 4 +- src/NCrypt/NCrypt.csproj | 2 - src/SetupApi.Desktop/SetupApi.Desktop.csproj | 2 - src/SetupApi.Desktop/SetupApi.Helpers.cs | 4 +- src/SetupApi.Desktop/SetupApi.cs | 4 +- src/User32.Desktop/User32.Desktop.csproj | 2 - src/User32.Desktop/User32.Helpers.cs | 4 +- src/User32.Desktop/User32.cs | 4 +- src/Windows.Core/Constants.cs | 4 +- src/Windows.Core/NTStatusFacilities.cs | 4 +- src/Windows.Core/NTStatusSeverity.cs | 4 +- src/Windows.Core/PInvokeExtensions.cs | 2 +- 83 files changed, 137 insertions(+), 205 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs index 282a31ea..ed3ab67d 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceControlAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Represents an action that the service control manager can perform. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs index 00a68352..2545c165 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceControlActionType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Specifies action levels for the Type member of the struct. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs index c802cd1e..e7fe955a 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceDelayedAutoStartInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Contains the delayed auto-start setting of an auto-start service. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs index 00459e85..2c6501a0 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Contains a service description. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs index 74bc4861..ad3cde28 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceFailureActions.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct ServiceFailureActions diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs index 7ad3fedc..4b491b50 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceInfoLevel.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Describes the configuration information to be changed. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs index 267374ca..6be06861 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtected.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// The protection type of the service diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs index 9bb0c9f5..1770546f 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceLaunchProtectedInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Indicates a service protection type. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs index 44c16649..1e6d697a 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServicePreferredNodeInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Represents the preferred node on which to run a service. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs index da9d0cd6..4d806f78 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServicePreshutdownInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Contains preshutdown settings diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs index c95b1ac6..ff0fdb69 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceRequiredPrivilegesInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Represents the required privileges for a service. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs index 913a1b1d..abab4e42 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceSidInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Represents a service security identifier (SID). diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs index de950c08..68b63fd8 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceSidType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Represents a service security identifier (SID). diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs index 7fbde13c..6cc4cbda 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Represents a service trigger event. This structure is used by the structure. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs index f5176507..2668c64e 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public partial class AdvApi32 + public static partial class AdvApi32 { public enum ServiceTriggerAction { diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs index a5f0ab67..757b17ed 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested struct. /// - public partial class AdvApi32 + public static partial class AdvApi32 { /// /// Contains trigger event information for a service. This structure is used by the and QueryServiceConfig2 functions. diff --git a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs index 31b65d53..b2576bad 100644 --- a/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs +++ b/src/AdvApi32.Desktop/AdvApi32+ServiceTriggerType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested enum. /// - public partial class AdvApi32 + public static partial class AdvApi32 { public enum ServiceTriggerType { diff --git a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj index c52fa31b..635923e9 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj +++ b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj @@ -61,8 +61,6 @@ - - diff --git a/src/AdvApi32.Desktop/AdvApi32.Helpers.cs b/src/AdvApi32.Desktop/AdvApi32.Helpers.cs index 43b3063a..5db926e5 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Helpers.cs +++ b/src/AdvApi32.Desktop/AdvApi32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class AdvApi32 + public static partial class AdvApi32 { public static void InstallService(string servicePath, string serviceName, string serviceDisplayName, string serviceDescription, string userName, string password) { diff --git a/src/AdvApi32.Desktop/AdvApi32.cs b/src/AdvApi32.Desktop/AdvApi32.cs index e035db72..59fc0d44 100644 --- a/src/AdvApi32.Desktop/AdvApi32.cs +++ b/src/AdvApi32.Desktop/AdvApi32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the AdvApi32.dll Windows library /// that are available to Desktop apps only. /// - public partial class AdvApi32 + public static partial class AdvApi32 : IFoobar { /// /// Used to prefix group names so that they can be distinguished from a service name, diff --git a/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs b/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs index 6ce26759..406bd009 100644 --- a/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs +++ b/src/BCrypt/BCrypt+AlgorithmIdentifiers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// The identifiers for the algorithms defined within BCrypt itself. diff --git a/src/BCrypt/BCrypt+BCryptBuffer.cs b/src/BCrypt/BCrypt+BCryptBuffer.cs index 8e63b24c..8ce6809d 100644 --- a/src/BCrypt/BCrypt+BCryptBuffer.cs +++ b/src/BCrypt/BCrypt+BCryptBuffer.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// Used to represent a generic CNG buffer. diff --git a/src/BCrypt/BCrypt+BCryptBufferDesc.cs b/src/BCrypt/BCrypt+BCryptBufferDesc.cs index 408f3b98..928bccd4 100644 --- a/src/BCrypt/BCrypt+BCryptBufferDesc.cs +++ b/src/BCrypt/BCrypt+BCryptBufferDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// Used to contain a set of generic CNG buffers. diff --git a/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs b/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs index fea9c41a..caf74047 100644 --- a/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs +++ b/src/BCrypt/BCrypt+SafeAlgorithmHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// A BCrypt algorithm handle. diff --git a/src/BCrypt/BCrypt+SafeHashHandle.cs b/src/BCrypt/BCrypt+SafeHashHandle.cs index ac104836..419e282a 100644 --- a/src/BCrypt/BCrypt+SafeHashHandle.cs +++ b/src/BCrypt/BCrypt+SafeHashHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// A BCrypt cryptographic hash handle. diff --git a/src/BCrypt/BCrypt+SafeKeyHandle.cs b/src/BCrypt/BCrypt+SafeKeyHandle.cs index a1dfdf64..924e951a 100644 --- a/src/BCrypt/BCrypt+SafeKeyHandle.cs +++ b/src/BCrypt/BCrypt+SafeKeyHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// A BCrypt cryptographic key handle. diff --git a/src/BCrypt/BCrypt+SafeSecretHandle.cs b/src/BCrypt/BCrypt+SafeSecretHandle.cs index bb558e5c..b56c7d09 100644 --- a/src/BCrypt/BCrypt+SafeSecretHandle.cs +++ b/src/BCrypt/BCrypt+SafeSecretHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// The nested class. /// - public partial class BCrypt + public static partial class BCrypt { /// /// A safe handle for BCrypt secrets. diff --git a/src/BCrypt/BCrypt.Helpers.cs b/src/BCrypt/BCrypt.Helpers.cs index 4535999f..6cbaa6d8 100644 --- a/src/BCrypt/BCrypt.Helpers.cs +++ b/src/BCrypt/BCrypt.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class BCrypt + public static partial class BCrypt { /// /// Loads and initializes a CNG provider. diff --git a/src/BCrypt/BCrypt.cs b/src/BCrypt/BCrypt.cs index fd0ef43b..29ce6b04 100644 --- a/src/BCrypt/BCrypt.cs +++ b/src/BCrypt/BCrypt.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// /// Exported functions from the BCrypt.dll Windows library. /// - public partial class BCrypt + public static partial class BCrypt { /// /// Loads and initializes a CNG provider. diff --git a/src/BCrypt/BCrypt.csproj b/src/BCrypt/BCrypt.csproj index e9923540..ef0f928b 100644 --- a/src/BCrypt/BCrypt.csproj +++ b/src/BCrypt/BCrypt.csproj @@ -60,8 +60,6 @@ - - diff --git a/src/DbgHelp/DbgHelp+Characteristics.cs b/src/DbgHelp/DbgHelp+Characteristics.cs index 6f2d8807..a476693e 100644 --- a/src/DbgHelp/DbgHelp+Characteristics.cs +++ b/src/DbgHelp/DbgHelp+Characteristics.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class DbgHelp + public static partial class DbgHelp { /// /// Describes a native binary image. diff --git a/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs b/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs index d8abee40..9022d67f 100644 --- a/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs +++ b/src/DbgHelp/DbgHelp+LOADED_IMAGE.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class DbgHelp + public static partial class DbgHelp { /// /// Contains information about the loaded image. diff --git a/src/DbgHelp/DbgHelp.Helpers.cs b/src/DbgHelp/DbgHelp.Helpers.cs index 67de8ebf..e66326e8 100644 --- a/src/DbgHelp/DbgHelp.Helpers.cs +++ b/src/DbgHelp/DbgHelp.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class DbgHelp + public static partial class DbgHelp { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/DbgHelp/DbgHelp.cs b/src/DbgHelp/DbgHelp.cs index 1e4c8923..f8ed233a 100644 --- a/src/DbgHelp/DbgHelp.cs +++ b/src/DbgHelp/DbgHelp.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the DbgHelp.dll Windows library /// that are available to Desktop and Store apps. /// - public partial class DbgHelp + public static partial class DbgHelp { } } diff --git a/src/Gdi32.Desktop/Gdi32.Desktop.csproj b/src/Gdi32.Desktop/Gdi32.Desktop.csproj index 0fc2e679..02a0254c 100644 --- a/src/Gdi32.Desktop/Gdi32.Desktop.csproj +++ b/src/Gdi32.Desktop/Gdi32.Desktop.csproj @@ -23,8 +23,6 @@ - - diff --git a/src/Gdi32.Desktop/Gdi32.Helpers.cs b/src/Gdi32.Desktop/Gdi32.Helpers.cs index 3d15aff5..73e8ea46 100644 --- a/src/Gdi32.Desktop/Gdi32.Helpers.cs +++ b/src/Gdi32.Desktop/Gdi32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class Gdi32 + public static partial class Gdi32 { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/Gdi32.Desktop/Gdi32.cs b/src/Gdi32.Desktop/Gdi32.cs index 8e9b8502..8747d074 100644 --- a/src/Gdi32.Desktop/Gdi32.cs +++ b/src/Gdi32.Desktop/Gdi32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Exported functions from the Gdi32.dll Windows library. /// - public partial class Gdi32 + public static partial class Gdi32 { [DllImport(nameof(Gdi32))] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/src/Hid.Desktop/Hid.Desktop.csproj b/src/Hid.Desktop/Hid.Desktop.csproj index edae0fe3..eb1140af 100644 --- a/src/Hid.Desktop/Hid.Desktop.csproj +++ b/src/Hid.Desktop/Hid.Desktop.csproj @@ -39,8 +39,6 @@ - - diff --git a/src/Hid.Desktop/Hid.cs b/src/Hid.Desktop/Hid.cs index d28e734c..25184d7b 100644 --- a/src/Hid.Desktop/Hid.cs +++ b/src/Hid.Desktop/Hid.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -7,7 +7,7 @@ namespace PInvoke /// Exported functions from the Hid.dll Windows library /// that are available to Desktop apps only. /// - public partial class Hid + public static partial class Hid { } } diff --git a/src/Hid.Shared/Hid+HiddAttributes.cs b/src/Hid.Shared/Hid+HiddAttributes.cs index d589f0cf..af239b70 100644 --- a/src/Hid.Shared/Hid+HiddAttributes.cs +++ b/src/Hid.Shared/Hid+HiddAttributes.cs @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class Hid + public static partial class Hid { /// /// The HIDD_ATTRIBUTES structure contains vendor information about a HIDClass device. diff --git a/src/Hid.Shared/Hid+HidpCaps.cs b/src/Hid.Shared/Hid+HidpCaps.cs index a419ee5d..fde9f540 100644 --- a/src/Hid.Shared/Hid+HidpCaps.cs +++ b/src/Hid.Shared/Hid+HidpCaps.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class Hid + public static partial class Hid { /// /// The HIDP_CAPS structure contains information about a top-level collection's capability. diff --git a/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs b/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs index 4ca758c3..40f8dcbd 100644 --- a/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs +++ b/src/Hid.Shared/Hid+SafePreparsedDataHandle.cs @@ -10,7 +10,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class Hid + public static partial class Hid { /// /// Represents a preparsed data handle created by diff --git a/src/Hid.Shared/Hid.Helpers.cs b/src/Hid.Shared/Hid.Helpers.cs index 8962b234..84ebf7c0 100644 --- a/src/Hid.Shared/Hid.Helpers.cs +++ b/src/Hid.Shared/Hid.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -13,7 +13,7 @@ namespace PInvoke /// a slightly higher level of functionality to ease calling into native code. /// [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Functions are named like their native counterparts")] - public partial class Hid + public static partial class Hid { public static Guid HidD_GetHidGuid() { diff --git a/src/Hid.Shared/Hid.cs b/src/Hid.Shared/Hid.cs index 1b7580bb..50ae0072 100644 --- a/src/Hid.Shared/Hid.cs +++ b/src/Hid.Shared/Hid.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -12,7 +12,7 @@ namespace PInvoke /// Exported functions from the Hid.dll Windows library /// that are available to Desktop and Store apps. /// - public partial class Hid + public static partial class Hid { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. diff --git a/src/Hid/Hid.csproj b/src/Hid/Hid.csproj index e2b8e981..5bc198b2 100644 --- a/src/Hid/Hid.csproj +++ b/src/Hid/Hid.csproj @@ -23,8 +23,6 @@ - - diff --git a/src/ImageHlp/ImageHlp.Helpers.cs b/src/ImageHlp/ImageHlp.Helpers.cs index ca87666b..6fb9f678 100644 --- a/src/ImageHlp/ImageHlp.Helpers.cs +++ b/src/ImageHlp/ImageHlp.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class ImageHlp + public static partial class ImageHlp { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/ImageHlp/ImageHlp.cs b/src/ImageHlp/ImageHlp.cs index 08d7c1ee..61d11032 100644 --- a/src/ImageHlp/ImageHlp.cs +++ b/src/ImageHlp/ImageHlp.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// Exported functions from the ImageHlp.dll Windows library /// that are available to Desktop and Store apps. /// - public partial class ImageHlp + public static partial class ImageHlp { /// /// Maps an image and preloads data from the mapped file. diff --git a/src/ImageHlp/ImageHlp.csproj b/src/ImageHlp/ImageHlp.csproj index 907da4e9..5937a174 100644 --- a/src/ImageHlp/ImageHlp.csproj +++ b/src/ImageHlp/ImageHlp.csproj @@ -38,10 +38,8 @@ - - diff --git a/src/Kernel32.Desktop/Kernel32.Desktop.csproj b/src/Kernel32.Desktop/Kernel32.Desktop.csproj index 8360c4fd..9421dae7 100644 --- a/src/Kernel32.Desktop/Kernel32.Desktop.csproj +++ b/src/Kernel32.Desktop/Kernel32.Desktop.csproj @@ -28,7 +28,6 @@ - @@ -48,7 +47,6 @@ - diff --git a/src/Kernel32.Desktop/Kernel32.Helpers.cs b/src/Kernel32.Desktop/Kernel32.Helpers.cs index 49290528..8c572a45 100644 --- a/src/Kernel32.Desktop/Kernel32.Helpers.cs +++ b/src/Kernel32.Desktop/Kernel32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class Kernel32 + public static partial class Kernel32 { /// Retrieves information about the first process encountered in a system snapshot. /// diff --git a/src/Kernel32.Desktop/Kernel32.cs b/src/Kernel32.Desktop/Kernel32.cs index c2f3c6fb..7ffde6e7 100644 --- a/src/Kernel32.Desktop/Kernel32.cs +++ b/src/Kernel32.Desktop/Kernel32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// /// Exported functions from the Kernel32.dll Windows library. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// Creates a new process and its primary thread. The new process runs in the security context of the calling process. diff --git a/src/Kernel32.Shared/Kernel32+FileAttribute.cs b/src/Kernel32.Shared/Kernel32+FileAttribute.cs index d41bf28b..c28da2b3 100644 --- a/src/Kernel32.Shared/Kernel32+FileAttribute.cs +++ b/src/Kernel32.Shared/Kernel32+FileAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// Defines the Win32 FileAttributes enum. diff --git a/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs b/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs index 0291a255..3ca67dff 100644 --- a/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs +++ b/src/Kernel32.Shared/Kernel32+SafeFindFilesHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// Represents a Win32 handle that can be closed with . diff --git a/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs b/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs index 0c3baf0c..4387eb74 100644 --- a/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs +++ b/src/Kernel32.Shared/Kernel32+SafeObjectHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// Represents a Win32 handle that can be closed with . diff --git a/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs b/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs index f411ffe7..7835cab5 100644 --- a/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs +++ b/src/Kernel32.Shared/Kernel32+WaitForSingleObjectResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// Values that may be returned from the function. diff --git a/src/Kernel32.Shared/Kernel32.Helpers.cs b/src/Kernel32.Shared/Kernel32.Helpers.cs index 0705e1cf..0da4ba81 100644 --- a/src/Kernel32.Shared/Kernel32.Helpers.cs +++ b/src/Kernel32.Shared/Kernel32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// Returns the error code returned by the last unmanaged function that was called using platform invoke that has diff --git a/src/Kernel32.Shared/Kernel32.cs b/src/Kernel32.Shared/Kernel32.cs index caaf329a..15464c1a 100644 --- a/src/Kernel32.Shared/Kernel32.cs +++ b/src/Kernel32.Shared/Kernel32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// /// Exported functions from the Kernel32.dll Windows library. /// - public partial class Kernel32 + public static partial class Kernel32 { /// /// The maximum length of file paths for most Win32 functions. diff --git a/src/Kernel32.Shared/Kernel32Extensions.cs b/src/Kernel32.Shared/Kernel32Extensions.cs index b9adb731..aaca6cb9 100644 --- a/src/Kernel32.Shared/Kernel32Extensions.cs +++ b/src/Kernel32.Shared/Kernel32Extensions.cs @@ -1,9 +1,9 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 { - public class Kernel32Extensions + public static class Kernel32Extensions { /// /// Throws an exception if a P/Invoke failed. diff --git a/src/Kernel32/Kernel32.csproj b/src/Kernel32/Kernel32.csproj index 43c30b0a..9d0ffa06 100644 --- a/src/Kernel32/Kernel32.csproj +++ b/src/Kernel32/Kernel32.csproj @@ -23,8 +23,6 @@ - - diff --git a/src/MockGenerator/MockGenerator.csproj b/src/MockGenerator/MockGenerator.csproj index e0e3cdbf..9cffa6b8 100644 --- a/src/MockGenerator/MockGenerator.csproj +++ b/src/MockGenerator/MockGenerator.csproj @@ -43,51 +43,11 @@ ..\..\packages\Microsoft.CodeAnalysis.CSharp.1.0.0\lib\net45\Microsoft.CodeAnalysis.CSharp.dll True - - ..\..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.1.0.0\lib\net45\Microsoft.CodeAnalysis.CSharp.Workspaces.dll - True - - - ..\..\packages\Microsoft.CodeAnalysis.VisualBasic.1.0.0\lib\net45\Microsoft.CodeAnalysis.VisualBasic.dll - True - - - ..\..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.1.0.0\lib\net45\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll - True - - - ..\..\packages\Microsoft.CodeAnalysis.Workspaces.Common.1.0.0\lib\net45\Microsoft.CodeAnalysis.Workspaces.dll - True - - - ..\..\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 - - ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll - True - - - ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll - True - - - ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll - True - - - ..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll - True - - - ..\..\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 diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 73a4b6ce..4c18b317 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -67,7 +67,7 @@ private static void Run() { Console.WriteLine("Solution save succeeded!"); } - + Console.ReadLine(); } @@ -159,7 +159,7 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) .AddMembers(newClassDeclaration) .ToFullString()); - AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", + AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) .AddMembers(newInterfaceDeclaration) .ToFullString()); diff --git a/src/MockGenerator/packages.config b/src/MockGenerator/packages.config index 9da500ec..fa91bc8a 100644 --- a/src/MockGenerator/packages.config +++ b/src/MockGenerator/packages.config @@ -1,14 +1,8 @@  - - - - - - \ No newline at end of file diff --git a/src/NCrypt/NCrypt+KeyStorageImplementationType.cs b/src/NCrypt/NCrypt+KeyStorageImplementationType.cs index 66a804ff..09e5ad13 100644 --- a/src/NCrypt/NCrypt+KeyStorageImplementationType.cs +++ b/src/NCrypt/NCrypt+KeyStorageImplementationType.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Describes the key storage implementation types that may be returned by the diff --git a/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs b/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs index 9073c8d0..22f630dc 100644 --- a/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs +++ b/src/NCrypt/NCrypt+KeyStoragePropertyIdentifiers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Defines the names of the built-in key storage property identifiers diff --git a/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs b/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs index 749adf24..dfee143f 100644 --- a/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptCreatePersistedKeyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Flags that may be passed to the method. diff --git a/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs b/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs index d87198b7..d3854c2d 100644 --- a/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptFinalizeKeyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -8,7 +8,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Flags that may be passed to the function. diff --git a/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs b/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs index 7a06637d..9723b2ae 100644 --- a/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptGetPropertyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Flags that may be supplied to the function. diff --git a/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs b/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs index ec42fc15..d4f19b07 100644 --- a/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs +++ b/src/NCrypt/NCrypt+NCryptSetPropertyFlags.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Contains the nested type. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Flags that may be supplied to the function. diff --git a/src/NCrypt/NCrypt+SafeKeyHandle.cs b/src/NCrypt/NCrypt+SafeKeyHandle.cs index ee863375..46a4845a 100644 --- a/src/NCrypt/NCrypt+SafeKeyHandle.cs +++ b/src/NCrypt/NCrypt+SafeKeyHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class NCrypt + public static partial class NCrypt { /// /// An NCrypt key handle. diff --git a/src/NCrypt/NCrypt+SafeProviderHandle.cs b/src/NCrypt/NCrypt+SafeProviderHandle.cs index 6a210b43..09decaf3 100644 --- a/src/NCrypt/NCrypt+SafeProviderHandle.cs +++ b/src/NCrypt/NCrypt+SafeProviderHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Contains the nested class. /// - public partial class NCrypt + public static partial class NCrypt { /// /// An NCrypt open storage provider handle. diff --git a/src/NCrypt/NCrypt.Helpers.cs b/src/NCrypt/NCrypt.Helpers.cs index 55fe0182..4e3108b4 100644 --- a/src/NCrypt/NCrypt.Helpers.cs +++ b/src/NCrypt/NCrypt.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -11,7 +11,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Loads and initializes a CNG key storage provider. diff --git a/src/NCrypt/NCrypt.cs b/src/NCrypt/NCrypt.cs index 348fc612..b92c67b7 100644 --- a/src/NCrypt/NCrypt.cs +++ b/src/NCrypt/NCrypt.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the NCrypt.dll Windows library /// that are available to Desktop and Store apps. /// - public partial class NCrypt + public static partial class NCrypt { /// /// Loads and initializes a CNG key storage provider. diff --git a/src/NCrypt/NCrypt.csproj b/src/NCrypt/NCrypt.csproj index 4ff0bd16..02126362 100644 --- a/src/NCrypt/NCrypt.csproj +++ b/src/NCrypt/NCrypt.csproj @@ -23,7 +23,6 @@ - @@ -38,7 +37,6 @@ - diff --git a/src/SetupApi.Desktop/SetupApi.Desktop.csproj b/src/SetupApi.Desktop/SetupApi.Desktop.csproj index 1a42774e..fcc8f4f4 100644 --- a/src/SetupApi.Desktop/SetupApi.Desktop.csproj +++ b/src/SetupApi.Desktop/SetupApi.Desktop.csproj @@ -38,7 +38,6 @@ - @@ -47,7 +46,6 @@ - diff --git a/src/SetupApi.Desktop/SetupApi.Helpers.cs b/src/SetupApi.Desktop/SetupApi.Helpers.cs index dd58394f..80fad4fd 100644 --- a/src/SetupApi.Desktop/SetupApi.Helpers.cs +++ b/src/SetupApi.Desktop/SetupApi.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -12,7 +12,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class SetupApi + public static partial class SetupApi { private static readonly Lazy DeviceInterfaceDetailDataSize = new Lazy(() => { diff --git a/src/SetupApi.Desktop/SetupApi.cs b/src/SetupApi.Desktop/SetupApi.cs index e8e44627..88cf9f30 100644 --- a/src/SetupApi.Desktop/SetupApi.cs +++ b/src/SetupApi.Desktop/SetupApi.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the SetupApi.dll Windows library /// that are available to Desktop apps only. /// - public partial class SetupApi + public static partial class SetupApi { /// /// The SetupDiGetClassDevs function returns a handle to a device information set diff --git a/src/User32.Desktop/User32.Desktop.csproj b/src/User32.Desktop/User32.Desktop.csproj index a10d221e..ade71ad1 100644 --- a/src/User32.Desktop/User32.Desktop.csproj +++ b/src/User32.Desktop/User32.Desktop.csproj @@ -21,7 +21,6 @@ - @@ -29,7 +28,6 @@ - diff --git a/src/User32.Desktop/User32.Helpers.cs b/src/User32.Desktop/User32.Helpers.cs index 4dac6efe..e4a3666c 100644 --- a/src/User32.Desktop/User32.Helpers.cs +++ b/src/User32.Desktop/User32.Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -10,7 +10,7 @@ namespace PInvoke /// Methods and nested types that are not strictly P/Invokes but provide /// a slightly higher level of functionality to ease calling into native code. /// - public partial class User32 + public static partial class User32 { // This is where you define methods that assist in calling P/Invoke methods. // For example, if a P/Invoke method requires allocating unmanaged memory diff --git a/src/User32.Desktop/User32.cs b/src/User32.Desktop/User32.cs index d2122cc1..4ae899e2 100644 --- a/src/User32.Desktop/User32.cs +++ b/src/User32.Desktop/User32.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -9,7 +9,7 @@ namespace PInvoke /// /// Exported functions from the User32.dll Windows library. /// - public partial class User32 + public static partial class User32 { [DllImport(nameof(User32))] public static extern int SetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); diff --git a/src/Windows.Core/Constants.cs b/src/Windows.Core/Constants.cs index 955a134f..904637c2 100644 --- a/src/Windows.Core/Constants.cs +++ b/src/Windows.Core/Constants.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Constants defined by common C or Windows headers. /// - public partial class Constants + public static partial class Constants { /// /// An infinite timeout. diff --git a/src/Windows.Core/NTStatusFacilities.cs b/src/Windows.Core/NTStatusFacilities.cs index 2efb43b5..cc3cbd55 100644 --- a/src/Windows.Core/NTStatusFacilities.cs +++ b/src/Windows.Core/NTStatusFacilities.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Represent the 16 facility bits in enumeration. /// - internal class NTStatusFacilities + internal static class NTStatusFacilities { internal const uint HidErrorCode = (uint)0x11 << 16; } diff --git a/src/Windows.Core/NTStatusSeverity.cs b/src/Windows.Core/NTStatusSeverity.cs index f1293d44..491baa28 100644 --- a/src/Windows.Core/NTStatusSeverity.cs +++ b/src/Windows.Core/NTStatusSeverity.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -6,7 +6,7 @@ namespace PInvoke /// /// Represent the 4 high bits of a enumeration : Severity (2 bits), Customer code (1 bit) and Reserved (1 bit). /// - internal class NTStatusSeverity + internal static class NTStatusSeverity { internal const uint Success = (uint)0x0 << 28; internal const uint Informational = (uint)0x4 << 28; diff --git a/src/Windows.Core/PInvokeExtensions.cs b/src/Windows.Core/PInvokeExtensions.cs index cd35d308..af36e519 100644 --- a/src/Windows.Core/PInvokeExtensions.cs +++ b/src/Windows.Core/PInvokeExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 From 0244024e569579079475408ee041be5aed23aa09 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 03:48:52 +0100 Subject: [PATCH 31/46] cleanup. --- src/AdvApi32.Desktop/AdvApi32.cs | 2 +- src/MockGenerator/MockGenerator.csproj | 40 ++++++++++++++++++++++++++ src/MockGenerator/packages.config | 3 ++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/AdvApi32.Desktop/AdvApi32.cs b/src/AdvApi32.Desktop/AdvApi32.cs index 59fc0d44..55b17ecd 100644 --- a/src/AdvApi32.Desktop/AdvApi32.cs +++ b/src/AdvApi32.Desktop/AdvApi32.cs @@ -10,7 +10,7 @@ namespace PInvoke /// Exported functions from the AdvApi32.dll Windows library /// that are available to Desktop apps only. /// - public static partial class AdvApi32 : IFoobar + public static partial class AdvApi32 { /// /// Used to prefix group names so that they can be distinguished from a service name, diff --git a/src/MockGenerator/MockGenerator.csproj b/src/MockGenerator/MockGenerator.csproj index 9cffa6b8..afeea15a 100644 --- a/src/MockGenerator/MockGenerator.csproj +++ b/src/MockGenerator/MockGenerator.csproj @@ -43,11 +43,51 @@ ..\..\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 diff --git a/src/MockGenerator/packages.config b/src/MockGenerator/packages.config index fa91bc8a..621ff548 100644 --- a/src/MockGenerator/packages.config +++ b/src/MockGenerator/packages.config @@ -3,6 +3,9 @@ + + + \ No newline at end of file From 698fb35498fc60bdd09dcdd138b66607dad83aad Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:10:09 +0100 Subject: [PATCH 32/46] new stuff. --- src/MockGenerator/Program.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 4c18b317..04e6bb6a 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -36,6 +36,8 @@ private static void Main() private static void Run() { + Console.WriteLine("Loading solution"); + var currentDirectory = Environment.CurrentDirectory; var workspace = MSBuildWorkspace.Create(); @@ -147,6 +149,7 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio ClassCache[newClassModifier.Identifier.Text] = newClassDeclaration; newInterfaceDeclaration = DecorateInterfaceWithWrapperFunction( + classDeclaration.Identifier, methodDeclaration, invokeMethodIdentifier, newInterfaceDeclaration); @@ -281,12 +284,14 @@ private static string GetBaseFileName(string file, out string fileDirectory) } private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( + SyntaxToken classIdentifier, MethodDeclarationSyntax methodDeclaration, IdentifierNameSyntax invokeMethodIdentifier, InterfaceDeclarationSyntax interfaceDeclaration) { var dllImport = methodDeclaration.AttributeLists .First(x => x.OpenBracketToken.HasLeadingTrivia); + var parameterList = methodDeclaration.ParameterList; var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.List(), SyntaxFactory.TokenList(), @@ -294,7 +299,17 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( default(ExplicitInterfaceSpecifierSyntax), invokeMethodIdentifier.Identifier, methodDeclaration.TypeParameterList, - methodDeclaration.ParameterList, + parameterList + .Update( + parameterList.OpenParenToken, + SyntaxFactory.SeparatedList(parameterList.Parameters + .Select(x => SyntaxFactory.Parameter( + x.AttributeLists, + x.Modifiers, + SyntaxFactory.IdentifierName($"{classIdentifier.Text}.{x.Type.ToString()} "), + x.Identifier, + x.Default))), + parameterList.CloseParenToken), methodDeclaration.ConstraintClauses, default(BlockSyntax), SyntaxFactory.Token(SyntaxKind.SemicolonToken)); From 3410aeed8d02f39585bafb5fa1b3e56b53c91ace Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:27:32 +0100 Subject: [PATCH 33/46] better using. --- src/MockGenerator/Program.cs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 04e6bb6a..1f1fc971 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -149,7 +149,6 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio ClassCache[newClassModifier.Identifier.Text] = newClassDeclaration; newInterfaceDeclaration = DecorateInterfaceWithWrapperFunction( - classDeclaration.Identifier, methodDeclaration, invokeMethodIdentifier, newInterfaceDeclaration); @@ -163,7 +162,12 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .AddMembers(newClassDeclaration) .ToFullString()); AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", - CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, + SyntaxFactory.List(new [] + { + SyntaxFactory.UsingDirective( + SyntaxFactory.IdentifierName(classDeclaration.Identifier)) + })) .AddMembers(newInterfaceDeclaration) .ToFullString()); } @@ -249,14 +253,21 @@ private static void PrepareClassCacheEntry(IdentifierNameSyntax newClassModifier } private static NamespaceDeclarationSyntax CreateNewEmptyNamespaceDeclaration( - NamespaceDeclarationSyntax namespaceDeclaration) + 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, - namespaceDeclaration.Usings, + namespaceUsings, SyntaxFactory.List(), namespaceDeclaration.CloseBraceToken, namespaceDeclaration.SemicolonToken); @@ -284,14 +295,12 @@ private static string GetBaseFileName(string file, out string fileDirectory) } private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( - SyntaxToken classIdentifier, MethodDeclarationSyntax methodDeclaration, IdentifierNameSyntax invokeMethodIdentifier, InterfaceDeclarationSyntax interfaceDeclaration) { var dllImport = methodDeclaration.AttributeLists .First(x => x.OpenBracketToken.HasLeadingTrivia); - var parameterList = methodDeclaration.ParameterList; var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.List(), SyntaxFactory.TokenList(), @@ -299,17 +308,7 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( default(ExplicitInterfaceSpecifierSyntax), invokeMethodIdentifier.Identifier, methodDeclaration.TypeParameterList, - parameterList - .Update( - parameterList.OpenParenToken, - SyntaxFactory.SeparatedList(parameterList.Parameters - .Select(x => SyntaxFactory.Parameter( - x.AttributeLists, - x.Modifiers, - SyntaxFactory.IdentifierName($"{classIdentifier.Text}.{x.Type.ToString()} "), - x.Identifier, - x.Default))), - parameterList.CloseParenToken), + methodDeclaration.ParameterList, methodDeclaration.ConstraintClauses, default(BlockSyntax), SyntaxFactory.Token(SyntaxKind.SemicolonToken)); From 3074d18524ab5993ab30fb8e8a3c0a04bcdd2297 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:31:37 +0100 Subject: [PATCH 34/46] stuff. --- src/MockGenerator/Program.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 1f1fc971..ce2d2ad6 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -115,7 +115,9 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio var methodDeclarations = classDeclaration.Members .OfType() - .Where(a => a.AttributeLists.Any(b => b.Attributes.Any(c => c.Name.ToString() == "DllImport"))) + .Where(a => a.AttributeLists.Any( + b => b.Attributes.Any( + c => c.Name.ToString() == "DllImport"))) .ToArray(); if (methodDeclarations.Length <= 0) { @@ -166,7 +168,11 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio SyntaxFactory.List(new [] { SyntaxFactory.UsingDirective( - SyntaxFactory.IdentifierName(classDeclaration.Identifier)) + SyntaxFactory.IdentifierName(classDeclaration.Identifier + .WithLeadingTrivia() + .WithTrailingTrivia()) + .WithLeadingTrivia(WhitespaceCharacter)) + .WithLeadingTrivia(TabCharacter) })) .AddMembers(newInterfaceDeclaration) .ToFullString()); From b733dd1239ad33dc820067812780e03228afed6a Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:39:51 +0100 Subject: [PATCH 35/46] foobar. --- src/MockGenerator/Program.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index ce2d2ad6..ccba1076 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -100,6 +100,7 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio 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; } @@ -117,10 +118,12 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .OfType() .Where(a => a.AttributeLists.Any( b => b.Attributes.Any( - c => c.Name.ToString() == "DllImport"))) + c => c.Name.ToString() == "DllImport")) + && IsNotPublicStaticExternMethod(a)) .ToArray(); if (methodDeclarations.Length <= 0) { + Console.WriteLine($"\tSkipping class {className} because it has no public static extern methods with DllImport attributes."); continue; } @@ -136,11 +139,6 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio foreach (var methodDeclaration in methodDeclarations) { - if (IsPublicStaticExternMethod(methodDeclaration)) - { - continue; - } - var invokeMethodIdentifier = SyntaxFactory.IdentifierName($"Invoke{methodDeclaration.Identifier.Text}"); @@ -164,8 +162,8 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .AddMembers(newClassDeclaration) .ToFullString()); AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", - CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, - SyntaxFactory.List(new [] + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, + SyntaxFactory.List(new[] { SyntaxFactory.UsingDirective( SyntaxFactory.IdentifierName(classDeclaration.Identifier @@ -173,6 +171,7 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .WithTrailingTrivia()) .WithLeadingTrivia(WhitespaceCharacter)) .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter) })) .AddMembers(newInterfaceDeclaration) .ToFullString()); @@ -280,7 +279,7 @@ private static NamespaceDeclarationSyntax CreateNewEmptyNamespaceDeclaration( return newNamespaceDeclaration; } - private static bool IsPublicStaticExternMethod(MethodDeclarationSyntax methodDeclaration) + private static bool IsNotPublicStaticExternMethod(MethodDeclarationSyntax methodDeclaration) { var externMethodKeyword = methodDeclaration.Modifiers .SingleOrDefault(x => x.IsKind(SyntaxKind.ExternKeyword)); From 837083309a0606a721b3fbb16d52a599850f852f Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:47:42 +0100 Subject: [PATCH 36/46] removed mockables. --- src/AdvApi32.Desktop/AdvApi32Mockable.cs | 33 ------------------------ src/Hid/HidMockable.cs | 20 -------------- src/Hid/IHidMockable.cs | 19 -------------- src/NCrypt/INCryptMockable.cs | 24 ----------------- src/NCrypt/NCryptMockable.cs | 25 ------------------ 5 files changed, 121 deletions(-) delete mode 100644 src/AdvApi32.Desktop/AdvApi32Mockable.cs delete mode 100644 src/Hid/HidMockable.cs delete mode 100644 src/Hid/IHidMockable.cs delete mode 100644 src/NCrypt/INCryptMockable.cs delete mode 100644 src/NCrypt/NCryptMockable.cs diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs deleted file mode 100644 index a6338509..00000000 --- a/src/AdvApi32.Desktop/AdvApi32Mockable.cs +++ /dev/null @@ -1,33 +0,0 @@ -// 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; - public partial class AdvApi32 : IAdvApi32Mockable { - /// - /// 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 - /// - public bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo) - => ChangeServiceConfig2(hService, dwInfoLevel, lpInfo); - } -} diff --git a/src/Hid/HidMockable.cs b/src/Hid/HidMockable.cs deleted file mode 100644 index 361ff375..00000000 --- a/src/Hid/HidMockable.cs +++ /dev/null @@ -1,20 +0,0 @@ -// 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); - } -} \ No newline at end of file diff --git a/src/Hid/IHidMockable.cs b/src/Hid/IHidMockable.cs deleted file mode 100644 index adb0fdd5..00000000 --- a/src/Hid/IHidMockable.cs +++ /dev/null @@ -1,19 +0,0 @@ -// 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); - } -} \ No newline at end of file diff --git a/src/NCrypt/INCryptMockable.cs b/src/NCrypt/INCryptMockable.cs deleted file mode 100644 index c4357396..00000000 --- a/src/NCrypt/INCryptMockable.cs +++ /dev/null @@ -1,24 +0,0 @@ -// 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; - public interface INCryptMockable { /// - /// 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. - SECURITY_STATUS InvokeNCryptOpenStorageProvider( - out SafeProviderHandle phProvider, - string pszProviderName, - NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None); - } -} diff --git a/src/NCrypt/NCryptMockable.cs b/src/NCrypt/NCryptMockable.cs deleted file mode 100644 index be0c3c60..00000000 --- a/src/NCrypt/NCryptMockable.cs +++ /dev/null @@ -1,25 +0,0 @@ -// 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; - public partial class NCrypt : INCryptMockable { /// - /// 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. - public SECURITY_STATUS InvokeNCryptOpenStorageProvider( - out SafeProviderHandle phProvider, - string pszProviderName, - NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None) - => NCryptOpenStorageProvider(phProvider, pszProviderName, dwFlags ); - } -} From ade941285f0de47076c4c84ed029370f6777c5c8 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:54:12 +0100 Subject: [PATCH 37/46] fooo --- src/MockGenerator/Program.cs | 39 +++++++++++++++--------------------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index ccba1076..16fa6765 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -104,16 +104,6 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio continue; } - var staticModifier = classDeclaration.Modifiers.SingleOrDefault(x => x.IsKind(SyntaxKind.StaticKeyword)); - if (staticModifier != default(SyntaxToken)) - { - compilationUnit = compilationUnit.ReplaceNode( - classDeclaration, - classDeclaration.WithModifiers( - classDeclaration.Modifiers.Remove(staticModifier))); - File.WriteAllText(file, compilationUnit.ToFullString()); - } - var methodDeclarations = classDeclaration.Members .OfType() .Where(a => a.AttributeLists.Any( @@ -129,7 +119,7 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio var newInterfaceModifier = SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); - var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}"); + var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}Mockable"); PrepareClassCacheEntry(newClassModifier, classDeclaration, newInterfaceModifier); PrepareInterfaceCacheEntry(newInterfaceModifier); @@ -157,22 +147,25 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio string fileDirectory; var baseFileName = GetBaseFileName(file, out fileDirectory); + var usings = new[] + { + SyntaxFactory.UsingDirective( + SyntaxFactory.Token(SyntaxKind.StaticKeyword), + null, + SyntaxFactory.IdentifierName(classDeclaration.Identifier + .WithLeadingTrivia() + .WithTrailingTrivia()) + .WithLeadingTrivia(WhitespaceCharacter)) + .WithLeadingTrivia(TabCharacter) + .WithTrailingTrivia(NewLineCharacter) + }; + AddPathToProject(workspace, ref solution, ref project, $"{baseFileName}Mockable.cs", - CreateNewEmptyNamespaceDeclaration(namespaceDeclaration) + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) .AddMembers(newClassDeclaration) .ToFullString()); AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", - CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, - SyntaxFactory.List(new[] - { - SyntaxFactory.UsingDirective( - SyntaxFactory.IdentifierName(classDeclaration.Identifier - .WithLeadingTrivia() - .WithTrailingTrivia()) - .WithLeadingTrivia(WhitespaceCharacter)) - .WithLeadingTrivia(TabCharacter) - .WithTrailingTrivia(NewLineCharacter) - })) + CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) .AddMembers(newInterfaceDeclaration) .ToFullString()); } From 395db2d3b28f16cadc400c7be0e26e9486f676bb Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 04:57:21 +0100 Subject: [PATCH 38/46] whitespace. --- src/MockGenerator/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 16fa6765..1ebcceab 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -150,7 +150,8 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio var usings = new[] { SyntaxFactory.UsingDirective( - SyntaxFactory.Token(SyntaxKind.StaticKeyword), + SyntaxFactory.Token(SyntaxKind.StaticKeyword) + .WithLeadingTrivia(WhitespaceCharacter), null, SyntaxFactory.IdentifierName(classDeclaration.Identifier .WithLeadingTrivia() From 55ead2a4bce5ad54c5f3d9f6fbd97834f4694165 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 05:13:09 +0100 Subject: [PATCH 39/46] blah. --- src/MockGenerator/Program.cs | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 1ebcceab..290c5a46 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -109,7 +109,7 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .Where(a => a.AttributeLists.Any( b => b.Attributes.Any( c => c.Name.ToString() == "DllImport")) - && IsNotPublicStaticExternMethod(a)) + && IsPublicStaticExternMethod(a)) .ToArray(); if (methodDeclarations.Length <= 0) { @@ -231,9 +231,6 @@ private static void PrepareClassCacheEntry(IdentifierNameSyntax newClassModifier SyntaxFactory.TokenList( SyntaxFactory .Token(SyntaxKind.PublicKeyword) - .WithTrailingTrivia(WhitespaceCharacter), - SyntaxFactory - .Token(SyntaxKind.PartialKeyword) .WithTrailingTrivia(WhitespaceCharacter)), newClassModifier.Identifier .WithTrailingTrivia(WhitespaceCharacter) @@ -273,7 +270,7 @@ private static NamespaceDeclarationSyntax CreateNewEmptyNamespaceDeclaration( return newNamespaceDeclaration; } - private static bool IsNotPublicStaticExternMethod(MethodDeclarationSyntax methodDeclaration) + private static bool IsPublicStaticExternMethod(MethodDeclarationSyntax methodDeclaration) { var externMethodKeyword = methodDeclaration.Modifiers .SingleOrDefault(x => x.IsKind(SyntaxKind.ExternKeyword)); @@ -281,7 +278,7 @@ private static bool IsNotPublicStaticExternMethod(MethodDeclarationSyntax method .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); + return externMethodKeyword != default(SyntaxToken) && staticMethodKeyword != default(SyntaxToken) && publicMethodKeyword != default(SyntaxToken); } private static string GetBaseFileName(string file, out string fileDirectory) @@ -302,7 +299,7 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( .First(x => x.OpenBracketToken.HasLeadingTrivia); var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.List(), - SyntaxFactory.TokenList(), + GetModifiersForWrapperFunction(methodDeclaration), methodDeclaration.ReturnType, default(ExplicitInterfaceSpecifierSyntax), invokeMethodIdentifier.Identifier, @@ -322,6 +319,18 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( 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) @@ -334,7 +343,10 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec { var identifierName = SyntaxFactory.Argument( null, - x.Modifiers.FirstOrDefault(z => z.IsKind(SyntaxKind.RefKeyword) || z.IsKind(SyntaxKind.OutKeyword)), + x.Modifiers + .FirstOrDefault(z => z.IsKind(SyntaxKind.RefKeyword) || z.IsKind(SyntaxKind.OutKeyword)) + .WithLeadingTrivia() + .WithTrailingTrivia(), SyntaxFactory.IdentifierName(x.Identifier)); if (i > 0) { @@ -359,8 +371,8 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec var wrapperMethodDeclaration = SyntaxFactory.MethodDeclaration( SyntaxFactory.List(), - SyntaxFactory.TokenList( - SyntaxFactory.Token(SyntaxKind.PublicKeyword) + GetModifiersForWrapperFunction(methodDeclaration) + .Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword) .WithTrailingTrivia(WhitespaceCharacter)), methodDeclaration.ReturnType, default(ExplicitInterfaceSpecifierSyntax), From ceadefbddad28e0f93dee539de7cfb4c6a31c80f Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 05:28:10 +0100 Subject: [PATCH 40/46] new progress. --- src/MockGenerator/Program.cs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 290c5a46..86696c0f 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -182,16 +182,19 @@ private static Document GetExistingDocument(Project project, string path) private static void AddPathToProject(Workspace workspace, ref Solution solution, ref Project project, string fileName, string contents) { var document = GetExistingDocument(project, fileName); - if (document == null) + if (document != null) { - Console.WriteLine($"\t - Adding {fileName} to project"); - document = project.AddDocument(fileName, - contents, - null, - Path.Combine(Path.GetDirectoryName(project.FilePath), fileName)); - project = document.Project; + 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) @@ -345,8 +348,7 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec null, x.Modifiers .FirstOrDefault(z => z.IsKind(SyntaxKind.RefKeyword) || z.IsKind(SyntaxKind.OutKeyword)) - .WithLeadingTrivia() - .WithTrailingTrivia(), + .WithLeadingTrivia(), SyntaxFactory.IdentifierName(x.Identifier)); if (i > 0) { From db23b473f13457b31faa04e0627c371b0ab21f7b Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 11:25:51 +0100 Subject: [PATCH 41/46] generated code updates. --- src/AdvApi32.Desktop/AdvApi32.Desktop.csproj | 2 + src/AdvApi32.Desktop/IAdvApi32Mockable.cs | 149 +++ src/BCrypt/BCrypt.csproj | 2 + src/BCrypt/BCryptMockable.cs | 440 +++++++- src/BCrypt/IBCryptMockable.cs | 414 ++++++- src/Gdi32.Desktop/Gdi32.Desktop.csproj | 2 + src/Gdi32.Desktop/Gdi32Mockable.cs | 3 +- src/Gdi32.Desktop/IGdi32Mockable.cs | 1 + src/Hid.Desktop/Hid.Desktop.csproj | 2 + src/Hid.Desktop/HidMockable.cs | 149 ++- src/Hid.Desktop/IHidMockable.cs | 130 +++ src/Hid/Hid.csproj | 2 + src/ImageHlp/IImageHlpMockable.cs | 14 + src/ImageHlp/ImageHlp.csproj | 2 + src/ImageHlp/ImageHlpMockable.cs | 19 +- src/Kernel32.Desktop/IKernel32Mockable.cs | 968 ++++++++++++++++- src/Kernel32.Desktop/Kernel32.Desktop.csproj | 2 + src/Kernel32.Desktop/Kernel32Mockable.cs | 1007 +++++++++++++++++- src/Kernel32/IKernel32Mockable.cs | 328 ++++++ src/Kernel32/Kernel32.csproj | 2 + src/Kernel32/Kernel32Mockable.cs | 344 +++++- src/MockGenerator/Program.cs | 25 +- src/NCrypt/NCrypt.csproj | 2 + src/SetupApi.Desktop/ISetupApiMockable.cs | 116 ++ src/SetupApi.Desktop/SetupApi.Desktop.csproj | 2 + src/SetupApi.Desktop/SetupApiMockable.cs | 121 ++- src/User32.Desktop/IUser32Mockable.cs | 26 + src/User32.Desktop/User32.Desktop.csproj | 2 + src/User32.Desktop/User32Mockable.cs | 35 +- 29 files changed, 4270 insertions(+), 41 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj index 635923e9..c52fa31b 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/IAdvApi32Mockable.cs b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs index c16f3504..c8dbdabd 100644 --- a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs @@ -5,6 +5,7 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; + using static AdvApi32; public interface IAdvApi32Mockable { /// /// Changes the optional configuration parameters of a service. @@ -28,5 +29,153 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is zero /// bool InvokeChangeServiceConfig2(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 + /// + SafeServiceHandle InvokeCreateService(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 + /// + bool InvokeDeleteService(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 . + /// + SafeServiceHandle InvokeOpenSCManager(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. + /// + SafeServiceHandle InvokeOpenService(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. + /// + bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); } } diff --git a/src/BCrypt/BCrypt.csproj b/src/BCrypt/BCrypt.csproj index ef0f928b..e9923540 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 index 2dce78d4..ecd09370 100644 --- a/src/BCrypt/BCryptMockable.cs +++ b/src/BCrypt/BCryptMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -7,7 +7,8 @@ namespace PInvoke using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; - public partial class BCrypt : IBCryptMockable { /// + using static BCrypt; + public class BCryptMockable : IBCryptMockable { /// /// Loads and initializes a CNG provider. /// /// @@ -45,7 +46,7 @@ public NTStatus InvokeBCryptOpenAlgorithmProvider( string pszAlgId, string pszImplementation, BCryptOpenAlgorithmProviderFlags dwFlags) - => BCryptOpenAlgorithmProvider(phAlgorithm, pszAlgId, pszImplementation, dwFlags); + => BCryptOpenAlgorithmProvider(out phAlgorithm, pszAlgId, pszImplementation, dwFlags); /// /// Create a hash or Message Authentication Code (MAC) object. @@ -83,7 +84,7 @@ public NTStatus InvokeBCryptCreateHash( byte[] pbSecret, int cbSecret, BCryptCreateHashFlags dwFlags) - => BCryptCreateHash(hAlgorithm, phHash, pbHashObject, cbHashObject, pbSecret, cbSecret, dwFlags); + => BCryptCreateHash(hAlgorithm, out phHash, pbHashObject, cbHashObject, pbSecret, cbSecret, dwFlags); /// /// Encrypts a block of data. @@ -135,7 +136,7 @@ public NTStatus InvokeBCryptEncrypt( int cbOutput, out int pcbResult, BCryptEncryptFlags dwFlags) - => BCryptEncrypt(hKey, pbInput, cbInput, pPaddingInfo, pbIV, cbIV, pbOutput, cbOutput, pcbResult, dwFlags); + => BCryptEncrypt(hKey, pbInput, cbInput, pPaddingInfo, pbIV, cbIV, pbOutput, cbOutput, out pcbResult, dwFlags); /// /// Decrypts a block of data. @@ -186,7 +187,7 @@ public NTStatus InvokeBCryptDecrypt( int cbOutput, out int pcbResult, BCryptEncryptFlags dwFlags) - => BCryptDecrypt(hKey, pbInput, cbInput, pPaddingInfo, pbIV, cbIV, pbOutput, cbOutput, pcbResult, 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. @@ -232,5 +233,432 @@ public NTStatus InvokeBCryptFinishHash( 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. + /// + public NTStatus InvokeBCryptSignHash( + 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. + /// + public NTStatus InvokeBCryptVerifySignature( + 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. + /// + public NTStatus InvokeBCryptGenerateKeyPair( + 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. + public NTStatus InvokeBCryptGenerateSymmetricKey( + 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. + /// + public NTStatus InvokeBCryptFinalizeKeyPair( + 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. + public NTStatus InvokeBCryptDestroyKey( + 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. + public NTStatus InvokeBCryptDestroySecret( + 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. + public NTStatus InvokeBCryptImportKey( + 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. + public NTStatus InvokeBCryptImportKeyPair( + 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. + public NTStatus InvokeBCryptExportKey( + 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. + public NTStatus InvokeBCryptSecretAgreement( + 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. + /// + public NTStatus InvokeBCryptDeriveKey( + 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. + public NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, + int inputSize, + BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) + => BCryptSetProperty(hObject, property, input, inputSize, 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. + /// + /// The name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// 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. + public NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + string 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. + public NTStatus InvokeBCryptGetProperty( + 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. + public NTStatus InvokeBCryptGenRandom( + SafeAlgorithmHandle hAlgorithm, + byte[] pbBuffer, + int cbBuffer, + BCryptGenRandomFlags flags = BCryptGenRandomFlags.None) + => BCryptGenRandom(hAlgorithm, pbBuffer, cbBuffer, flags ); } } diff --git a/src/BCrypt/IBCryptMockable.cs b/src/BCrypt/IBCryptMockable.cs index 30c70a8a..bfd084cd 100644 --- a/src/BCrypt/IBCryptMockable.cs +++ b/src/BCrypt/IBCryptMockable.cs @@ -1,4 +1,4 @@ -// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. +// 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 @@ -7,6 +7,7 @@ namespace PInvoke using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; + using static BCrypt; public interface IBCryptMockable { /// /// Loads and initializes a CNG provider. /// @@ -226,5 +227,416 @@ NTStatus InvokeBCryptFinishHash( [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. + /// + NTStatus InvokeBCryptSignHash( + 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. + /// + NTStatus InvokeBCryptVerifySignature( + 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. + /// + NTStatus InvokeBCryptGenerateKeyPair( + 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. + NTStatus InvokeBCryptGenerateSymmetricKey( + 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. + /// + NTStatus InvokeBCryptFinalizeKeyPair( + 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. + NTStatus InvokeBCryptDestroyKey( + 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. + NTStatus InvokeBCryptDestroySecret( + 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. + NTStatus InvokeBCryptImportKey( + 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. + NTStatus InvokeBCryptImportKeyPair( + 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. + NTStatus InvokeBCryptExportKey( + 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. + NTStatus InvokeBCryptSecretAgreement( + 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. + /// + NTStatus InvokeBCryptDeriveKey( + 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. + NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, + int inputSize, + BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None); + + /// + /// Sets the value of a named property for a CNG object. + /// + /// A handle that represents the CNG object to set the property value for. + /// + /// The name of the property to set. This can be one of the predefined or a custom property identifier. + /// + /// 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. + NTStatus InvokeBCryptSetProperty( + SafeHandle hObject, + string property, + string 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. + NTStatus InvokeBCryptGetProperty( + 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. + NTStatus InvokeBCryptGenRandom( + 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..0fc2e679 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 index 145e9b84..d2899714 100644 --- a/src/Gdi32.Desktop/Gdi32Mockable.cs +++ b/src/Gdi32.Desktop/Gdi32Mockable.cs @@ -5,7 +5,8 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; - public partial class Gdi32 : IGdi32Mockable { public bool InvokeDeleteObject(IntPtr hObject) + using static Gdi32; + public class Gdi32Mockable : IGdi32Mockable { public bool InvokeDeleteObject(IntPtr hObject) => DeleteObject(hObject); } } diff --git a/src/Gdi32.Desktop/IGdi32Mockable.cs b/src/Gdi32.Desktop/IGdi32Mockable.cs index f07917c6..b31cdd0b 100644 --- a/src/Gdi32.Desktop/IGdi32Mockable.cs +++ b/src/Gdi32.Desktop/IGdi32Mockable.cs @@ -5,6 +5,7 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; + using static Gdi32; public interface IGdi32Mockable { bool InvokeDeleteObject(IntPtr hObject); } } diff --git a/src/Hid.Desktop/Hid.Desktop.csproj b/src/Hid.Desktop/Hid.Desktop.csproj index eb1140af..edae0fe3 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 index fef52b19..7c4d0023 100644 --- a/src/Hid.Desktop/HidMockable.cs +++ b/src/Hid.Desktop/HidMockable.cs @@ -7,7 +7,8 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using static Kernel32; - public partial class Hid : IHidMockable { /// + using static Hid; + public class HidMockable : IHidMockable { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// /// @@ -15,7 +16,7 @@ public partial class Hid : IHidMockable { /// /// for HIDClass devices. /// public void InvokeHidD_GetHidGuid(out Guid hidGuid) - => HidD_GetHidGuid(hidGuid); + => HidD_GetHidGuid(out hidGuid); /// /// Returns the attributes of a specified top-level collection. @@ -29,7 +30,7 @@ public void InvokeHidD_GetHidGuid(out Guid hidGuid) public bool InvokeHidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes) - => HidD_GetAttributes(hidDeviceObject, attributes); + => HidD_GetAttributes(hidDeviceObject, ref attributes); /// /// Returns a top-level collection's embedded string that identifies the manufacturer. @@ -136,7 +137,7 @@ public bool InvokeHidD_SetNumInputBuffers( public bool InvokeHidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle) - => HidD_GetPreparsedData(hidDeviceObject, preparsedDataHandle); + => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); /// /// Returns a top-level collection's structure. @@ -151,7 +152,7 @@ public bool InvokeHidD_GetPreparsedData( /// specified preparsed data is invalid. /// public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) - => HidP_GetCaps(preparsedData, capabilities); + => HidP_GetCaps(preparsedData, ref capabilities); /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// @@ -160,6 +161,142 @@ public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref Hi /// for HIDClass devices. /// public void InvokeHidD_GetHidGuid(out Guid hidGuid) - => HidD_GetHidGuid(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. + public bool InvokeHidD_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). + /// + 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, 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. + /// + public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + => HidP_GetCaps(preparsedData, ref capabilities); } } \ No newline at end of file diff --git a/src/Hid.Desktop/IHidMockable.cs b/src/Hid.Desktop/IHidMockable.cs index fca05093..7a78b964 100644 --- a/src/Hid.Desktop/IHidMockable.cs +++ b/src/Hid.Desktop/IHidMockable.cs @@ -7,6 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using static Kernel32; + using static Hid; public interface IHidMockable { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// @@ -152,5 +153,134 @@ bool InvokeHidD_GetPreparsedData( /// 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..e2b8e981 100644 --- a/src/Hid/Hid.csproj +++ b/src/Hid/Hid.csproj @@ -23,6 +23,8 @@ + + diff --git a/src/ImageHlp/IImageHlpMockable.cs b/src/ImageHlp/IImageHlpMockable.cs index 5ccfcd66..b70004f2 100644 --- a/src/ImageHlp/IImageHlpMockable.cs +++ b/src/ImageHlp/IImageHlpMockable.cs @@ -6,6 +6,7 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static DbgHelp; + using static ImageHlp; public interface IImageHlpMockable { /// /// Maps an image and preloads data from the mapped file. /// @@ -24,5 +25,18 @@ bool InvokeMapAndLoad( 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 . + /// + bool InvokeUnMapAndLoad( + ref LOADED_IMAGE LoadedImage); } } diff --git a/src/ImageHlp/ImageHlp.csproj b/src/ImageHlp/ImageHlp.csproj index 5937a174..907da4e9 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 index 3f2dc493..850bfbfe 100644 --- a/src/ImageHlp/ImageHlpMockable.cs +++ b/src/ImageHlp/ImageHlpMockable.cs @@ -6,7 +6,8 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static DbgHelp; - public partial class ImageHlp : IImageHlpMockable { /// + using static ImageHlp; + public class ImageHlpMockable : IImageHlpMockable { /// /// Maps an image and preloads data from the mapped file. /// /// The file name of the image (executable file or DLL) that is loaded. @@ -24,6 +25,20 @@ public bool InvokeMapAndLoad( out LOADED_IMAGE LoadedImage, bool DotDll, bool ReadOnly) - => MapAndLoad(ImageName, DllPath, LoadedImage, DotDll, 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 . + /// + public bool InvokeUnMapAndLoad( + ref LOADED_IMAGE LoadedImage) + => UnMapAndLoad(ref LoadedImage); } } diff --git a/src/Kernel32.Desktop/IKernel32Mockable.cs b/src/Kernel32.Desktop/IKernel32Mockable.cs index 29a294a3..14747637 100644 --- a/src/Kernel32.Desktop/IKernel32Mockable.cs +++ b/src/Kernel32.Desktop/IKernel32Mockable.cs @@ -6,6 +6,8 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using System.Text; + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; public interface IKernel32Mockable { /// /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. @@ -154,7 +156,7 @@ public interface IKernel32Mockable { /// returns . /// /// - bool InvokeCancelIoEx( + unsafe bool InvokeCancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped); @@ -218,7 +220,7 @@ bool InvokeCancelIoEx( /// it designates the read operation is pending completion asynchronously. /// /// - bool InvokeReadFile( + unsafe bool InvokeReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -293,7 +295,7 @@ bool InvokeReadFile( /// it designates the write operation is pending completion asynchronously. /// /// - bool InvokeWriteFile( + unsafe bool InvokeWriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -439,5 +441,965 @@ bool InvokeCreateProcess( 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 . + /// + bool InvokeCreateProcessAsUser( + 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. + /// + void InvokeGetStartupInfo( + 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. + /// + bool InvokeInitializeProcThreadAttributeList( + 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 . + /// + bool InvokeUpdateProcThreadAttribute( + 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. + /// + void InvokeDeleteProcThreadAttributeList( + 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 . + /// + bool InvokeAllocConsole(); + + /// + /// 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 . + /// + bool InvokeFreeConsole(); + + /// + /// 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 . + /// + bool InvokeAttachConsole(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 . + /// + SafeObjectHandle InvokeCreateFile( + 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. + /// + SafeFindFilesHandle InvokeFindFirstFile(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. + /// + bool InvokeFindNextFile(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. + /// + /// + SafeObjectHandle InvokeCreateToolhelp32Snapshot( + 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. + /// + bool InvokeProcess32First(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. + /// + bool InvokeProcess32Next( + 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. + bool InvokeQueryFullProcessImageName( + 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. + SafeObjectHandle InvokeOpenProcess( + 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. + /// + /// + unsafe bool InvokeGetOverlappedResult( + 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. + /// + /// + bool InvokeCancelIo(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 + /// . + /// + /// + bool InvokeIsWow64Process(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 . + /// + bool InvokeCreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize); + + /// + /// 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 . + /// + /// + unsafe 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. + /// + /// + unsafe 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. + /// + /// + unsafe 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.Desktop/Kernel32.Desktop.csproj b/src/Kernel32.Desktop/Kernel32.Desktop.csproj index 9421dae7..8360c4fd 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 index 32ef45eb..a5fcde71 100644 --- a/src/Kernel32.Desktop/Kernel32Mockable.cs +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -6,7 +6,9 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using System.Text; - public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable , IKernel32Mockable , IKernel32Mockable { + using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; + public class Kernel32Mockable : 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. @@ -40,7 +42,7 @@ public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable , IKernel3 /// 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); + => 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. @@ -159,7 +161,7 @@ public SafeObjectHandle InvokeGetCurrentProcess() /// returns . /// /// - public bool InvokeCancelIoEx( + unsafe public bool InvokeCancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped) => CancelIoEx(hFile, lpOverlapped); @@ -224,7 +226,7 @@ public bool InvokeCancelIoEx( /// it designates the read operation is pending completion asynchronously. /// /// - public bool InvokeReadFile( + unsafe public bool InvokeReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -300,7 +302,7 @@ public bool InvokeReadFile( /// it designates the write operation is pending completion asynchronously. /// /// - public bool InvokeWriteFile( + unsafe public bool InvokeWriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -452,6 +454,999 @@ public bool InvokeCreateProcess( string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation) - => CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, 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 . + /// + public bool InvokeCreateProcessAsUser( + 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. + /// + public void InvokeGetStartupInfo( + 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. + /// + public bool InvokeInitializeProcThreadAttributeList( + 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 . + /// + public bool InvokeUpdateProcThreadAttribute( + 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. + /// + public void InvokeDeleteProcThreadAttributeList( + 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 . + /// + public bool InvokeAllocConsole() + => 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 . + /// + public bool InvokeFreeConsole() + => 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 . + /// + public bool InvokeAttachConsole(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 . + /// + public SafeObjectHandle InvokeCreateFile( + 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. + /// + public SafeFindFilesHandle InvokeFindFirstFile(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. + /// + public bool InvokeFindNextFile(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. + /// + /// + public SafeObjectHandle InvokeCreateToolhelp32Snapshot( + 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. + /// + public bool InvokeProcess32First(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. + /// + public bool InvokeProcess32Next( + 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. + public bool InvokeQueryFullProcessImageName( + 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. + public SafeObjectHandle InvokeOpenProcess( + 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. + /// + /// + unsafe public bool InvokeGetOverlappedResult( + 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. + /// + /// + public bool InvokeCancelIo(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 + /// . + /// + /// + public bool InvokeIsWow64Process(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 . + /// + public bool InvokeCreatePipe( + out SafeObjectHandle hReadPipe, + out SafeObjectHandle hWritePipe, + SECURITY_ATTRIBUTES lpPipeAttributes, + uint nSize) + => CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize); + + /// + /// 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, 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 . + /// + 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 . + /// + /// + unsafe 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. + /// + /// + unsafe 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. + /// + /// + unsafe 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/IKernel32Mockable.cs b/src/Kernel32/IKernel32Mockable.cs index 3e85a1f1..28f14439 100644 --- a/src/Kernel32/IKernel32Mockable.cs +++ b/src/Kernel32/IKernel32Mockable.cs @@ -7,6 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; + using static Kernel32; public interface IKernel32Mockable { /// /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. @@ -41,5 +42,332 @@ public interface IKernel32Mockable { /// 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 . + /// + /// + unsafe 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. + /// + /// + unsafe 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. + /// + /// + unsafe 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/Kernel32.csproj b/src/Kernel32/Kernel32.csproj index 9d0ffa06..43c30b0a 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 index b9f5c05e..0eaeb2e2 100644 --- a/src/Kernel32/Kernel32Mockable.cs +++ b/src/Kernel32/Kernel32Mockable.cs @@ -7,7 +7,8 @@ namespace PInvoke using System.Runtime.InteropServices; using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; - public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable , IKernel32Mockable { + using static Kernel32; + public class Kernel32Mockable : 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. @@ -41,6 +42,345 @@ public partial class Kernel32 : IKernel32Mockable , IKernel32Mockable , IKernel3 /// 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); + => 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 . + /// + 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 . + /// + /// + unsafe 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. + /// + /// + unsafe 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. + /// + /// + unsafe 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/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 86696c0f..54d20f4d 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -50,12 +50,15 @@ private static void Run() var project = projects[i]; Console.WriteLine($"Processing project {project.Name}"); - foreach (var file in project.Documents - .Select(x => x.FilePath) - .Where(x => x.EndsWith(".cs"))) + var documents = project.Documents + .Where(x => x.FilePath.EndsWith(".cs")) + .ToArray(); + for (int index = 0; index < documents.Length; index++) { - Console.WriteLine($"\tProcessing {Path.GetFileName(file)}"); - ProcessSourceCodes(workspace, ref solution, ref project, file); + var document = documents[index]; + + Console.WriteLine($"\tProcessing {Path.GetFileName(document.FilePath)}"); + ProcessSourceCodes(ref solution, ref project, ref document); } projects = GetProjectsFromSolution(solution); @@ -80,11 +83,9 @@ private static Project[] GetProjectsFromSolution(Solution solution) .ToArray(); } - private static void ProcessSourceCodes(Workspace workspace, ref Solution solution, ref Project project, string file) + private static void ProcessSourceCodes(ref Solution solution, ref Project project, ref Document document) { - var syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(file)); - - var compilationUnit = syntaxTree.GetRoot() as CompilationUnitSyntax; + var compilationUnit = document.GetSyntaxRootAsync().Result as CompilationUnitSyntax; if (compilationUnit == null || compilationUnit.Members.Count == 0) return; var namespaceDeclarations = compilationUnit.Members.OfType(); @@ -161,11 +162,11 @@ private static void ProcessSourceCodes(Workspace workspace, ref Solution solutio .WithTrailingTrivia(NewLineCharacter) }; - AddPathToProject(workspace, ref solution, ref project, $"{baseFileName}Mockable.cs", + AddPathToProject(ref solution, ref project, $"{baseFileName}Mockable.cs", CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) .AddMembers(newClassDeclaration) .ToFullString()); - AddPathToProject(workspace, ref solution, ref project, $"I{baseFileName}Mockable.cs", + AddPathToProject(ref solution, ref project, $"I{baseFileName}Mockable.cs", CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) .AddMembers(newInterfaceDeclaration) .ToFullString()); @@ -179,7 +180,7 @@ private static Document GetExistingDocument(Project project, string path) return project.Documents.FirstOrDefault(x => x.Name == Path.GetFileName(path)); } - private static void AddPathToProject(Workspace workspace, ref Solution solution, ref Project project, string fileName, string contents) + private static void AddPathToProject(ref Solution solution, ref Project project, string fileName, string contents) { var document = GetExistingDocument(project, fileName); if (document != null) diff --git a/src/NCrypt/NCrypt.csproj b/src/NCrypt/NCrypt.csproj index 02126362..4ff0bd16 100644 --- a/src/NCrypt/NCrypt.csproj +++ b/src/NCrypt/NCrypt.csproj @@ -23,6 +23,7 @@ + @@ -37,6 +38,7 @@ + diff --git a/src/SetupApi.Desktop/ISetupApiMockable.cs b/src/SetupApi.Desktop/ISetupApiMockable.cs index c561ddfe..47677921 100644 --- a/src/SetupApi.Desktop/ISetupApiMockable.cs +++ b/src/SetupApi.Desktop/ISetupApiMockable.cs @@ -5,6 +5,7 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; + using static SetupApi; public interface ISetupApiMockable { /// /// The SetupDiGetClassDevs function returns a handle to a device information set /// that contains requested device information elements for a local computer. @@ -51,5 +52,120 @@ SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( 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 + /// . + /// + bool InvokeSetupDiEnumDeviceInterfaces( + 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 + /// . + /// + bool InvokeSetupDiGetDeviceInterfaceDetail( + 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 + /// . + /// + bool InvokeSetupDiEnumDeviceInfo( + 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..1a42774e 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 index ae0da9fc..2440cf31 100644 --- a/src/SetupApi.Desktop/SetupApiMockable.cs +++ b/src/SetupApi.Desktop/SetupApiMockable.cs @@ -5,7 +5,8 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; - public partial class SetupApi : ISetupApiMockable { /// + using static SetupApi; + public class SetupApiMockable : ISetupApiMockable { /// /// The SetupDiGetClassDevs function returns a handle to a device information set /// that contains requested device information elements for a local computer. /// @@ -52,5 +53,123 @@ public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( 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 + /// . + /// + public bool InvokeSetupDiEnumDeviceInterfaces( + 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 + /// . + /// + public bool InvokeSetupDiGetDeviceInterfaceDetail( + 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 + /// . + /// + public bool InvokeSetupDiEnumDeviceInfo( + SafeDeviceInfoSetHandle deviceInfoSet, + uint memberIndex, + DeviceInfoData deviceInfoData) + => SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, deviceInfoData); } } \ No newline at end of file diff --git a/src/User32.Desktop/IUser32Mockable.cs b/src/User32.Desktop/IUser32Mockable.cs index 00f12d57..a3fc2d8f 100644 --- a/src/User32.Desktop/IUser32Mockable.cs +++ b/src/User32.Desktop/IUser32Mockable.cs @@ -5,6 +5,32 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; + using static User32; public interface IUser32Mockable { int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); + + int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); + + bool InvokeSetWindowPos( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int X, + int Y, + int cx, + int cy, + SetWindowPosFlags uFlags); + + IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent); + + IntPtr InvokeFindWindowEx( + IntPtr parentHandle, + IntPtr childAfter, + string className, + string windowTitle); + + bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); + + IntPtr InvokeGetForegroundWindow(); + + int InvokeSendMessage(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..a10d221e 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 index 8fc4d1ef..ad8f133d 100644 --- a/src/User32.Desktop/User32Mockable.cs +++ b/src/User32.Desktop/User32Mockable.cs @@ -5,7 +5,40 @@ namespace PInvoke { using System; using System.Runtime.InteropServices; - public partial class User32 : IUser32Mockable { public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) + using static User32; + public class User32Mockable : IUser32Mockable { public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) => SetWindowLong(hWnd, nIndex, dwNewLong); + + public int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) + => GetWindowLong(hWnd, nIndex); + + public bool InvokeSetWindowPos( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int X, + int Y, + int cx, + int cy, + SetWindowPosFlags uFlags) + => SetWindowPos(hWnd, hWndInsertAfter, X, Y, cx, cy, uFlags); + + public IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent) + => SetParent(hWndChild, hWndNewParent); + + public IntPtr InvokeFindWindowEx( + IntPtr parentHandle, + IntPtr childAfter, + string className, + string windowTitle) + => FindWindowEx(parentHandle, childAfter, className, windowTitle); + + public bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) + => ShowWindow(hWnd, nCmdShow); + + public IntPtr InvokeGetForegroundWindow() + => GetForegroundWindow(); + + public int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) + => SendMessage(hWnd, wMsg, wParam, lParam); } } From 9e9840f186d73a2f68dbd3f4cd0ae25e4f4d441f Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 11:33:25 +0100 Subject: [PATCH 42/46] fix for duplicate code. --- src/BCrypt/BCryptMockable.cs | 19 -- src/BCrypt/IBCryptMockable.cs | 18 -- src/Hid.Desktop/HidMockable.cs | 145 --------- src/Hid.Desktop/IHidMockable.cs | 137 -------- src/Kernel32.Desktop/IKernel32Mockable.cs | 361 --------------------- src/Kernel32.Desktop/Kernel32Mockable.cs | 374 ---------------------- src/MockGenerator/Program.cs | 16 +- 7 files changed, 15 insertions(+), 1055 deletions(-) diff --git a/src/BCrypt/BCryptMockable.cs b/src/BCrypt/BCryptMockable.cs index ecd09370..8d9a99c0 100644 --- a/src/BCrypt/BCryptMockable.cs +++ b/src/BCrypt/BCryptMockable.cs @@ -602,25 +602,6 @@ public NTStatus InvokeBCryptSetProperty( BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) => BCryptSetProperty(hObject, property, input, inputSize, 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. - /// - /// The name of the property to set. This can be one of the predefined or a custom property identifier. - /// - /// 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. - public NTStatus InvokeBCryptSetProperty( - SafeHandle hObject, - string property, - string input, - int inputSize, - BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None) - => BCryptSetProperty(hObject, property, input, inputSize, flags ); - /// /// Retrieves the value of a named property for a CNG object. /// diff --git a/src/BCrypt/IBCryptMockable.cs b/src/BCrypt/IBCryptMockable.cs index bfd084cd..d24dfe2d 100644 --- a/src/BCrypt/IBCryptMockable.cs +++ b/src/BCrypt/IBCryptMockable.cs @@ -583,24 +583,6 @@ NTStatus InvokeBCryptSetProperty( int inputSize, BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None); - /// - /// Sets the value of a named property for a CNG object. - /// - /// A handle that represents the CNG object to set the property value for. - /// - /// The name of the property to set. This can be one of the predefined or a custom property identifier. - /// - /// 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. - NTStatus InvokeBCryptSetProperty( - SafeHandle hObject, - string property, - string input, - int inputSize, - BCryptSetPropertyFlags flags = BCryptSetPropertyFlags.None); - /// /// Retrieves the value of a named property for a CNG object. /// diff --git a/src/Hid.Desktop/HidMockable.cs b/src/Hid.Desktop/HidMockable.cs index 7c4d0023..13cfaef0 100644 --- a/src/Hid.Desktop/HidMockable.cs +++ b/src/Hid.Desktop/HidMockable.cs @@ -139,151 +139,6 @@ public bool InvokeHidD_GetPreparsedData( 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. - /// - public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) - => HidP_GetCaps(preparsedData, ref 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(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. - public bool InvokeHidD_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). - /// - 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, out preparsedDataHandle); - /// /// Returns a top-level collection's structure. /// diff --git a/src/Hid.Desktop/IHidMockable.cs b/src/Hid.Desktop/IHidMockable.cs index 7a78b964..dd02db51 100644 --- a/src/Hid.Desktop/IHidMockable.cs +++ b/src/Hid.Desktop/IHidMockable.cs @@ -132,143 +132,6 @@ 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. /// diff --git a/src/Kernel32.Desktop/IKernel32Mockable.cs b/src/Kernel32.Desktop/IKernel32Mockable.cs index 14747637..a0d1608e 100644 --- a/src/Kernel32.Desktop/IKernel32Mockable.cs +++ b/src/Kernel32.Desktop/IKernel32Mockable.cs @@ -1040,366 +1040,5 @@ bool InvokeCreatePipe( out SafeObjectHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize); - - /// - /// 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 . - /// - /// - unsafe 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. - /// - /// - unsafe 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. - /// - /// - unsafe 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.Desktop/Kernel32Mockable.cs b/src/Kernel32.Desktop/Kernel32Mockable.cs index a5fcde71..c3135e63 100644 --- a/src/Kernel32.Desktop/Kernel32Mockable.cs +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -1074,379 +1074,5 @@ public bool InvokeCreatePipe( SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize) => CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize); - - /// - /// 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, 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 . - /// - 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 . - /// - /// - unsafe 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. - /// - /// - unsafe 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. - /// - /// - unsafe 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/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 54d20f4d..67fea110 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -146,7 +146,7 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec InterfaceCache[newInterfaceModifier.Identifier.Text] = newInterfaceDeclaration; string fileDirectory; - var baseFileName = GetBaseFileName(file, out fileDirectory); + var baseFileName = GetBaseFileName(document.FilePath, out fileDirectory); var usings = new[] { @@ -299,6 +299,13 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( 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( @@ -339,6 +346,13 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec 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 From 0ff5a717ee764e898d36fa9bb252ea77c478586e Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 11:33:44 +0100 Subject: [PATCH 43/46] mockables. --- src/AdvApi32.Desktop/AdvApi32Mockable.cs | 187 +++++++++++++++++++++++ src/Hid/HidMockable.cs | 157 +++++++++++++++++++ src/Hid/IHidMockable.cs | 149 ++++++++++++++++++ src/NCrypt/INCryptMockable.cs | 119 +++++++++++++++ src/NCrypt/NCryptMockable.cs | 124 +++++++++++++++ 5 files changed, 736 insertions(+) create mode 100644 src/AdvApi32.Desktop/AdvApi32Mockable.cs create mode 100644 src/Hid/HidMockable.cs create mode 100644 src/Hid/IHidMockable.cs create mode 100644 src/NCrypt/INCryptMockable.cs create mode 100644 src/NCrypt/NCryptMockable.cs diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs new file mode 100644 index 00000000..84901a4a --- /dev/null +++ b/src/AdvApi32.Desktop/AdvApi32Mockable.cs @@ -0,0 +1,187 @@ +// 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; + public class AdvApi32Mockable : IAdvApi32Mockable { + /// + /// 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 + /// + public bool InvokeChangeServiceConfig2(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 + /// + public SafeServiceHandle InvokeCreateService(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 + /// + public bool InvokeDeleteService(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 . + /// + public SafeServiceHandle InvokeOpenSCManager(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. + /// + public SafeServiceHandle InvokeOpenService(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. + /// + public bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) + => StartService(hService, dwNumServiceArgs, lpServiceArgVectors); + } +} diff --git a/src/Hid/HidMockable.cs b/src/Hid/HidMockable.cs new file mode 100644 index 00000000..13cfaef0 --- /dev/null +++ b/src/Hid/HidMockable.cs @@ -0,0 +1,157 @@ +// 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; + public class HidMockable : 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(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. + public bool InvokeHidD_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). + /// + 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, 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. + /// + public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + => HidP_GetCaps(preparsedData, ref capabilities); + } +} \ No newline at end of file diff --git a/src/Hid/IHidMockable.cs b/src/Hid/IHidMockable.cs new file mode 100644 index 00000000..dd02db51 --- /dev/null +++ b/src/Hid/IHidMockable.cs @@ -0,0 +1,149 @@ +// 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; + 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); + } +} \ No newline at end of file diff --git a/src/NCrypt/INCryptMockable.cs b/src/NCrypt/INCryptMockable.cs new file mode 100644 index 00000000..125e96cc --- /dev/null +++ b/src/NCrypt/INCryptMockable.cs @@ -0,0 +1,119 @@ +// 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; + public interface INCryptMockable { /// + /// 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. + SECURITY_STATUS InvokeNCryptOpenStorageProvider( + 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. + SECURITY_STATUS InvokeNCryptCreatePersistedKey( + 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. + SECURITY_STATUS InvokeNCryptFinalizeKey( + 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. + SECURITY_STATUS InvokeNCryptGetProperty( + 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. + SECURITY_STATUS InvokeNCryptSetProperty( + SafeHandle hObject, + string pszProperty, + byte[] pbInput, + int cbInput, + NCryptSetPropertyFlags dwFlags); + } +} diff --git a/src/NCrypt/NCryptMockable.cs b/src/NCrypt/NCryptMockable.cs new file mode 100644 index 00000000..e32ce68f --- /dev/null +++ b/src/NCrypt/NCryptMockable.cs @@ -0,0 +1,124 @@ +// 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; + public class NCryptMockable : INCryptMockable { /// + /// 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. + public SECURITY_STATUS InvokeNCryptOpenStorageProvider( + 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. + public SECURITY_STATUS InvokeNCryptCreatePersistedKey( + 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. + public SECURITY_STATUS InvokeNCryptFinalizeKey( + 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. + public SECURITY_STATUS InvokeNCryptGetProperty( + 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. + public SECURITY_STATUS InvokeNCryptSetProperty( + SafeHandle hObject, + string pszProperty, + byte[] pbInput, + int cbInput, + NCryptSetPropertyFlags dwFlags) + => NCryptSetProperty(hObject, pszProperty, pbInput, cbInput, dwFlags); + } +} From 47b5846f0825ddfd93c9254ee602e7fecf1ea7ca Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 11:56:32 +0100 Subject: [PATCH 44/46] new changes. --- src/AdvApi32.Desktop/AdvApi32Mockable.cs | 19 ++-- src/AdvApi32.Desktop/IAdvApi32Mockable.cs | 21 +++-- src/BCrypt/BCryptMockable.cs | 64 ++++++++----- src/BCrypt/IBCryptMockable.cs | 66 +++++++++----- src/Gdi32.Desktop/Gdi32Mockable.cs | 4 +- src/Gdi32.Desktop/IGdi32Mockable.cs | 4 +- src/Hid.Desktop/HidMockable.cs | 25 ++++-- src/Hid.Desktop/IHidMockable.cs | 27 ++++-- src/Hid/HidMockable.cs | 25 ++++-- src/Hid/IHidMockable.cs | 27 ++++-- src/ImageHlp/IImageHlpMockable.cs | 9 +- src/ImageHlp/ImageHlpMockable.cs | 7 +- src/Kernel32.Desktop/IKernel32Mockable.cs | 105 ++++++++++++++-------- src/Kernel32.Desktop/Kernel32Mockable.cs | 103 ++++++++++++++------- src/Kernel32/IKernel32Mockable.cs | 42 ++++++--- src/Kernel32/Kernel32Mockable.cs | 40 ++++++--- src/MockGenerator/Program.cs | 38 +++++++- src/NCrypt/INCryptMockable.cs | 18 ++-- src/NCrypt/NCryptMockable.cs | 16 ++-- src/SetupApi.Desktop/ISetupApiMockable.cs | 15 ++-- src/SetupApi.Desktop/SetupApiMockable.cs | 13 ++- src/User32.Desktop/IUser32Mockable.cs | 25 ++++-- src/User32.Desktop/User32Mockable.cs | 25 ++++-- 23 files changed, 505 insertions(+), 233 deletions(-) diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs index 84901a4a..3af8f540 100644 --- a/src/AdvApi32.Desktop/AdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/AdvApi32Mockable.cs @@ -6,6 +6,7 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static AdvApi32; + [System.Runtime.CompilerServices.CompilerGenerated] public class AdvApi32Mockable : IAdvApi32Mockable { /// /// Changes the optional configuration parameters of a service. @@ -28,7 +29,8 @@ public class AdvApi32Mockable : IAdvApi32Mockable { /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero /// - public bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo) => ChangeServiceConfig2(hService, dwInfoLevel, lpInfo); /// @@ -102,7 +104,8 @@ public bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLe /// If the function succeeds, the return value is a handle to the service. /// If the function fails, the return value is NULL /// - public SafeServiceHandle InvokeCreateService(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) + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeServiceHandle InvokeCreateService(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); /// @@ -115,7 +118,8 @@ public SafeServiceHandle InvokeCreateService(SafeServiceHandle hSCManager, strin /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero /// - public bool InvokeDeleteService(SafeServiceHandle hService) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeDeleteService(SafeServiceHandle hService) => DeleteService(hService); /// @@ -140,7 +144,8 @@ public bool InvokeDeleteService(SafeServiceHandle hService) /// 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 . /// - public SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess) + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess) => OpenSCManager(lpMachineName, lpDatabaseName, dwDesiredAccess); /// @@ -161,7 +166,8 @@ public SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpData /// If the function succeeds, the return value is a handle to the service. /// If the function fails, the return value is NULL. /// - public SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess) + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess) => OpenService(hSCManager, lpServiceName, dwDesiredAccess); /// @@ -181,7 +187,8 @@ public SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. /// - public bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) => StartService(hService, dwNumServiceArgs, lpServiceArgVectors); } } diff --git a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs index c8dbdabd..54a9fec3 100644 --- a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/IAdvApi32Mockable.cs @@ -6,7 +6,8 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static AdvApi32; - public interface IAdvApi32Mockable { + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IAdvApi32Mockable { /// /// Changes the optional configuration parameters of a service. /// @@ -28,7 +29,8 @@ public interface IAdvApi32Mockable { /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero /// - bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo); /// /// Creates a service object and adds it to the specified service control manager database. @@ -101,7 +103,8 @@ public interface IAdvApi32Mockable { /// If the function succeeds, the return value is a handle to the service. /// If the function fails, the return value is NULL /// - SafeServiceHandle InvokeCreateService(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); + [System.Runtime.CompilerServices.CompilerGenerated] + SafeServiceHandle InvokeCreateService(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. @@ -113,7 +116,8 @@ public interface IAdvApi32Mockable { /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero /// - bool InvokeDeleteService(SafeServiceHandle hService); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeDeleteService(SafeServiceHandle hService); /// /// Establishes a connection to the service control manager on the specified computer and opens the specified service control manager database. @@ -137,7 +141,8 @@ public interface IAdvApi32Mockable { /// 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 . /// - SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess); + [System.Runtime.CompilerServices.CompilerGenerated] + SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess); /// /// Opens an existing service. @@ -157,7 +162,8 @@ public interface IAdvApi32Mockable { /// If the function succeeds, the return value is a handle to the service. /// If the function fails, the return value is NULL. /// - SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess); + [System.Runtime.CompilerServices.CompilerGenerated] + SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess); /// /// Starts a service. @@ -176,6 +182,7 @@ public interface IAdvApi32Mockable { /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. /// - bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); } } diff --git a/src/BCrypt/BCryptMockable.cs b/src/BCrypt/BCryptMockable.cs index 8d9a99c0..1a3eb131 100644 --- a/src/BCrypt/BCryptMockable.cs +++ b/src/BCrypt/BCryptMockable.cs @@ -8,6 +8,7 @@ namespace PInvoke using System.Collections.Generic; using System.Runtime.InteropServices; using static BCrypt; + [System.Runtime.CompilerServices.CompilerGenerated] public class BCryptMockable : IBCryptMockable { /// /// Loads and initializes a CNG provider. /// @@ -41,7 +42,8 @@ public class BCryptMockable : IBCryptMockable { /// /// /// Returns a status code that indicates the success or failure of the function. /// - public NTStatus InvokeBCryptOpenAlgorithmProvider( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptOpenAlgorithmProvider( out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, @@ -76,7 +78,8 @@ public NTStatus InvokeBCryptOpenAlgorithmProvider( /// /// Flags that modify the behavior of the function. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptCreateHash( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptCreateHash( SafeAlgorithmHandle hAlgorithm, out SafeHashHandle phHash, byte[] pbHashObject, @@ -125,7 +128,8 @@ public NTStatus InvokeBCryptCreateHash( /// /// 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. /// - public NTStatus InvokeBCryptEncrypt( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptEncrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -176,7 +180,8 @@ public NTStatus InvokeBCryptEncrypt( /// 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. - public NTStatus InvokeBCryptDecrypt( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptDecrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -205,7 +210,8 @@ public NTStatus InvokeBCryptDecrypt( /// 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. /// - public NTStatus InvokeBCryptHashData( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptHashData( SafeHashHandle hHash, byte[] pbInput, int cbInput, @@ -227,7 +233,8 @@ public NTStatus InvokeBCryptHashData( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptFinishHash( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptFinishHash( SafeHashHandle hHash, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbOutput, int cbOutput, @@ -265,7 +272,8 @@ public NTStatus InvokeBCryptFinishHash( /// /// To later verify that the signature is valid, call the function with an identical key and an identical hash of the original data. /// - public NTStatus InvokeBCryptSignHash( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptSignHash( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbInput, @@ -306,7 +314,8 @@ public NTStatus InvokeBCryptSignHash( /// Returns a status code that indicates the success or failure of the function. /// In particular, an invalid signature will produce a result. /// - public NTStatus InvokeBCryptVerifySignature( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptVerifySignature( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbHash, @@ -329,7 +338,8 @@ public NTStatus InvokeBCryptVerifySignature( /// function to set its properties; however, the key cannot be used until the /// BCryptFinalizeKeyPair function is called. /// - public NTStatus InvokeBCryptGenerateKeyPair( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptGenerateKeyPair( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, int dwLength, @@ -363,7 +373,8 @@ public NTStatus InvokeBCryptGenerateKeyPair( /// /// 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. - public NTStatus InvokeBCryptGenerateSymmetricKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptGenerateSymmetricKey( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, byte[] pbKeyObject, @@ -384,7 +395,8 @@ public NTStatus InvokeBCryptGenerateSymmetricKey( /// After this function has been called, the BCryptSetProperty function /// can no longer be used for this key. /// - public NTStatus InvokeBCryptFinalizeKeyPair( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptFinalizeKeyPair( SafeKeyHandle hKey, BCryptFinalizeKeyPairFlags dwFlags = BCryptFinalizeKeyPairFlags.None) => BCryptFinalizeKeyPair(hKey, dwFlags ); @@ -394,7 +406,8 @@ public NTStatus InvokeBCryptFinalizeKeyPair( /// /// The handle of the key to destroy. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptDestroyKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptDestroyKey( IntPtr hKey) => BCryptDestroyKey(hKey); @@ -403,7 +416,8 @@ public NTStatus InvokeBCryptDestroyKey( /// /// The handle of the secret to destroy. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptDestroySecret( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptDestroySecret( IntPtr hSecret) => BCryptDestroySecret(hSecret); @@ -443,7 +457,8 @@ public NTStatus InvokeBCryptDestroySecret( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptImportKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptImportKey( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -466,7 +481,8 @@ public NTStatus InvokeBCryptImportKey( /// 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. - public NTStatus InvokeBCryptImportKeyPair( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptImportKeyPair( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -503,7 +519,8 @@ public NTStatus InvokeBCryptImportKeyPair( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptExportKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptExportKey( SafeKeyHandle hKey, SafeKeyHandle hExportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -531,7 +548,8 @@ public NTStatus InvokeBCryptExportKey( /// /// 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. - public NTStatus InvokeBCryptSecretAgreement( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptSecretAgreement( SafeKeyHandle privateKey, SafeKeyHandle publicKey, out SafeSecretHandle secret, @@ -573,7 +591,8 @@ public NTStatus InvokeBCryptSecretAgreement( /// /// Returns a status code that indicates the success or failure of the function. /// - public NTStatus InvokeBCryptDeriveKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptDeriveKey( SafeSecretHandle sharedSecret, string keyDerivationFunction, [In] ref BCryptBufferDesc kdfParameters, @@ -594,7 +613,8 @@ public NTStatus InvokeBCryptDeriveKey( /// 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. - public NTStatus InvokeBCryptSetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptSetProperty( SafeHandle hObject, string property, [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, @@ -612,7 +632,8 @@ public NTStatus InvokeBCryptSetProperty( /// 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. - public NTStatus InvokeBCryptGetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptGetProperty( SafeHandle hObject, string property, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, @@ -635,7 +656,8 @@ public NTStatus InvokeBCryptGetProperty( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - public NTStatus InvokeBCryptGenRandom( + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeBCryptGenRandom( SafeAlgorithmHandle hAlgorithm, byte[] pbBuffer, int cbBuffer, diff --git a/src/BCrypt/IBCryptMockable.cs b/src/BCrypt/IBCryptMockable.cs index d24dfe2d..0eaddbd0 100644 --- a/src/BCrypt/IBCryptMockable.cs +++ b/src/BCrypt/IBCryptMockable.cs @@ -8,7 +8,8 @@ namespace PInvoke using System.Collections.Generic; using System.Runtime.InteropServices; using static BCrypt; - public interface IBCryptMockable { /// + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IBCryptMockable { /// /// Loads and initializes a CNG provider. /// /// @@ -41,7 +42,8 @@ public interface IBCryptMockable { /// /// /// Returns a status code that indicates the success or failure of the function. /// - NTStatus InvokeBCryptOpenAlgorithmProvider( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptOpenAlgorithmProvider( out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, @@ -75,7 +77,8 @@ NTStatus InvokeBCryptOpenAlgorithmProvider( /// /// Flags that modify the behavior of the function. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptCreateHash( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptCreateHash( SafeAlgorithmHandle hAlgorithm, out SafeHashHandle phHash, byte[] pbHashObject, @@ -123,7 +126,8 @@ NTStatus InvokeBCryptCreateHash( /// /// 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. /// - NTStatus InvokeBCryptEncrypt( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptEncrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -173,7 +177,8 @@ NTStatus InvokeBCryptEncrypt( /// 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. - NTStatus InvokeBCryptDecrypt( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptDecrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -201,7 +206,8 @@ NTStatus InvokeBCryptDecrypt( /// 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. /// - NTStatus InvokeBCryptHashData( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptHashData( SafeHashHandle hHash, byte[] pbInput, int cbInput, @@ -222,7 +228,8 @@ NTStatus InvokeBCryptHashData( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptFinishHash( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptFinishHash( SafeHashHandle hHash, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbOutput, int cbOutput, @@ -259,7 +266,8 @@ NTStatus InvokeBCryptFinishHash( /// /// To later verify that the signature is valid, call the function with an identical key and an identical hash of the original data. /// - NTStatus InvokeBCryptSignHash( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptSignHash( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbInput, @@ -299,7 +307,8 @@ NTStatus InvokeBCryptSignHash( /// Returns a status code that indicates the success or failure of the function. /// In particular, an invalid signature will produce a result. /// - NTStatus InvokeBCryptVerifySignature( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptVerifySignature( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbHash, @@ -321,7 +330,8 @@ NTStatus InvokeBCryptVerifySignature( /// function to set its properties; however, the key cannot be used until the /// BCryptFinalizeKeyPair function is called. /// - NTStatus InvokeBCryptGenerateKeyPair( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptGenerateKeyPair( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, int dwLength, @@ -354,7 +364,8 @@ NTStatus InvokeBCryptGenerateKeyPair( /// /// 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. - NTStatus InvokeBCryptGenerateSymmetricKey( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptGenerateSymmetricKey( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, byte[] pbKeyObject, @@ -374,7 +385,8 @@ NTStatus InvokeBCryptGenerateSymmetricKey( /// After this function has been called, the BCryptSetProperty function /// can no longer be used for this key. /// - NTStatus InvokeBCryptFinalizeKeyPair( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptFinalizeKeyPair( SafeKeyHandle hKey, BCryptFinalizeKeyPairFlags dwFlags = BCryptFinalizeKeyPairFlags.None); @@ -383,7 +395,8 @@ NTStatus InvokeBCryptFinalizeKeyPair( /// /// The handle of the key to destroy. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptDestroyKey( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptDestroyKey( IntPtr hKey); /// @@ -391,7 +404,8 @@ NTStatus InvokeBCryptDestroyKey( /// /// The handle of the secret to destroy. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptDestroySecret( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptDestroySecret( IntPtr hSecret); /// @@ -430,7 +444,8 @@ NTStatus InvokeBCryptDestroySecret( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptImportKey( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptImportKey( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -452,7 +467,8 @@ NTStatus InvokeBCryptImportKey( /// 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. - NTStatus InvokeBCryptImportKeyPair( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptImportKeyPair( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -488,7 +504,8 @@ NTStatus InvokeBCryptImportKeyPair( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptExportKey( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptExportKey( SafeKeyHandle hKey, SafeKeyHandle hExportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -515,7 +532,8 @@ NTStatus InvokeBCryptExportKey( /// /// 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. - NTStatus InvokeBCryptSecretAgreement( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptSecretAgreement( SafeKeyHandle privateKey, SafeKeyHandle publicKey, out SafeSecretHandle secret, @@ -556,7 +574,8 @@ NTStatus InvokeBCryptSecretAgreement( /// /// Returns a status code that indicates the success or failure of the function. /// - NTStatus InvokeBCryptDeriveKey( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptDeriveKey( SafeSecretHandle sharedSecret, string keyDerivationFunction, [In] ref BCryptBufferDesc kdfParameters, @@ -576,7 +595,8 @@ NTStatus InvokeBCryptDeriveKey( /// 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. - NTStatus InvokeBCryptSetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptSetProperty( SafeHandle hObject, string property, [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, @@ -593,7 +613,8 @@ NTStatus InvokeBCryptSetProperty( /// 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. - NTStatus InvokeBCryptGetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptGetProperty( SafeHandle hObject, string property, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, @@ -615,7 +636,8 @@ NTStatus InvokeBCryptGetProperty( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - NTStatus InvokeBCryptGenRandom( + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeBCryptGenRandom( SafeAlgorithmHandle hAlgorithm, byte[] pbBuffer, int cbBuffer, diff --git a/src/Gdi32.Desktop/Gdi32Mockable.cs b/src/Gdi32.Desktop/Gdi32Mockable.cs index d2899714..886fe5aa 100644 --- a/src/Gdi32.Desktop/Gdi32Mockable.cs +++ b/src/Gdi32.Desktop/Gdi32Mockable.cs @@ -6,7 +6,9 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static Gdi32; - public class Gdi32Mockable : IGdi32Mockable { public bool InvokeDeleteObject(IntPtr hObject) + [System.Runtime.CompilerServices.CompilerGenerated] + public class Gdi32Mockable : IGdi32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeDeleteObject(IntPtr hObject) => DeleteObject(hObject); } } diff --git a/src/Gdi32.Desktop/IGdi32Mockable.cs b/src/Gdi32.Desktop/IGdi32Mockable.cs index b31cdd0b..b6270705 100644 --- a/src/Gdi32.Desktop/IGdi32Mockable.cs +++ b/src/Gdi32.Desktop/IGdi32Mockable.cs @@ -6,6 +6,8 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static Gdi32; - public interface IGdi32Mockable { bool InvokeDeleteObject(IntPtr hObject); + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IGdi32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeDeleteObject(IntPtr hObject); } } diff --git a/src/Hid.Desktop/HidMockable.cs b/src/Hid.Desktop/HidMockable.cs index 13cfaef0..b33c0e3f 100644 --- a/src/Hid.Desktop/HidMockable.cs +++ b/src/Hid.Desktop/HidMockable.cs @@ -8,6 +8,7 @@ namespace PInvoke using System.Text; using static Kernel32; using static Hid; + [System.Runtime.CompilerServices.CompilerGenerated] public class HidMockable : IHidMockable { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// @@ -15,7 +16,8 @@ public class HidMockable : IHidMockable { /// /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public void InvokeHidD_GetHidGuid(out Guid hidGuid) => HidD_GetHidGuid(out hidGuid); /// @@ -27,7 +29,8 @@ public void InvokeHidD_GetHidGuid(out Guid hidGuid) /// attributes of the collection specified by HidDeviceObject. /// /// TRUE if succeeds; otherwise, it returns FALSE. - public bool InvokeHidD_GetAttributes( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes) => HidD_GetAttributes(hidDeviceObject, ref attributes); @@ -50,7 +53,8 @@ public bool InvokeHidD_GetAttributes( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -75,7 +79,8 @@ public bool InvokeHidD_GetManufacturerString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -104,7 +109,8 @@ public bool InvokeHidD_GetProductString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -120,7 +126,8 @@ public bool InvokeHidD_GetSerialNumberString( /// input reports generated by the HidDeviceObject collection. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - public bool InvokeHidD_SetNumInputBuffers( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers) => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); @@ -134,7 +141,8 @@ public bool InvokeHidD_SetNumInputBuffers( /// preparsed data in a structure. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - public bool InvokeHidD_GetPreparsedData( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle) => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); @@ -151,7 +159,8 @@ public bool InvokeHidD_GetPreparsedData( /// on success or if rhe /// specified preparsed data is invalid. /// - public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) => HidP_GetCaps(preparsedData, ref capabilities); } } \ No newline at end of file diff --git a/src/Hid.Desktop/IHidMockable.cs b/src/Hid.Desktop/IHidMockable.cs index dd02db51..972f2186 100644 --- a/src/Hid.Desktop/IHidMockable.cs +++ b/src/Hid.Desktop/IHidMockable.cs @@ -8,14 +8,16 @@ namespace PInvoke using System.Text; using static Kernel32; using static Hid; - public interface IHidMockable { /// + [System.Runtime.CompilerServices.CompilerGenerated] + 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); + [System.Runtime.CompilerServices.CompilerGenerated] + void InvokeHidD_GetHidGuid(out Guid hidGuid); /// /// Returns the attributes of a specified top-level collection. @@ -26,7 +28,8 @@ public interface IHidMockable { /// /// attributes of the collection specified by HidDeviceObject. /// /// TRUE if succeeds; otherwise, it returns FALSE. - bool InvokeHidD_GetAttributes( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes); @@ -48,7 +51,8 @@ bool InvokeHidD_GetAttributes( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -72,7 +76,8 @@ bool InvokeHidD_GetManufacturerString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -100,7 +105,8 @@ bool InvokeHidD_GetProductString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -115,7 +121,8 @@ bool InvokeHidD_GetSerialNumberString( /// input reports generated by the HidDeviceObject collection. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - bool InvokeHidD_SetNumInputBuffers( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers); @@ -128,7 +135,8 @@ bool InvokeHidD_SetNumInputBuffers( /// preparsed data in a structure. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - bool InvokeHidD_GetPreparsedData( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle); @@ -144,6 +152,7 @@ bool InvokeHidD_GetPreparsedData( /// on success or if rhe /// specified preparsed data is invalid. /// - NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); } } \ No newline at end of file diff --git a/src/Hid/HidMockable.cs b/src/Hid/HidMockable.cs index 13cfaef0..b33c0e3f 100644 --- a/src/Hid/HidMockable.cs +++ b/src/Hid/HidMockable.cs @@ -8,6 +8,7 @@ namespace PInvoke using System.Text; using static Kernel32; using static Hid; + [System.Runtime.CompilerServices.CompilerGenerated] public class HidMockable : IHidMockable { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// @@ -15,7 +16,8 @@ public class HidMockable : IHidMockable { /// /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public void InvokeHidD_GetHidGuid(out Guid hidGuid) => HidD_GetHidGuid(out hidGuid); /// @@ -27,7 +29,8 @@ public void InvokeHidD_GetHidGuid(out Guid hidGuid) /// attributes of the collection specified by HidDeviceObject. /// /// TRUE if succeeds; otherwise, it returns FALSE. - public bool InvokeHidD_GetAttributes( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes) => HidD_GetAttributes(hidDeviceObject, ref attributes); @@ -50,7 +53,8 @@ public bool InvokeHidD_GetAttributes( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -75,7 +79,8 @@ public bool InvokeHidD_GetManufacturerString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -104,7 +109,8 @@ public bool InvokeHidD_GetProductString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -120,7 +126,8 @@ public bool InvokeHidD_GetSerialNumberString( /// input reports generated by the HidDeviceObject collection. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - public bool InvokeHidD_SetNumInputBuffers( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers) => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); @@ -134,7 +141,8 @@ public bool InvokeHidD_SetNumInputBuffers( /// preparsed data in a structure. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - public bool InvokeHidD_GetPreparsedData( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeHidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle) => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); @@ -151,7 +159,8 @@ public bool InvokeHidD_GetPreparsedData( /// on success or if rhe /// specified preparsed data is invalid. /// - public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + [System.Runtime.CompilerServices.CompilerGenerated] + public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) => HidP_GetCaps(preparsedData, ref capabilities); } } \ No newline at end of file diff --git a/src/Hid/IHidMockable.cs b/src/Hid/IHidMockable.cs index dd02db51..972f2186 100644 --- a/src/Hid/IHidMockable.cs +++ b/src/Hid/IHidMockable.cs @@ -8,14 +8,16 @@ namespace PInvoke using System.Text; using static Kernel32; using static Hid; - public interface IHidMockable { /// + [System.Runtime.CompilerServices.CompilerGenerated] + 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); + [System.Runtime.CompilerServices.CompilerGenerated] + void InvokeHidD_GetHidGuid(out Guid hidGuid); /// /// Returns the attributes of a specified top-level collection. @@ -26,7 +28,8 @@ public interface IHidMockable { /// /// attributes of the collection specified by HidDeviceObject. /// /// TRUE if succeeds; otherwise, it returns FALSE. - bool InvokeHidD_GetAttributes( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes); @@ -48,7 +51,8 @@ bool InvokeHidD_GetAttributes( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -72,7 +76,8 @@ bool InvokeHidD_GetManufacturerString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -100,7 +105,8 @@ bool InvokeHidD_GetProductString( /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -115,7 +121,8 @@ bool InvokeHidD_GetSerialNumberString( /// input reports generated by the HidDeviceObject collection. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - bool InvokeHidD_SetNumInputBuffers( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers); @@ -128,7 +135,8 @@ bool InvokeHidD_SetNumInputBuffers( /// preparsed data in a structure. /// /// TRUE if it succeeds; otherwise, it returns FALSE. - bool InvokeHidD_GetPreparsedData( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeHidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle); @@ -144,6 +152,7 @@ bool InvokeHidD_GetPreparsedData( /// on success or if rhe /// specified preparsed data is invalid. /// - NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + [System.Runtime.CompilerServices.CompilerGenerated] + NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); } } \ No newline at end of file diff --git a/src/ImageHlp/IImageHlpMockable.cs b/src/ImageHlp/IImageHlpMockable.cs index b70004f2..f7797f61 100644 --- a/src/ImageHlp/IImageHlpMockable.cs +++ b/src/ImageHlp/IImageHlpMockable.cs @@ -7,7 +7,8 @@ namespace PInvoke using System.Runtime.InteropServices; using static DbgHelp; using static ImageHlp; - public interface IImageHlpMockable { /// + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IImageHlpMockable { /// /// Maps an image and preloads data from the mapped file. /// /// The file name of the image (executable file or DLL) that is loaded. @@ -19,7 +20,8 @@ public interface IImageHlpMockable { /// /// If the function succeeds, the return value is TRUE. /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// - bool InvokeMapAndLoad( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeMapAndLoad( string ImageName, string DllPath, out LOADED_IMAGE LoadedImage, @@ -36,7 +38,8 @@ bool InvokeMapAndLoad( /// If the function succeeds, the return value is TRUE. /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// - bool InvokeUnMapAndLoad( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeUnMapAndLoad( ref LOADED_IMAGE LoadedImage); } } diff --git a/src/ImageHlp/ImageHlpMockable.cs b/src/ImageHlp/ImageHlpMockable.cs index 850bfbfe..452c68a3 100644 --- a/src/ImageHlp/ImageHlpMockable.cs +++ b/src/ImageHlp/ImageHlpMockable.cs @@ -7,6 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static DbgHelp; using static ImageHlp; + [System.Runtime.CompilerServices.CompilerGenerated] public class ImageHlpMockable : IImageHlpMockable { /// /// Maps an image and preloads data from the mapped file. /// @@ -19,7 +20,8 @@ public class ImageHlpMockable : IImageHlpMockable { /// /// If the function succeeds, the return value is TRUE. /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// - public bool InvokeMapAndLoad( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeMapAndLoad( string ImageName, string DllPath, out LOADED_IMAGE LoadedImage, @@ -37,7 +39,8 @@ public bool InvokeMapAndLoad( /// If the function succeeds, the return value is TRUE. /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// - public bool InvokeUnMapAndLoad( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeUnMapAndLoad( ref LOADED_IMAGE LoadedImage) => UnMapAndLoad(ref LoadedImage); } diff --git a/src/Kernel32.Desktop/IKernel32Mockable.cs b/src/Kernel32.Desktop/IKernel32Mockable.cs index a0d1608e..2231e014 100644 --- a/src/Kernel32.Desktop/IKernel32Mockable.cs +++ b/src/Kernel32.Desktop/IKernel32Mockable.cs @@ -8,7 +8,8 @@ namespace PInvoke using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; - public interface IKernel32Mockable { + [System.Runtime.CompilerServices.CompilerGenerated] + 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. @@ -41,7 +42,8 @@ public interface IKernel32Mockable { /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + 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. @@ -87,18 +89,21 @@ public interface IKernel32Mockable { /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + 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(); + [System.Runtime.CompilerServices.CompilerGenerated] + 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(); + [System.Runtime.CompilerServices.CompilerGenerated] + uint InvokeGetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. /// The return value is a pseudo handle to the current process. @@ -123,7 +128,8 @@ public interface IKernel32Mockable { /// duplicate handle must be closed. /// /// - SafeObjectHandle InvokeGetCurrentProcess(); + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle InvokeGetCurrentProcess(); /// /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations @@ -156,7 +162,8 @@ public interface IKernel32Mockable { /// returns . /// /// - unsafe bool InvokeCancelIoEx( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeCancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped); @@ -220,7 +227,8 @@ unsafe bool InvokeCancelIoEx( /// it designates the read operation is pending completion asynchronously. /// /// - unsafe bool InvokeReadFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -295,7 +303,8 @@ unsafe bool InvokeReadFile( /// it designates the write operation is pending completion asynchronously. /// /// - unsafe bool InvokeWriteFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeWriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -313,7 +322,8 @@ unsafe bool InvokeWriteFile( /// /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeSuspendThread(SafeObjectHandle hThread); /// /// Suspends the specified WOW64 thread. @@ -325,7 +335,8 @@ unsafe bool InvokeWriteFile( /// /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + 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. @@ -338,7 +349,8 @@ unsafe bool InvokeWriteFile( /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeResumeThread(SafeObjectHandle hThread); /// /// Waits until the specified object is in the signaled state or the time-out interval elapses. @@ -356,7 +368,8 @@ unsafe bool InvokeWriteFile( /// /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + WaitForSingleObjectResult InvokeWaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds); @@ -368,7 +381,8 @@ WaitForSingleObjectResult InvokeWaitForSingleObject( /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeCloseHandle(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. @@ -430,7 +444,8 @@ WaitForSingleObjectResult InvokeWaitForSingleObject( /// 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 InvokeCreateProcess( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeCreateProcess( string lpApplicationName, string lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, @@ -509,7 +524,8 @@ bool InvokeCreateProcess( /// 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 InvokeCreateProcessAsUser( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeCreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, @@ -531,7 +547,8 @@ bool InvokeCreateProcessAsUser( /// /// This function does not return a value, and does not fail. /// - void InvokeGetStartupInfo( + [System.Runtime.CompilerServices.CompilerGenerated] + void InvokeGetStartupInfo( out STARTUPINFO lpStartupInfo); /// @@ -558,7 +575,8 @@ void InvokeGetStartupInfo( /// 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. /// - bool InvokeInitializeProcThreadAttributeList( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeInitializeProcThreadAttributeList( IntPtr lpAttributeList, uint dwAttributeCount, uint dwFlags, @@ -590,7 +608,8 @@ bool InvokeInitializeProcThreadAttributeList( /// 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 InvokeUpdateProcThreadAttribute( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeUpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, ref uint Attribute, @@ -605,7 +624,8 @@ bool InvokeUpdateProcThreadAttribute( /// /// The attribute list. This list is created by the function. /// - void InvokeDeleteProcThreadAttributeList( + [System.Runtime.CompilerServices.CompilerGenerated] + void InvokeDeleteProcThreadAttributeList( IntPtr lpAttributeList); /// @@ -615,7 +635,8 @@ void InvokeDeleteProcThreadAttributeList( /// 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 InvokeAllocConsole(); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeAllocConsole(); /// /// Detaches the calling process from its console. @@ -624,7 +645,8 @@ void InvokeDeleteProcThreadAttributeList( /// 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 InvokeFreeConsole(); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeFreeConsole(); /// /// Attaches the calling process to the console of the specified process. @@ -638,7 +660,8 @@ void InvokeDeleteProcThreadAttributeList( /// 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 InvokeAttachConsole(uint dwProcessId); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeAttachConsole(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. @@ -694,7 +717,8 @@ void InvokeDeleteProcThreadAttributeList( /// 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 . /// - SafeObjectHandle InvokeCreateFile( + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle InvokeCreateFile( string filename, FileAccess access, FileShare share, @@ -720,7 +744,8 @@ SafeObjectHandle InvokeCreateFile( /// 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. /// - SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); + [System.Runtime.CompilerServices.CompilerGenerated] + SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); /// /// Continues a file search from a previous call to the , FindFirstFileEx, or FindFirstFileTransacted functions. @@ -732,7 +757,8 @@ SafeObjectHandle InvokeCreateFile( /// 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. /// - bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeFindNextFile(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 @@ -798,7 +824,8 @@ SafeObjectHandle InvokeCreateFile( /// function to retrieve the full name of an executable image for both 32- and 64-bit processes from a 32-bit process. /// /// - SafeObjectHandle InvokeCreateToolhelp32Snapshot( + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle InvokeCreateToolhelp32Snapshot( CreateToolhelp32SnapshotFlags dwFlags, uint th32ProcessID); @@ -817,7 +844,8 @@ SafeObjectHandle InvokeCreateToolhelp32Snapshot( /// the function if no processes exist or the snapshot does not contain process /// information. /// - bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); /// Retrieves information about the next process recorded in a system snapshot. /// @@ -836,7 +864,8 @@ SafeObjectHandle InvokeCreateToolhelp32Snapshot( /// /// function. /// - bool InvokeProcess32Next( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeProcess32Next( SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); @@ -857,7 +886,8 @@ bool InvokeProcess32Next( /// If the function fails, the return value is zero.To get extended error information, call . /// /// Minimum OS: Windows Vista / Windows Server 2008. - bool InvokeQueryFullProcessImageName( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeQueryFullProcessImageName( SafeObjectHandle hProcess, QueryFullProcessImageNameFlags dwFlags, StringBuilder lpExeName, @@ -890,7 +920,8 @@ bool InvokeQueryFullProcessImageName( /// /// /// If the function succeeds, the return value is an open handle to the specified process. - SafeObjectHandle InvokeOpenProcess( + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle InvokeOpenProcess( ProcessAccess dwDesiredAccess, bool bInheritHandle, uint dwProcessId); @@ -947,7 +978,8 @@ SafeObjectHandle InvokeOpenProcess( /// situation, there is no way to know which operation caused the object's state to be signaled. /// /// - unsafe bool InvokeGetOverlappedResult( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeGetOverlappedResult( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped, out uint lpNumberOfBytesTransferred, @@ -987,7 +1019,8 @@ unsafe bool InvokeGetOverlappedResult( /// normally. /// /// - bool InvokeCancelIo(SafeObjectHandle hFile); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeCancelIo(SafeObjectHandle hFile); /// /// Determines whether the specified process is running under WOW64 (x86 emulator that allows 32-bit Windows-based @@ -1013,7 +1046,8 @@ unsafe bool InvokeGetOverlappedResult( /// . /// /// - bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process); /// /// Creates an anonymous pipe, and returns handles to the read and write ends of the pipe. @@ -1035,7 +1069,8 @@ unsafe bool InvokeGetOverlappedResult( /// 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 InvokeCreatePipe( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeCreatePipe( out SafeObjectHandle hReadPipe, out SafeObjectHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, diff --git a/src/Kernel32.Desktop/Kernel32Mockable.cs b/src/Kernel32.Desktop/Kernel32Mockable.cs index c3135e63..142f248f 100644 --- a/src/Kernel32.Desktop/Kernel32Mockable.cs +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -8,6 +8,7 @@ namespace PInvoke using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; + [System.Runtime.CompilerServices.CompilerGenerated] public class Kernel32Mockable : IKernel32Mockable { /// /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. @@ -41,7 +42,8 @@ public class Kernel32Mockable : IKernel32Mockable { /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + 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, out lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags); /// @@ -88,20 +90,23 @@ public SafeFindFilesHandle InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_ /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + 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() + [System.Runtime.CompilerServices.CompilerGenerated] + 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() + [System.Runtime.CompilerServices.CompilerGenerated] + public uint InvokeGetCurrentProcessId() => GetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. @@ -127,7 +132,8 @@ public uint InvokeGetCurrentProcessId() /// duplicate handle must be closed. /// /// - public SafeObjectHandle InvokeGetCurrentProcess() + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle InvokeGetCurrentProcess() => GetCurrentProcess(); /// @@ -161,7 +167,8 @@ public SafeObjectHandle InvokeGetCurrentProcess() /// returns . /// /// - unsafe public bool InvokeCancelIoEx( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeCancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped) => CancelIoEx(hFile, lpOverlapped); @@ -226,7 +233,8 @@ unsafe public bool InvokeCancelIoEx( /// it designates the read operation is pending completion asynchronously. /// /// - unsafe public bool InvokeReadFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -302,7 +310,8 @@ unsafe public bool InvokeReadFile( /// it designates the write operation is pending completion asynchronously. /// /// - unsafe public bool InvokeWriteFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeWriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -321,7 +330,8 @@ unsafe public bool InvokeWriteFile( /// /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeSuspendThread(SafeObjectHandle hThread) => SuspendThread(hThread); /// @@ -334,7 +344,8 @@ public int InvokeSuspendThread(SafeObjectHandle hThread) /// /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeWow64SuspendThread(SafeObjectHandle hThread) => Wow64SuspendThread(hThread); /// @@ -348,7 +359,8 @@ public int InvokeWow64SuspendThread(SafeObjectHandle hThread) /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeResumeThread(SafeObjectHandle hThread) => ResumeThread(hThread); /// @@ -367,7 +379,8 @@ public int InvokeResumeThread(SafeObjectHandle hThread) /// /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public WaitForSingleObjectResult InvokeWaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds) => WaitForSingleObject(hHandle, dwMilliseconds); @@ -380,7 +393,8 @@ public WaitForSingleObjectResult InvokeWaitForSingleObject( /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeCloseHandle(IntPtr hObject) => CloseHandle(hObject); /// /// Creates a new process and its primary thread. The new process runs in the security context of the calling process. @@ -443,7 +457,8 @@ public bool InvokeCloseHandle(IntPtr hObject) /// 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 InvokeCreateProcess( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeCreateProcess( string lpApplicationName, string lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, @@ -523,7 +538,8 @@ public bool InvokeCreateProcess( /// 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 InvokeCreateProcessAsUser( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeCreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, @@ -546,7 +562,8 @@ public bool InvokeCreateProcessAsUser( /// /// This function does not return a value, and does not fail. /// - public void InvokeGetStartupInfo( + [System.Runtime.CompilerServices.CompilerGenerated] + public void InvokeGetStartupInfo( out STARTUPINFO lpStartupInfo) => GetStartupInfo(out lpStartupInfo); @@ -574,7 +591,8 @@ public void InvokeGetStartupInfo( /// 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. /// - public bool InvokeInitializeProcThreadAttributeList( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeInitializeProcThreadAttributeList( IntPtr lpAttributeList, uint dwAttributeCount, uint dwFlags, @@ -607,7 +625,8 @@ public bool InvokeInitializeProcThreadAttributeList( /// 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 InvokeUpdateProcThreadAttribute( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeUpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, ref uint Attribute, @@ -623,7 +642,8 @@ public bool InvokeUpdateProcThreadAttribute( /// /// The attribute list. This list is created by the function. /// - public void InvokeDeleteProcThreadAttributeList( + [System.Runtime.CompilerServices.CompilerGenerated] + public void InvokeDeleteProcThreadAttributeList( IntPtr lpAttributeList) => DeleteProcThreadAttributeList(lpAttributeList); @@ -634,7 +654,8 @@ public void InvokeDeleteProcThreadAttributeList( /// 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 InvokeAllocConsole() + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeAllocConsole() => AllocConsole(); /// @@ -644,7 +665,8 @@ public bool InvokeAllocConsole() /// 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 InvokeFreeConsole() + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeFreeConsole() => FreeConsole(); /// @@ -659,7 +681,8 @@ public bool InvokeFreeConsole() /// 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 InvokeAttachConsole(uint dwProcessId) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeAttachConsole(uint dwProcessId) => AttachConsole(dwProcessId); /// @@ -716,7 +739,8 @@ public bool InvokeAttachConsole(uint dwProcessId) /// 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 . /// - public SafeObjectHandle InvokeCreateFile( + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle InvokeCreateFile( string filename, FileAccess access, FileShare share, @@ -743,7 +767,8 @@ public SafeObjectHandle InvokeCreateFile( /// 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. /// - public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) => FindFirstFile(lpFileName, out lpFindFileData); /// @@ -756,7 +781,8 @@ public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND /// 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. /// - public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) => FindNextFile(hFindFile, out lpFindFileData); /// @@ -823,7 +849,8 @@ public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DAT /// function to retrieve the full name of an executable image for both 32- and 64-bit processes from a 32-bit process. /// /// - public SafeObjectHandle InvokeCreateToolhelp32Snapshot( + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle InvokeCreateToolhelp32Snapshot( CreateToolhelp32SnapshotFlags dwFlags, uint th32ProcessID) => CreateToolhelp32Snapshot(dwFlags, th32ProcessID); @@ -843,7 +870,8 @@ public SafeObjectHandle InvokeCreateToolhelp32Snapshot( /// the function if no processes exist or the snapshot does not contain process /// information. /// - public bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) => Process32First(hSnapshot, lppe); /// Retrieves information about the next process recorded in a system snapshot. @@ -863,7 +891,8 @@ public bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSEN /// /// function. /// - public bool InvokeProcess32Next( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeProcess32Next( SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) => Process32Next(hSnapshot, lppe); @@ -885,7 +914,8 @@ public bool InvokeProcess32Next( /// If the function fails, the return value is zero.To get extended error information, call . /// /// Minimum OS: Windows Vista / Windows Server 2008. - public bool InvokeQueryFullProcessImageName( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeQueryFullProcessImageName( SafeObjectHandle hProcess, QueryFullProcessImageNameFlags dwFlags, StringBuilder lpExeName, @@ -919,7 +949,8 @@ public bool InvokeQueryFullProcessImageName( /// /// /// If the function succeeds, the return value is an open handle to the specified process. - public SafeObjectHandle InvokeOpenProcess( + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle InvokeOpenProcess( ProcessAccess dwDesiredAccess, bool bInheritHandle, uint dwProcessId) @@ -977,7 +1008,8 @@ public SafeObjectHandle InvokeOpenProcess( /// situation, there is no way to know which operation caused the object's state to be signaled. /// /// - unsafe public bool InvokeGetOverlappedResult( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeGetOverlappedResult( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped, out uint lpNumberOfBytesTransferred, @@ -1018,7 +1050,8 @@ unsafe public bool InvokeGetOverlappedResult( /// normally. /// /// - public bool InvokeCancelIo(SafeObjectHandle hFile) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeCancelIo(SafeObjectHandle hFile) => CancelIo(hFile); /// @@ -1045,7 +1078,8 @@ public bool InvokeCancelIo(SafeObjectHandle hFile) /// . /// /// - public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) => IsWow64Process(hProcess, out Wow64Process); /// @@ -1068,7 +1102,8 @@ public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Proces /// 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 InvokeCreatePipe( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeCreatePipe( out SafeObjectHandle hReadPipe, out SafeObjectHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, diff --git a/src/Kernel32/IKernel32Mockable.cs b/src/Kernel32/IKernel32Mockable.cs index 28f14439..833321dc 100644 --- a/src/Kernel32/IKernel32Mockable.cs +++ b/src/Kernel32/IKernel32Mockable.cs @@ -8,7 +8,8 @@ namespace PInvoke using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; - public interface IKernel32Mockable { + [System.Runtime.CompilerServices.CompilerGenerated] + 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. @@ -41,7 +42,8 @@ public interface IKernel32Mockable { /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + 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. @@ -87,18 +89,21 @@ public interface IKernel32Mockable { /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + 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(); + [System.Runtime.CompilerServices.CompilerGenerated] + 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(); + [System.Runtime.CompilerServices.CompilerGenerated] + uint InvokeGetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. /// The return value is a pseudo handle to the current process. @@ -123,7 +128,8 @@ public interface IKernel32Mockable { /// duplicate handle must be closed. /// /// - SafeObjectHandle InvokeGetCurrentProcess(); + [System.Runtime.CompilerServices.CompilerGenerated] + SafeObjectHandle InvokeGetCurrentProcess(); /// /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations @@ -156,7 +162,8 @@ public interface IKernel32Mockable { /// returns . /// /// - unsafe bool InvokeCancelIoEx( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeCancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped); @@ -220,7 +227,8 @@ unsafe bool InvokeCancelIoEx( /// it designates the read operation is pending completion asynchronously. /// /// - unsafe bool InvokeReadFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -295,7 +303,8 @@ unsafe bool InvokeReadFile( /// it designates the write operation is pending completion asynchronously. /// /// - unsafe bool InvokeWriteFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe bool InvokeWriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -313,7 +322,8 @@ unsafe bool InvokeWriteFile( /// /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeSuspendThread(SafeObjectHandle hThread); /// /// Suspends the specified WOW64 thread. @@ -325,7 +335,8 @@ unsafe bool InvokeWriteFile( /// /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + 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. @@ -338,7 +349,8 @@ unsafe bool InvokeWriteFile( /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeResumeThread(SafeObjectHandle hThread); /// /// Waits until the specified object is in the signaled state or the time-out interval elapses. @@ -356,7 +368,8 @@ unsafe bool InvokeWriteFile( /// /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + WaitForSingleObjectResult InvokeWaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds); @@ -368,6 +381,7 @@ WaitForSingleObjectResult InvokeWaitForSingleObject( /// 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); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeCloseHandle(IntPtr hObject); } } diff --git a/src/Kernel32/Kernel32Mockable.cs b/src/Kernel32/Kernel32Mockable.cs index 0eaeb2e2..19dfdb09 100644 --- a/src/Kernel32/Kernel32Mockable.cs +++ b/src/Kernel32/Kernel32Mockable.cs @@ -8,6 +8,7 @@ namespace PInvoke using System.Text; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; + [System.Runtime.CompilerServices.CompilerGenerated] public class Kernel32Mockable : IKernel32Mockable { /// /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. @@ -41,7 +42,8 @@ public class Kernel32Mockable : IKernel32Mockable { /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + 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, out lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags); /// @@ -88,20 +90,23 @@ public SafeFindFilesHandle InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_ /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + 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() + [System.Runtime.CompilerServices.CompilerGenerated] + 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() + [System.Runtime.CompilerServices.CompilerGenerated] + public uint InvokeGetCurrentProcessId() => GetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. @@ -127,7 +132,8 @@ public uint InvokeGetCurrentProcessId() /// duplicate handle must be closed. /// /// - public SafeObjectHandle InvokeGetCurrentProcess() + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeObjectHandle InvokeGetCurrentProcess() => GetCurrentProcess(); /// @@ -161,7 +167,8 @@ public SafeObjectHandle InvokeGetCurrentProcess() /// returns . /// /// - unsafe public bool InvokeCancelIoEx( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeCancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped) => CancelIoEx(hFile, lpOverlapped); @@ -226,7 +233,8 @@ unsafe public bool InvokeCancelIoEx( /// it designates the read operation is pending completion asynchronously. /// /// - unsafe public bool InvokeReadFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -302,7 +310,8 @@ unsafe public bool InvokeReadFile( /// it designates the write operation is pending completion asynchronously. /// /// - unsafe public bool InvokeWriteFile( + [System.Runtime.CompilerServices.CompilerGenerated] + unsafe public bool InvokeWriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -321,7 +330,8 @@ unsafe public bool InvokeWriteFile( /// /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeSuspendThread(SafeObjectHandle hThread) => SuspendThread(hThread); /// @@ -334,7 +344,8 @@ public int InvokeSuspendThread(SafeObjectHandle hThread) /// /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeWow64SuspendThread(SafeObjectHandle hThread) => Wow64SuspendThread(hThread); /// @@ -348,7 +359,8 @@ public int InvokeWow64SuspendThread(SafeObjectHandle hThread) /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeResumeThread(SafeObjectHandle hThread) => ResumeThread(hThread); /// @@ -367,7 +379,8 @@ public int InvokeResumeThread(SafeObjectHandle hThread) /// /// 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( + [System.Runtime.CompilerServices.CompilerGenerated] + public WaitForSingleObjectResult InvokeWaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds) => WaitForSingleObject(hHandle, dwMilliseconds); @@ -380,7 +393,8 @@ public WaitForSingleObjectResult InvokeWaitForSingleObject( /// 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) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeCloseHandle(IntPtr hObject) => CloseHandle(hObject); } } diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 67fea110..7d91d840 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -204,7 +204,13 @@ private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterface { InterfaceCache.Add(newInterfaceModifier.Identifier.Text, SyntaxFactory.InterfaceDeclaration( - SyntaxFactory.List(), + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter, + TabCharacter) + }), SyntaxFactory.TokenList( SyntaxFactory .Token(SyntaxKind.PublicKeyword) @@ -231,7 +237,12 @@ private static void PrepareClassCacheEntry(IdentifierNameSyntax newClassModifier var baseList = classDeclaration.BaseList ?? SyntaxFactory.BaseList(); ClassCache.Add(newClassModifier.Identifier.Text, SyntaxFactory.ClassDeclaration( - SyntaxFactory.List(), + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + }), SyntaxFactory.TokenList( SyntaxFactory .Token(SyntaxKind.PublicKeyword) @@ -309,7 +320,12 @@ private static InterfaceDeclarationSyntax DecorateInterfaceWithWrapperFunction( var dllImport = methodDeclaration.AttributeLists .First(x => x.OpenBracketToken.HasLeadingTrivia); var interfaceMethodDeclaration = SyntaxFactory.MethodDeclaration( - SyntaxFactory.List(), + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter) + }), GetModifiersForWrapperFunction(methodDeclaration), methodDeclaration.ReturnType, default(ExplicitInterfaceSpecifierSyntax), @@ -387,7 +403,13 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec SyntaxFactory.SeparatedList(arguments)))); var wrapperMethodDeclaration = SyntaxFactory.MethodDeclaration( - SyntaxFactory.List(), + SyntaxFactory.List(new[] { + GetCompilerGeneratedAttribute() + .WithTrailingTrivia( + NewLineCharacter, + TabCharacter, + TabCharacter) + }), GetModifiersForWrapperFunction(methodDeclaration) .Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword) .WithTrailingTrivia(WhitespaceCharacter)), @@ -410,5 +432,13 @@ private static ClassDeclarationSyntax DecorateClassWithWrapperFunction(MethodDec .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/NCrypt/INCryptMockable.cs b/src/NCrypt/INCryptMockable.cs index 125e96cc..c4eeaa1d 100644 --- a/src/NCrypt/INCryptMockable.cs +++ b/src/NCrypt/INCryptMockable.cs @@ -6,7 +6,8 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static NCrypt; - public interface INCryptMockable { /// + [System.Runtime.CompilerServices.CompilerGenerated] + public interface INCryptMockable { /// /// Loads and initializes a CNG key storage provider. /// /// @@ -17,7 +18,8 @@ public interface INCryptMockable { /// /// /// Flags that modify the behavior of the function. /// Returns a status code that indicates the success or failure of the function. - SECURITY_STATUS InvokeNCryptOpenStorageProvider( + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS InvokeNCryptOpenStorageProvider( out SafeProviderHandle phProvider, string pszProviderName, NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None); @@ -42,7 +44,8 @@ SECURITY_STATUS InvokeNCryptOpenStorageProvider( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - SECURITY_STATUS InvokeNCryptCreatePersistedKey( + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS InvokeNCryptCreatePersistedKey( SafeProviderHandle hProvider, out SafeKeyHandle phKey, string pszAlgId, @@ -60,7 +63,8 @@ SECURITY_STATUS InvokeNCryptCreatePersistedKey( /// Flags that modify function behavior. /// /// Returns a status code that indicates the success or failure of the function. - SECURITY_STATUS InvokeNCryptFinalizeKey( + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS InvokeNCryptFinalizeKey( SafeKeyHandle hKey, NCryptFinalizeKeyFlags dwFlags = NCryptFinalizeKeyFlags.None); @@ -86,7 +90,8 @@ SECURITY_STATUS InvokeNCryptFinalizeKey( /// /// Flags that modify function behavior. /// Returns a status code that indicates the success or failure of the function. - SECURITY_STATUS InvokeNCryptGetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS InvokeNCryptGetProperty( SafeHandle hObject, string pszProperty, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, @@ -109,7 +114,8 @@ SECURITY_STATUS InvokeNCryptGetProperty( /// /// Flags that modify function behavior. /// Returns a status code that indicates the success or failure of the function. - SECURITY_STATUS InvokeNCryptSetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + SECURITY_STATUS InvokeNCryptSetProperty( SafeHandle hObject, string pszProperty, byte[] pbInput, diff --git a/src/NCrypt/NCryptMockable.cs b/src/NCrypt/NCryptMockable.cs index e32ce68f..af5fa6dd 100644 --- a/src/NCrypt/NCryptMockable.cs +++ b/src/NCrypt/NCryptMockable.cs @@ -6,6 +6,7 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static NCrypt; + [System.Runtime.CompilerServices.CompilerGenerated] public class NCryptMockable : INCryptMockable { /// /// Loads and initializes a CNG key storage provider. /// @@ -17,7 +18,8 @@ public class NCryptMockable : INCryptMockable { /// /// /// Flags that modify the behavior of the function. /// Returns a status code that indicates the success or failure of the function. - public SECURITY_STATUS InvokeNCryptOpenStorageProvider( + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS InvokeNCryptOpenStorageProvider( out SafeProviderHandle phProvider, string pszProviderName, NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None) @@ -43,7 +45,8 @@ public SECURITY_STATUS InvokeNCryptOpenStorageProvider( /// /// A set of flags that modify the behavior of this function. /// Returns a status code that indicates the success or failure of the function. - public SECURITY_STATUS InvokeNCryptCreatePersistedKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS InvokeNCryptCreatePersistedKey( SafeProviderHandle hProvider, out SafeKeyHandle phKey, string pszAlgId, @@ -62,7 +65,8 @@ public SECURITY_STATUS InvokeNCryptCreatePersistedKey( /// Flags that modify function behavior. /// /// Returns a status code that indicates the success or failure of the function. - public SECURITY_STATUS InvokeNCryptFinalizeKey( + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS InvokeNCryptFinalizeKey( SafeKeyHandle hKey, NCryptFinalizeKeyFlags dwFlags = NCryptFinalizeKeyFlags.None) => NCryptFinalizeKey(hKey, dwFlags ); @@ -89,7 +93,8 @@ public SECURITY_STATUS InvokeNCryptFinalizeKey( /// /// Flags that modify function behavior. /// Returns a status code that indicates the success or failure of the function. - public SECURITY_STATUS InvokeNCryptGetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS InvokeNCryptGetProperty( SafeHandle hObject, string pszProperty, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, @@ -113,7 +118,8 @@ public SECURITY_STATUS InvokeNCryptGetProperty( /// /// Flags that modify function behavior. /// Returns a status code that indicates the success or failure of the function. - public SECURITY_STATUS InvokeNCryptSetProperty( + [System.Runtime.CompilerServices.CompilerGenerated] + public SECURITY_STATUS InvokeNCryptSetProperty( SafeHandle hObject, string pszProperty, byte[] pbInput, diff --git a/src/SetupApi.Desktop/ISetupApiMockable.cs b/src/SetupApi.Desktop/ISetupApiMockable.cs index 47677921..b521fd3b 100644 --- a/src/SetupApi.Desktop/ISetupApiMockable.cs +++ b/src/SetupApi.Desktop/ISetupApiMockable.cs @@ -6,7 +6,8 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static SetupApi; - public interface ISetupApiMockable { /// + [System.Runtime.CompilerServices.CompilerGenerated] + public interface ISetupApiMockable { /// /// The SetupDiGetClassDevs function returns a handle to a device information set /// that contains requested device information elements for a local computer. /// @@ -47,7 +48,8 @@ public interface ISetupApiMockable { /// /// 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. /// - SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( + [System.Runtime.CompilerServices.CompilerGenerated] + SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( NullableGuid classGuid, string enumerator, IntPtr hwndParent, @@ -90,7 +92,8 @@ SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( /// error, is returned and the error code for the failure can be retrieved by calling /// . /// - bool InvokeSetupDiEnumDeviceInterfaces( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeSetupDiEnumDeviceInterfaces( SafeDeviceInfoSetHandle deviceInfoSet, DeviceInfoData deviceInfoData, ref Guid interfaceClassGuid, @@ -137,7 +140,8 @@ bool InvokeSetupDiEnumDeviceInterfaces( /// error, is returned and the error code for the failure can be retrieved by calling /// . /// - bool InvokeSetupDiGetDeviceInterfaceDetail( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeSetupDiGetDeviceInterfaceDetail( SafeDeviceInfoSetHandle deviceInfoSet, ref DeviceInterfaceData deviceInterfaceData, IntPtr deviceInterfaceDetailData, @@ -163,7 +167,8 @@ bool InvokeSetupDiGetDeviceInterfaceDetail( /// error, is returned and the error code for the failure can be retrieved by calling /// . /// - bool InvokeSetupDiEnumDeviceInfo( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeSetupDiEnumDeviceInfo( SafeDeviceInfoSetHandle deviceInfoSet, uint memberIndex, DeviceInfoData deviceInfoData); diff --git a/src/SetupApi.Desktop/SetupApiMockable.cs b/src/SetupApi.Desktop/SetupApiMockable.cs index 2440cf31..fc5516c2 100644 --- a/src/SetupApi.Desktop/SetupApiMockable.cs +++ b/src/SetupApi.Desktop/SetupApiMockable.cs @@ -6,6 +6,7 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static SetupApi; + [System.Runtime.CompilerServices.CompilerGenerated] public class SetupApiMockable : ISetupApiMockable { /// /// The SetupDiGetClassDevs function returns a handle to a device information set /// that contains requested device information elements for a local computer. @@ -47,7 +48,8 @@ public class SetupApiMockable : ISetupApiMockable { /// /// 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. /// - public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( + [System.Runtime.CompilerServices.CompilerGenerated] + public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( NullableGuid classGuid, string enumerator, IntPtr hwndParent, @@ -91,7 +93,8 @@ public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( /// error, is returned and the error code for the failure can be retrieved by calling /// . /// - public bool InvokeSetupDiEnumDeviceInterfaces( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeSetupDiEnumDeviceInterfaces( SafeDeviceInfoSetHandle deviceInfoSet, DeviceInfoData deviceInfoData, ref Guid interfaceClassGuid, @@ -139,7 +142,8 @@ public bool InvokeSetupDiEnumDeviceInterfaces( /// error, is returned and the error code for the failure can be retrieved by calling /// . /// - public bool InvokeSetupDiGetDeviceInterfaceDetail( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeSetupDiGetDeviceInterfaceDetail( SafeDeviceInfoSetHandle deviceInfoSet, ref DeviceInterfaceData deviceInterfaceData, IntPtr deviceInterfaceDetailData, @@ -166,7 +170,8 @@ public bool InvokeSetupDiGetDeviceInterfaceDetail( /// error, is returned and the error code for the failure can be retrieved by calling /// . /// - public bool InvokeSetupDiEnumDeviceInfo( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeSetupDiEnumDeviceInfo( SafeDeviceInfoSetHandle deviceInfoSet, uint memberIndex, DeviceInfoData deviceInfoData) diff --git a/src/User32.Desktop/IUser32Mockable.cs b/src/User32.Desktop/IUser32Mockable.cs index a3fc2d8f..d8814923 100644 --- a/src/User32.Desktop/IUser32Mockable.cs +++ b/src/User32.Desktop/IUser32Mockable.cs @@ -6,11 +6,15 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static User32; - public interface IUser32Mockable { int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); + [System.Runtime.CompilerServices.CompilerGenerated] + public interface IUser32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); - int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); + [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); - bool InvokeSetWindowPos( + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeSetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, @@ -19,18 +23,23 @@ bool InvokeSetWindowPos( int cy, SetWindowPosFlags uFlags); - IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent); + [System.Runtime.CompilerServices.CompilerGenerated] + IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent); - IntPtr InvokeFindWindowEx( + [System.Runtime.CompilerServices.CompilerGenerated] + IntPtr InvokeFindWindowEx( IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); - bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); + [System.Runtime.CompilerServices.CompilerGenerated] + bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); - IntPtr InvokeGetForegroundWindow(); + [System.Runtime.CompilerServices.CompilerGenerated] + IntPtr InvokeGetForegroundWindow(); - int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); + [System.Runtime.CompilerServices.CompilerGenerated] + int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); } } diff --git a/src/User32.Desktop/User32Mockable.cs b/src/User32.Desktop/User32Mockable.cs index ad8f133d..3bdfec02 100644 --- a/src/User32.Desktop/User32Mockable.cs +++ b/src/User32.Desktop/User32Mockable.cs @@ -6,13 +6,17 @@ namespace PInvoke using System; using System.Runtime.InteropServices; using static User32; - public class User32Mockable : IUser32Mockable { public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) + [System.Runtime.CompilerServices.CompilerGenerated] + public class User32Mockable : IUser32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) => SetWindowLong(hWnd, nIndex, dwNewLong); - public int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) => GetWindowLong(hWnd, nIndex); - public bool InvokeSetWindowPos( + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeSetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, @@ -22,23 +26,28 @@ public bool InvokeSetWindowPos( SetWindowPosFlags uFlags) => SetWindowPos(hWnd, hWndInsertAfter, X, Y, cx, cy, uFlags); - public IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent) + [System.Runtime.CompilerServices.CompilerGenerated] + public IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent) => SetParent(hWndChild, hWndNewParent); - public IntPtr InvokeFindWindowEx( + [System.Runtime.CompilerServices.CompilerGenerated] + public IntPtr InvokeFindWindowEx( IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle) => FindWindowEx(parentHandle, childAfter, className, windowTitle); - public bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) + [System.Runtime.CompilerServices.CompilerGenerated] + public bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) => ShowWindow(hWnd, nCmdShow); - public IntPtr InvokeGetForegroundWindow() + [System.Runtime.CompilerServices.CompilerGenerated] + public IntPtr InvokeGetForegroundWindow() => GetForegroundWindow(); - public int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) + [System.Runtime.CompilerServices.CompilerGenerated] + public int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) => SendMessage(hWnd, wMsg, wParam, lParam); } } From c1b983b24712ec52f1cff8da3502a738279b96c6 Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 12:03:38 +0100 Subject: [PATCH 45/46] removed invoke prefix. --- src/MockGenerator/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 7d91d840..596f060e 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -131,7 +131,7 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec foreach (var methodDeclaration in methodDeclarations) { var invokeMethodIdentifier = - SyntaxFactory.IdentifierName($"Invoke{methodDeclaration.Identifier.Text}"); + SyntaxFactory.IdentifierName($"{methodDeclaration.Identifier.Text}"); newClassDeclaration = DecorateClassWithWrapperFunction( methodDeclaration, From a137f66dceb4db0e2336c067b3eaaf9cca73106b Mon Sep 17 00:00:00 2001 From: ffMathy Date: Sun, 22 Nov 2015 12:16:55 +0100 Subject: [PATCH 46/46] new code format. --- src/AdvApi32.Desktop/AdvApi32.Desktop.csproj | 2 +- src/AdvApi32.Desktop/AdvApi32Mockable.cs | 14 ++-- .../{IAdvApi32Mockable.cs => IAdvApi32.cs} | 14 ++-- src/BCrypt/BCrypt.csproj | 2 +- src/BCrypt/BCryptMockable.cs | 44 ++++++------ src/BCrypt/{IBCryptMockable.cs => IBCrypt.cs} | 44 ++++++------ src/Gdi32.Desktop/Gdi32.Desktop.csproj | 2 +- src/Gdi32.Desktop/Gdi32Mockable.cs | 4 +- .../{IGdi32Mockable.cs => IGdi32.cs} | 4 +- src/Hid.Desktop/Hid.Desktop.csproj | 2 +- src/Hid.Desktop/HidMockable.cs | 18 ++--- .../IHidMockable.cs => Hid.Desktop/IHid.cs} | 18 ++--- src/Hid/Hid.csproj | 2 +- src/Hid/HidMockable.cs | 18 ++--- .../IHidMockable.cs => Hid/IHid.cs} | 18 ++--- .../{IImageHlpMockable.cs => IImageHlp.cs} | 6 +- src/ImageHlp/ImageHlp.csproj | 2 +- src/ImageHlp/ImageHlpMockable.cs | 6 +- .../{IKernel32Mockable.cs => IKernel32.cs} | 70 +++++++++---------- src/Kernel32.Desktop/Kernel32.Desktop.csproj | 2 +- src/Kernel32.Desktop/Kernel32Mockable.cs | 70 +++++++++---------- .../{IKernel32Mockable.cs => IKernel32.cs} | 28 ++++---- src/Kernel32/Kernel32.csproj | 2 +- src/Kernel32/Kernel32Mockable.cs | 28 ++++---- src/MockGenerator/Program.cs | 10 +-- src/NCrypt/{INCryptMockable.cs => INCrypt.cs} | 12 ++-- src/NCrypt/NCrypt.csproj | 2 +- src/NCrypt/NCryptMockable.cs | 12 ++-- .../{ISetupApiMockable.cs => ISetupApi.cs} | 10 +-- src/SetupApi.Desktop/SetupApi.Desktop.csproj | 2 +- src/SetupApi.Desktop/SetupApiMockable.cs | 10 +-- .../{IUser32Mockable.cs => IUser32.cs} | 18 ++--- src/User32.Desktop/User32.Desktop.csproj | 2 +- src/User32.Desktop/User32Mockable.cs | 18 ++--- 34 files changed, 256 insertions(+), 260 deletions(-) rename src/AdvApi32.Desktop/{IAdvApi32Mockable.cs => IAdvApi32.cs} (93%) rename src/BCrypt/{IBCryptMockable.cs => IBCrypt.cs} (98%) rename src/Gdi32.Desktop/{IGdi32Mockable.cs => IGdi32.cs} (73%) rename src/{Hid/IHidMockable.cs => Hid.Desktop/IHid.cs} (94%) rename src/{Hid.Desktop/IHidMockable.cs => Hid/IHid.cs} (94%) rename src/ImageHlp/{IImageHlpMockable.cs => IImageHlp.cs} (95%) rename src/Kernel32.Desktop/{IKernel32Mockable.cs => IKernel32.cs} (97%) rename src/Kernel32/{IKernel32Mockable.cs => IKernel32.cs} (96%) rename src/NCrypt/{INCryptMockable.cs => INCrypt.cs} (96%) rename src/SetupApi.Desktop/{ISetupApiMockable.cs => ISetupApi.cs} (97%) rename src/User32.Desktop/{IUser32Mockable.cs => IUser32.cs} (66%) diff --git a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj index c52fa31b..f7f633e7 100644 --- a/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj +++ b/src/AdvApi32.Desktop/AdvApi32.Desktop.csproj @@ -62,7 +62,7 @@ - + diff --git a/src/AdvApi32.Desktop/AdvApi32Mockable.cs b/src/AdvApi32.Desktop/AdvApi32Mockable.cs index 3af8f540..b669d43a 100644 --- a/src/AdvApi32.Desktop/AdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/AdvApi32Mockable.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static AdvApi32; [System.Runtime.CompilerServices.CompilerGenerated] - public class AdvApi32Mockable : IAdvApi32Mockable { + class AdvApi32Mockable : IAdvApi32 { /// /// Changes the optional configuration parameters of a service. /// @@ -30,7 +30,7 @@ public class AdvApi32Mockable : IAdvApi32Mockable { /// If the function fails, the return value is zero /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo) + public bool ChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo) => ChangeServiceConfig2(hService, dwInfoLevel, lpInfo); /// @@ -105,7 +105,7 @@ public bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLe /// If the function fails, the return value is NULL /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeServiceHandle InvokeCreateService(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) + 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); /// @@ -119,7 +119,7 @@ public SafeServiceHandle InvokeCreateService(SafeServiceHandle hSCManager, strin /// If the function fails, the return value is zero /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeDeleteService(SafeServiceHandle hService) + public bool DeleteService(SafeServiceHandle hService) => DeleteService(hService); /// @@ -145,7 +145,7 @@ public bool InvokeDeleteService(SafeServiceHandle hService) /// If the function fails, the return value is NULL.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess) + public SafeServiceHandle OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess) => OpenSCManager(lpMachineName, lpDatabaseName, dwDesiredAccess); /// @@ -167,7 +167,7 @@ public SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpData /// If the function fails, the return value is NULL. /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess) + public SafeServiceHandle OpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess) => OpenService(hSCManager, lpServiceName, dwDesiredAccess); /// @@ -188,7 +188,7 @@ public SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string /// If the function fails, the return value is zero. /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) + public bool StartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors) => StartService(hService, dwNumServiceArgs, lpServiceArgVectors); } } diff --git a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs b/src/AdvApi32.Desktop/IAdvApi32.cs similarity index 93% rename from src/AdvApi32.Desktop/IAdvApi32Mockable.cs rename to src/AdvApi32.Desktop/IAdvApi32.cs index 54a9fec3..f05122d8 100644 --- a/src/AdvApi32.Desktop/IAdvApi32Mockable.cs +++ b/src/AdvApi32.Desktop/IAdvApi32.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static AdvApi32; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IAdvApi32Mockable { + public interface IAdvApi32 { /// /// Changes the optional configuration parameters of a service. /// @@ -30,7 +30,7 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is zero /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo); + bool ChangeServiceConfig2(SafeServiceHandle hService, ServiceInfoLevel dwInfoLevel, IntPtr lpInfo); /// /// Creates a service object and adds it to the specified service control manager database. @@ -104,7 +104,7 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is NULL /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeServiceHandle InvokeCreateService(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); + 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. @@ -117,7 +117,7 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is zero /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeDeleteService(SafeServiceHandle hService); + bool DeleteService(SafeServiceHandle hService); /// /// Establishes a connection to the service control manager on the specified computer and opens the specified service control manager database. @@ -142,7 +142,7 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is NULL.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeServiceHandle InvokeOpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess); + SafeServiceHandle OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerAccess dwDesiredAccess); /// /// Opens an existing service. @@ -163,7 +163,7 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is NULL. /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeServiceHandle InvokeOpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess); + SafeServiceHandle OpenService(SafeServiceHandle hSCManager, string lpServiceName, ServiceAccess dwDesiredAccess); /// /// Starts a service. @@ -183,6 +183,6 @@ public interface IAdvApi32Mockable { /// If the function fails, the return value is zero. /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeStartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); + bool StartService(SafeServiceHandle hService, int dwNumServiceArgs, string lpServiceArgVectors); } } diff --git a/src/BCrypt/BCrypt.csproj b/src/BCrypt/BCrypt.csproj index e9923540..29621222 100644 --- a/src/BCrypt/BCrypt.csproj +++ b/src/BCrypt/BCrypt.csproj @@ -61,7 +61,7 @@ - + diff --git a/src/BCrypt/BCryptMockable.cs b/src/BCrypt/BCryptMockable.cs index 1a3eb131..46b91609 100644 --- a/src/BCrypt/BCryptMockable.cs +++ b/src/BCrypt/BCryptMockable.cs @@ -9,7 +9,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static BCrypt; [System.Runtime.CompilerServices.CompilerGenerated] - public class BCryptMockable : IBCryptMockable { /// + class BCryptMockable : IBCrypt { /// /// Loads and initializes a CNG provider. /// /// @@ -43,7 +43,7 @@ public class BCryptMockable : IBCryptMockable { /// /// Returns a status code that indicates the success or failure of the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptOpenAlgorithmProvider( + public NTStatus BCryptOpenAlgorithmProvider( out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, @@ -79,7 +79,7 @@ public NTStatus InvokeBCryptOpenAlgorithmProvider( /// 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 InvokeBCryptCreateHash( + public NTStatus BCryptCreateHash( SafeAlgorithmHandle hAlgorithm, out SafeHashHandle phHash, byte[] pbHashObject, @@ -129,7 +129,7 @@ public NTStatus InvokeBCryptCreateHash( /// 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 InvokeBCryptEncrypt( + public NTStatus BCryptEncrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -181,7 +181,7 @@ public NTStatus InvokeBCryptEncrypt( /// /// Returns a status code that indicates the success or failure of the function. [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptDecrypt( + public NTStatus BCryptDecrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -211,7 +211,7 @@ public NTStatus InvokeBCryptDecrypt( /// After the function has been called for a specified handle, that handle cannot be reused. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptHashData( + public NTStatus BCryptHashData( SafeHashHandle hHash, byte[] pbInput, int cbInput, @@ -234,7 +234,7 @@ public NTStatus InvokeBCryptHashData( /// 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 InvokeBCryptFinishHash( + public NTStatus BCryptFinishHash( SafeHashHandle hHash, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbOutput, int cbOutput, @@ -273,7 +273,7 @@ public NTStatus InvokeBCryptFinishHash( /// 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 InvokeBCryptSignHash( + public NTStatus BCryptSignHash( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbInput, @@ -315,7 +315,7 @@ public NTStatus InvokeBCryptSignHash( /// In particular, an invalid signature will produce a result. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptVerifySignature( + public NTStatus BCryptVerifySignature( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbHash, @@ -339,7 +339,7 @@ public NTStatus InvokeBCryptVerifySignature( /// BCryptFinalizeKeyPair function is called. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptGenerateKeyPair( + public NTStatus BCryptGenerateKeyPair( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, int dwLength, @@ -374,7 +374,7 @@ public NTStatus InvokeBCryptGenerateKeyPair( /// 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 InvokeBCryptGenerateSymmetricKey( + public NTStatus BCryptGenerateSymmetricKey( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, byte[] pbKeyObject, @@ -396,7 +396,7 @@ public NTStatus InvokeBCryptGenerateSymmetricKey( /// can no longer be used for this key. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptFinalizeKeyPair( + public NTStatus BCryptFinalizeKeyPair( SafeKeyHandle hKey, BCryptFinalizeKeyPairFlags dwFlags = BCryptFinalizeKeyPairFlags.None) => BCryptFinalizeKeyPair(hKey, dwFlags ); @@ -407,7 +407,7 @@ public NTStatus InvokeBCryptFinalizeKeyPair( /// 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 InvokeBCryptDestroyKey( + public NTStatus BCryptDestroyKey( IntPtr hKey) => BCryptDestroyKey(hKey); @@ -417,7 +417,7 @@ public NTStatus InvokeBCryptDestroyKey( /// 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 InvokeBCryptDestroySecret( + public NTStatus BCryptDestroySecret( IntPtr hSecret) => BCryptDestroySecret(hSecret); @@ -458,7 +458,7 @@ public NTStatus InvokeBCryptDestroySecret( /// 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 InvokeBCryptImportKey( + public NTStatus BCryptImportKey( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -482,7 +482,7 @@ public NTStatus InvokeBCryptImportKey( /// 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 InvokeBCryptImportKeyPair( + public NTStatus BCryptImportKeyPair( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -520,7 +520,7 @@ public NTStatus InvokeBCryptImportKeyPair( /// 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 InvokeBCryptExportKey( + public NTStatus BCryptExportKey( SafeKeyHandle hKey, SafeKeyHandle hExportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -549,7 +549,7 @@ public NTStatus InvokeBCryptExportKey( /// 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 InvokeBCryptSecretAgreement( + public NTStatus BCryptSecretAgreement( SafeKeyHandle privateKey, SafeKeyHandle publicKey, out SafeSecretHandle secret, @@ -592,7 +592,7 @@ public NTStatus InvokeBCryptSecretAgreement( /// Returns a status code that indicates the success or failure of the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeBCryptDeriveKey( + public NTStatus BCryptDeriveKey( SafeSecretHandle sharedSecret, string keyDerivationFunction, [In] ref BCryptBufferDesc kdfParameters, @@ -614,7 +614,7 @@ public NTStatus InvokeBCryptDeriveKey( /// 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 InvokeBCryptSetProperty( + public NTStatus BCryptSetProperty( SafeHandle hObject, string property, [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, @@ -633,7 +633,7 @@ public NTStatus InvokeBCryptSetProperty( /// 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 InvokeBCryptGetProperty( + public NTStatus BCryptGetProperty( SafeHandle hObject, string property, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, @@ -657,7 +657,7 @@ public NTStatus InvokeBCryptGetProperty( /// 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 InvokeBCryptGenRandom( + public NTStatus BCryptGenRandom( SafeAlgorithmHandle hAlgorithm, byte[] pbBuffer, int cbBuffer, diff --git a/src/BCrypt/IBCryptMockable.cs b/src/BCrypt/IBCrypt.cs similarity index 98% rename from src/BCrypt/IBCryptMockable.cs rename to src/BCrypt/IBCrypt.cs index 0eaddbd0..3b028d74 100644 --- a/src/BCrypt/IBCryptMockable.cs +++ b/src/BCrypt/IBCrypt.cs @@ -9,7 +9,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static BCrypt; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IBCryptMockable { /// + public interface IBCrypt { /// /// Loads and initializes a CNG provider. /// /// @@ -43,7 +43,7 @@ public interface IBCryptMockable { /// /// Returns a status code that indicates the success or failure of the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptOpenAlgorithmProvider( + NTStatus BCryptOpenAlgorithmProvider( out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, @@ -78,7 +78,7 @@ NTStatus InvokeBCryptOpenAlgorithmProvider( /// 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 InvokeBCryptCreateHash( + NTStatus BCryptCreateHash( SafeAlgorithmHandle hAlgorithm, out SafeHashHandle phHash, byte[] pbHashObject, @@ -127,7 +127,7 @@ NTStatus InvokeBCryptCreateHash( /// 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 InvokeBCryptEncrypt( + NTStatus BCryptEncrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -178,7 +178,7 @@ NTStatus InvokeBCryptEncrypt( /// /// Returns a status code that indicates the success or failure of the function. [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptDecrypt( + NTStatus BCryptDecrypt( SafeKeyHandle hKey, byte[] pbInput, int cbInput, @@ -207,7 +207,7 @@ NTStatus InvokeBCryptDecrypt( /// After the function has been called for a specified handle, that handle cannot be reused. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptHashData( + NTStatus BCryptHashData( SafeHashHandle hHash, byte[] pbInput, int cbInput, @@ -229,7 +229,7 @@ NTStatus InvokeBCryptHashData( /// 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 InvokeBCryptFinishHash( + NTStatus BCryptFinishHash( SafeHashHandle hHash, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbOutput, int cbOutput, @@ -267,7 +267,7 @@ NTStatus InvokeBCryptFinishHash( /// 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 InvokeBCryptSignHash( + NTStatus BCryptSignHash( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbInput, @@ -308,7 +308,7 @@ NTStatus InvokeBCryptSignHash( /// In particular, an invalid signature will produce a result. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptVerifySignature( + NTStatus BCryptVerifySignature( SafeKeyHandle hKey, IntPtr pPaddingInfo, byte[] pbHash, @@ -331,7 +331,7 @@ NTStatus InvokeBCryptVerifySignature( /// BCryptFinalizeKeyPair function is called. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptGenerateKeyPair( + NTStatus BCryptGenerateKeyPair( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, int dwLength, @@ -365,7 +365,7 @@ NTStatus InvokeBCryptGenerateKeyPair( /// 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 InvokeBCryptGenerateSymmetricKey( + NTStatus BCryptGenerateSymmetricKey( SafeAlgorithmHandle hAlgorithm, out SafeKeyHandle phKey, byte[] pbKeyObject, @@ -386,7 +386,7 @@ NTStatus InvokeBCryptGenerateSymmetricKey( /// can no longer be used for this key. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptFinalizeKeyPair( + NTStatus BCryptFinalizeKeyPair( SafeKeyHandle hKey, BCryptFinalizeKeyPairFlags dwFlags = BCryptFinalizeKeyPairFlags.None); @@ -396,7 +396,7 @@ NTStatus InvokeBCryptFinalizeKeyPair( /// 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 InvokeBCryptDestroyKey( + NTStatus BCryptDestroyKey( IntPtr hKey); /// @@ -405,7 +405,7 @@ NTStatus InvokeBCryptDestroyKey( /// 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 InvokeBCryptDestroySecret( + NTStatus BCryptDestroySecret( IntPtr hSecret); /// @@ -445,7 +445,7 @@ NTStatus InvokeBCryptDestroySecret( /// 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 InvokeBCryptImportKey( + NTStatus BCryptImportKey( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -468,7 +468,7 @@ NTStatus InvokeBCryptImportKey( /// 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 InvokeBCryptImportKeyPair( + NTStatus BCryptImportKeyPair( SafeAlgorithmHandle hAlgorithm, SafeKeyHandle hImportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -505,7 +505,7 @@ NTStatus InvokeBCryptImportKeyPair( /// 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 InvokeBCryptExportKey( + NTStatus BCryptExportKey( SafeKeyHandle hKey, SafeKeyHandle hExportKey, [MarshalAs(UnmanagedType.LPWStr)] string pszBlobType, @@ -533,7 +533,7 @@ NTStatus InvokeBCryptExportKey( /// 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 InvokeBCryptSecretAgreement( + NTStatus BCryptSecretAgreement( SafeKeyHandle privateKey, SafeKeyHandle publicKey, out SafeSecretHandle secret, @@ -575,7 +575,7 @@ NTStatus InvokeBCryptSecretAgreement( /// Returns a status code that indicates the success or failure of the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeBCryptDeriveKey( + NTStatus BCryptDeriveKey( SafeSecretHandle sharedSecret, string keyDerivationFunction, [In] ref BCryptBufferDesc kdfParameters, @@ -596,7 +596,7 @@ NTStatus InvokeBCryptDeriveKey( /// 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 InvokeBCryptSetProperty( + NTStatus BCryptSetProperty( SafeHandle hObject, string property, [In, MarshalAs(UnmanagedType.LPArray)] byte[] input, @@ -614,7 +614,7 @@ NTStatus InvokeBCryptSetProperty( /// 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 InvokeBCryptGetProperty( + NTStatus BCryptGetProperty( SafeHandle hObject, string property, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] output, @@ -637,7 +637,7 @@ NTStatus InvokeBCryptGetProperty( /// 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 InvokeBCryptGenRandom( + NTStatus BCryptGenRandom( SafeAlgorithmHandle hAlgorithm, byte[] pbBuffer, int cbBuffer, diff --git a/src/Gdi32.Desktop/Gdi32.Desktop.csproj b/src/Gdi32.Desktop/Gdi32.Desktop.csproj index 0fc2e679..d58904a0 100644 --- a/src/Gdi32.Desktop/Gdi32.Desktop.csproj +++ b/src/Gdi32.Desktop/Gdi32.Desktop.csproj @@ -24,7 +24,7 @@ - + diff --git a/src/Gdi32.Desktop/Gdi32Mockable.cs b/src/Gdi32.Desktop/Gdi32Mockable.cs index 886fe5aa..ae07df4f 100644 --- a/src/Gdi32.Desktop/Gdi32Mockable.cs +++ b/src/Gdi32.Desktop/Gdi32Mockable.cs @@ -7,8 +7,8 @@ namespace PInvoke using System.Runtime.InteropServices; using static Gdi32; [System.Runtime.CompilerServices.CompilerGenerated] - public class Gdi32Mockable : IGdi32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeDeleteObject(IntPtr hObject) + class Gdi32Mockable : IGdi32 { [System.Runtime.CompilerServices.CompilerGenerated] + public bool DeleteObject(IntPtr hObject) => DeleteObject(hObject); } } diff --git a/src/Gdi32.Desktop/IGdi32Mockable.cs b/src/Gdi32.Desktop/IGdi32.cs similarity index 73% rename from src/Gdi32.Desktop/IGdi32Mockable.cs rename to src/Gdi32.Desktop/IGdi32.cs index b6270705..4d52674f 100644 --- a/src/Gdi32.Desktop/IGdi32Mockable.cs +++ b/src/Gdi32.Desktop/IGdi32.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static Gdi32; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IGdi32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeDeleteObject(IntPtr hObject); + 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 edae0fe3..6656d431 100644 --- a/src/Hid.Desktop/Hid.Desktop.csproj +++ b/src/Hid.Desktop/Hid.Desktop.csproj @@ -40,7 +40,7 @@ - + diff --git a/src/Hid.Desktop/HidMockable.cs b/src/Hid.Desktop/HidMockable.cs index b33c0e3f..b0f2d55c 100644 --- a/src/Hid.Desktop/HidMockable.cs +++ b/src/Hid.Desktop/HidMockable.cs @@ -9,7 +9,7 @@ namespace PInvoke using static Kernel32; using static Hid; [System.Runtime.CompilerServices.CompilerGenerated] - public class HidMockable : IHidMockable { /// + class HidMockable : IHid { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// /// @@ -17,7 +17,7 @@ public class HidMockable : IHidMockable { /// /// for HIDClass devices. /// [System.Runtime.CompilerServices.CompilerGenerated] - public void InvokeHidD_GetHidGuid(out Guid hidGuid) + public void HidD_GetHidGuid(out Guid hidGuid) => HidD_GetHidGuid(out hidGuid); /// @@ -30,7 +30,7 @@ public void InvokeHidD_GetHidGuid(out Guid hidGuid) /// /// TRUE if succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetAttributes( + public bool HidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes) => HidD_GetAttributes(hidDeviceObject, ref attributes); @@ -54,7 +54,7 @@ public bool InvokeHidD_GetAttributes( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetManufacturerString( + public bool HidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -80,7 +80,7 @@ public bool InvokeHidD_GetManufacturerString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetProductString( + public bool HidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -110,7 +110,7 @@ public bool InvokeHidD_GetProductString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetSerialNumberString( + public bool HidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -127,7 +127,7 @@ public bool InvokeHidD_GetSerialNumberString( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_SetNumInputBuffers( + public bool HidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers) => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); @@ -142,7 +142,7 @@ public bool InvokeHidD_SetNumInputBuffers( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetPreparsedData( + public bool HidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle) => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); @@ -160,7 +160,7 @@ public bool InvokeHidD_GetPreparsedData( /// specified preparsed data is invalid. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + 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/IHidMockable.cs b/src/Hid.Desktop/IHid.cs similarity index 94% rename from src/Hid/IHidMockable.cs rename to src/Hid.Desktop/IHid.cs index 972f2186..2a2ff521 100644 --- a/src/Hid/IHidMockable.cs +++ b/src/Hid.Desktop/IHid.cs @@ -9,7 +9,7 @@ namespace PInvoke using static Kernel32; using static Hid; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IHidMockable { /// + public interface IHid { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// /// @@ -17,7 +17,7 @@ public interface IHidMockable { /// /// for HIDClass devices. /// [System.Runtime.CompilerServices.CompilerGenerated] - void InvokeHidD_GetHidGuid(out Guid hidGuid); + void HidD_GetHidGuid(out Guid hidGuid); /// /// Returns the attributes of a specified top-level collection. @@ -29,7 +29,7 @@ public interface IHidMockable { /// /// /// TRUE if succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetAttributes( + bool HidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes); @@ -52,7 +52,7 @@ bool InvokeHidD_GetAttributes( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetManufacturerString( + bool HidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -77,7 +77,7 @@ bool InvokeHidD_GetManufacturerString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetProductString( + bool HidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -106,7 +106,7 @@ bool InvokeHidD_GetProductString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetSerialNumberString( + bool HidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -122,7 +122,7 @@ bool InvokeHidD_GetSerialNumberString( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_SetNumInputBuffers( + bool HidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers); @@ -136,7 +136,7 @@ bool InvokeHidD_SetNumInputBuffers( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetPreparsedData( + bool HidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle); @@ -153,6 +153,6 @@ bool InvokeHidD_GetPreparsedData( /// specified preparsed data is invalid. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + NTStatus HidP_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 e2b8e981..9c5acff0 100644 --- a/src/Hid/Hid.csproj +++ b/src/Hid/Hid.csproj @@ -24,7 +24,7 @@ - + diff --git a/src/Hid/HidMockable.cs b/src/Hid/HidMockable.cs index b33c0e3f..b0f2d55c 100644 --- a/src/Hid/HidMockable.cs +++ b/src/Hid/HidMockable.cs @@ -9,7 +9,7 @@ namespace PInvoke using static Kernel32; using static Hid; [System.Runtime.CompilerServices.CompilerGenerated] - public class HidMockable : IHidMockable { /// + class HidMockable : IHid { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// /// @@ -17,7 +17,7 @@ public class HidMockable : IHidMockable { /// /// for HIDClass devices. /// [System.Runtime.CompilerServices.CompilerGenerated] - public void InvokeHidD_GetHidGuid(out Guid hidGuid) + public void HidD_GetHidGuid(out Guid hidGuid) => HidD_GetHidGuid(out hidGuid); /// @@ -30,7 +30,7 @@ public void InvokeHidD_GetHidGuid(out Guid hidGuid) /// /// TRUE if succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetAttributes( + public bool HidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes) => HidD_GetAttributes(hidDeviceObject, ref attributes); @@ -54,7 +54,7 @@ public bool InvokeHidD_GetAttributes( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetManufacturerString( + public bool HidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -80,7 +80,7 @@ public bool InvokeHidD_GetManufacturerString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetProductString( + public bool HidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -110,7 +110,7 @@ public bool InvokeHidD_GetProductString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetSerialNumberString( + public bool HidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength) @@ -127,7 +127,7 @@ public bool InvokeHidD_GetSerialNumberString( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_SetNumInputBuffers( + public bool HidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers) => HidD_SetNumInputBuffers(hidDeviceObject, numberBuffers); @@ -142,7 +142,7 @@ public bool InvokeHidD_SetNumInputBuffers( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeHidD_GetPreparsedData( + public bool HidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle) => HidD_GetPreparsedData(hidDeviceObject, out preparsedDataHandle); @@ -160,7 +160,7 @@ public bool InvokeHidD_GetPreparsedData( /// specified preparsed data is invalid. /// [System.Runtime.CompilerServices.CompilerGenerated] - public NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities) + 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/IHidMockable.cs b/src/Hid/IHid.cs similarity index 94% rename from src/Hid.Desktop/IHidMockable.cs rename to src/Hid/IHid.cs index 972f2186..2a2ff521 100644 --- a/src/Hid.Desktop/IHidMockable.cs +++ b/src/Hid/IHid.cs @@ -9,7 +9,7 @@ namespace PInvoke using static Kernel32; using static Hid; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IHidMockable { /// + public interface IHid { /// /// The HidD_GetHidGuid routine returns the device interfaceGUID for HIDClass devices. /// /// @@ -17,7 +17,7 @@ public interface IHidMockable { /// /// for HIDClass devices. /// [System.Runtime.CompilerServices.CompilerGenerated] - void InvokeHidD_GetHidGuid(out Guid hidGuid); + void HidD_GetHidGuid(out Guid hidGuid); /// /// Returns the attributes of a specified top-level collection. @@ -29,7 +29,7 @@ public interface IHidMockable { /// /// /// TRUE if succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetAttributes( + bool HidD_GetAttributes( SafeObjectHandle hidDeviceObject, ref HiddAttributes attributes); @@ -52,7 +52,7 @@ bool InvokeHidD_GetAttributes( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetManufacturerString( + bool HidD_GetManufacturerString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -77,7 +77,7 @@ bool InvokeHidD_GetManufacturerString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetProductString( + bool HidD_GetProductString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -106,7 +106,7 @@ bool InvokeHidD_GetProductString( /// maximum string length is 126 wide characters (not including the terminating NULL character). /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetSerialNumberString( + bool HidD_GetSerialNumberString( SafeObjectHandle hidDeviceObject, StringBuilder buffer, int bufferLength); @@ -122,7 +122,7 @@ bool InvokeHidD_GetSerialNumberString( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_SetNumInputBuffers( + bool HidD_SetNumInputBuffers( SafeObjectHandle hidDeviceObject, uint numberBuffers); @@ -136,7 +136,7 @@ bool InvokeHidD_SetNumInputBuffers( /// /// TRUE if it succeeds; otherwise, it returns FALSE. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeHidD_GetPreparsedData( + bool HidD_GetPreparsedData( SafeObjectHandle hidDeviceObject, out SafePreparsedDataHandle preparsedDataHandle); @@ -153,6 +153,6 @@ bool InvokeHidD_GetPreparsedData( /// specified preparsed data is invalid. /// [System.Runtime.CompilerServices.CompilerGenerated] - NTStatus InvokeHidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); + NTStatus HidP_GetCaps(SafePreparsedDataHandle preparsedData, ref HidpCaps capabilities); } } \ No newline at end of file diff --git a/src/ImageHlp/IImageHlpMockable.cs b/src/ImageHlp/IImageHlp.cs similarity index 95% rename from src/ImageHlp/IImageHlpMockable.cs rename to src/ImageHlp/IImageHlp.cs index f7797f61..c6aa6ed1 100644 --- a/src/ImageHlp/IImageHlpMockable.cs +++ b/src/ImageHlp/IImageHlp.cs @@ -8,7 +8,7 @@ namespace PInvoke using static DbgHelp; using static ImageHlp; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IImageHlpMockable { /// + 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. @@ -21,7 +21,7 @@ public interface IImageHlpMockable { /// /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeMapAndLoad( + bool MapAndLoad( string ImageName, string DllPath, out LOADED_IMAGE LoadedImage, @@ -39,7 +39,7 @@ bool InvokeMapAndLoad( /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeUnMapAndLoad( + bool UnMapAndLoad( ref LOADED_IMAGE LoadedImage); } } diff --git a/src/ImageHlp/ImageHlp.csproj b/src/ImageHlp/ImageHlp.csproj index 907da4e9..60c6edec 100644 --- a/src/ImageHlp/ImageHlp.csproj +++ b/src/ImageHlp/ImageHlp.csproj @@ -38,7 +38,7 @@ - + diff --git a/src/ImageHlp/ImageHlpMockable.cs b/src/ImageHlp/ImageHlpMockable.cs index 452c68a3..50840366 100644 --- a/src/ImageHlp/ImageHlpMockable.cs +++ b/src/ImageHlp/ImageHlpMockable.cs @@ -8,7 +8,7 @@ namespace PInvoke using static DbgHelp; using static ImageHlp; [System.Runtime.CompilerServices.CompilerGenerated] - public class ImageHlpMockable : IImageHlpMockable { /// + 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. @@ -21,7 +21,7 @@ public class ImageHlpMockable : IImageHlpMockable { /// /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeMapAndLoad( + public bool MapAndLoad( string ImageName, string DllPath, out LOADED_IMAGE LoadedImage, @@ -40,7 +40,7 @@ public bool InvokeMapAndLoad( /// If the function fails, the return value is FALSE. To retrieve extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeUnMapAndLoad( + public bool UnMapAndLoad( ref LOADED_IMAGE LoadedImage) => UnMapAndLoad(ref LoadedImage); } diff --git a/src/Kernel32.Desktop/IKernel32Mockable.cs b/src/Kernel32.Desktop/IKernel32.cs similarity index 97% rename from src/Kernel32.Desktop/IKernel32Mockable.cs rename to src/Kernel32.Desktop/IKernel32.cs index 2231e014..95cf993e 100644 --- a/src/Kernel32.Desktop/IKernel32Mockable.cs +++ b/src/Kernel32.Desktop/IKernel32.cs @@ -9,7 +9,7 @@ namespace PInvoke using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IKernel32Mockable { + 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. @@ -43,7 +43,7 @@ public interface IKernel32Mockable { /// 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 InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags); + 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. @@ -90,20 +90,20 @@ public interface IKernel32Mockable { /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments); + 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 InvokeGetCurrentThreadId(); + 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 InvokeGetCurrentProcessId(); + uint GetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. /// The return value is a pseudo handle to the current process. @@ -129,7 +129,7 @@ public interface IKernel32Mockable { /// /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeObjectHandle InvokeGetCurrentProcess(); + SafeObjectHandle GetCurrentProcess(); /// /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations @@ -163,7 +163,7 @@ public interface IKernel32Mockable { /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeCancelIoEx( + unsafe bool CancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped); @@ -228,7 +228,7 @@ unsafe bool InvokeCancelIoEx( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeReadFile( + unsafe bool ReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -304,7 +304,7 @@ unsafe bool InvokeReadFile( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeWriteFile( + unsafe bool WriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -323,7 +323,7 @@ unsafe bool InvokeWriteFile( /// 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 InvokeSuspendThread(SafeObjectHandle hThread); + int SuspendThread(SafeObjectHandle hThread); /// /// Suspends the specified WOW64 thread. @@ -336,7 +336,7 @@ unsafe bool InvokeWriteFile( /// 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 InvokeWow64SuspendThread(SafeObjectHandle hThread); + 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. @@ -350,7 +350,7 @@ unsafe bool InvokeWriteFile( /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeResumeThread(SafeObjectHandle hThread); + int ResumeThread(SafeObjectHandle hThread); /// /// Waits until the specified object is in the signaled state or the time-out interval elapses. @@ -369,7 +369,7 @@ unsafe bool InvokeWriteFile( /// 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 InvokeWaitForSingleObject( + WaitForSingleObjectResult WaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds); @@ -382,7 +382,7 @@ WaitForSingleObjectResult InvokeWaitForSingleObject( /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeCloseHandle(IntPtr hObject); + 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. @@ -445,7 +445,7 @@ WaitForSingleObjectResult InvokeWaitForSingleObject( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeCreateProcess( + bool CreateProcess( string lpApplicationName, string lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, @@ -525,7 +525,7 @@ bool InvokeCreateProcess( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeCreateProcessAsUser( + bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, @@ -548,7 +548,7 @@ bool InvokeCreateProcessAsUser( /// This function does not return a value, and does not fail. /// [System.Runtime.CompilerServices.CompilerGenerated] - void InvokeGetStartupInfo( + void GetStartupInfo( out STARTUPINFO lpStartupInfo); /// @@ -576,7 +576,7 @@ void InvokeGetStartupInfo( /// When you have finished using the list, call the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeInitializeProcThreadAttributeList( + bool InitializeProcThreadAttributeList( IntPtr lpAttributeList, uint dwAttributeCount, uint dwFlags, @@ -609,7 +609,7 @@ bool InvokeInitializeProcThreadAttributeList( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeUpdateProcThreadAttribute( + bool UpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, ref uint Attribute, @@ -625,7 +625,7 @@ bool InvokeUpdateProcThreadAttribute( /// The attribute list. This list is created by the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - void InvokeDeleteProcThreadAttributeList( + void DeleteProcThreadAttributeList( IntPtr lpAttributeList); /// @@ -636,7 +636,7 @@ void InvokeDeleteProcThreadAttributeList( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeAllocConsole(); + bool AllocConsole(); /// /// Detaches the calling process from its console. @@ -646,7 +646,7 @@ void InvokeDeleteProcThreadAttributeList( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeFreeConsole(); + bool FreeConsole(); /// /// Attaches the calling process to the console of the specified process. @@ -661,7 +661,7 @@ void InvokeDeleteProcThreadAttributeList( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeAttachConsole(uint dwProcessId); + 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. @@ -718,7 +718,7 @@ void InvokeDeleteProcThreadAttributeList( /// If the function fails, the return value is INVALID_HANDLE_VALUE.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeObjectHandle InvokeCreateFile( + SafeObjectHandle CreateFile( string filename, FileAccess access, FileShare share, @@ -745,7 +745,7 @@ SafeObjectHandle InvokeCreateFile( /// If the function fails because no matching files can be found, the function returns ERROR_FILE_NOT_FOUND. /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); + SafeFindFilesHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); /// /// Continues a file search from a previous call to the , FindFirstFileEx, or FindFirstFileTransacted functions. @@ -758,7 +758,7 @@ SafeObjectHandle InvokeCreateFile( /// If the function fails because no more matching files can be found, the function returns ERROR_NO_MORE_FILES. /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData); + 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 @@ -825,7 +825,7 @@ SafeObjectHandle InvokeCreateFile( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeObjectHandle InvokeCreateToolhelp32Snapshot( + SafeObjectHandle CreateToolhelp32Snapshot( CreateToolhelp32SnapshotFlags dwFlags, uint th32ProcessID); @@ -845,7 +845,7 @@ SafeObjectHandle InvokeCreateToolhelp32Snapshot( /// information. /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); + bool Process32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); /// Retrieves information about the next process recorded in a system snapshot. /// @@ -865,7 +865,7 @@ SafeObjectHandle InvokeCreateToolhelp32Snapshot( /// function. /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeProcess32Next( + bool Process32Next( SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe); @@ -887,7 +887,7 @@ bool InvokeProcess32Next( /// /// Minimum OS: Windows Vista / Windows Server 2008. [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeQueryFullProcessImageName( + bool QueryFullProcessImageName( SafeObjectHandle hProcess, QueryFullProcessImageNameFlags dwFlags, StringBuilder lpExeName, @@ -921,7 +921,7 @@ bool InvokeQueryFullProcessImageName( /// /// If the function succeeds, the return value is an open handle to the specified process. [System.Runtime.CompilerServices.CompilerGenerated] - SafeObjectHandle InvokeOpenProcess( + SafeObjectHandle OpenProcess( ProcessAccess dwDesiredAccess, bool bInheritHandle, uint dwProcessId); @@ -979,7 +979,7 @@ SafeObjectHandle InvokeOpenProcess( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeGetOverlappedResult( + unsafe bool GetOverlappedResult( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped, out uint lpNumberOfBytesTransferred, @@ -1020,7 +1020,7 @@ unsafe bool InvokeGetOverlappedResult( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeCancelIo(SafeObjectHandle hFile); + bool CancelIo(SafeObjectHandle hFile); /// /// Determines whether the specified process is running under WOW64 (x86 emulator that allows 32-bit Windows-based @@ -1047,7 +1047,7 @@ unsafe bool InvokeGetOverlappedResult( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process); + bool IsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process); /// /// Creates an anonymous pipe, and returns handles to the read and write ends of the pipe. @@ -1070,7 +1070,7 @@ unsafe bool InvokeGetOverlappedResult( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeCreatePipe( + bool CreatePipe( out SafeObjectHandle hReadPipe, out SafeObjectHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, diff --git a/src/Kernel32.Desktop/Kernel32.Desktop.csproj b/src/Kernel32.Desktop/Kernel32.Desktop.csproj index 8360c4fd..53225954 100644 --- a/src/Kernel32.Desktop/Kernel32.Desktop.csproj +++ b/src/Kernel32.Desktop/Kernel32.Desktop.csproj @@ -28,7 +28,7 @@ - + diff --git a/src/Kernel32.Desktop/Kernel32Mockable.cs b/src/Kernel32.Desktop/Kernel32Mockable.cs index 142f248f..fa61b026 100644 --- a/src/Kernel32.Desktop/Kernel32Mockable.cs +++ b/src/Kernel32.Desktop/Kernel32Mockable.cs @@ -9,7 +9,7 @@ namespace PInvoke using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; [System.Runtime.CompilerServices.CompilerGenerated] - public class Kernel32Mockable : IKernel32Mockable { + 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. @@ -43,7 +43,7 @@ public class Kernel32Mockable : IKernel32Mockable { /// 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 InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags) + 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); /// @@ -91,7 +91,7 @@ public SafeFindFilesHandle InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_ /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments) + 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); /// @@ -99,14 +99,14 @@ public int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint /// /// The thread identifier of the calling thread. [System.Runtime.CompilerServices.CompilerGenerated] - public uint InvokeGetCurrentThreadId() + 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 InvokeGetCurrentProcessId() + public uint GetCurrentProcessId() => GetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. @@ -133,7 +133,7 @@ public uint InvokeGetCurrentProcessId() /// /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeObjectHandle InvokeGetCurrentProcess() + public SafeObjectHandle GetCurrentProcess() => GetCurrentProcess(); /// @@ -168,7 +168,7 @@ public SafeObjectHandle InvokeGetCurrentProcess() /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeCancelIoEx( + unsafe public bool CancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped) => CancelIoEx(hFile, lpOverlapped); @@ -234,7 +234,7 @@ unsafe public bool InvokeCancelIoEx( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeReadFile( + unsafe public bool ReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -311,7 +311,7 @@ unsafe public bool InvokeReadFile( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeWriteFile( + unsafe public bool WriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -331,7 +331,7 @@ unsafe public bool InvokeWriteFile( /// 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 InvokeSuspendThread(SafeObjectHandle hThread) + public int SuspendThread(SafeObjectHandle hThread) => SuspendThread(hThread); /// @@ -345,7 +345,7 @@ public int InvokeSuspendThread(SafeObjectHandle hThread) /// 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 InvokeWow64SuspendThread(SafeObjectHandle hThread) + public int Wow64SuspendThread(SafeObjectHandle hThread) => Wow64SuspendThread(hThread); /// @@ -360,7 +360,7 @@ public int InvokeWow64SuspendThread(SafeObjectHandle hThread) /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public int InvokeResumeThread(SafeObjectHandle hThread) + public int ResumeThread(SafeObjectHandle hThread) => ResumeThread(hThread); /// @@ -380,7 +380,7 @@ public int InvokeResumeThread(SafeObjectHandle hThread) /// 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 InvokeWaitForSingleObject( + public WaitForSingleObjectResult WaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds) => WaitForSingleObject(hHandle, dwMilliseconds); @@ -394,7 +394,7 @@ public WaitForSingleObjectResult InvokeWaitForSingleObject( /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeCloseHandle(IntPtr hObject) + 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. @@ -458,7 +458,7 @@ public bool InvokeCloseHandle(IntPtr hObject) /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeCreateProcess( + public bool CreateProcess( string lpApplicationName, string lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, @@ -539,7 +539,7 @@ public bool InvokeCreateProcess( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeCreateProcessAsUser( + public bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, @@ -563,7 +563,7 @@ public bool InvokeCreateProcessAsUser( /// This function does not return a value, and does not fail. /// [System.Runtime.CompilerServices.CompilerGenerated] - public void InvokeGetStartupInfo( + public void GetStartupInfo( out STARTUPINFO lpStartupInfo) => GetStartupInfo(out lpStartupInfo); @@ -592,7 +592,7 @@ public void InvokeGetStartupInfo( /// When you have finished using the list, call the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeInitializeProcThreadAttributeList( + public bool InitializeProcThreadAttributeList( IntPtr lpAttributeList, uint dwAttributeCount, uint dwFlags, @@ -626,7 +626,7 @@ public bool InvokeInitializeProcThreadAttributeList( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeUpdateProcThreadAttribute( + public bool UpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, ref uint Attribute, @@ -643,7 +643,7 @@ public bool InvokeUpdateProcThreadAttribute( /// The attribute list. This list is created by the function. /// [System.Runtime.CompilerServices.CompilerGenerated] - public void InvokeDeleteProcThreadAttributeList( + public void DeleteProcThreadAttributeList( IntPtr lpAttributeList) => DeleteProcThreadAttributeList(lpAttributeList); @@ -655,7 +655,7 @@ public void InvokeDeleteProcThreadAttributeList( /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeAllocConsole() + public bool AllocConsole() => AllocConsole(); /// @@ -666,7 +666,7 @@ public bool InvokeAllocConsole() /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeFreeConsole() + public bool FreeConsole() => FreeConsole(); /// @@ -682,7 +682,7 @@ public bool InvokeFreeConsole() /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeAttachConsole(uint dwProcessId) + public bool AttachConsole(uint dwProcessId) => AttachConsole(dwProcessId); /// @@ -740,7 +740,7 @@ public bool InvokeAttachConsole(uint dwProcessId) /// If the function fails, the return value is INVALID_HANDLE_VALUE.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeObjectHandle InvokeCreateFile( + public SafeObjectHandle CreateFile( string filename, FileAccess access, FileShare share, @@ -768,7 +768,7 @@ public SafeObjectHandle InvokeCreateFile( /// If the function fails because no matching files can be found, the function returns ERROR_FILE_NOT_FOUND. /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) + public SafeFindFilesHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData) => FindFirstFile(lpFileName, out lpFindFileData); /// @@ -782,7 +782,7 @@ public SafeFindFilesHandle InvokeFindFirstFile(string lpFileName, out WIN32_FIND /// 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 InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) + public bool FindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DATA lpFindFileData) => FindNextFile(hFindFile, out lpFindFileData); /// @@ -850,7 +850,7 @@ public bool InvokeFindNextFile(SafeFindFilesHandle hFindFile, out WIN32_FIND_DAT /// /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeObjectHandle InvokeCreateToolhelp32Snapshot( + public SafeObjectHandle CreateToolhelp32Snapshot( CreateToolhelp32SnapshotFlags dwFlags, uint th32ProcessID) => CreateToolhelp32Snapshot(dwFlags, th32ProcessID); @@ -871,7 +871,7 @@ public SafeObjectHandle InvokeCreateToolhelp32Snapshot( /// information. /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) + public bool Process32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) => Process32First(hSnapshot, lppe); /// Retrieves information about the next process recorded in a system snapshot. @@ -892,7 +892,7 @@ public bool InvokeProcess32First(SafeObjectHandle hSnapshot, [In, Out] PROCESSEN /// function. /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeProcess32Next( + public bool Process32Next( SafeObjectHandle hSnapshot, [In, Out] PROCESSENTRY32 lppe) => Process32Next(hSnapshot, lppe); @@ -915,7 +915,7 @@ public bool InvokeProcess32Next( /// /// Minimum OS: Windows Vista / Windows Server 2008. [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeQueryFullProcessImageName( + public bool QueryFullProcessImageName( SafeObjectHandle hProcess, QueryFullProcessImageNameFlags dwFlags, StringBuilder lpExeName, @@ -950,7 +950,7 @@ public bool InvokeQueryFullProcessImageName( /// /// If the function succeeds, the return value is an open handle to the specified process. [System.Runtime.CompilerServices.CompilerGenerated] - public SafeObjectHandle InvokeOpenProcess( + public SafeObjectHandle OpenProcess( ProcessAccess dwDesiredAccess, bool bInheritHandle, uint dwProcessId) @@ -1009,7 +1009,7 @@ public SafeObjectHandle InvokeOpenProcess( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeGetOverlappedResult( + unsafe public bool GetOverlappedResult( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped, out uint lpNumberOfBytesTransferred, @@ -1051,7 +1051,7 @@ unsafe public bool InvokeGetOverlappedResult( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeCancelIo(SafeObjectHandle hFile) + public bool CancelIo(SafeObjectHandle hFile) => CancelIo(hFile); /// @@ -1079,7 +1079,7 @@ public bool InvokeCancelIo(SafeObjectHandle hFile) /// /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) + public bool IsWow64Process(SafeObjectHandle hProcess, out bool Wow64Process) => IsWow64Process(hProcess, out Wow64Process); /// @@ -1103,7 +1103,7 @@ public bool InvokeIsWow64Process(SafeObjectHandle hProcess, out bool Wow64Proces /// If the function fails, the return value is zero. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeCreatePipe( + public bool CreatePipe( out SafeObjectHandle hReadPipe, out SafeObjectHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, diff --git a/src/Kernel32/IKernel32Mockable.cs b/src/Kernel32/IKernel32.cs similarity index 96% rename from src/Kernel32/IKernel32Mockable.cs rename to src/Kernel32/IKernel32.cs index 833321dc..81ce35bb 100644 --- a/src/Kernel32/IKernel32Mockable.cs +++ b/src/Kernel32/IKernel32.cs @@ -9,7 +9,7 @@ namespace PInvoke using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IKernel32Mockable { + 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. @@ -43,7 +43,7 @@ public interface IKernel32Mockable { /// 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 InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags); + 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. @@ -90,20 +90,20 @@ public interface IKernel32Mockable { /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments); + 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 InvokeGetCurrentThreadId(); + 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 InvokeGetCurrentProcessId(); + uint GetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. /// The return value is a pseudo handle to the current process. @@ -129,7 +129,7 @@ public interface IKernel32Mockable { /// /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeObjectHandle InvokeGetCurrentProcess(); + SafeObjectHandle GetCurrentProcess(); /// /// Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations @@ -163,7 +163,7 @@ public interface IKernel32Mockable { /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeCancelIoEx( + unsafe bool CancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped); @@ -228,7 +228,7 @@ unsafe bool InvokeCancelIoEx( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeReadFile( + unsafe bool ReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -304,7 +304,7 @@ unsafe bool InvokeReadFile( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe bool InvokeWriteFile( + unsafe bool WriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -323,7 +323,7 @@ unsafe bool InvokeWriteFile( /// 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 InvokeSuspendThread(SafeObjectHandle hThread); + int SuspendThread(SafeObjectHandle hThread); /// /// Suspends the specified WOW64 thread. @@ -336,7 +336,7 @@ unsafe bool InvokeWriteFile( /// 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 InvokeWow64SuspendThread(SafeObjectHandle hThread); + 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. @@ -350,7 +350,7 @@ unsafe bool InvokeWriteFile( /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeResumeThread(SafeObjectHandle hThread); + int ResumeThread(SafeObjectHandle hThread); /// /// Waits until the specified object is in the signaled state or the time-out interval elapses. @@ -369,7 +369,7 @@ unsafe bool InvokeWriteFile( /// 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 InvokeWaitForSingleObject( + WaitForSingleObjectResult WaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds); @@ -382,6 +382,6 @@ WaitForSingleObjectResult InvokeWaitForSingleObject( /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeCloseHandle(IntPtr hObject); + bool CloseHandle(IntPtr hObject); } } diff --git a/src/Kernel32/Kernel32.csproj b/src/Kernel32/Kernel32.csproj index 43c30b0a..117672ee 100644 --- a/src/Kernel32/Kernel32.csproj +++ b/src/Kernel32/Kernel32.csproj @@ -23,7 +23,7 @@ - + diff --git a/src/Kernel32/Kernel32Mockable.cs b/src/Kernel32/Kernel32Mockable.cs index 19dfdb09..4dbef8d0 100644 --- a/src/Kernel32/Kernel32Mockable.cs +++ b/src/Kernel32/Kernel32Mockable.cs @@ -9,7 +9,7 @@ namespace PInvoke using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using static Kernel32; [System.Runtime.CompilerServices.CompilerGenerated] - public class Kernel32Mockable : IKernel32Mockable { + 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. @@ -43,7 +43,7 @@ public class Kernel32Mockable : IKernel32Mockable { /// 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 InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, FindFirstFileExFlags dwAdditionalFlags) + 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); /// @@ -91,7 +91,7 @@ public SafeFindFilesHandle InvokeFindFirstFileEx(string lpFileName, FINDEX_INFO_ /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr[] Arguments) + 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); /// @@ -99,14 +99,14 @@ public int InvokeFormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint /// /// The thread identifier of the calling thread. [System.Runtime.CompilerServices.CompilerGenerated] - public uint InvokeGetCurrentThreadId() + 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 InvokeGetCurrentProcessId() + public uint GetCurrentProcessId() => GetCurrentProcessId(); /// Retrieves a pseudo handle for the current process. @@ -133,7 +133,7 @@ public uint InvokeGetCurrentProcessId() /// /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeObjectHandle InvokeGetCurrentProcess() + public SafeObjectHandle GetCurrentProcess() => GetCurrentProcess(); /// @@ -168,7 +168,7 @@ public SafeObjectHandle InvokeGetCurrentProcess() /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeCancelIoEx( + unsafe public bool CancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped) => CancelIoEx(hFile, lpOverlapped); @@ -234,7 +234,7 @@ unsafe public bool InvokeCancelIoEx( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeReadFile( + unsafe public bool ReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, @@ -311,7 +311,7 @@ unsafe public bool InvokeReadFile( /// /// [System.Runtime.CompilerServices.CompilerGenerated] - unsafe public bool InvokeWriteFile( + unsafe public bool WriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, @@ -331,7 +331,7 @@ unsafe public bool InvokeWriteFile( /// 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 InvokeSuspendThread(SafeObjectHandle hThread) + public int SuspendThread(SafeObjectHandle hThread) => SuspendThread(hThread); /// @@ -345,7 +345,7 @@ public int InvokeSuspendThread(SafeObjectHandle hThread) /// 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 InvokeWow64SuspendThread(SafeObjectHandle hThread) + public int Wow64SuspendThread(SafeObjectHandle hThread) => Wow64SuspendThread(hThread); /// @@ -360,7 +360,7 @@ public int InvokeWow64SuspendThread(SafeObjectHandle hThread) /// If the function fails, the return value is (DWORD) -1. To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public int InvokeResumeThread(SafeObjectHandle hThread) + public int ResumeThread(SafeObjectHandle hThread) => ResumeThread(hThread); /// @@ -380,7 +380,7 @@ public int InvokeResumeThread(SafeObjectHandle hThread) /// 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 InvokeWaitForSingleObject( + public WaitForSingleObjectResult WaitForSingleObject( SafeHandle hHandle, uint dwMilliseconds) => WaitForSingleObject(hHandle, dwMilliseconds); @@ -394,7 +394,7 @@ public WaitForSingleObjectResult InvokeWaitForSingleObject( /// If the function fails, the return value is zero.To get extended error information, call . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeCloseHandle(IntPtr hObject) + public bool CloseHandle(IntPtr hObject) => CloseHandle(hObject); } } diff --git a/src/MockGenerator/Program.cs b/src/MockGenerator/Program.cs index 596f060e..aef35dfe 100644 --- a/src/MockGenerator/Program.cs +++ b/src/MockGenerator/Program.cs @@ -119,7 +119,7 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec } var newInterfaceModifier = - SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}Mockable"); + SyntaxFactory.IdentifierName($"I{classDeclaration.Identifier.Text}"); var newClassModifier = SyntaxFactory.IdentifierName($"{classDeclaration.Identifier.Text}Mockable"); PrepareClassCacheEntry(newClassModifier, classDeclaration, newInterfaceModifier); @@ -166,7 +166,7 @@ private static void ProcessSourceCodes(ref Solution solution, ref Project projec CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) .AddMembers(newClassDeclaration) .ToFullString()); - AddPathToProject(ref solution, ref project, $"I{baseFileName}Mockable.cs", + AddPathToProject(ref solution, ref project, $"I{baseFileName}.cs", CreateNewEmptyNamespaceDeclaration(namespaceDeclaration, usings) .AddMembers(newInterfaceDeclaration) .ToFullString()); @@ -208,7 +208,6 @@ private static void PrepareInterfaceCacheEntry(IdentifierNameSyntax newInterface GetCompilerGeneratedAttribute() .WithTrailingTrivia( NewLineCharacter, - TabCharacter, TabCharacter) }), SyntaxFactory.TokenList( @@ -243,10 +242,7 @@ private static void PrepareClassCacheEntry(IdentifierNameSyntax newClassModifier NewLineCharacter, TabCharacter) }), - SyntaxFactory.TokenList( - SyntaxFactory - .Token(SyntaxKind.PublicKeyword) - .WithTrailingTrivia(WhitespaceCharacter)), + SyntaxFactory.TokenList(), newClassModifier.Identifier .WithTrailingTrivia(WhitespaceCharacter) .WithLeadingTrivia(WhitespaceCharacter), diff --git a/src/NCrypt/INCryptMockable.cs b/src/NCrypt/INCrypt.cs similarity index 96% rename from src/NCrypt/INCryptMockable.cs rename to src/NCrypt/INCrypt.cs index c4eeaa1d..1ade8118 100644 --- a/src/NCrypt/INCryptMockable.cs +++ b/src/NCrypt/INCrypt.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static NCrypt; [System.Runtime.CompilerServices.CompilerGenerated] - public interface INCryptMockable { /// + public interface INCrypt { /// /// Loads and initializes a CNG key storage provider. /// /// @@ -19,7 +19,7 @@ public interface INCryptMockable { /// /// 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 InvokeNCryptOpenStorageProvider( + SECURITY_STATUS NCryptOpenStorageProvider( out SafeProviderHandle phProvider, string pszProviderName, NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None); @@ -45,7 +45,7 @@ SECURITY_STATUS InvokeNCryptOpenStorageProvider( /// 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 InvokeNCryptCreatePersistedKey( + SECURITY_STATUS NCryptCreatePersistedKey( SafeProviderHandle hProvider, out SafeKeyHandle phKey, string pszAlgId, @@ -64,7 +64,7 @@ SECURITY_STATUS InvokeNCryptCreatePersistedKey( /// /// Returns a status code that indicates the success or failure of the function. [System.Runtime.CompilerServices.CompilerGenerated] - SECURITY_STATUS InvokeNCryptFinalizeKey( + SECURITY_STATUS NCryptFinalizeKey( SafeKeyHandle hKey, NCryptFinalizeKeyFlags dwFlags = NCryptFinalizeKeyFlags.None); @@ -91,7 +91,7 @@ SECURITY_STATUS InvokeNCryptFinalizeKey( /// Flags that modify function behavior. /// Returns a status code that indicates the success or failure of the function. [System.Runtime.CompilerServices.CompilerGenerated] - SECURITY_STATUS InvokeNCryptGetProperty( + SECURITY_STATUS NCryptGetProperty( SafeHandle hObject, string pszProperty, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, @@ -115,7 +115,7 @@ SECURITY_STATUS InvokeNCryptGetProperty( /// Flags that modify function behavior. /// Returns a status code that indicates the success or failure of the function. [System.Runtime.CompilerServices.CompilerGenerated] - SECURITY_STATUS InvokeNCryptSetProperty( + SECURITY_STATUS NCryptSetProperty( SafeHandle hObject, string pszProperty, byte[] pbInput, diff --git a/src/NCrypt/NCrypt.csproj b/src/NCrypt/NCrypt.csproj index 4ff0bd16..381dffb7 100644 --- a/src/NCrypt/NCrypt.csproj +++ b/src/NCrypt/NCrypt.csproj @@ -23,7 +23,7 @@ - + diff --git a/src/NCrypt/NCryptMockable.cs b/src/NCrypt/NCryptMockable.cs index af5fa6dd..512a0fef 100644 --- a/src/NCrypt/NCryptMockable.cs +++ b/src/NCrypt/NCryptMockable.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static NCrypt; [System.Runtime.CompilerServices.CompilerGenerated] - public class NCryptMockable : INCryptMockable { /// + class NCryptMockable : INCrypt { /// /// Loads and initializes a CNG key storage provider. /// /// @@ -19,7 +19,7 @@ public class NCryptMockable : INCryptMockable { /// /// 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 InvokeNCryptOpenStorageProvider( + public SECURITY_STATUS NCryptOpenStorageProvider( out SafeProviderHandle phProvider, string pszProviderName, NCryptOpenStorageProviderFlags dwFlags = NCryptOpenStorageProviderFlags.None) @@ -46,7 +46,7 @@ public SECURITY_STATUS InvokeNCryptOpenStorageProvider( /// 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 InvokeNCryptCreatePersistedKey( + public SECURITY_STATUS NCryptCreatePersistedKey( SafeProviderHandle hProvider, out SafeKeyHandle phKey, string pszAlgId, @@ -66,7 +66,7 @@ public SECURITY_STATUS InvokeNCryptCreatePersistedKey( /// /// Returns a status code that indicates the success or failure of the function. [System.Runtime.CompilerServices.CompilerGenerated] - public SECURITY_STATUS InvokeNCryptFinalizeKey( + public SECURITY_STATUS NCryptFinalizeKey( SafeKeyHandle hKey, NCryptFinalizeKeyFlags dwFlags = NCryptFinalizeKeyFlags.None) => NCryptFinalizeKey(hKey, dwFlags ); @@ -94,7 +94,7 @@ public SECURITY_STATUS InvokeNCryptFinalizeKey( /// 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 InvokeNCryptGetProperty( + public SECURITY_STATUS NCryptGetProperty( SafeHandle hObject, string pszProperty, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] pbOutput, @@ -119,7 +119,7 @@ public SECURITY_STATUS InvokeNCryptGetProperty( /// 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 InvokeNCryptSetProperty( + public SECURITY_STATUS NCryptSetProperty( SafeHandle hObject, string pszProperty, byte[] pbInput, diff --git a/src/SetupApi.Desktop/ISetupApiMockable.cs b/src/SetupApi.Desktop/ISetupApi.cs similarity index 97% rename from src/SetupApi.Desktop/ISetupApiMockable.cs rename to src/SetupApi.Desktop/ISetupApi.cs index b521fd3b..70cfff1d 100644 --- a/src/SetupApi.Desktop/ISetupApiMockable.cs +++ b/src/SetupApi.Desktop/ISetupApi.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static SetupApi; [System.Runtime.CompilerServices.CompilerGenerated] - public interface ISetupApiMockable { /// + public interface ISetupApi { /// /// The SetupDiGetClassDevs function returns a handle to a device information set /// that contains requested device information elements for a local computer. /// @@ -49,7 +49,7 @@ public interface ISetupApiMockable { /// /// installed devices that matched the supplied parameters. If the operation fails, the function returns an invalid handle. /// [System.Runtime.CompilerServices.CompilerGenerated] - SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( + SafeDeviceInfoSetHandle SetupDiGetClassDevs( NullableGuid classGuid, string enumerator, IntPtr hwndParent, @@ -93,7 +93,7 @@ SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( /// . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeSetupDiEnumDeviceInterfaces( + bool SetupDiEnumDeviceInterfaces( SafeDeviceInfoSetHandle deviceInfoSet, DeviceInfoData deviceInfoData, ref Guid interfaceClassGuid, @@ -141,7 +141,7 @@ bool InvokeSetupDiEnumDeviceInterfaces( /// . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeSetupDiGetDeviceInterfaceDetail( + bool SetupDiGetDeviceInterfaceDetail( SafeDeviceInfoSetHandle deviceInfoSet, ref DeviceInterfaceData deviceInterfaceData, IntPtr deviceInterfaceDetailData, @@ -168,7 +168,7 @@ bool InvokeSetupDiGetDeviceInterfaceDetail( /// . /// [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeSetupDiEnumDeviceInfo( + bool SetupDiEnumDeviceInfo( SafeDeviceInfoSetHandle deviceInfoSet, uint memberIndex, DeviceInfoData deviceInfoData); diff --git a/src/SetupApi.Desktop/SetupApi.Desktop.csproj b/src/SetupApi.Desktop/SetupApi.Desktop.csproj index 1a42774e..1dbedf75 100644 --- a/src/SetupApi.Desktop/SetupApi.Desktop.csproj +++ b/src/SetupApi.Desktop/SetupApi.Desktop.csproj @@ -38,7 +38,7 @@ - + diff --git a/src/SetupApi.Desktop/SetupApiMockable.cs b/src/SetupApi.Desktop/SetupApiMockable.cs index fc5516c2..f0c3bbf6 100644 --- a/src/SetupApi.Desktop/SetupApiMockable.cs +++ b/src/SetupApi.Desktop/SetupApiMockable.cs @@ -7,7 +7,7 @@ namespace PInvoke using System.Runtime.InteropServices; using static SetupApi; [System.Runtime.CompilerServices.CompilerGenerated] - public class SetupApiMockable : ISetupApiMockable { /// + class SetupApiMockable : ISetupApi { /// /// The SetupDiGetClassDevs function returns a handle to a device information set /// that contains requested device information elements for a local computer. /// @@ -49,7 +49,7 @@ public class SetupApiMockable : ISetupApiMockable { /// /// installed devices that matched the supplied parameters. If the operation fails, the function returns an invalid handle. /// [System.Runtime.CompilerServices.CompilerGenerated] - public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( + public SafeDeviceInfoSetHandle SetupDiGetClassDevs( NullableGuid classGuid, string enumerator, IntPtr hwndParent, @@ -94,7 +94,7 @@ public SafeDeviceInfoSetHandle InvokeSetupDiGetClassDevs( /// . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeSetupDiEnumDeviceInterfaces( + public bool SetupDiEnumDeviceInterfaces( SafeDeviceInfoSetHandle deviceInfoSet, DeviceInfoData deviceInfoData, ref Guid interfaceClassGuid, @@ -143,7 +143,7 @@ public bool InvokeSetupDiEnumDeviceInterfaces( /// . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeSetupDiGetDeviceInterfaceDetail( + public bool SetupDiGetDeviceInterfaceDetail( SafeDeviceInfoSetHandle deviceInfoSet, ref DeviceInterfaceData deviceInterfaceData, IntPtr deviceInterfaceDetailData, @@ -171,7 +171,7 @@ public bool InvokeSetupDiGetDeviceInterfaceDetail( /// . /// [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeSetupDiEnumDeviceInfo( + public bool SetupDiEnumDeviceInfo( SafeDeviceInfoSetHandle deviceInfoSet, uint memberIndex, DeviceInfoData deviceInfoData) diff --git a/src/User32.Desktop/IUser32Mockable.cs b/src/User32.Desktop/IUser32.cs similarity index 66% rename from src/User32.Desktop/IUser32Mockable.cs rename to src/User32.Desktop/IUser32.cs index d8814923..02f1eed8 100644 --- a/src/User32.Desktop/IUser32Mockable.cs +++ b/src/User32.Desktop/IUser32.cs @@ -7,14 +7,14 @@ namespace PInvoke using System.Runtime.InteropServices; using static User32; [System.Runtime.CompilerServices.CompilerGenerated] - public interface IUser32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); + public interface IUser32 { [System.Runtime.CompilerServices.CompilerGenerated] + int SetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong); [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); + int GetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex); [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeSetWindowPos( + bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, @@ -24,22 +24,22 @@ bool InvokeSetWindowPos( SetWindowPosFlags uFlags); [System.Runtime.CompilerServices.CompilerGenerated] - IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent); + IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); [System.Runtime.CompilerServices.CompilerGenerated] - IntPtr InvokeFindWindowEx( + IntPtr FindWindowEx( IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle); [System.Runtime.CompilerServices.CompilerGenerated] - bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); + bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); [System.Runtime.CompilerServices.CompilerGenerated] - IntPtr InvokeGetForegroundWindow(); + IntPtr GetForegroundWindow(); [System.Runtime.CompilerServices.CompilerGenerated] - int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); + 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 a10d221e..832d115a 100644 --- a/src/User32.Desktop/User32.Desktop.csproj +++ b/src/User32.Desktop/User32.Desktop.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/User32.Desktop/User32Mockable.cs b/src/User32.Desktop/User32Mockable.cs index 3bdfec02..cedf25b4 100644 --- a/src/User32.Desktop/User32Mockable.cs +++ b/src/User32.Desktop/User32Mockable.cs @@ -7,16 +7,16 @@ namespace PInvoke using System.Runtime.InteropServices; using static User32; [System.Runtime.CompilerServices.CompilerGenerated] - public class User32Mockable : IUser32Mockable { [System.Runtime.CompilerServices.CompilerGenerated] - public int InvokeSetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex, SetWindowLongFlags dwNewLong) + 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 InvokeGetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) + public int GetWindowLong(IntPtr hWnd, WindowLongIndexFlags nIndex) => GetWindowLong(hWnd, nIndex); [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeSetWindowPos( + public bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, @@ -27,11 +27,11 @@ public bool InvokeSetWindowPos( => SetWindowPos(hWnd, hWndInsertAfter, X, Y, cx, cy, uFlags); [System.Runtime.CompilerServices.CompilerGenerated] - public IntPtr InvokeSetParent(IntPtr hWndChild, IntPtr hWndNewParent) + public IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent) => SetParent(hWndChild, hWndNewParent); [System.Runtime.CompilerServices.CompilerGenerated] - public IntPtr InvokeFindWindowEx( + public IntPtr FindWindowEx( IntPtr parentHandle, IntPtr childAfter, string className, @@ -39,15 +39,15 @@ public IntPtr InvokeFindWindowEx( => FindWindowEx(parentHandle, childAfter, className, windowTitle); [System.Runtime.CompilerServices.CompilerGenerated] - public bool InvokeShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) + public bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow) => ShowWindow(hWnd, nCmdShow); [System.Runtime.CompilerServices.CompilerGenerated] - public IntPtr InvokeGetForegroundWindow() + public IntPtr GetForegroundWindow() => GetForegroundWindow(); [System.Runtime.CompilerServices.CompilerGenerated] - public int InvokeSendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) + public int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam) => SendMessage(hWnd, wMsg, wParam, lParam); } }