From 370be858928c2c537c112859ccd54cd1b0d56715 Mon Sep 17 00:00:00 2001
From: Siddhesh Poyarekar <siddhesh@sourceware.org>
Date: Tue, 3 Sep 2024 14:58:33 -0400
Subject: [PATCH] libio: Attempt wide backup free only for non-legacy code

_wide_data and _mode are not available in legacy code, so do not attempt
to free the wide backup buffer in legacy code.

Resolves: BZ #32137 and BZ #27821

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit ae4d44b1d501421ad9a3af95279b8f4d1546f1ce)
---
 NEWS           | 2 ++
 libio/genops.c | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/NEWS b/NEWS
index 7a9a4b7ea3..a2adce11ff 100644
--- a/NEWS
+++ b/NEWS
@@ -36,6 +36,7 @@ Security related changes:
 
 The following bugs are resolved with this release:
 
+  [27821] ungetc: Fix backup buffer leak on program exit
   [29039] Corrupt DTV after reuse of a TLS module ID following dlclose with unused TLS
   [30081] resolv: Do not wait for non-existing second DNS response after error
   [30694] The iconv program no longer tells the user which given encoding name was wrong
@@ -57,6 +58,7 @@ The following bugs are resolved with this release:
   [31965] rseq extension mechanism does not work as intended
   [31968] mremap implementation in C does not handle arguments correctly
   [32052] Name space violation in fortify wrappers
+  [32137] libio: Attempt wide backup free only for non-legacy code
 
 Version 2.38
 
diff --git a/libio/genops.c b/libio/genops.c
index fb06245467..7b30aab095 100644
--- a/libio/genops.c
+++ b/libio/genops.c
@@ -792,7 +792,7 @@ _IO_unbuffer_all (void)
       /* Free up the backup area if it was ever allocated.  */
       if (_IO_have_backup (fp))
 	_IO_free_backup_area (fp);
-      if (fp->_mode > 0 && _IO_have_wbackup (fp))
+      if (!legacy && fp->_mode > 0 && _IO_have_wbackup (fp))
 	_IO_free_wbackup_area (fp);
 
       if (! (fp->_flags & _IO_UNBUFFERED)
-- 
2.27.0

