From nobody Tue Oct 7 21:23:40 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EDE6023B63A; Sat, 5 Jul 2025 20:33:51 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751747632; cv=none; b=oqtEOLNpCkbhpAvo1cXbnZpkOcgNV9oLKRnNvNjMMIi3sIuk8Q9ZHrzmgKUU1PqHAXJvfDSpqJrpD9OQNuoY4j0mD8c9Rpa4AH0tBA713hsZ/mADK1Kb6OE9BKW2nYfm8m+eK7X3rLKTyUwBhivGp1hq33LrZwRJ7ZSIHoMiDVc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751747632; c=relaxed/simple; bh=c7Bo2eDkD0F/AkM6BOw7KB8MLG0DrouzGLLc8l13biQ=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=r09/dtt7L1LDIE+zPtGpFw9WkhWaZEj3epUYlDnH6LuLmjtrl+SbzRE6u1XY6VTYzww0b6iYqEBjksK1ekASovl8HlMxbCU/57DRcrF0inN4IDFOIl+wcAoBBxSQV0oQZTe9q40/m4Z4ZpTG4hpe1ZA+jzQj1p2gEGFDHeIYnfw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=O5hbx9w9; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="O5hbx9w9" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 91627C4CEED; Sat, 5 Jul 2025 20:33:50 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1751747631; bh=c7Bo2eDkD0F/AkM6BOw7KB8MLG0DrouzGLLc8l13biQ=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=O5hbx9w97+zyL6YBKFfr9nF1GPnuY/5ukMqCyyRIsPrABCtwHhVPAN/DnV2u6c+32 xW0bHiikiwyJy6yvZefvbyxFRSAlii1ZZ5DcZ7TvOFWMiNYWFs3YWfFTs9ctbxrLQ4 i2zJ6myUejCOyNYQokLo05iwY3fC4MG64DZVHzQfhDMNIzHds+LfSkTvWbZocOTwfZ Cwlfe3KkuQbIYiKAqFHQBk6H8OzM+HYxCfBugJn6+Cu534Kh+7NumcgA4GDuom7cHt UV3jYy5PerDxlbSeUx35OvGQM9tVypdyOEQlp76wRC4BI3oLy4nxOIxrdp5ct+ybWG Rk9LjLniHg0rA== Date: Sat, 5 Jul 2025 22:33:49 +0200 From: Alejandro Colomar To: linux-mm@kvack.org, linux-hardening@vger.kernel.org Cc: Alejandro Colomar , Kees Cook , Christopher Bazley , shadow <~hallyn/shadow@lists.sr.ht>, linux-kernel@vger.kernel.org, Andrew Morton , kasan-dev@googlegroups.com, Dmitry Vyukov , Alexander Potapenko , Marco Elver , Christoph Lameter , David Rientjes , Vlastimil Babka , Roman Gushchin , Harry Yoo Subject: [RFC v1 1/3] vsprintf: Add [v]seprintf(), [v]stprintf() Message-ID: <2d20eaf1752efefcc23d0e7c5c2311dd5ae252af.1751747518.git.alx@kernel.org> X-Mailer: git-send-email 2.50.0 References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Disposition: inline In-Reply-To: Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" seprintf() =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D seprintf() is a function similar to stpcpy(3) in the sense that it returns a pointer that is suitable for chaining to other copy operations. It takes a pointer to the end of the buffer as a sentinel for when to truncate, which unlike a size, doesn't need to be updated after every call. This makes it much more ergonomic, avoiding manually calculating the size after each copy, which is error prone. It also makes error handling much easier, by reporting truncation with a null pointer, which is accepted and transparently passed down by subsequent seprintf() calls. This results in only needing to report errors once after a chain of seprintf() calls, unlike snprintf(3), which requires checking after every call. p =3D buf; e =3D buf + countof(buf); p =3D seprintf(p, e, foo); p =3D seprintf(p, e, bar); if (p =3D=3D NULL) goto trunc; vs len =3D 0; size =3D countof(buf); len +=3D snprintf(buf + len, size - len, foo); if (len >=3D size) goto trunc; len +=3D snprintf(buf + len, size - len, bar); if (len >=3D size) goto trunc; And also better than scnprintf() calls: len =3D 0; size =3D countof(buf); len +=3D scnprintf(buf + len, size - len, foo); len +=3D scnprintf(buf + len, size - len, bar); if (len >=3D size) goto trunc; It seems aparent that it's a more elegant approach to string catenation. stprintf() =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D stprintf() is a helper that is needed for implementing seprintf() --although it could be open-coded within vseprintf(), of course--, but it's also useful by itself. It has the same interface properties as strscpy(): that is, it copies with truncation, and reports truncation with -E2BIG. It would be useful to replace some calls to snprintf(3) and scnprintf() which don't need chaining, and where it's simpler to pass a size. It is better than plain snprintf(3), because it results in simpler error detection (it doesn't need a check >=3Dcountof(buf), but rather <0). Cc: Kees Cook Cc: Christopher Bazley Signed-off-by: Alejandro Colomar --- lib/vsprintf.c | 109 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/lib/vsprintf.c b/lib/vsprintf.c index 01699852f30c..a3efacadb5e5 100644 --- a/lib/vsprintf.c +++ b/lib/vsprintf.c @@ -2892,6 +2892,37 @@ int vsnprintf(char *buf, size_t size, const char *fm= t_str, va_list args) } EXPORT_SYMBOL(vsnprintf); =20 +/** + * vstprintf - Format a string and place it in a buffer + * @buf: The buffer to place the result into + * @size: The size of the buffer, including the trailing null space + * @fmt: The format string to use + * @args: Arguments for the format string + * + * The return value is the length of the new string. + * If the string is truncated, the function returns -E2BIG. + * + * If you're not already dealing with a va_list consider using stprintf(). + * + * See the vsnprintf() documentation for format string extensions over C99. + */ +int vstprintf(char *buf, size_t size, const char *fmt, va_list args) +{ + int len; + + len =3D vsnprintf(buf, size, fmt, args); + + // It seems the kernel's vsnprintf() doesn't fail? + //if (unlikely(len < 0)) + // return -E2BIG; + + if (unlikely(len >=3D size)) + return -E2BIG; + + return len; +} +EXPORT_SYMBOL(vstprintf); + /** * vscnprintf - Format a string and place it in a buffer * @buf: The buffer to place the result into @@ -2923,6 +2954,36 @@ int vscnprintf(char *buf, size_t size, const char *f= mt, va_list args) } EXPORT_SYMBOL(vscnprintf); =20 +/** + * vseprintf - Format a string and place it in a buffer + * @p: The buffer to place the result into + * @end: A pointer to one past the last character in the buffer + * @fmt: The format string to use + * @args: Arguments for the format string + * + * The return value is a pointer to the trailing '\0'. + * If @p is NULL, the function returns NULL. + * If the string is truncated, the function returns NULL. + * + * If you're not already dealing with a va_list consider using seprintf(). + * + * See the vsnprintf() documentation for format string extensions over C99. + */ +char *vseprintf(char *p, const char end[0], const char *fmt, va_list args) +{ + int len; + + if (unlikely(p =3D=3D NULL)) + return NULL; + + len =3D vstprintf(p, end - p, fmt, args); + if (unlikely(len < 0)) + return NULL; + + return p + len; +} +EXPORT_SYMBOL(vseprintf); + /** * snprintf - Format a string and place it in a buffer * @buf: The buffer to place the result into @@ -2950,6 +3011,30 @@ int snprintf(char *buf, size_t size, const char *fmt= , ...) } EXPORT_SYMBOL(snprintf); =20 +/** + * stprintf - Format a string and place it in a buffer + * @buf: The buffer to place the result into + * @size: The size of the buffer, including the trailing null space + * @fmt: The format string to use + * @...: Arguments for the format string + * + * The return value is the length of the new string. + * If the string is truncated, the function returns -E2BIG. + */ + +int stprintf(char *buf, size_t size, const char *fmt, ...) +{ + va_list args; + int len; + + va_start(args, fmt); + len =3D vstprintf(buf, size, fmt, args); + va_end(args); + + return len; +} +EXPORT_SYMBOL(stprintf); + /** * scnprintf - Format a string and place it in a buffer * @buf: The buffer to place the result into @@ -2974,6 +3059,30 @@ int scnprintf(char *buf, size_t size, const char *fm= t, ...) } EXPORT_SYMBOL(scnprintf); =20 +/** + * seprintf - Format a string and place it in a buffer + * @p: The buffer to place the result into + * @end: A pointer to one past the last character in the buffer + * @fmt: The format string to use + * @...: Arguments for the format string + * + * The return value is a pointer to the trailing '\0'. + * If @buf is NULL, the function returns NULL. + * If the string is truncated, the function returns NULL. + */ + +char *seprintf(char *p, const char end[0], const char *fmt, ...) +{ + va_list args; + + va_start(args, fmt); + p =3D vseprintf(p, end, fmt, args); + va_end(args); + + return p; +} +EXPORT_SYMBOL(seprintf); + /** * vsprintf - Format a string and place it in a buffer * @buf: The buffer to place the result into --=20 2.50.0 From nobody Tue Oct 7 21:23:40 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EDA85242D97; Sat, 5 Jul 2025 20:33:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751747634; cv=none; b=FPtR/qsFRfYLhwzWrsPcoesa85hDmQHxVHJ74bPuRytEtmlRJySD1XQPVQvqjNBNnH7WmjJaVukNi9CB6PiuGKVT+B35VukC4X3dEcBMttu+YxFdA2FvTiFYL2dOl8mieRX++sW6Up4NJrGUMyrgDLdMWiW4mnw9/jtFa6w5x+s= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751747634; c=relaxed/simple; bh=E6qxb2TT4uMSovjaBjyMjuMigA4rgXTycVqc1w44q/I=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=TogwyFrH/UESrkHc8PfhIi4uKbAOhlkwCXnvMcS7A/X74/wk/GKYY+k3YjrGtSYy+OcN0PfepmDKEUmkkC4ldLkdvaXahBkscRtuwhAC3doyM2KrqlYoZfb4UdEIxoJVN/fH4AQ/graq8c0U8V/oaLskw5jJxcdnSBCM6Ug3uUw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Dh1NQMIe; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Dh1NQMIe" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9B287C4CEED; Sat, 5 Jul 2025 20:33:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1751747633; bh=E6qxb2TT4uMSovjaBjyMjuMigA4rgXTycVqc1w44q/I=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=Dh1NQMIeos18mmb6bY+28BAts5KBo82AirvGqy2ye0JnT9SGtElTW1I6jeyw/4LYD 8D4GTjmGepTrj95fC/S+Po6xpfZva+HtuP+knmg0CntC7w6/AIURe7D/DlN3Y7T+Xh xvE9FMl81Ce+6GO3vky2ZBPVaibFhYqshISvcnA2AC6KL8ujXnknLXMHw2Xo7lnwpp Eo4wIgniW4hC942CH9k+pq68ZLY/0gRFdsWRXtv18Yqo4lHk5wNOhv3UKsWylPVHI+ D88xhZDquGL/6TESiVBoeMfX4VZVwHEoIbIAusdOlB1y7HIbrOL/y/Ln+b+5xKMtEu 8nI1VyiG2czyA== Date: Sat, 5 Jul 2025 22:33:51 +0200 From: Alejandro Colomar To: linux-mm@kvack.org, linux-hardening@vger.kernel.org Cc: Alejandro Colomar , Kees Cook , Christopher Bazley , shadow <~hallyn/shadow@lists.sr.ht>, linux-kernel@vger.kernel.org, Andrew Morton , kasan-dev@googlegroups.com, Dmitry Vyukov , Alexander Potapenko , Marco Elver , Christoph Lameter , David Rientjes , Vlastimil Babka , Roman Gushchin , Harry Yoo Subject: [RFC v1 2/3] stacktrace, stackdepot: Add seprintf()-like variants of functions Message-ID: X-Mailer: git-send-email 2.50.0 References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Disposition: inline In-Reply-To: Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" I think there's an anomaly in stack_depot_s*print(). If we have zero entries, we don't copy anything, which means the string is still not a string. Normally, this function is called surrounded by other calls to s*printf(), which guarantee that there's a '\0', but maybe we should make sure to write a '\0' here? Cc: Kees Cook Cc: Christopher Bazley Signed-off-by: Alejandro Colomar --- include/linux/stackdepot.h | 13 +++++++++++++ include/linux/stacktrace.h | 3 +++ kernel/stacktrace.c | 28 ++++++++++++++++++++++++++++ lib/stackdepot.c | 12 ++++++++++++ 4 files changed, 56 insertions(+) diff --git a/include/linux/stackdepot.h b/include/linux/stackdepot.h index 2cc21ffcdaf9..a7749fc3ac7c 100644 --- a/include/linux/stackdepot.h +++ b/include/linux/stackdepot.h @@ -219,6 +219,19 @@ void stack_depot_print(depot_stack_handle_t stack); int stack_depot_snprint(depot_stack_handle_t handle, char *buf, size_t siz= e, int spaces); =20 +/** + * stack_depot_seprint - Print a stack trace from stack depot into a buffer + * + * @handle: Stack depot handle returned from stack_depot_save() + * @p: Pointer to the print buffer + * @end: Pointer to one past the last element in the buffer + * @spaces: Number of leading spaces to print + * + * Return: Pointer to trailing '\0'; or NULL on truncation + */ +char *stack_depot_seprint(depot_stack_handle_t handle, char *p, + const char end[0], int spaces); + /** * stack_depot_put - Drop a reference to a stack trace from stack depot * diff --git a/include/linux/stacktrace.h b/include/linux/stacktrace.h index 97455880ac41..748936386c89 100644 --- a/include/linux/stacktrace.h +++ b/include/linux/stacktrace.h @@ -67,6 +67,9 @@ void stack_trace_print(const unsigned long *trace, unsign= ed int nr_entries, int spaces); int stack_trace_snprint(char *buf, size_t size, const unsigned long *entri= es, unsigned int nr_entries, int spaces); +char *stack_trace_seprint(char *p, const char end[0], + const unsigned long *entries, unsigned int nr_entries, + int spaces); unsigned int stack_trace_save(unsigned long *store, unsigned int size, unsigned int skipnr); unsigned int stack_trace_save_tsk(struct task_struct *task, diff --git a/kernel/stacktrace.c b/kernel/stacktrace.c index afb3c116da91..65caf9e63673 100644 --- a/kernel/stacktrace.c +++ b/kernel/stacktrace.c @@ -70,6 +70,34 @@ int stack_trace_snprint(char *buf, size_t size, const un= signed long *entries, } EXPORT_SYMBOL_GPL(stack_trace_snprint); =20 +/** + * stack_trace_seprint - Print the entries in the stack trace into a buffer + * @p: Pointer to the print buffer + * @end: Pointer to one past the last element in the buffer + * @entries: Pointer to storage array + * @nr_entries: Number of entries in the storage array + * @spaces: Number of leading spaces to print + * + * Return: Pointer to the trailing '\0'; or NULL on truncation. + */ +char *stack_trace_seprint(char *p, const char end[0], + const unsigned long *entries, unsigned int nr_entries, + int spaces) +{ + unsigned int i; + + if (WARN_ON(!entries)) + return 0; + + for (i =3D 0; i < nr_entries; i++) { + p =3D seprintf(p, end, "%*c%pS\n", 1 + spaces, ' ', + (void *)entries[i]); + } + + return p; +} +EXPORT_SYMBOL_GPL(stack_trace_seprint); + #ifdef CONFIG_ARCH_STACKWALK =20 struct stacktrace_cookie { diff --git a/lib/stackdepot.c b/lib/stackdepot.c index 73d7b50924ef..a61903040724 100644 --- a/lib/stackdepot.c +++ b/lib/stackdepot.c @@ -771,6 +771,18 @@ int stack_depot_snprint(depot_stack_handle_t handle, c= har *buf, size_t size, } EXPORT_SYMBOL_GPL(stack_depot_snprint); =20 +char *stack_depot_seprint(depot_stack_handle_t handle, char *p, + const char end[0], int spaces) +{ + unsigned long *entries; + unsigned int nr_entries; + + nr_entries =3D stack_depot_fetch(handle, &entries); + return nr_entries ? stack_trace_seprint(p, e, entries, nr_entries, + spaces) : p; +} +EXPORT_SYMBOL_GPL(stack_depot_seprint); + depot_stack_handle_t __must_check stack_depot_set_extra_bits( depot_stack_handle_t handle, unsigned int extra_bits) { --=20 2.50.0 From nobody Tue Oct 7 21:23:40 2025 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 46071211A3F; Sat, 5 Jul 2025 20:33:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751747636; cv=none; b=pKyxGusOzc34R+DAZuaFKuTryQlRp45+j99Aw3fW4G8EPDkyIXUskYd7bK1ZSdF8COqMii+nOwaVs0AGEUSn/2eK4e3gOFcczWSZF9tXwMxweIJaFNdnfIbSv86RrVjPhp5cPhVbdDqBZ3rOqBxix/J/xNoTMTVfZEqlfln57rQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751747636; c=relaxed/simple; bh=GJ/5VUMCSvyaJvDw2jTAUB+TVwoxvpKqQaf73jDQdi4=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=INfH2AjSyWujMX2TKRdBoEpJh8bm3PvOsSLlBLiJCx7yrrAsN9jhyEOemBol9rJUJl6lUKsJXvdXHRu4KfvBoy6P/y+TLZ27+0ZHDy7Srs6cdWgqi66hCQYk5OCv4LkGqt+nBg1+zhGvNav0YrgqIAEpeSAmQipr0OzMOn2hyxQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=hyxkMuLH; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="hyxkMuLH" Received: by smtp.kernel.org (Postfix) with ESMTPSA id B311BC4CEF2; Sat, 5 Jul 2025 20:33:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1751747635; bh=GJ/5VUMCSvyaJvDw2jTAUB+TVwoxvpKqQaf73jDQdi4=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=hyxkMuLH6q67TcM3jeXMoxP4XpsNnF6y+uBWtIf6fyyo+ALKJl6Gc/+2PckC+TYjI ygU0sE53zsuqL+TK+K/cP9TRPigq09xqW2uNlQyCarbEsJYXNh0GaPR5eYghS+xvuW yoQ5YSZvYwF0crxbcODpEEI1jSGAOkG+tuxMig10261JWOlJZ6FFoSSGnT8nsX0Zre YwXb7RXeF6wQANB/Rt2gej5bdzjVqizEe5KNgPXbuVuynHFJFql8kWK1TniRhdc7h2 5IEvSAW5o+w6OJGrOwZpz8MlYZ5eEbdDl17s+7uL/7f9hKypTQXPfYqHTBwabfupc5 5y+R+JKKAJehQ== Date: Sat, 5 Jul 2025 22:33:53 +0200 From: Alejandro Colomar To: linux-mm@kvack.org, linux-hardening@vger.kernel.org Cc: Alejandro Colomar , Kees Cook , Christopher Bazley , shadow <~hallyn/shadow@lists.sr.ht>, linux-kernel@vger.kernel.org, Andrew Morton , kasan-dev@googlegroups.com, Dmitry Vyukov , Alexander Potapenko , Marco Elver , Christoph Lameter , David Rientjes , Vlastimil Babka , Roman Gushchin , Harry Yoo Subject: [RFC v1 3/3] mm: Use seprintf() instead of less ergonomic APIs Message-ID: X-Mailer: git-send-email 2.50.0 References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Disposition: inline In-Reply-To: Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" While doing this, I detected some anomalies in the existing code: mm/kfence/kfence_test.c: The last call to scnprintf() did increment 'cur', but it's unused after that, so it was dead code. I've removed the dead code in this patch. mm/mempolicy.c: This file uses the 'p +=3D snprintf()' anti-pattern. That will overflow the pointer on truncation, which has undefined behavior. Using seprintf(), this bug is fixed. As in the previous file, here there was also dead code in the last scnprintf() call, by incrementing a pointer that is not used after the call. I've removed the dead code. mm/page_owner.c: Within print_page_owner(), there are some calls to scnprintf(), which do report truncation. And then there are other calls to snprintf(), where we handle errors (there are two 'goto err'). I've kept the existing error handling, as I trust it's there for a good reason (i.e., we may want to avoid calling print_page_owner_memcg() if we truncated before). Please review if this amount of error handling is the right one, or if we want to add or remove some. For seprintf(), a single test for null after the last call is enough to detect truncation. mm/slub.c: Again, the 'p +=3D snprintf()' anti-pattern. This is UB, and by using seprintf() we've fixed the bug. Cc: Kees Cook Cc: Christopher Bazley Signed-off-by: Alejandro Colomar --- mm/kfence/kfence_test.c | 24 ++++++++++++------------ mm/kmsan/kmsan_test.c | 4 ++-- mm/mempolicy.c | 18 +++++++++--------- mm/page_owner.c | 32 +++++++++++++++++--------------- mm/slub.c | 5 +++-- 5 files changed, 43 insertions(+), 40 deletions(-) diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c index 00034e37bc9f..ff734c514c03 100644 --- a/mm/kfence/kfence_test.c +++ b/mm/kfence/kfence_test.c @@ -113,26 +113,26 @@ static bool report_matches(const struct expect_report= *r) end =3D &expect[0][sizeof(expect[0]) - 1]; switch (r->type) { case KFENCE_ERROR_OOB: - cur +=3D scnprintf(cur, end - cur, "BUG: KFENCE: out-of-bounds %s", + cur =3D seprintf(cur, end, "BUG: KFENCE: out-of-bounds %s", get_access_type(r)); break; case KFENCE_ERROR_UAF: - cur +=3D scnprintf(cur, end - cur, "BUG: KFENCE: use-after-free %s", + cur =3D seprintf(cur, end, "BUG: KFENCE: use-after-free %s", get_access_type(r)); break; case KFENCE_ERROR_CORRUPTION: - cur +=3D scnprintf(cur, end - cur, "BUG: KFENCE: memory corruption"); + cur =3D seprintf(cur, end, "BUG: KFENCE: memory corruption"); break; case KFENCE_ERROR_INVALID: - cur +=3D scnprintf(cur, end - cur, "BUG: KFENCE: invalid %s", + cur =3D seprintf(cur, end, "BUG: KFENCE: invalid %s", get_access_type(r)); break; case KFENCE_ERROR_INVALID_FREE: - cur +=3D scnprintf(cur, end - cur, "BUG: KFENCE: invalid free"); + cur =3D seprintf(cur, end, "BUG: KFENCE: invalid free"); break; } =20 - scnprintf(cur, end - cur, " in %pS", r->fn); + seprintf(cur, end, " in %pS", r->fn); /* The exact offset won't match, remove it; also strip module name. */ cur =3D strchr(expect[0], '+'); if (cur) @@ -144,26 +144,26 @@ static bool report_matches(const struct expect_report= *r) =20 switch (r->type) { case KFENCE_ERROR_OOB: - cur +=3D scnprintf(cur, end - cur, "Out-of-bounds %s at", get_access_typ= e(r)); + cur =3D seprintf(cur, end, "Out-of-bounds %s at", get_access_type(r)); addr =3D arch_kfence_test_address(addr); break; case KFENCE_ERROR_UAF: - cur +=3D scnprintf(cur, end - cur, "Use-after-free %s at", get_access_ty= pe(r)); + cur =3D seprintf(cur, end, "Use-after-free %s at", get_access_type(r)); addr =3D arch_kfence_test_address(addr); break; case KFENCE_ERROR_CORRUPTION: - cur +=3D scnprintf(cur, end - cur, "Corrupted memory at"); + cur =3D seprintf(cur, end, "Corrupted memory at"); break; case KFENCE_ERROR_INVALID: - cur +=3D scnprintf(cur, end - cur, "Invalid %s at", get_access_type(r)); + cur =3D seprintf(cur, end, "Invalid %s at", get_access_type(r)); addr =3D arch_kfence_test_address(addr); break; case KFENCE_ERROR_INVALID_FREE: - cur +=3D scnprintf(cur, end - cur, "Invalid free of"); + cur =3D seprintf(cur, end, "Invalid free of"); break; } =20 - cur +=3D scnprintf(cur, end - cur, " 0x%p", (void *)addr); + seprintf(cur, end, " 0x%p", (void *)addr); =20 spin_lock_irqsave(&observed.lock, flags); if (!report_available()) diff --git a/mm/kmsan/kmsan_test.c b/mm/kmsan/kmsan_test.c index 9733a22c46c1..a062a46b2d24 100644 --- a/mm/kmsan/kmsan_test.c +++ b/mm/kmsan/kmsan_test.c @@ -107,9 +107,9 @@ static bool report_matches(const struct expect_report *= r) cur =3D expected_header; end =3D &expected_header[sizeof(expected_header) - 1]; =20 - cur +=3D scnprintf(cur, end - cur, "BUG: KMSAN: %s", r->error_type); + cur =3D seprintf(cur, end, "BUG: KMSAN: %s", r->error_type); =20 - scnprintf(cur, end - cur, " in %s", r->symbol); + seprintf(cur, end, " in %s", r->symbol); /* The exact offset won't match, remove it; also strip module name. */ cur =3D strchr(expected_header, '+'); if (cur) diff --git a/mm/mempolicy.c b/mm/mempolicy.c index b28a1e6ae096..c696e4a6f4c2 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -3359,6 +3359,7 @@ int mpol_parse_str(char *str, struct mempolicy **mpol) void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol) { char *p =3D buffer; + char *e =3D buffer + maxlen; nodemask_t nodes =3D NODE_MASK_NONE; unsigned short mode =3D MPOL_DEFAULT; unsigned short flags =3D 0; @@ -3384,33 +3385,32 @@ void mpol_to_str(char *buffer, int maxlen, struct m= empolicy *pol) break; default: WARN_ON_ONCE(1); - snprintf(p, maxlen, "unknown"); + seprintf(p, e, "unknown"); return; } =20 - p +=3D snprintf(p, maxlen, "%s", policy_modes[mode]); + p =3D seprintf(p, e, "%s", policy_modes[mode]); =20 if (flags & MPOL_MODE_FLAGS) { - p +=3D snprintf(p, buffer + maxlen - p, "=3D"); + p =3D seprintf(p, e, "=3D"); =20 /* * Static and relative are mutually exclusive. */ if (flags & MPOL_F_STATIC_NODES) - p +=3D snprintf(p, buffer + maxlen - p, "static"); + p =3D seprintf(p, e, "static"); else if (flags & MPOL_F_RELATIVE_NODES) - p +=3D snprintf(p, buffer + maxlen - p, "relative"); + p =3D seprintf(p, e, "relative"); =20 if (flags & MPOL_F_NUMA_BALANCING) { if (!is_power_of_2(flags & MPOL_MODE_FLAGS)) - p +=3D snprintf(p, buffer + maxlen - p, "|"); - p +=3D snprintf(p, buffer + maxlen - p, "balancing"); + p =3D seprintf(p, e, "|"); + p =3D seprintf(p, e, "balancing"); } } =20 if (!nodes_empty(nodes)) - p +=3D scnprintf(p, buffer + maxlen - p, ":%*pbl", - nodemask_pr_args(&nodes)); + seprintf(p, e, ":%*pbl", nodemask_pr_args(&nodes)); } =20 #ifdef CONFIG_SYSFS diff --git a/mm/page_owner.c b/mm/page_owner.c index cc4a6916eec6..5811738e3320 100644 --- a/mm/page_owner.c +++ b/mm/page_owner.c @@ -496,7 +496,7 @@ void pagetypeinfo_showmixedcount_print(struct seq_file = *m, /* * Looking for memcg information and print it out */ -static inline int print_page_owner_memcg(char *kbuf, size_t count, int ret, +static inline char *print_page_owner_memcg(char *p, const char end[0], struct page *page) { #ifdef CONFIG_MEMCG @@ -511,8 +511,7 @@ static inline int print_page_owner_memcg(char *kbuf, si= ze_t count, int ret, goto out_unlock; =20 if (memcg_data & MEMCG_DATA_OBJEXTS) - ret +=3D scnprintf(kbuf + ret, count - ret, - "Slab cache page\n"); + p =3D seprintf(p, end, "Slab cache page\n"); =20 memcg =3D page_memcg_check(page); if (!memcg) @@ -520,7 +519,7 @@ static inline int print_page_owner_memcg(char *kbuf, si= ze_t count, int ret, =20 online =3D (memcg->css.flags & CSS_ONLINE); cgroup_name(memcg->css.cgroup, name, sizeof(name)); - ret +=3D scnprintf(kbuf + ret, count - ret, + p =3D seprintf(p, end, "Charged %sto %smemcg %s\n", PageMemcgKmem(page) ? "(via objcg) " : "", online ? "" : "offline ", @@ -529,7 +528,7 @@ static inline int print_page_owner_memcg(char *kbuf, si= ze_t count, int ret, rcu_read_unlock(); #endif /* CONFIG_MEMCG */ =20 - return ret; + return p; } =20 static ssize_t @@ -538,14 +537,16 @@ print_page_owner(char __user *buf, size_t count, unsi= gned long pfn, depot_stack_handle_t handle) { int ret, pageblock_mt, page_mt; - char *kbuf; + char *kbuf, *p, *e; =20 count =3D min_t(size_t, count, PAGE_SIZE); kbuf =3D kmalloc(count, GFP_KERNEL); if (!kbuf) return -ENOMEM; =20 - ret =3D scnprintf(kbuf, count, + p =3D kbuf; + e =3D kbuf + count; + p =3D seprintf(p, e, "Page allocated via order %u, mask %#x(%pGg), pid %d, tgid %d (%s), ts = %llu ns\n", page_owner->order, page_owner->gfp_mask, &page_owner->gfp_mask, page_owner->pid, @@ -555,7 +556,7 @@ print_page_owner(char __user *buf, size_t count, unsign= ed long pfn, /* Print information relevant to grouping pages by mobility */ pageblock_mt =3D get_pageblock_migratetype(page); page_mt =3D gfp_migratetype(page_owner->gfp_mask); - ret +=3D scnprintf(kbuf + ret, count - ret, + p =3D seprintf(p, e, "PFN 0x%lx type %s Block %lu type %s Flags %pGp\n", pfn, migratetype_names[page_mt], @@ -563,22 +564,23 @@ print_page_owner(char __user *buf, size_t count, unsi= gned long pfn, migratetype_names[pageblock_mt], &page->flags); =20 - ret +=3D stack_depot_snprint(handle, kbuf + ret, count - ret, 0); - if (ret >=3D count) - goto err; + p =3D stack_depot_seprint(handle, p, e, 0); + if (p =3D=3D NULL) + goto err; // XXX: Should we remove this error handling? =20 if (page_owner->last_migrate_reason !=3D -1) { - ret +=3D scnprintf(kbuf + ret, count - ret, + p =3D seprintf(p, e, "Page has been migrated, last migrate reason: %s\n", migrate_reason_names[page_owner->last_migrate_reason]); } =20 - ret =3D print_page_owner_memcg(kbuf, count, ret, page); + p =3D print_page_owner_memcg(p, e, page); =20 - ret +=3D snprintf(kbuf + ret, count - ret, "\n"); - if (ret >=3D count) + p =3D seprintf(p, e, "\n"); + if (p =3D=3D NULL) goto err; =20 + ret =3D p - kbuf; if (copy_to_user(buf, kbuf, ret)) ret =3D -EFAULT; =20 diff --git a/mm/slub.c b/mm/slub.c index be8b09e09d30..b67c6ca0d0f7 100644 --- a/mm/slub.c +++ b/mm/slub.c @@ -7451,6 +7451,7 @@ static char *create_unique_id(struct kmem_cache *s) { char *name =3D kmalloc(ID_STR_LENGTH, GFP_KERNEL); char *p =3D name; + char *e =3D name + ID_STR_LENGTH; =20 if (!name) return ERR_PTR(-ENOMEM); @@ -7475,9 +7476,9 @@ static char *create_unique_id(struct kmem_cache *s) *p++ =3D 'A'; if (p !=3D name + 1) *p++ =3D '-'; - p +=3D snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size); + p =3D seprintf(p, e, "%07u", s->size); =20 - if (WARN_ON(p > name + ID_STR_LENGTH - 1)) { + if (WARN_ON(p =3D=3D NULL)) { kfree(name); return ERR_PTR(-EINVAL); } --=20 2.50.0