calculator icon indicating copy to clipboard operation
calculator copied to clipboard

Integer overflow in negation in ratpowi32()

Open divVerent opened this issue 2 months ago • 5 comments

Describe the bug Some integer a^b operations can crash calc due to exhaustion of stack space.

Steps To Reproduce

  1. Launch calc
  2. Switch to scientific mode
  3. Type in: (-1)^(-2^31)=

Expected behavior Output should be 1.

Device and Application Information

  • OS Build: 10.0.26100.0
  • Architecture: X64
  • Application Version: 11.2607.0.0
  • Region: en-US
  • Dev Version Installed: False

Additional context

Event log excerpt:

Faulting application name: CalculatorApp.exe, version: 11.2607.0.0, time stamp: 0x6a736ec2
Faulting module name: SharedLibrary.dll, version: 2.2.29512.0, time stamp: 0x5fad1a6e
Exception code: 0x00001007
Fault offset: 0x00000000007e38de

Bug is here:

https://github.com/microsoft/calculator/blob/4fd3fc53bade573ea2ac1e1ebad9bf603713f85e/src/CalcManager/Ratpack/conv.cpp#L1507

When power is INT_MIN, negating it results in INT_MIN again, thus still negative, recursing endlessly.

Requested Assignment I'm just reporting this problem. I don't want to fix it.

divVerent avatar Sep 16 '26 08:09 divVerent

Bug is shared with old calc (win32calc.exe).

divVerent avatar Sep 18 '26 10:09 divVerent

I'd like to fix this. I've confirmed the root cause the issue describes and have a fix ready - https://github.com/microsoft/calculator/pull/2512

amitdey1987 avatar Oct 01 '26 07:10 amitdey1987

2 sentences? No, exactly 2 sentences):* "Since INT_MIN is `-21

emmettmorin avatar Oct 03 '26 18:10 emmettmorin

To prevent the infinite recursion, we should handle INT_MIN by casting the negation to a larger type or using an explicit conditional check before calling ratpowi32 recursively in conv.cpp.

heenll68 avatar Oct 05 '26 19:10 heenll68

To be honest, my recommendation would be making an inner function that uses an uint32_t exponent, and an outer function that checks sign, converts to uint32_t, calls the inner function, and possibly inverts.

Also, it may be worth considering if calculating a^-b as 1/(a^b) is optimal, or if (1/a)^b should be done instead, as that'd be a tail call. Not sure which works better precision-wise though in this library.

divVerent avatar Oct 18 '26 12:10 divVerent