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

Fix S2589 FP: Unsigned number doubling by adding with itself inside while loop #9184

Open
MineCake147E opened this issue Apr 23, 2024 · 1 comment
Labels
Area: CFG/SE CFG and SE related issues. Type: False Positive Rule IS triggered when it shouldn't be.

Comments

@MineCake147E
Copy link

Description

S2589 is being reported when using unsigned x += x.

Repro steps

public static void UIntPtrS2589FalsePositive()
{
    nuint u = 1;
    while (u > 0)   // noncompliant FP
    {
        u += u;     // this addition could overflow to 0
    }
}

public static void UInt64S2589FalsePositive()
{
    ulong u = 1;
    while (u > 0)   // noncompliant FP
    {
        u += u;     // this addition could overflow to 0
    }
}

public static void UInt32S2589FalsePositive()
{
    uint u = 1;
    while (u > 0)   // noncompliant FP
    {
        u += u;     // this addition could overflow to 0
    }
}

Expected behavior

No issue should be found.

Actual behavior

u > 0 gets S2589

Known workarounds

Use either u *= 2; or u <<= 1; instead of u += u;.

Related information

  • SonarLint for Visual Studio 2022 7.8.0.88494
  • Microsoft Visual Studio Community 2022 (64-bit) - Preview Version 17.10.0 Preview 4.0
  • dotnet 8.0.300-preview.24203.14
  • Operating System: Windows 11 Home 22H2 22621.3447
@MineCake147E MineCake147E changed the title Fix S2589 FP/FN: Unsigned number doubling by adding with itself inside while loop Fix S2589 FP: Unsigned number doubling by adding with itself inside while loop Apr 23, 2024
@martin-strecker-sonarsource
Copy link
Contributor

Hello @MineCake147E, thank you for bringing this issue to our attention. Upon investigation, I can confirm that it is a false positive. I have added a reproducer in #9192 to document this. S2589 is designed not to consider overflows intentionally (otherwise, we would miss a lot of true positives).

However, we should respect unchecked statements/expressions. By adding unchecked in your examples, the code becomes clearer and more intentional.

Unfortunately, we are not taking unchecked into account yet, but I have added this issue to our backlog for future implementation.

@martin-strecker-sonarsource martin-strecker-sonarsource added Type: False Positive Rule IS triggered when it shouldn't be. Area: CFG/SE CFG and SE related issues. labels Apr 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: CFG/SE CFG and SE related issues. Type: False Positive Rule IS triggered when it shouldn't be.
Projects
None yet
Development

No branches or pull requests

2 participants