Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect and report suspicious characters in NativeMethods.txt #548

Merged
merged 1 commit into from
May 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/Microsoft.Windows.CsWin32/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,30 @@ group method by GetClassNameForModule(entry.Key) into x

private string DebuggerDisplayString => $"Generator: {this.InputAssemblyName}";

/// <summary>
/// Tests whether a string contains characters that do not belong in an API name.
/// </summary>
/// <param name="apiName">The user-supplied string that was expected to match some API name.</param>
/// <returns><see langword="true"/> if the string contains characters that are likely mistakenly included and causing a mismatch; <see langword="false"/> otherwise.</returns>
public static bool ContainsIllegalCharactersForAPIName(string apiName)
{
for (int i = 0; i < apiName.Length; i++)
{
char ch = apiName[i];
bool allowed = false;
allowed |= char.IsLetterOrDigit(ch);
allowed |= ch == '_';
allowed |= ch == '.'; // for qualified name searches

if (!allowed)
{
return true;
}
}

return false;
}

/// <inheritdoc/>
public void Dispose()
{
Expand Down
13 changes: 12 additions & 1 deletion src/Microsoft.Windows.CsWin32/SourceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ public class SourceGenerator : ISourceGenerator
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public static readonly DiagnosticDescriptor NoMatchingMethodOrTypeWithBadCharacters = new DiagnosticDescriptor(
"PInvoke001",
"No matching method, type or constant found",
"Method, type or constant \"{0}\" not found. It contains unexpected characters, possibly including invisible characters, which can happen when copying and pasting from docs.microsoft.com among other places. Try deleting the line and retyping it.",
"Functionality",
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public static readonly DiagnosticDescriptor NoMatchingMethodOrTypeWithSuggestions = new DiagnosticDescriptor(
"PInvoke001",
"No matching method, type or constant found",
Expand Down Expand Up @@ -315,7 +323,10 @@ void ReportNoMatch(Location? location, string failedAttempt)
}
else
{
context.ReportDiagnostic(Diagnostic.Create(NoMatchingMethodOrType, location, failedAttempt));
context.ReportDiagnostic(Diagnostic.Create(
Generator.ContainsIllegalCharactersForAPIName(failedAttempt) ? NoMatchingMethodOrTypeWithBadCharacters : NoMatchingMethodOrType,
location,
failedAttempt));
}
}
}
Expand Down
58 changes: 58 additions & 0 deletions test/Microsoft.Windows.CsWin32.Tests/GeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -2500,6 +2501,63 @@ public void OpensMetadataForSharedReading()
Assert.True(this.generator.TryGenerate("CreateFile", CancellationToken.None));
}

[Fact]
public void ContainsIllegalCharactersForAPIName_InvisibleCharacters()
{
// You can't see them, but there are invisible hyphens in this name.
// Copy-paste from docs.microsoft.com has been known to include these invisible characters and break matching in NativeMethods.txt.
Assert.True(Generator.ContainsIllegalCharactersForAPIName("SHGet­Known­Folder­Item"));
}

[Fact]
public void ContainsIllegalCharactersForAPIName_DisallowedVisibleCharacters()
{
Assert.True(Generator.ContainsIllegalCharactersForAPIName("Method-1"));
}

[Fact]
public void ContainsIllegalCharactersForAPIName_LegalNames()
{
Assert.False(Generator.ContainsIllegalCharactersForAPIName("SHGetKnownFolderItem"));
Assert.False(Generator.ContainsIllegalCharactersForAPIName("Method1"));
Assert.False(Generator.ContainsIllegalCharactersForAPIName("Method_1"));
Assert.False(Generator.ContainsIllegalCharactersForAPIName("Qualified.Name"));
}

[Fact]
public void ContainsIllegalCharactersForAPIName_AllActualAPINames()
{
using FileStream metadataStream = File.OpenRead(MetadataPath);
using System.Reflection.PortableExecutable.PEReader peReader = new(metadataStream);
MetadataReader metadataReader = peReader.GetMetadataReader();
foreach (MethodDefinitionHandle methodDefHandle in metadataReader.MethodDefinitions)
{
MethodDefinition methodDef = metadataReader.GetMethodDefinition(methodDefHandle);
string methodName = metadataReader.GetString(methodDef.Name);
Assert.False(Generator.ContainsIllegalCharactersForAPIName(methodName), methodName);
}

foreach (TypeDefinitionHandle typeDefHandle in metadataReader.TypeDefinitions)
{
TypeDefinition typeDef = metadataReader.GetTypeDefinition(typeDefHandle);
string typeName = metadataReader.GetString(typeDef.Name);
if (typeName == "<Module>")
{
// Skip this special one.
continue;
}

Assert.False(Generator.ContainsIllegalCharactersForAPIName(typeName), typeName);
}

foreach (FieldDefinitionHandle fieldDefHandle in metadataReader.FieldDefinitions)
{
FieldDefinition fieldDef = metadataReader.GetFieldDefinition(fieldDefHandle);
string fieldName = metadataReader.GetString(fieldDef.Name);
Assert.False(Generator.ContainsIllegalCharactersForAPIName(fieldName), fieldName);
}
}

private static string ConstructGlobalConfigString(bool omitDocs = false)
{
StringBuilder globalConfigBuilder = new();
Expand Down