Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Date: Thu, 26 Oct 2023 17:56:09 -0700
From: Peter Kasting <pkasting@...gle.com>
To: musl@...ts.openwall.com
Subject: vfprintf(..., "%lc", (wint_t)0) fails to output a \0

(I'm not subscribed here, please CC me on any responses.)

I believe* the following program will fail on musl:

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>

int main() {
  char buf[16];
  memset(buf, 1, 16);
  int len = sprintf(buf, "%lc", (wint_t)0);
  assert(len > 0);
  assert(buf[0] == 0);
  return 0;
}

This should write a \0 to the buffer, but will write nothing.

*I don't have direct access to a musl environment to compile and test the
code above, so this is speculation. I reproduced this bug indirectly via a
Linux Alpine test environment here at Google while trying to make changes
to Abseil's string-handling implementation.

>From code inspection, the problem occurs at
https://git.musl-libc.org/cgit/musl/tree/src/stdio/vfprintf.c#n611. Here
the loop guard tests `*ws` to ensure it stops on null terminators. However,
when we fall through from handling this input case (of "%lc", 0), *ws ==
wc[0] == 0, so wctomb() is never called.

The C99 spec here arguably allows this behavior, but I believe its intent
is to specify the behavior glibc's implementation exhibits (where a 0 is
written). Section 7.19.6.1.8 says regarding %lc, "...the wint_t argument is
converted as if by an ls conversion specification with no precision and an
argument that points to the initial element of a two-element array of
wchar_t, the first element containing the wint_t argument to the lc
conversion specification and the second a null wide character." And
regarding %ls, "...the argument shall be a pointer to the initial element
of an array of wchar_t type. Wide characters from the array are converted
to multibyte characters...up to and including a terminating null wide
character. The resulting multibyte characters are written up to (but not
including) the terminating null character (byte)." One could argue that the
first (zero) element in the array, being a 0, is "a terminating null wide
character" that should be converted to a multibyte character, but
subsequently not written (since the conversion will result in solely a
terminating null character). But it seems like the intent of the spec was
to say that a %lc argument is always converted and written, with the second
array element always treated as "the null terminator". I don't know if
there is further clarifying language/discussion in some mailing list or
archives somewhere.

PK

Content of type "text/html" skipped

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.