zstd icon indicating copy to clipboard operation
zstd copied to clipboard

Possible division by zero in zstdcli_trace.c

Open Aruise opened this issue 8 months ago • 5 comments

Hi,

In function TRACE_log 'duration' is received from function ZSTD_trace_compress_end, which states that it could be zero

Which leads to a possible division by zero bug

void ZSTD_trace_compress_end(ZSTD_TraceCtx ctx, ZSTD_Trace const* trace)
{
    PTime const beginNanos = (PTime)ctx;
    PTime const endNanos = UTIL_clockSpanNano(g_enableTime);
    PTime const durationNanos = endNanos > beginNanos ? endNanos - beginNanos : 0;
    assert(g_traceFile != NULL);
    assert(trace->version == ZSTD_VERSION_NUMBER); /* CLI version must match. */
    TRACE_log("compress", durationNanos, trace);
}

PTime const durationNanos = endNanos > beginNanos ? endNanos - beginNanos : 0; states that 'durationNanos' will be either 'endNanos - beginNanos', if 'endNanos' is bigger, or zero otherwise

Next this function calls TRACE_log("compress", durationNanos, trace);

In TRACE_log, further, it passed to a equation, where possibly division by zero happens

static void TRACE_log(char const* method, PTime duration, ZSTD_Trace const* trace)
{
    int level = 0;
    int workers = 0;
    double const ratio = (double)trace->uncompressedSize / (double)trace->compressedSize;
    double const speed = ((double)trace->uncompressedSize * 1000) / (double)duration;
    if (trace->params) {
...

double const speed = ((double)trace->uncompressedSize * 1000) / (double)duration; here, if 'durationNanos' was zero, will be a division by zero

Same with ZSTD_trace_decompress_end

Aruise avatar Apr 17 '25 09:04 Aruise

Thanks for the report @Aruise! Looks like a bug. It will only be triggered if the user passes --trace on the command line, which I don't expect many people are doing, so the impact should be quite limited.

terrelln avatar Apr 17 '25 20:04 terrelln

Hey, I'm interested in working on this issue. Would it be okay if I take it?"

Mrigankkh avatar Apr 27 '25 22:04 Mrigankkh

@Mrigankkh absolutely!

terrelln avatar Apr 30 '25 23:04 terrelln

Awesome! On it!

Mrigankkh avatar Apr 30 '25 23:04 Mrigankkh

Created a Pull Request for the Bug Fix: https://github.com/facebook/zstd/pull/4379

Mrigankkh avatar May 01 '25 01:05 Mrigankkh