1
0
mirror of https://sourceware.org/git/glibc.git synced 2025-07-29 11:41:21 +03:00

Set behavior of sprintf-like functions with overlapping source and destination

According to ISO C99, passing the same buffer as source and destination
to sprintf, snprintf, vsprintf, or vsnprintf has undefined behavior.
Until the commit

  commit 4e2f43f842
  Author: Zack Weinberg <zackw@panix.com>
  Date:   Wed Mar 7 14:32:03 2018 -0500

      Use PRINTF_FORTIFY instead of _IO_FLAGS2_FORTIFY (bug 11319)

a call to sprintf or vsprintf with overlapping buffers, for instance
vsprintf (buf, "%sTEXT", buf), would append `TEXT' into buf, while a
call to snprintf or vsnprintf would override the contents of buf.
After the aforementioned commit, the behavior of sprintf and vsprintf
changed (so that they also override the contents of buf).

This patch reverts this behavioral change, because it will likely break
applications that rely on the previous behavior, even though it is
undefined by ISO C.  As noted by Szabolcs Nagy, this is used in SPEC2017
507.cactuBSSN_r/src/PUGH/PughUtils.c:

  sprintf(mess,"  Size:");
  for (i=0;i<dim+1;i++)
  {
      sprintf(mess,"%s %d",mess,pughGH->GFExtras[dim]->nsize[i]);
  }

More important to notice is the fact that the overwriting of the
destination buffer is not the only behavior affected by the refactoring.
Before the refactoring, sprintf and vsprintf would use _IO_str_jumps,
whereas __sprintf_chk and __vsprintf_chk would use _IO_str_chk_jumps.
After the refactoring, all use _IO_str_chk_jumps, which would make
sprintf and vsprintf report buffer overflows and terminate the program.
This patch also reverts this behavior, by installing the appropriate
jump table for each *sprintf functions.

Apart from reverting the changes, this patch adds a test case that has
the old behavior hardcoded, so that regressions are noticed if something
else unintentionally changes the behavior.

Tested for powerpc64le.
This commit is contained in:
Gabriel F. T. Gomes
2018-12-19 18:01:14 -02:00
parent d5c6df0b0e
commit 2d9837c1fb
8 changed files with 149 additions and 4 deletions

View File

@ -77,8 +77,18 @@ __vsprintf_internal (char *string, size_t maxlen,
sf._sbf._f._lock = NULL;
#endif
_IO_no_init (&sf._sbf._f, _IO_USER_LOCK, -1, NULL, NULL);
_IO_JUMPS (&sf._sbf) = &_IO_str_chk_jumps;
string[0] = '\0';
/* When called from fortified sprintf/vsprintf, erase the destination
buffer and try to detect overflows. When called from regular
sprintf/vsprintf, do not erase the destination buffer, because
known user code relies on this behavior (even though its undefined
by ISO C), nor try to detect overflows. */
if ((mode_flags & PRINTF_CHK) != 0)
{
_IO_JUMPS (&sf._sbf) = &_IO_str_chk_jumps;
string[0] = '\0';
}
else
_IO_JUMPS (&sf._sbf) = &_IO_str_jumps;
_IO_str_init_static_internal (&sf, string,
(maxlen == -1) ? -1 : maxlen - 1,
string);