zsh-workers
 help / color / mirror / code / Atom feed
* PATCH: Fix use-after-free for print -zf and print -sf
@ 2015-02-10  7:12 Mikael Magnusson
  2015-02-10  7:16 ` Mikael Magnusson
  0 siblings, 1 reply; 7+ messages in thread
From: Mikael Magnusson @ 2015-02-10  7:12 UTC (permalink / raw)
  To: zsh-workers

% print -zf hi
 mem.c:1525: BUG: attempt to free already free storage                                        
% XY<81>^A

This is only visible (for me) with --enable-zsh-mem, but the bug is
always there. As the error message says, we do a double free. The reason
is that while we fflush the open_memstream'd fout, which updates buf,
we then after copying the pointer do fclose, which updates the pointer
again and frees the old memory area. Boom.

I don't know what the nicest way to handle this is. We could do what
this patch does, or we could copy the contents of buf after flushing,
but that would cause two extra pointless copies compared to this patch.

We could also set fout = stdout to avoid changing the final if, but I
recall someone complained about the extra fflush of stdout on my other
patch a while back.

---
 Src/builtin.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/Src/builtin.c b/Src/builtin.c
index 19155fd..e0f6a5c 100644
--- a/Src/builtin.c
+++ b/Src/builtin.c
@@ -4526,7 +4526,8 @@ bin_print(char *name, char **args, Options ops, int func)
     if (OPT_ISSET(ops,'z') || OPT_ISSET(ops,'s')) {
 #ifdef HAVE_OPEN_MEMSTREAM
 	putc(0, fout);
-	fflush(fout);
+	fclose(fout);
+	fout = NULL;
 #else
 	rewind(fout);
 	buf = (char *)zalloc(count + 1);
@@ -4548,7 +4549,7 @@ bin_print(char *name, char **args, Options ops, int func)
     }
 
     /* Testing EBADF special-cases >&- redirections */
-    if ((fout != stdout) ? (fclose(fout) != 0) :
+    if (fout && (fout != stdout) ? (fclose(fout) != 0) :
 	(fflush(fout) != 0 && errno != EBADF)) {
 	zwarnnam(name, "write error: %e", errno);
 	ret = 1;
-- 
2.2.0.GIT


^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2015-02-10 11:38 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2015-02-10  7:12 PATCH: Fix use-after-free for print -zf and print -sf Mikael Magnusson
2015-02-10  7:16 ` Mikael Magnusson
2015-02-10  9:37   ` Peter Stephenson
2015-02-10 11:13     ` Mikael Magnusson
2015-02-10 11:18       ` Peter Stephenson
2015-02-10 11:32         ` Mikael Magnusson
2015-02-10 11:38           ` Peter Stephenson

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).