#1057344 libgmp10: major formatted output function bug with %c and the value 0

Package:
libgmp10
Source:
libgmp10
Description:
Multiprecision arithmetic library
Submitter:
Vincent Lefevre
Date:
2023-12-15 03:12:03 UTC
Severity:
normal
Tags:
#1057344#5
Date:
2023-12-03 20:10:39 UTC
From:
To:
I've reported the following bug upstream. Debian/stable is affected
(at least on the testcase below, but the various issues are probably
related).

With GMP 6.3.0, the formatted output functions do not handle %c
with the value 0 correctly. For gmp_sprintf, the return value is
incorrect. For gmp_asprintf and gmp_vasprintf, this is either a
buffer overflow (according to the GMP manual: "The block will be
the size of the string and null-terminator.") or, in case this
is an error in the GMP manual, possible memory corruption when
freeing the allocated memory, if the custom memory allocation
function cares about the size parameter.

Testcase for gmp_sprintf:
------------------------------------------------------------
#include <stdio.h>
#include <gmp.h>

static void test (int flag)
{
  char s[3] = { 1, 1, 1 };
  int r;

  r = (flag ? sprintf : gmp_sprintf) (s, "%c", 0);
  printf ("%4s: r = %d, s = { %d %d %d }\n",
          flag ? "libc" : "gmp", r, s[0], s[1], s[2]);
}

int main (void)
{
  test (0);
  test (1);
  return 0;
}
------------------------------------------------------------

which currently gives:

 gmp: r = 0, s = { 0 0 1 }
libc: r = 1, s = { 0 0 1 }

MPFR has various issues concerning %c with the value 0, but an
attempt to fix them fails due to

  length = gmp_vasprintf (...);
[...]
  mpfr_free_str (s);

which is similar to GMP's tests/misc/t-printf.c file, which contains

  got_len = gmp_vasprintf (&got, fmt, ap);
[...]
  (*__gmp_free_func) (got, strlen(got)+1);

But replacing

  mpfr_free_str (s);

by

  mpfr_free_func (s, length + 1);

i.e. using the return value length instead of strlen(s), also fails.
I suppose that this is related to the incorrect return value.

#1057344#10
Date:
2023-12-15 01:50:21 UTC
From:
To:
severity 1057344 normal
thanks

I understand the bug may have severe consequences but it doesn't appear to
rise to the level of grave in my opinion.

#1057344#13
Date:
2023-12-15 01:50:21 UTC
From:
To:
severity 1057344 normal
thanks

I understand the bug may have severe consequences but it doesn't appear to
rise to the level of grave in my opinion.