]> git.cworth.org Git - apitrace/blobdiff - trace_local_writer.cpp
Merge branch 'master' into compression
[apitrace] / trace_local_writer.cpp
index 062f0889ea3b44ec38d5da06cef4246a6f881d4a..ea6c111eb8756ff6b0fa2386bebf5560d71d766a 100644 (file)
@@ -30,9 +30,8 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <zlib.h>
-
 #include "os.hpp"
+#include "trace_file.hpp"
 #include "trace_writer.hpp"
 #include "trace_format.hpp"
 
 namespace Trace {
 
 
+static void exceptionCallback(void)
+{
+    OS::DebugMessage("apitrace: flushing trace due to an exception\n");
+    localWriter.flush();
+}
+
+
+LocalWriter::LocalWriter() :
+    acquired(0)
+{}
+
+LocalWriter::~LocalWriter()
+{
+    OS::ResetExceptionCallback();
+}
+
 void
 LocalWriter::open(void) {
 
@@ -80,12 +95,20 @@ LocalWriter::open(void) {
     OS::DebugMessage("apitrace: tracing to %s\n", szFileName);
 
     Writer::open(szFileName);
+
+    OS::SetExceptionCallback(exceptionCallback);
+
+#if 0
+    // For debugging the exception handler
+    *((int *)0) = 0;
+#endif
 }
 
 unsigned LocalWriter::beginEnter(const FunctionSig *sig) {
     OS::AcquireMutex();
+    ++acquired;
 
-    if (!g_gzFile) {
+    if (!m_file->isOpened()) {
         open();
     }
 
@@ -94,21 +117,40 @@ unsigned LocalWriter::beginEnter(const FunctionSig *sig) {
 
 void LocalWriter::endEnter(void) {
     Writer::endEnter();
-    gzflush(g_gzFile, Z_SYNC_FLUSH);
+    --acquired;
     OS::ReleaseMutex();
 }
 
 void LocalWriter::beginLeave(unsigned call) {
     OS::AcquireMutex();
+    ++acquired;
     Writer::beginLeave(call);
 }
 
 void LocalWriter::endLeave(void) {
     Writer::endLeave();
-    gzflush(g_gzFile, Z_SYNC_FLUSH);
+    --acquired;
     OS::ReleaseMutex();
 }
 
+void LocalWriter::flush(void) {
+    /*
+     * Do nothing if the mutex is already acquired (e.g., if a segfault happen
+     * while writing the file) to prevent dead-lock.
+     */
+
+    if (!acquired) {
+        OS::AcquireMutex();
+        if (m_file->isOpened()) {
+            m_file->flush();
+        }
+        OS::ReleaseMutex();
+    }
+}
+
+
+LocalWriter localWriter;
+
 
 } /* namespace Trace */