SonarSource/sonar-dotnet

Fix S1144 FP: Unused fields in class with StructLayout

Closed this issue · 1 comments

sm-g commented

Description

When class has StructLayout, we need all its props for memory allocation.

Repro steps

For example

public class Foo {

public void Bar(){

  var netResource = new NetResource
  {
                Scope = ResourceScope.GlobalNetwork,
                ResourceType = ResourceType.Disk,
                DisplayType = ResourceDisplaytype.Share,
                RemoteName = "foo"
  };

  _ = WNetAddConnection2(netResource, "pass", "user", 0);

}

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags);

        [StructLayout(LayoutKind.Sequential)]
        private struct NetResource
        {
            public ResourceScope Scope;
            public ResourceType ResourceType;
            public ResourceDisplaytype DisplayType;
            public int Usage;
            public string LocalName;
            public string RemoteName;
            public string Comment;
            public string Provider;
        }
}

Expected behavior

no issue

Actual behavior

S1144 on not used props of NetResource struct

Related information

SonarAnalyzer.CSharp 8.54.0.64047

Thank you @sm-g for reporting. You are right. The usage of the StructLayoutAttribute from the System.Runtime.InteropServices namespace is a strong indicator for interop scenarios. The struct is defined by the external API and can not be changed by you. S1144 should not rise in such a case.

I added the issue to our backlog and you can track any progress by following this issue.