Skip to content

Fix possible 32-bit integer overflow in TSC to time base calculations (timer.c and related areas) #448

@travisg

Description

@travisg

There may be a risk of 32-bit integer overflow during the calculation and conversion of TSC (Time Stamp Counter) to time base values in platform/pc/timer.c and potentially other related areas. Specifically, the use of 32-bit math for ratios, multiplications, or divisions involving TSC frequency and time base (e.g., fp_32_64_div_32_32, u32_mul_u64_fp32_64, etc.) could lead to incorrect results or undefined behavior when TSC frequencies are high (as is common on modern hardware).

How to reproduce/observe:

  • Review the usage of 32-bit types and calculations in the following code sections:
    • fp_32_64_div_32_32(&tsc_to_timebase, 1000, tsc_hz);
    • u32_mul_u64_fp32_64(__builtin_ia32_rdtsc(), tsc_to_timebase);
    • Any other related timer math in timer.c or similar files.
  • Consider scenarios where tsc_hz exceeds the 32-bit range or where large TSC values are multiplied/divided.

Expected behavior:

  • Calculations should use 64-bit safe math where appropriate, and conversions should be robust even on systems with very high TSC frequencies.

Suggested fix:

  • Audit timer math to ensure all multiplications and divisions that could overflow 32 bits are done with 64-bit types.
  • Add tests or asserts to detect potential overflows.
  • Update fixed-point and conversion helpers if needed.

Files to check:

  • platform/pc/timer.c
  • Any other files where TSC/time base math is performed.

References:

  • See code comments regarding TSC calibration and conversions.
  • Modern x86 CPUs with high TSC frequencies that may trigger the issue.

This issue is for correctness and forward compatibility with modern hardware.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions