From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S964900AbbJIJPB (ORCPT ); Fri, 9 Oct 2015 05:15:01 -0400 Received: from mail-lb0-f177.google.com ([209.85.217.177]:35117 "EHLO mail-lb0-f177.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1756371AbbJIJO4 (ORCPT ); Fri, 9 Oct 2015 05:14:56 -0400 From: Rasmus Villemoes To: Ingo Molnar Cc: Chris Metcalf , Linus Torvalds , Peter Zijlstra , Rasmus Villemoes , linux-kernel@vger.kernel.org Subject: [RFC 3/3] lib/vsprintf.c: eliminate potential race in string() Date: Fri, 9 Oct 2015 11:14:33 +0200 Message-Id: <1444382073-12139-3-git-send-email-linux@rasmusvillemoes.dk> X-Mailer: git-send-email 2.1.3 In-Reply-To: <87r3l4wgom.fsf_-_@rasmusvillemoes.dk> References: <87r3l4wgom.fsf_-_@rasmusvillemoes.dk> Sender: linux-kernel-owner@vger.kernel.org List-ID: X-Mailing-List: linux-kernel@vger.kernel.org If the string corresponding to a %s specifier can change under us, we might end up copying a \0 byte to the output buffer. There might be callers who expect the output buffer to contain a genuine C string whose length is exactly the snprintf return value (assuming truncation hasn't happened or has been checked for). We can avoid this by only passing over the source string once, stopping the first time we meet a nul byte (or when we reach the given precision), and then letting widen_string() handle left/right space padding. Signed-off-by: Rasmus Villemoes --- lib/vsprintf.c | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/lib/vsprintf.c b/lib/vsprintf.c index acead77594b5..d518849b6b75 100644 --- a/lib/vsprintf.c +++ b/lib/vsprintf.c @@ -557,32 +557,22 @@ char *widen_string(char *buf, int n, char *end, struct printf_spec spec) static noinline_for_stack char *string(char *buf, char *end, const char *s, struct printf_spec spec) { - int len, i; + int len = 0; + size_t lim = spec.precision; if ((unsigned long)s < PAGE_SIZE) s = "(null)"; - len = strnlen(s, spec.precision); - - if (!(spec.flags & LEFT)) { - while (len < spec.field_width--) { - if (buf < end) - *buf = ' '; - ++buf; - } - } - for (i = 0; i < len; ++i) { - if (buf < end) - *buf = *s; - ++buf; ++s; - } - while (len < spec.field_width--) { + while (lim--) { + char c = *s++; + if (!c) + break; if (buf < end) - *buf = ' '; + *buf = c; ++buf; + ++len; } - - return buf; + return widen_string(buf, len, end, spec); } static noinline_for_stack -- 2.1.3