From c61ca02d99108f9d80c394a3b037388e1f54828d Mon Sep 17 00:00:00 2001 From: Joachim Klein Date: Wed, 6 Jun 2018 14:35:43 +0200 Subject: [PATCH] PrismFileLog: make more robust (multiple close, print after close) On first close, we set the file pointer to 0 to indicate that it is not valid anymore. As PrismLog implements Close/AutoCloseable, multiple close calls have to be supported. Before, calling close multiple times could result in double free crashes on Linux (seen in development branches, not master). We also check that we don't write on a closed FILE pointer, but raise an exception instead. Here, we use a RuntimeException (IllegalStateException) instead of a PrismException as changing the PrismLog interface would be quite disruptive to the rest of the code. --- prism/src/prism/PrismFileLog.java | 14 ++++++++++++++ prism/src/prism/PrismLog.java | 1 + 2 files changed, 15 insertions(+) diff --git a/prism/src/prism/PrismFileLog.java b/prism/src/prism/PrismFileLog.java index 88716299..3a7a8489 100644 --- a/prism/src/prism/PrismFileLog.java +++ b/prism/src/prism/PrismFileLog.java @@ -132,13 +132,23 @@ public class PrismFileLog extends PrismLog @Override public void flush() { + if (fp == 0) { + throw new IllegalStateException("Trying to flush an invalid file handle (already closed?)"); + } PrismNative.PN_FlushFile(fp); } @Override public void close() { + if (fp == 0) { + // already closed, ignore (as specified by Closable contract) + return; + } + if (!stdout) PrismNative.PN_CloseFile(fp); + // set fp to zero to indicate that the file handle is not valid anymore + fp = 0; } @Override @@ -200,6 +210,10 @@ public class PrismFileLog extends PrismLog */ private void printToLog(String s) { + if (fp == 0) { + throw new IllegalStateException("Trying to write to an invalid file handle (already closed?)"); + } + PrismNative.PN_PrintToFile(fp, s); } } diff --git a/prism/src/prism/PrismLog.java b/prism/src/prism/PrismLog.java index 57d81dac..979e9655 100644 --- a/prism/src/prism/PrismLog.java +++ b/prism/src/prism/PrismLog.java @@ -92,6 +92,7 @@ public abstract class PrismLog implements Closeable, AutoCloseable public abstract void flush(); + @Override public abstract void close(); public abstract void print(boolean b);