From nobody Tue Oct 7 09:53:15 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 27D86442C; Thu, 10 Jul 2025 21:30:50 +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=1752183051; cv=none; b=R8Y4K2Nl0zjRru8tbW80WU9G7lLZfOpfXqk+j/62O1LJbngKaSKSxN+NWisGba2rlvfWQsJImBmBZqbwax+P4byzsw2lsIMeoaqM59uWUt3DGjRU3dLoDFSb4qOIJeaodrK3fQbETXrcLYbvnwmoB4XheR4mTudA7R89+Sgx9mM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183051; 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=sisrMRjx7kwPQtA9xEXy2LoMOYr9M1Jq+UuO9/RKnWC0TAlQbFsBOdC2YeUcfHr197dnjL+GPAmUBxMqDN0KgUoop6iIybm8W+w9eIVhJcONpL25ESPl+D1iTbNOu5ivc9bsq/MaMpuIbWnfSngRmuxGe4GOvLdoOnWXGZIf/OE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=dPANN/xW; 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="dPANN/xW" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 15833C4CEF6; Thu, 10 Jul 2025 21:30:45 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183050; bh=uP1Rd77wxX/Fb6ettFx80wxbqPad+vTShdCzOI/MZqw=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=dPANN/xWTuc7WxMQpqAFV5aOwLOMsb9ly9HOJg/d++a2uWkTjZd8DFsnoNHyR7jaV xc1CTlLvbE39tKkSHt4VCDF/zIoB9Lw06DiuwmvUccwxHy9Tz1cLQjWs2+V7vkk0f3 bq9oHpeCxXe4rvE0OLmXv9tKj0GP4FsyzX/x5Mo4N3Q+BAYBE2/4VuqWy8Zf4wVa07 P9+4ARBo7oLlkg+gQvgTmbv647YpBI27qIZK0pGWG5vi3LoTXAALvdHKvqGM+KVLPP FStK2OkSj0oze/P+HEIoMR8fJJWXge9EMVNNrIdF4q6bKcGXyckJX/0oX3LJuu7vLE /pi8htZLnV3jQ== Date: Thu, 10 Jul 2025 23:30:44 +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 v5 1/7] vsprintf: Add [v]sprintf_end() Message-ID: <2c4f793de0b849259088c1f52db44ace5a4e6f66.1752182685.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 Tue Oct 7 09:53:15 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 4F3B0442C; Thu, 10 Jul 2025 21:30:57 +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=1752183057; cv=none; b=tUu0XCz8WI3mXrpPLWY6yqYEaM3T2NT+T6BjBK59w/8fHPHBqi2vrDOo3a9xnIlXeuXu/rCxush2pq1uI6pJ5MtHOfbB40EpzN8XTrKWkV9he4xzDHut7f2mZWA8wqb3fT0wUjNMzQhaPrm71CtxZDO35W+yBK+C8O/YMtuAc3Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183057; c=relaxed/simple; bh=KFeH759S2pXUEgcinWQTZzWHu8P8w4ivkJjMDXMeyRQ=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=P+x2o87avAlfvm89BPCfGC4rMDmLqyrHzqc3yZzg0xxjXis9pB29Vh84vscVxBkf1p5pn/Jpqo2JpbW3S0gxcqXnUx0sIIsKLp5fMqyBCcd6sxON60RhlD0Wd64FoT3jAQDPLL91EMLgknc9EVdrcODd0gLMsnkJFxe6IfmTmUk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=lChuc2aI; 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="lChuc2aI" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9B5FDC4CEED; Thu, 10 Jul 2025 21:30:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183057; bh=KFeH759S2pXUEgcinWQTZzWHu8P8w4ivkJjMDXMeyRQ=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=lChuc2aIiaz+0Xm8z58EsB2dHZQKTk61AFuU2NkYge2fIKkiE9k7JcRFDKte6DbHY AJtgvve0gU4KmxO3Ho8wsXHyXVy5d0cllRYD+5RLan44LxpHFgfnr01I9UIz4oxYUG GnO17+7nijRIOuijJ2XJrkJwxD+V03QKG362wyPhVYqYablzyTtA5tzDvvrJ2FpaBC s3cPgtg2bDj7KsqYw4T/wNYRKrMNVbhxt7fehQMnHh/YLFHgEU09yFQStXHs2oox1v wHDN10DuGpyblOdjFc1Y5qlCvWMd+nd2mUptEGU1Y2DX1AKgOnRJHXJqB7HO8n6dsl q0WedwcuImZLg== Date: Thu, 10 Jul 2025 23:30:50 +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 v5 2/7] stacktrace, stackdepot: Add sprintf_end()-like variants of functions Message-ID: <894d02b08056c59b5acb79af73a1a698d56016f5.1752182685.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 Tue Oct 7 09:53:15 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 2064823B617; Thu, 10 Jul 2025 21:31:04 +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=1752183065; cv=none; b=Y0AMOwRp6arPrqalnDMH7EwxIgXqUPv4O3joK5Lr34fNLAgcXKuVS7RaI9lIcjskdGM3ItGMqHA9W3lBPA8eHzlgOfFoIZLN7kZI6+sCV8culhU4BVfITsaRbA6op9zR/apiqywzC/6wowSmNjVWfYk3UyX+XafAdGrqP5/PINc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183065; 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=L81SHBpGs2WeRprfNxijPP69Hve0ZM9fjDsl3V6TkCBmceXYj9AY+4V/T5tuAHdggNkZJ1REY3GTws3npF+8A8jMRktUrJwcrGwy7JTFwCEdI4vA/5VSUpRwxNONQdhjb1k7HPkGHjzARwks6ycs2r3uekBD2eNsXT0cwCvUDuE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Kza/FByE; 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="Kza/FByE" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 27AEEC4CEF4; Thu, 10 Jul 2025 21:30:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183064; bh=stTpsWR5B9qnU4lcgeg0tYr2I54PzkVTHHPWz1Iz+X8=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=Kza/FByE8gXA2NRCxqKNhHz+6CvqTaWHB2aPSGigaTcBqIbyqEi5nWZdOB1cCZWTq GEedjN2R0TTYi6gw1rgXIqHat+iC5k1w1Fn8h8r1pZ4non4ryM08vlLUFB/7yTVRWi b8ECsyA9gtDwTWzUOZ98/JWp7nJo5FVT572foGnhyS7zuYoDXxUd9H5qMJal6KaSZN TCZlhKCW9xZTyI5d+ZwfgfHLsJNda0Ponh6qCVh4x85qAKhJGq8c04nt2GXfY6jFGD //6dCLzhDgMv5cbMLJb6ieh1AI/WiMWGIE8i2hynN1U1h/4IDjxsOnAqOiVKUaCcbz fkuNSQWUc1dYw== Date: Thu, 10 Jul 2025 23:30:57 +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 , Sven Schnelle , Heiko Carstens , Tvrtko Ursulin , Christophe JAILLET , Hyeonggon Yoo <42.hyeyoo@gmail.com>, Chao Yu Subject: [RFC v5 3/7] mm: Use sprintf_end() instead of less ergonomic APIs Message-ID: <690ed4d22f57a4a1f2c72eb659ceb6b7ab3d5f41.1752182685.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 Tue Oct 7 09:53:15 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 A6B2328FA9F; Thu, 10 Jul 2025 21:31: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=1752183071; cv=none; b=AXTGPkIHX27wDNPf7ZDs9vgwfbszNhsDCZB9N61Siv9yucFAxVLoHg9tdniW37dsx7RawILygg4sdtiVKqqC4rX75Jwzzd8lbVlSPzYBFF9sNaYuOaBX6Gnvjzu8T1TQFdHdiWO47AGoSDsEX4Yz4WdanHKIgkQ7mH/0GaDTUJo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183071; 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=tGzxE78yWPFWf5kj+sQ91W0ul22ClrwaEj64N5L72/enW0oVznWAdBoFTGb78zdOCBDVarB8CoCijrc42bz1UffMf0dil8COXCUaANipGQSKAU8kh+C+AC/q+476mXMkwo7AZOVYlc3A+JYc1gDYcnEU3WwRDYcq4DvcJ1q5/GM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=pCHRPHOz; 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="pCHRPHOz" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9C0EBC4CEF6; Thu, 10 Jul 2025 21:31:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183071; bh=rA+UPFYPuwoFgyGzULq9cIi8t0p+DMJsALzl86HNlek=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=pCHRPHOz6GD24YpOAuQV/yUfqQ5wNujAhn95TxSXZ4FGZPAMDFYOH+YXnBlOlC1Pt oDqEgUjasc0gBr8iT445mPvy2THnXqGNyJ8ql5XYutgB3tn8cM10ZsLkJHiPb9JCI1 WgUEzz38o2CZhOGjxKIUKgzEHVGpgLhB3+xD47EpgkoyXOXbiU9PAaIQ0BLkng+B6V gvHqTqvFjoZVCDQqCuxwVF5xFXndhV3T6PxHVIodzEEfK5TJVlnk4nUqjJPYXc49N8 HWIynN4dqD1tq7OhAIcdqTKjtLLDUNi1t03dwctcoKxu1A7R00O5T3JXwCGVMNDCT5 zacvpKsgDNZWg== Date: Thu, 10 Jul 2025 23:31:04 +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 v5 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 Tue Oct 7 09:53:15 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 5489B2FE39D; Thu, 10 Jul 2025 21:31:18 +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=1752183079; cv=none; b=cRNy22NWR3zMahcnZBEIw54mkS5SppDztX8rfuUOJCSk7W7IEX1jYP/6v58xy8hydAySgCYQgrSeFE6aqzWKwM/nYS7sX6pWZIV1fDCALZ70d4yqW14bZ/TZ4OIQcOjfuWLQo/KDibJp3GRH79a4/4XQsaDMwzAcXQI94a7jfco= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183079; c=relaxed/simple; bh=wFPXfnEZslZWUhJFarJBIrU2i1EIAu502D8Y+SMDH6M=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=IWJqAHIUP9pv9D8PZbpIhWshNGL9AAHiv9twD4t3z/7Dl7FbeF/eCVa8kHNzfWL1AKqJI3YgvmjSW2mPAHKNd+mGc8MxDqt/5LkBWGvlqKAg2jidT4Q1oPo6475s/Ep8LOf3n0weyW+bWHz92iVZrG1Sr14dt1iZe4rT9iEFhjA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=lWuo1Zql; 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="lWuo1Zql" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2D0DAC4CEF4; Thu, 10 Jul 2025 21:31:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183077; bh=wFPXfnEZslZWUhJFarJBIrU2i1EIAu502D8Y+SMDH6M=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=lWuo1ZqlT8hDeYCOdQ83TdmvF3KTGpYjhd5zydhkKWryMLsY/yiK+N6Gb3hmh8X/T AT6fkItdv8vi0RopIXquZcY2WFs4NBlcXWveYLG3SKhskex1XkYyHoMRFE8Pq7nPB3 crYWMOb94V+RVJyuUPctglxGyyzCbhKkWT2uzfxIefWUfg+Sz/9dQny5+GJ2fuz0Uv xdbLu4BrdKkWrkzDFkqjrV3HQCOdPfSoAoD6/Bp8p5Tsa71nXhuP2XPQvCggDV5+th VUF7d2SevWeaVFMTwzUITeFqMKVJWvf9fnbkuosGwlSy0jzVnGlzRaFkg6XYuwSTQv INmQKlW3JVmxw== Date: Thu, 10 Jul 2025 23:31: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 , Jann Horn Subject: [RFC v5 5/7] mm: Fix benign off-by-one bugs Message-ID: <515445ae064d4b8599899bf0d8b480dadd2ff843.1752182685.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 sprintf_end(), the situation isn't different: sprintf_end() 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 Tue Oct 7 09:53:15 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 D5BC51E520B; Thu, 10 Jul 2025 21:31:24 +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=1752183084; cv=none; b=n0tdeo3WsxeEJkTP4B/ZIvKKk1N1Z8ljnbWdj9OoS7gYgA+Gl8KABNsK6NGHrulAb2JBuwy6PhAfx5f2qnQJiLjSlzrwlmB0Uy5glhtvR/pauNhiZHlMdDWZ7U4qkhSZKiIUaGGnDNB/kcCyzoQTuGMR7eTcI0XSgVjoarfyZuQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183084; c=relaxed/simple; bh=BviaG8x5UaMaZ2NZNq4PRkpH6oax0KpIs4xoQwuZthQ=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=eA39cMw1Toyyge1/lVfyKAy2VF9Qc3u986b4ciZq59WldwlBzeaNQLOlamzCcmokplM845Auy+2xwHrTNCbo+Q5G1sI3a8ck6YPYbPfVJLrKDrGSDa+t/h9EW5FghLwYbkU+RYx2k3UJ/9voN9JalSfZXn8uwNzbkHDE+jIawu4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Czr/vs+w; 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="Czr/vs+w" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EC03CC4CEED; Thu, 10 Jul 2025 21:31:19 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183084; bh=BviaG8x5UaMaZ2NZNq4PRkpH6oax0KpIs4xoQwuZthQ=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=Czr/vs+wEbaVSdBx4yIctL/u3HxGAZE/y+vim/e+sn09CaMvg5y47zTkS/tEx/dWZ /5bMgPrsHpl/rJ4D040AqEYgVFJ/Bck6WuCkR+6rdeF+Ssazk9PLeLcR6qXSqPO9Zs nFQ5wcNxIVXgWmoNEcM0VWZ4IiA1ovl0PNxCk01jARFm8wHV+S3BrdNPxNDL9VW2bg WgQrf4d4jefyBADF/g5LDs2FSXi3xNaqHV/nfsV/F8zycPkRzF4JN3Y0P6flSPtLK3 aP1sBhHGoZLdhoBGvtgHJqyWNScaCGvORxWyQPho5YFfIKMmChAZODlEoGSIM77k9w Sy0yUgGXZv1tw== Date: Thu, 10 Jul 2025 23:31:18 +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 v5 6/7] sprintf: Add [v]sprintf_array() Message-ID: <04c1e026a67f1609167e834471d0f2fe977d9cb0.1752182685.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..8576a543e62c 100644 --- a/include/linux/sprintf.h +++ b/include/linux/sprintf.h @@ -4,6 +4,10 @@ =20 #include #include +#include + +#define sprintf_array(a, fmt, ...) sprintf_end(a, ENDOF(a), fmt, ##__VA_A= RGS__) +#define vsprintf_array(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 Tue Oct 7 09:53:15 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 3293B1E520B; Thu, 10 Jul 2025 21:31:31 +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=1752183091; cv=none; b=kKGnu6ZjTEudMpwSkM7ac3cM03O2+5rHoqJUZuoHZWqyLPKttNMmcFrFbnlwEZsIKONUj8CompVm5qdZLD22sWEfalUkx9kkYgWn10+OFmqDtDGiDTCoYMqmMbCiVMP4TBpfDZ7uS4RMpEVqxV0WAQ7cEMg0/9CcbqXPAZEo1yY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752183091; c=relaxed/simple; bh=VJYVfYb5aKbK4eQQkUA5lmVUT/3A2ehIMDd21vB14NU=; h=Date:From:To:Cc:Subject:Message-ID:References:MIME-Version: Content-Type:Content-Disposition:In-Reply-To; b=qm2b5W1lZgnuDwQwoOFmF9i+ClC1oBLRqLmXFUpI9ir0R93nGqTSi0YxwXV3lLm93t3GYrqzklD2Ck8fp+7FKj8fqJAad5ZmveDL8GiPdEeincZuhHN9fLcwi2FcsGGLlmO5bANu+Yj5wBzgPIp6QQtGA/NSX17Fv13OnuvcCaA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=CeSK1sDO; 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="CeSK1sDO" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7DFACC4CEF4; Thu, 10 Jul 2025 21:31:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1752183091; bh=VJYVfYb5aKbK4eQQkUA5lmVUT/3A2ehIMDd21vB14NU=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=CeSK1sDOqEclROIugmqbQobZxBiZYdf79kQefbcHMOIrfLbYKgKXDx74hfzKBA1vG BtdznHoti6CyrMOuAXA+R4jLegAAXftBL79z8VC8CJHmBXRzZGWMaG3ycxud3fzQm3 j9WYcAqeN6MIpkDiSzrd8s73a+/yJZh6fHmOFGZvQRCfpGlDTNetJyIPotmjAEnPRS mKP5Sqn74tj7b6ae+9hYkVBLg5C0C4SF0uiNnJUFKqdWh/aZMWfEaQJOlVQ/V94nUs 6Hlowmrz2W7Tx3VmqxJZeBRhnBLI4ZGtM5oF0OhPejveemcixwGk1PycR5fRTkMOgb t8nVu0In2zF2g== Date: Thu, 10 Jul 2025 23:31:24 +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 v5 7/7] mm: Use [v]sprintf_array() 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..c4e588135aea 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_array(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..61d97a387670 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_array(cma->name, "%s", name); else - snprintf(cma->name, CMA_MAX_NAME, "cma%d\n", cma_area_count); + sprintf_array(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..751eae9f6364 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_array(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..70acc8b3cbb8 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_array(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..0953cea93759 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_array(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..bae82a97a43c 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_array(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..3b40225e7873 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_array(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..3eea7a177330 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_array(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_array(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..a467102c2405 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_array(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..f529ac29557c 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_array(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..e66b5c5b1ecf 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_array(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