From nobody Sun Feb 8 19:22:04 2026 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 E616827FB21; Thu, 10 Jul 2025 02:48:23 +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=1752115704; cv=none; b=sGTJfeO2hvoaSfJwagOkHeytL1aMD25lsGc4q8IVsjicAWPTaZ0Ncloaxp0ffbxSylKf7b2WFkopryyE+LG0h8htVXjHpnWKFFQvhmxmuwRyW7UMAzX5f0f3zlrlTrgEfRfFYUX1PaIGro4oEzU0F6NwiTqkwWLuiB+LEe4JjTk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115704; c=relaxed/simple; bh=uP1Rd77wxX/Fb6ettFx80wxbqPad+vTShdCzOI/MZqw=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=ixpAuxknoRRZrlQjpKgrx0AHndLgJCil+rgQipazM0xnKhi/5m2ZnieMVZ5zSfDfrlkBUT+pBAqlnR30A3CSaXmA6xy/AD901209MbrI3OObESOWAtv/DgijPsnMI/pa4SKC4x4FV2NX2SsXwNLiwLFEqCCmhKuD7dsOR+UvfFI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=TU/xLkQv; 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="TU/xLkQv" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4C2CBC4CEF0; Thu, 10 Jul 2025 02:48:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115703; bh=uP1Rd77wxX/Fb6ettFx80wxbqPad+vTShdCzOI/MZqw=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=TU/xLkQvOm1nCV8vzE8nPX9PhH8RaLxUabLxCZkndzS2pe7Vb6aZTc1PDHKghXZqX sSskGWf3iDbZMOTJsUXeZi0kGyGP+P46LmKWrGPKbMVh2pnHVPFM/Nay7EZVPg28gH YxRAQ9CL2X2WmqoI0iOgwl5t+Z/LYa7dAexLdTAGwp7hyxnq6ywPt9V9iQ6mobzEYI nv7udlInO0wYjWlvR3u72uHFLx2ohsaPNrI+T5WwB7v4g+u85EmWWriA7lZjPogC4A Zwe2Bh5udiJE8U5S12fUBgEBuBCQ5FUcxGGemgRXmaU3Fqrp9SqZntUiBJ46AWGpGT S5khO3w7DtKfw== Date: Thu, 10 Jul 2025 04:48:11 +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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro , Martin Uecker , Sam James , Andrew Pinski Subject: [RFC v4 1/7] vsprintf: Add [v]sprintf_end() Message-ID: <2c4f793de0b849259088c1f52db44ace5a4e6f66.1752113247.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" sprintf_end() 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 sprintf_end() calls. This results in only needing to report errors once after a chain of sprintf_end() calls, unlike snprintf(3), which requires checking after every call. p =3D buf; e =3D buf + countof(buf); p =3D sprintf_end(p, e, foo); p =3D sprintf_end(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); // No ability to check. It seems aparent that it's a more elegant approach to string catenation. These functions will soon be proposed for standardization as [v]seprintf() into C2y, and they exist in Plan9 as seprint(2) --but the Plan9 implementation has important bugs--. Link: Cc: Kees Cook Cc: Christopher Bazley Cc: Rasmus Villemoes Cc: Marco Elver Cc: Michal Hocko Cc: Linus Torvalds Cc: Al Viro Signed-off-by: Alejandro Colomar --- include/linux/sprintf.h | 2 ++ lib/vsprintf.c | 59 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/include/linux/sprintf.h b/include/linux/sprintf.h index 51cab2def9ec..a0dc35574521 100644 --- a/include/linux/sprintf.h +++ b/include/linux/sprintf.h @@ -13,6 +13,8 @@ __printf(3, 4) int snprintf(char *buf, size_t size, const= char *fmt, ...); __printf(3, 0) int vsnprintf(char *buf, size_t size, const char *fmt, va_l= ist args); __printf(3, 4) int scnprintf(char *buf, size_t size, const char *fmt, ...); __printf(3, 0) int vscnprintf(char *buf, size_t size, const char *fmt, va_= list args); +__printf(3, 4) char *sprintf_end(char *p, const char end[0], const char *f= mt, ...); +__printf(3, 0) char *vsprintf_end(char *p, const char end[0], const char *= fmt, va_list args); __printf(2, 3) __malloc char *kasprintf(gfp_t gfp, const char *fmt, ...); __printf(2, 0) __malloc char *kvasprintf(gfp_t gfp, const char *fmt, va_li= st args); __printf(2, 0) const char *kvasprintf_const(gfp_t gfp, const char *fmt, va= _list args); diff --git a/lib/vsprintf.c b/lib/vsprintf.c index 01699852f30c..d32df53a713a 100644 --- a/lib/vsprintf.c +++ b/lib/vsprintf.c @@ -2923,6 +2923,40 @@ int vscnprintf(char *buf, size_t size, const char *f= mt, va_list args) } EXPORT_SYMBOL(vscnprintf); =20 +/** + * vsprintf_end - va_list string end-delimited print formatted + * @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 @end <=3D @p, the function returns NULL. + * + * See the vsnprintf() documentation for format string extensions over C99. + */ +char *vsprintf_end(char *p, const char end[0], const char *fmt, va_list ar= gs) +{ + int len; + size_t size; + + if (unlikely(p =3D=3D NULL)) + return NULL; + + size =3D end - p; + if (WARN_ON_ONCE(size =3D=3D 0 || size > INT_MAX)) + return NULL; + + len =3D vsnprintf(p, size, fmt, args); + if (unlikely(len >=3D size)) + return NULL; + + return p + len; +} +EXPORT_SYMBOL(vsprintf_end); + /** * snprintf - Format a string and place it in a buffer * @buf: The buffer to place the result into @@ -2974,6 +3008,31 @@ int scnprintf(char *buf, size_t size, const char *fm= t, ...) } EXPORT_SYMBOL(scnprintf); =20 +/** + * sprintf_end - string end-delimited print formatted + * @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. + * If @end <=3D @p, the function returns NULL. + */ + +char *sprintf_end(char *p, const char end[0], const char *fmt, ...) +{ + va_list args; + + va_start(args, fmt); + p =3D vsprintf_end(p, end, fmt, args); + va_end(args); + + return p; +} +EXPORT_SYMBOL(sprintf_end); + /** * vsprintf - Format a string and place it in a buffer * @buf: The buffer to place the result into --=20 2.50.0 From nobody Sun Feb 8 19:22:04 2026 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 B5CFA3208; Thu, 10 Jul 2025 02:48:33 +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=1752115713; cv=none; b=thB5VsVsyTmJAu1WikZdhl1D9MSctsVolKcGtb26t9N+oz7qMXoRxphoW8zv2X6GKCHg1lkg2qXUGIxuLIAW3xzn/dJi3Dpayb+VKUYPxHvfXTTB/dLWXUDo6F0uwUriXnxVemUZX3QSwgTYqIh/fDwLO31TWwHklO+hUUTzmLU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115713; c=relaxed/simple; bh=KFeH759S2pXUEgcinWQTZzWHu8P8w4ivkJjMDXMeyRQ=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=tFP1pZQpJ9AJzI1Zgvqc/Ygwq1ZDQkH3qRvh+8Az3xfwK3EWeW8Jk+bZ4Q6azI/mvFAf8iJxYZtd43SjaWAfqJgd+rOC4PsFyi0HSWEW6Zk42rIHpp+YuuX1/HswzotuGxkKtYG7MWR6dGTv0pm2xwqGFldFFyyn5MyEmDPt3dM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=eZnmLeDy; 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="eZnmLeDy" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2ED4FC4CEEF; Thu, 10 Jul 2025 02:48:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115713; bh=KFeH759S2pXUEgcinWQTZzWHu8P8w4ivkJjMDXMeyRQ=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=eZnmLeDy6ISGhj7UxlzL16OXqtnL01sGVlHeOdJlX0OUfb3Vl8JDoi+of/VZywuuh eA4l+ydES65zs59icoEwIzPa0icurtsUfqRKSm2KuAQf2xF50qR1eN/ev+xt8F9ahJ 9Tsdl+GS29Mv8zVA5i3qb+rp8NWC/cIrbyTvxNs4kJrgFOQYHyYlV4SOxwj8fJV6JA 1kWMJWb04PLyDr7aXahB9NBtLgwR/0ZATlmtNEeG4wc8ntomD0LFS0HspaM9qWAbIJ 9LG7P2Yc+Kp9urBgAuRLebi8OzTHKhyzcYGQ0sHY6uyue/LSIDpH95D6k3zmsTx0we opt3OmQtc3uZg== Date: Thu, 10 Jul 2025 04:48:23 +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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro Subject: [RFC v4 2/7] stacktrace, stackdepot: Add sprintf_end()-like variants of functions Message-ID: <894d02b08056c59b5acb79af73a1a698d56016f5.1752113247.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" Cc: Kees Cook Cc: Christopher Bazley Cc: Rasmus Villemoes Cc: Marco Elver Cc: Michal Hocko Cc: Linus Torvalds Cc: Al Viro Signed-off-by: Alejandro Colomar --- include/linux/stackdepot.h | 13 +++++++++++++ include/linux/stacktrace.h | 3 +++ kernel/stacktrace.c | 28 ++++++++++++++++++++++++++++ lib/stackdepot.c | 13 +++++++++++++ 4 files changed, 57 insertions(+) diff --git a/include/linux/stackdepot.h b/include/linux/stackdepot.h index 2cc21ffcdaf9..76182e874f67 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_sprint_end - Print a stack trace from stack depot into a bu= ffer + * + * @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_sprint_end(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..79ada795d479 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_sprint_end(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..f389647d8e44 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_sprint_end - Print the entries in the stack trace into a bu= ffer + * @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_sprint_end(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 sprintf_end(p, end, "%*c%pS\n", 1 + spaces, ' ', + (void *)entries[i]); + } + + return p; +} +EXPORT_SYMBOL_GPL(stack_trace_sprint_end); + #ifdef CONFIG_ARCH_STACKWALK =20 struct stacktrace_cookie { diff --git a/lib/stackdepot.c b/lib/stackdepot.c index 73d7b50924ef..48e5c0ff37e8 100644 --- a/lib/stackdepot.c +++ b/lib/stackdepot.c @@ -771,6 +771,19 @@ 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_sprint_end(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_sprint_end(p, end, entries, nr_entries, spaces) + : sprintf_end(p, end, ""); +} +EXPORT_SYMBOL_GPL(stack_depot_sprint_end); + 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 Sun Feb 8 19:22:04 2026 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 2094D27FB32; Thu, 10 Jul 2025 02:48:41 +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=1752115722; cv=none; b=d69EZumbekstCNy2Cl9vrG+vxXJjH9eUEZ7sJYclsnLahTo3ttDx1Hj0wKZmavvZFW+RmHzvBxGKd3uAYclE+9cxgLlewnIqCThgFX+HXjx9dHp64EStn7Ao3vzdNKhd+dXVQu0C8KQZqCK84hKoJw6gmDe5BZyk0k8/1zEo5B8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115722; c=relaxed/simple; bh=stTpsWR5B9qnU4lcgeg0tYr2I54PzkVTHHPWz1Iz+X8=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=D9I8hZTewV4UWz/YA8++QXrnoEHbwjA2sfBa9HZFGUMsSA49PjzLDXdiGQbva+9yW2Aoi14yVW2JTuwPwUn2WUrx+KzR/8v31C/T4cA1biDuwNshg3g8/pf1tVxczKpuR/nTPFpIxvzmI4wdhLiJyp0HfwZ6azmGH3rQuZG9OTI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=KoSvo+2s; 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="KoSvo+2s" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A6195C4CEF0; Thu, 10 Jul 2025 02:48:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115721; bh=stTpsWR5B9qnU4lcgeg0tYr2I54PzkVTHHPWz1Iz+X8=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=KoSvo+2sT1U4koTovZAMfUMSVLi1vnofl2Pe/8b524/++AQvOWehbViQ7mBoDMi6r RVHTD4pgVsjuAYLp8ZDZMPfrVpf0zMfObEFYXmzw/Jl8S0h54/T4p+HonmXRMSh/bE axHHEWHeGnwjmIRRZpuUdnSpDQKA+nwiGIKRRCh+zN3kJZRELwhI4yI/nRAiST2roh fhQkgHKzU41pfvsSzIDPKakTat7FffjweX+zM+9F74QQTF6bd7gQ2LPfy4xT484dO3 bm8kqbEjl/QEEpvn89jw5dS33sfX+jZ1sdaXfinLiRLye/UY/Gs+Ko3BGBBByOm5N/ 8/7E5ATQUnzDQ== Date: Thu, 10 Jul 2025 04:48:33 +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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro , Sven Schnelle , Heiko Carstens , Tvrtko Ursulin , Christophe JAILLET , Hyeonggon Yoo <42.hyeyoo@gmail.com>, Chao Yu Subject: [RFC v4 3/7] mm: Use sprintf_end() instead of less ergonomic APIs Message-ID: <690ed4d22f57a4a1f2c72eb659ceb6b7ab3d5f41.1752113247.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" 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. - 'end' is calculated as end =3D &expect[0][sizeof(expect[0] - 1)]; However, the '-1' doesn't seem to be necessary. When passing $2 to scnprintf(), the size was specified as 'end - cur'. And scnprintf() --just like snprintf(3)--, won't write more than $2 bytes (including the null byte). That means that scnprintf() wouldn't write more than &expect[0][sizeof(expect[0]) - 1] - expect[0] which simplifies to sizeof(expect[0]) - 1 bytes. But we have sizeof(expect[0]) bytes available, so we're wasting one byte entirely. This is a benign off-by-one bug. The two occurrences of this bug will be fixed in a following patch in this series. mm/kmsan/kmsan_test.c: The same benign off-by-one bug calculating the remaining size. mm/mempolicy.c: This file uses the 'p +=3D snprintf()' anti-pattern. That will overflow the pointer on truncation, which has undefined behavior. Using sprintf_end(), 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 sprintf_end(), 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 sprintf_end() we've fixed the bug. Cc: Kees Cook Cc: Christopher Bazley Cc: Sven Schnelle Cc: Marco Elver Cc: Heiko Carstens Cc: Tvrtko Ursulin Cc: Andrew Morton Cc: Linus Torvalds Cc: David Rientjes Cc: Christophe JAILLET Cc: Hyeonggon Yoo <42.hyeyoo@gmail.com> Cc: Chao Yu Cc: Vlastimil Babka Cc: Rasmus Villemoes Cc: Michal Hocko Cc: Al Viro 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..bae382eca4ab 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 sprintf_end(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 sprintf_end(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 sprintf_end(cur, end, "BUG: KFENCE: memory corruption"); break; case KFENCE_ERROR_INVALID: - cur +=3D scnprintf(cur, end - cur, "BUG: KFENCE: invalid %s", + cur =3D sprintf_end(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 sprintf_end(cur, end, "BUG: KFENCE: invalid free"); break; } =20 - scnprintf(cur, end - cur, " in %pS", r->fn); + sprintf_end(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 sprintf_end(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 sprintf_end(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 sprintf_end(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 sprintf_end(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 sprintf_end(cur, end, "Invalid free of"); break; } =20 - cur +=3D scnprintf(cur, end - cur, " 0x%p", (void *)addr); + sprintf_end(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..e48ca1972ff3 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 sprintf_end(cur, end, "BUG: KMSAN: %s", r->error_type); =20 - scnprintf(cur, end - cur, " in %s", r->symbol); + sprintf_end(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..6beb2710f97c 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"); + sprintf_end(p, e, "unknown"); return; } =20 - p +=3D snprintf(p, maxlen, "%s", policy_modes[mode]); + p =3D sprintf_end(p, e, "%s", policy_modes[mode]); =20 if (flags & MPOL_MODE_FLAGS) { - p +=3D snprintf(p, buffer + maxlen - p, "=3D"); + p =3D sprintf_end(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 sprintf_end(p, e, "static"); else if (flags & MPOL_F_RELATIVE_NODES) - p +=3D snprintf(p, buffer + maxlen - p, "relative"); + p =3D sprintf_end(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 sprintf_end(p, e, "|"); + p =3D sprintf_end(p, e, "balancing"); } } =20 if (!nodes_empty(nodes)) - p +=3D scnprintf(p, buffer + maxlen - p, ":%*pbl", - nodemask_pr_args(&nodes)); + sprintf_end(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..c00b3be01540 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 sprintf_end(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 sprintf_end(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 sprintf_end(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 sprintf_end(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_sprint_end(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 sprintf_end(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 sprintf_end(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..dcc857676857 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 sprintf_end(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 From nobody Sun Feb 8 19:22:04 2026 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 51F5627FB3C; Thu, 10 Jul 2025 02:48:49 +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=1752115729; cv=none; b=bjCdUSPhx4kNN56nnCW2uA7rTR+JmzXrY5GdfGYLr+aHL3Ve70p/oKdHjOHAGc2iYcAU7yzUC05egFV4H/I3VkTbj1HAbpvh59IuuguNsKsp5Y90z055qX5iHluI278RjUMV+YaDMk853GoQsg0fcisd6AcuYIY1V/HoPpGJPKI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115729; c=relaxed/simple; bh=rA+UPFYPuwoFgyGzULq9cIi8t0p+DMJsALzl86HNlek=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=EhsNpY7JHUqozlpX/tZIwRKZDBt8QCcCQUfAwFShfolSGxfr6257DFiT9CRjZBczu0ahAhXmom0wI38WD7yHCkudyrRVhQ1YZ6tKNwK5pPwCoL4ScKWwzkPLmBwkLTLf0nesV8/59FCAYpUd/0vjOdZiRKsCY3AdMeNQaJuPolI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Os+GBNrj; 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="Os+GBNrj" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 11458C4CEF5; Thu, 10 Jul 2025 02:48:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115728; bh=rA+UPFYPuwoFgyGzULq9cIi8t0p+DMJsALzl86HNlek=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=Os+GBNrjZeEhyYlj8yYdJoW9irRUw6vHagC99ydRypwCqbglrGNYPzSsxonCJSpDN pMIP8RHBXVO7MhvqA2muaq248nqu1XUn6DB0mAFBqEZcAOtGGT7bt5TdxGJYcNgloq rzXAXBG3p/NEloymUlkDHSHUL4sCpY+evRm2jUBHjFx6hvTUEFiA0fy8SDJtNCVKRP Q/fOumV2i9EYwJbRQjIHwFqLuuaPmmrbJ9q1nE0d7CTDzvZQtFAMf2zRLVYZ3kZ6R1 UCVcpxVprPL6nd9Ej+dlgnxU6OFJAZy4obv+83rUw1AvLTVOskpDIGduzLC4rF5gbo zIdu+kuI+IwHQ== Date: Thu, 10 Jul 2025 04:48:41 +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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro Subject: [RFC v4 4/7] array_size.h: Add ENDOF() 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" This macro is useful to calculate the second argument to sprintf_end(), avoiding off-by-one bugs. Cc: Kees Cook Cc: Christopher Bazley Cc: Rasmus Villemoes Cc: Marco Elver Cc: Michal Hocko Cc: Linus Torvalds Cc: Al Viro Signed-off-by: Alejandro Colomar --- include/linux/array_size.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/include/linux/array_size.h b/include/linux/array_size.h index 06d7d83196ca..781bdb70d939 100644 --- a/include/linux/array_size.h +++ b/include/linux/array_size.h @@ -10,4 +10,10 @@ */ #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(= arr)) =20 +/** + * ENDOF - get a pointer to one past the last element in array @a + * @a: array + */ +#define ENDOF(a) (a + ARRAY_SIZE(a)) + #endif /* _LINUX_ARRAY_SIZE_H */ --=20 2.50.0 From nobody Sun Feb 8 19:22:04 2026 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 64AE441AAC; Thu, 10 Jul 2025 02:48:56 +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=1752115736; cv=none; b=WqADhr8kmyBSLOj666KWK1VECXVfD/rtRrnXd6xkgTRAr6yaCYmZAlpoveOJVCtR1d7weqXAa7ozXXMQ/xSZFgPgWMlACOcOQPCzJioDOQzdVwyq/GweeABV1zWXvnB6yE4YLL/4h20eQ+Cyh8w/htCxdvJCTbgHNBlwexpVe04= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115736; c=relaxed/simple; bh=PdAxg442zwuG6bQe5bBQL6WgslGOXy2uA5CfnfLJmEM=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=HrcYJmY+1YQw+grHptjp/s0mH1b7TfcXE3FhBO7RlYrHMa8V7yXkQa1cPOI1coAM3LxXzqB4J8sMEjXFXQQwBtxnj0fqiZSxHHwOlXZjhtsOBzKntcoi2NzNgXh7aoGLqbYdTKKlfgjOBcnp5jZNcyy8pXk4uKCNNE+rbztxcQM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=TJ555ojK; 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="TJ555ojK" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 53A6AC4CEEF; Thu, 10 Jul 2025 02:48:51 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115736; bh=PdAxg442zwuG6bQe5bBQL6WgslGOXy2uA5CfnfLJmEM=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=TJ555ojKw/Ym1H1ofrJNdbx2gI0yCOWAR5I9V88VfdQtPrtDBBdY+g2sh2gZMtMBn oFxSO9VwjAO3IijZFxJ1hbgxlMf2VJGh9nviCfpJoGZV7wwCNvHGGc2WOpsc7ywGoL vw22WAPcl0IJ2xWBgaQZ3bspwJX36DL2BhCj7AMf9TCacmrq4XVhCeMOzynZIIV8uh K9XH4aO3/k9R8gdaNGv246ERSFbeFyQanfSAMCa7r5rF6ekTc9jk0mvc5DBH1deY3n 3HkxNha0PmcELuN2slgoTr+tdF3TM9MNzcabeYJLjDFln8Gz0xRchZXt3aOHriYuUT YsbpqrCfCURjw== Date: Thu, 10 Jul 2025 04:48: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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro , Jann Horn Subject: [RFC v4 5/7] mm: Fix benign off-by-one bugs Message-ID: <44a5cfc82acfdef6d339e71f1b214c443f808598.1752113247.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" We were wasting a byte due to an off-by-one bug. s[c]nprintf() doesn't write more than $2 bytes including the null byte, so trying to pass 'size-1' there is wasting one byte. Now that we use seprintf(), the situation isn't different: seprintf() will stop writing *before* 'end' --that is, at most the terminating null byte will be written at 'end-1'--. Acked-by: Marco Elver Cc: Kees Cook Cc: Christopher Bazley Cc: Alexander Potapenko Cc: Dmitry Vyukov Cc: Alexander Potapenko Cc: Jann Horn Cc: Andrew Morton Cc: Linus Torvalds Cc: Rasmus Villemoes Cc: Marco Elver Cc: Michal Hocko Cc: Al Viro Signed-off-by: Alejandro Colomar --- mm/kfence/kfence_test.c | 4 ++-- mm/kmsan/kmsan_test.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c index bae382eca4ab..c635aa9d478b 100644 --- a/mm/kfence/kfence_test.c +++ b/mm/kfence/kfence_test.c @@ -110,7 +110,7 @@ static bool report_matches(const struct expect_report *= r) =20 /* Title */ cur =3D expect[0]; - end =3D &expect[0][sizeof(expect[0]) - 1]; + end =3D ENDOF(expect[0]); switch (r->type) { case KFENCE_ERROR_OOB: cur =3D sprintf_end(cur, end, "BUG: KFENCE: out-of-bounds %s", @@ -140,7 +140,7 @@ static bool report_matches(const struct expect_report *= r) =20 /* Access information */ cur =3D expect[1]; - end =3D &expect[1][sizeof(expect[1]) - 1]; + end =3D ENDOF(expect[1]); =20 switch (r->type) { case KFENCE_ERROR_OOB: diff --git a/mm/kmsan/kmsan_test.c b/mm/kmsan/kmsan_test.c index e48ca1972ff3..9bda55992e3d 100644 --- a/mm/kmsan/kmsan_test.c +++ b/mm/kmsan/kmsan_test.c @@ -105,7 +105,7 @@ static bool report_matches(const struct expect_report *= r) =20 /* Title */ cur =3D expected_header; - end =3D &expected_header[sizeof(expected_header) - 1]; + end =3D ENDOF(expected_header); =20 cur =3D sprintf_end(cur, end, "BUG: KMSAN: %s", r->error_type); =20 --=20 2.50.0 From nobody Sun Feb 8 19:22:04 2026 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 E811C27FD68; Thu, 10 Jul 2025 02:49:03 +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=1752115744; cv=none; b=SXRWje9M7KiySRYms2IJSq55fOy+9B25alm52w6Cn0Eb7l8dUsjC0HDOJMB36f3oKKCzDdbaeHVeBbWZYuAOM+82UswKVuDPDDJu0OR408agFnVo/jMG346h5tZd6oDvKyoW4bEcxpP0um3slG3Ydd0+Kn0lmZP793oB6GLnC/4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115744; c=relaxed/simple; bh=bnX2EO5r+pqFtMRMv5EjlC3aGlquhrBGrjRfqkZ+Q4c=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=vBBVcphIHhodVFvIuGNrSsiXyYG/gmFf5DVKk/Kgd5x9ObvYExJcPhA9HYYZ2ddQFmn5IyRnkuib8xUhcfE4eTXQmGjTcxQs3wOD0j1n0qls26QdtG5bc0H+oKmSO8hrTnygw6v1dMDQLGPTaA+ANNW48+mXY5O4+iCAPhXbF+o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=L3XJL0VW; 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="L3XJL0VW" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A3AF5C4CEF6; Thu, 10 Jul 2025 02:48:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115743; bh=bnX2EO5r+pqFtMRMv5EjlC3aGlquhrBGrjRfqkZ+Q4c=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=L3XJL0VWa98yMD+KVZAyb+ZWjgF4nCzXocP5panSiFMJTI6BBx+tioK7gpXbtXdRa 9gmf65u9aod1uBDEOmNuIkPaWskc7Qamg1NtYETrPhmbsX0/bE5LS6ihmNIprt0HAM OQqVxElMWeExQdu9FWCgqejKvctDCJtCiBDkQeev9hoRBe2/3M9NduTGx3xb2RmYAh 6P+9WMVVSARkiwNZnChurBRLW5pqd9q0n2PhPE/+9hH3M2TdTRsDh/W9rHtXQtIOpW MHVz3EUT/Ch2XNMl4LjWHqxWcgMeSCUYrOySerOqT4Y44A7goUdD09KmNKYXkxoduw L0fhF/Aqu48yA== Date: Thu, 10 Jul 2025 04:48:56 +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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro Subject: [RFC v4 6/7] sprintf: Add [V]SPRINTF_END() Message-ID: <0314948eb22524d8938fab645052840eb0c20cfa.1752113247.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" These macros take the end of the array argument implicitly to avoid programmer mistakes. This guarantees that the input is an array, unlike snprintf(buf, sizeof(buf), ...); which is dangerous if the programmer passes a pointer instead of an array. These macros are essentially the same as the 2-argument version of strscpy(), but with a formatted string, and returning a pointer to the terminating '\0' (or NULL, on error). Cc: Rasmus Villemoes Cc: Marco Elver Cc: Michal Hocko Cc: Linus Torvalds Cc: Al Viro Signed-off-by: Alejandro Colomar --- include/linux/sprintf.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/include/linux/sprintf.h b/include/linux/sprintf.h index a0dc35574521..33eb03d0b9b8 100644 --- a/include/linux/sprintf.h +++ b/include/linux/sprintf.h @@ -4,6 +4,10 @@ =20 #include #include +#include + +#define SPRINTF_END(a, fmt, ...) sprintf_end(a, ENDOF(a), fmt, ##__VA_ARG= S__) +#define VSPRINTF_END(a, fmt, ap) vsprintf_end(a, ENDOF(a), fmt, ap) =20 int num_to_str(char *buf, int size, unsigned long long num, unsigned int w= idth); =20 --=20 2.50.0 From nobody Sun Feb 8 19:22:04 2026 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 B987B3208; Thu, 10 Jul 2025 02:49:11 +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=1752115751; cv=none; b=tLTuEolyymygWdRycP4Cy2g0HhdJPGYqS546r7C2CRagCajoUUM+uvtqYhVIZRGTY0ckJvksqWzTiVLNfp8Q86H7AveuzCPxKMoE3BWT3GkHp8zPvWQ/3P6VgWngjs3KGadMKBTpCcQHQXEVJk+1wPinLqdHv8QLwBB4lZRRAGA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752115751; c=relaxed/simple; bh=En+Iya8BEITJchISNZUlAS9xNApPSGz+tWs96YVWasQ=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=U8mCdbanCjBL+zGGgr1bdGdUiFqb7VfWdFTSy5Ag/Eq7GuFeS53SlDTA/s7gTLs3zwCp3tF5GWJdU8ueizKOkzETvDayaeaOLR2TPPUZlfL5dT4Wogr386vlxkFhJqB8pPy6FvixH2WtUv+NJVSE5h3wPKqEZlYyeQzyBMh0sPM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Rtj1GYIu; 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="Rtj1GYIu" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C1F95C4AF09; Thu, 10 Jul 2025 02:49:05 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752115751; bh=En+Iya8BEITJchISNZUlAS9xNApPSGz+tWs96YVWasQ=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=Rtj1GYIuVkOk5l25BPrGzLsdrPA8HXWMNO7QkCRBiFthatnOP1tTlQ6nXVlF0F13w TfdqSVccohtn7+DGwYcAmy3AGKeO6B0yg8uAM0he/tIt6XfhvWffHHFyJXr2mSBPEG nQiMvDyFKD/s9ZNMzlBpL1SD+sb2xoi24+pd1UTR2Ii3TKyghjRFYWgmV2RchFE0nl sYkn858HvVgORUAkLtArJlA5bUJ5/JZgrHemxn1D2/1plkJO/Vb//S/T1XOxMUwH0T zo8cqA1D1jWvLxkOGxH5mvh/I0YJuEsAokH00Q95Z/pps+RTCT2iFC8YyQrFRfi7+8 +1A7nLLEJvjbw== Date: Thu, 10 Jul 2025 04:49:03 +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 , Andrew Clayton , Rasmus Villemoes , Michal Hocko , Linus Torvalds , Al Viro Subject: [RFC v4 7/7] mm: Use [V]SPRINTF_END() to avoid specifying the array size 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" Cc: Rasmus Villemoes Cc: Marco Elver Cc: Michal Hocko Cc: Linus Torvalds Cc: Al Viro Signed-off-by: Alejandro Colomar --- mm/backing-dev.c | 2 +- mm/cma.c | 4 ++-- mm/cma_debug.c | 2 +- mm/hugetlb.c | 3 +-- mm/hugetlb_cgroup.c | 2 +- mm/hugetlb_cma.c | 2 +- mm/kasan/report.c | 3 +-- mm/memblock.c | 4 ++-- mm/percpu.c | 2 +- mm/shrinker_debug.c | 2 +- mm/zswap.c | 2 +- 11 files changed, 13 insertions(+), 15 deletions(-) diff --git a/mm/backing-dev.c b/mm/backing-dev.c index 783904d8c5ef..20a75fd9f205 100644 --- a/mm/backing-dev.c +++ b/mm/backing-dev.c @@ -1090,7 +1090,7 @@ int bdi_register_va(struct backing_dev_info *bdi, con= st char *fmt, va_list args) if (bdi->dev) /* The driver needs to use separate queues per device */ return 0; =20 - vsnprintf(bdi->dev_name, sizeof(bdi->dev_name), fmt, args); + VSPRINTF_END(bdi->dev_name, fmt, args); dev =3D device_create(&bdi_class, NULL, MKDEV(0, 0), bdi, bdi->dev_name); if (IS_ERR(dev)) return PTR_ERR(dev); diff --git a/mm/cma.c b/mm/cma.c index c04be488b099..05f8f036b811 100644 --- a/mm/cma.c +++ b/mm/cma.c @@ -237,9 +237,9 @@ static int __init cma_new_area(const char *name, phys_a= ddr_t size, cma_area_count++; =20 if (name) - snprintf(cma->name, CMA_MAX_NAME, "%s", name); + SPRINTF_END(cma->name, "%s", name); else - snprintf(cma->name, CMA_MAX_NAME, "cma%d\n", cma_area_count); + SPRINTF_END(cma->name, "cma%d\n", cma_area_count); =20 cma->available_count =3D cma->count =3D size >> PAGE_SHIFT; cma->order_per_bit =3D order_per_bit; diff --git a/mm/cma_debug.c b/mm/cma_debug.c index fdf899532ca0..6df439b400c1 100644 --- a/mm/cma_debug.c +++ b/mm/cma_debug.c @@ -186,7 +186,7 @@ static void cma_debugfs_add_one(struct cma *cma, struct= dentry *root_dentry) rangedir =3D debugfs_create_dir("ranges", tmp); for (r =3D 0; r < cma->nranges; r++) { cmr =3D &cma->ranges[r]; - snprintf(rdirname, sizeof(rdirname), "%d", r); + SPRINTF_END(rdirname, "%d", r); dir =3D debugfs_create_dir(rdirname, rangedir); debugfs_create_file("base_pfn", 0444, dir, &cmr->base_pfn, &cma_debugfs_fops); diff --git a/mm/hugetlb.c b/mm/hugetlb.c index 6a3cf7935c14..2e6aa3efafb2 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -4780,8 +4780,7 @@ void __init hugetlb_add_hstate(unsigned int order) for (i =3D 0; i < MAX_NUMNODES; ++i) INIT_LIST_HEAD(&h->hugepage_freelists[i]); INIT_LIST_HEAD(&h->hugepage_activelist); - snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB", - huge_page_size(h)/SZ_1K); + SPRINTF_END(h->name, "hugepages-%lukB", huge_page_size(h)/SZ_1K); =20 parsed_hstate =3D h; } diff --git a/mm/hugetlb_cgroup.c b/mm/hugetlb_cgroup.c index 58e895f3899a..4b5330ff9cef 100644 --- a/mm/hugetlb_cgroup.c +++ b/mm/hugetlb_cgroup.c @@ -822,7 +822,7 @@ hugetlb_cgroup_cfttypes_init(struct hstate *h, struct c= ftype *cft, for (i =3D 0; i < tmpl_size; cft++, tmpl++, i++) { *cft =3D *tmpl; /* rebuild the name */ - snprintf(cft->name, MAX_CFTYPE_NAME, "%s.%s", buf, tmpl->name); + SPRINTF_END(cft->name, "%s.%s", buf, tmpl->name); /* rebuild the private */ cft->private =3D MEMFILE_PRIVATE(idx, tmpl->private); /* rebuild the file_offset */ diff --git a/mm/hugetlb_cma.c b/mm/hugetlb_cma.c index e0f2d5c3a84c..6bccad5b4216 100644 --- a/mm/hugetlb_cma.c +++ b/mm/hugetlb_cma.c @@ -211,7 +211,7 @@ void __init hugetlb_cma_reserve(int order) =20 size =3D round_up(size, PAGE_SIZE << order); =20 - snprintf(name, sizeof(name), "hugetlb%d", nid); + SPRINTF_END(name, "hugetlb%d", nid); /* * Note that 'order per bit' is based on smallest size that * may be returned to CMA allocator in the case of diff --git a/mm/kasan/report.c b/mm/kasan/report.c index 8357e1a33699..c2c9bef78edf 100644 --- a/mm/kasan/report.c +++ b/mm/kasan/report.c @@ -486,8 +486,7 @@ static void print_memory_metadata(const void *addr) char buffer[4 + (BITS_PER_LONG / 8) * 2]; char metadata[META_BYTES_PER_ROW]; =20 - snprintf(buffer, sizeof(buffer), - (i =3D=3D 0) ? ">%px: " : " %px: ", row); + SPRINTF_END(buffer, (i =3D=3D 0) ? ">%px: " : " %px: ", row); =20 /* * We should not pass a shadow pointer to generic diff --git a/mm/memblock.c b/mm/memblock.c index 0e9ebb8aa7fe..6bb21aacb15d 100644 --- a/mm/memblock.c +++ b/mm/memblock.c @@ -2021,7 +2021,7 @@ static void __init_memblock memblock_dump(struct memb= lock_type *type) flags =3D rgn->flags; #ifdef CONFIG_NUMA if (numa_valid_node(memblock_get_region_node(rgn))) - snprintf(nid_buf, sizeof(nid_buf), " on node %d", + SPRINTF_END(nid_buf, " on node %d", memblock_get_region_node(rgn)); #endif pr_info(" %s[%#x]\t[%pa-%pa], %pa bytes%s flags: %#x\n", @@ -2379,7 +2379,7 @@ int reserve_mem_release_by_name(const char *name) =20 start =3D phys_to_virt(map->start); end =3D start + map->size - 1; - snprintf(buf, sizeof(buf), "reserve_mem:%s", name); + SPRINTF_END(buf, "reserve_mem:%s", name); free_reserved_area(start, end, 0, buf); map->size =3D 0; =20 diff --git a/mm/percpu.c b/mm/percpu.c index b35494c8ede2..efe5d1517a96 100644 --- a/mm/percpu.c +++ b/mm/percpu.c @@ -3186,7 +3186,7 @@ int __init pcpu_page_first_chunk(size_t reserved_size= , pcpu_fc_cpu_to_node_fn_t int upa; int nr_g0_units; =20 - snprintf(psize_str, sizeof(psize_str), "%luK", PAGE_SIZE >> 10); + SPRINTF_END(psize_str, "%luK", PAGE_SIZE >> 10); =20 ai =3D pcpu_build_alloc_info(reserved_size, 0, PAGE_SIZE, NULL); if (IS_ERR(ai)) diff --git a/mm/shrinker_debug.c b/mm/shrinker_debug.c index 20eaee3e97f7..9a6e959882c6 100644 --- a/mm/shrinker_debug.c +++ b/mm/shrinker_debug.c @@ -176,7 +176,7 @@ int shrinker_debugfs_add(struct shrinker *shrinker) return id; shrinker->debugfs_id =3D id; =20 - snprintf(buf, sizeof(buf), "%s-%d", shrinker->name, id); + SPRINTF_END(buf, "%s-%d", shrinker->name, id); =20 /* create debugfs entry */ entry =3D debugfs_create_dir(buf, shrinker_debugfs_root); diff --git a/mm/zswap.c b/mm/zswap.c index 204fb59da33c..7a8041f84e18 100644 --- a/mm/zswap.c +++ b/mm/zswap.c @@ -271,7 +271,7 @@ static struct zswap_pool *zswap_pool_create(char *type,= char *compressor) return NULL; =20 /* unique name for each pool specifically required by zsmalloc */ - snprintf(name, 38, "zswap%x", atomic_inc_return(&zswap_pools_count)); + SPRINTF_END(name, "zswap%x", atomic_inc_return(&zswap_pools_count)); pool->zpool =3D zpool_create_pool(type, name, gfp); if (!pool->zpool) { pr_err("%s zpool not available\n", type); --=20 2.50.0