From 1e07be4de953a24b1cf8c85debca7383360136b0 Mon Sep 17 00:00:00 2001
From: antonkukoba <akukoba@adfsolutions.com>
Date: Thu, 26 Dec 2013 14:15:54 +0200
Subject: [PATCH] Fixed Tls initialization problem

Visual Studio optimization removes GetTlsIndex class constructor execution in release builds, due to it's not used anywhere. So the previous code has never initialized tlsIndex variable with anything. Such behavior sometime caused the crashes due to error code was not saved into unallocated TLS.
I've made the explicit calls of GetTlsIndex methods to force class instance creation.
p.s. You may see it yourself how TlsGetValue() fails each time by running the release build under MS Application verifier.
---
 tsk/base/tsk_error_win32.cpp | 24 ++++++++++++++++--------
 1 file changed, 16 insertions(+), 8 deletions(-)

diff --git a/tsk/base/tsk_error_win32.cpp b/tsk/base/tsk_error_win32.cpp
index c67b1e0e6..0e7172cc5 100644
--- a/tsk/base/tsk_error_win32.cpp
+++ b/tsk/base/tsk_error_win32.cpp
@@ -15,22 +15,26 @@
 
 #include <windows.h>
 
-static DWORD tlsIndex;
-
 namespace tsk {
 
-	static DWORD tlsIndex;
-
 	class GetTlsIndex {
 	public:
 		GetTlsIndex() {
 			tlsIndex = TlsAlloc();
 		}
+		
 		~GetTlsIndex() {
 			TlsFree(tlsIndex);
 		}
+    
+		DWORD GetIndex() {
+			return tlsIndex;
+		}
+	private:
+		static DWORD tlsIndex;
 	};
 
+	DWORD GetTlsIndex::tlsIndex;
 	static GetTlsIndex getTlsIndex;
 }
 
@@ -40,11 +44,13 @@ namespace tsk {
  */
 extern "C"
 void *tsk_error_win32_get_per_thread_(unsigned struct_size) {
-	void *ptr = TlsGetValue(tlsIndex);
+
+	DWORD index = tsk::getTlsIndex.GetIndex();
+	void *ptr = TlsGetValue( index );
 	if (ptr == 0) {
 		ptr = malloc(struct_size);
 		memset(ptr, 0, struct_size);
-		TlsSetValue(tlsIndex, ptr);
+		TlsSetValue(index, ptr);
 	}
 	return ptr;
 }
@@ -54,10 +60,12 @@ void *tsk_error_win32_get_per_thread_(unsigned struct_size) {
 */
 extern "C"
 void tsk_error_win32_thread_cleanup() {
-	void *ptr = TlsGetValue(tlsIndex);
+
+	DWORD index = tsk::getTlsIndex.GetIndex();
+	void *ptr = TlsGetValue(index);
 	if (ptr != 0) {
 		free(ptr);
-		TlsSetValue(tlsIndex, 0);
+		TlsSetValue(index, 0);
 	}
 }
 
-- 
GitLab