You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by sw...@apache.org on 2024/07/24 00:12:53 UTC

(logging-log4cxx) branch master updated: Prevent a possible 'use after free' fault when using AsyncAppender (#397)

This is an automated email from the ASF dual-hosted git repository.

swebb2066 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/logging-log4cxx.git


The following commit(s) were added to refs/heads/master by this push:
     new d925a2e3 Prevent a possible 'use after free' fault when using AsyncAppender (#397)
d925a2e3 is described below

commit d925a2e3c2caba570ed2b20bb1e4bfd871352956
Author: Stephen Webb <st...@ieee.org>
AuthorDate: Wed Jul 24 10:12:48 2024 +1000

    Prevent a possible 'use after free' fault when using AsyncAppender (#397)
    
    * Prefer thread_local over APR
    
    * Provide a minimal Optional for C++11
    
    * Document ThreadSpecificData methods
    
    * Update the change report
---
 src/main/cpp/asyncappender.cpp                     |   8 +-
 src/main/cpp/loggingevent.cpp                      | 325 +++++++--------------
 src/main/cpp/ndc.cpp                               |   4 +-
 src/main/cpp/smtpappender.cpp                      |   7 +-
 src/main/cpp/threadspecificdata.cpp                | 106 ++++++-
 src/main/include/log4cxx/helpers/optional.h        |  62 ++++
 .../include/log4cxx/helpers/threadspecificdata.h   |  46 ++-
 src/main/include/log4cxx/ndc.h                     |   4 +-
 src/main/include/log4cxx/spi/loggingevent.h        |  11 +-
 src/site/markdown/change-report-gh.md              |   1 +
 src/test/cpp/asyncappendertestcase.cpp             |  21 +-
 11 files changed, 330 insertions(+), 265 deletions(-)

diff --git a/src/main/cpp/asyncappender.cpp b/src/main/cpp/asyncappender.cpp
index 82894d91..69533ff6 100644
--- a/src/main/cpp/asyncappender.cpp
+++ b/src/main/cpp/asyncappender.cpp
@@ -282,12 +282,8 @@ void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p)
 		priv->appenders.appendLoopOnAppenders(event, p);
 	}
 
-	// Set the NDC and MDC for the calling thread as these
-	// LoggingEvent fields were not set at event creation time.
-	LogString ndcVal;
-	event->getNDC(ndcVal);
-	// Get a copy of this thread's MDC.
-	event->getMDCCopy();
+	// Get a copy of this thread's diagnostic context
+	event->LoadDC();
 
 	if (!priv->dispatcher.joinable())
 	{
diff --git a/src/main/cpp/loggingevent.cpp b/src/main/cpp/loggingevent.cpp
index df9545ce..e76ded9b 100644
--- a/src/main/cpp/loggingevent.cpp
+++ b/src/main/cpp/loggingevent.cpp
@@ -28,16 +28,9 @@
 #endif
 #include <log4cxx/helpers/aprinitializer.h>
 #include <log4cxx/helpers/threadspecificdata.h>
-#include <log4cxx/helpers/transcoder.h>
-
-#include <apr_portable.h>
-#include <apr_strings.h>
-#include <log4cxx/helpers/stringhelper.h>
 #include <log4cxx/helpers/bytebuffer.h>
-#include <log4cxx/logger.h>
-#include <log4cxx/private/log4cxx_private.h>
 #include <log4cxx/helpers/date.h>
-#include <thread>
+#include <log4cxx/helpers/optional.h>
 
 using namespace LOG4CXX_NS;
 using namespace LOG4CXX_NS::spi;
@@ -45,16 +38,13 @@ using namespace LOG4CXX_NS::helpers;
 
 struct LoggingEvent::LoggingEventPrivate
 {
-	LoggingEventPrivate() :
-		ndc(0),
-		mdcCopy(0),
-		properties(0),
-		ndcLookupRequired(true),
-		mdcCopyLookupRequired(true),
+	LoggingEventPrivate(const ThreadSpecificData::NamePairPtr& p = ThreadSpecificData::getCurrentData()->getNames()) :
 		timeStamp(0),
-		locationInfo(),
-		threadName(getCurrentThreadName()),
-		threadUserName(getCurrentThreadUserName())
+#if LOG4CXX_ABI_VERSION <= 15
+		threadName(p->idString),
+		threadUserName(p->threadName),
+#endif
+		pNames(p)
 	{
 	}
 
@@ -63,107 +53,108 @@ struct LoggingEvent::LoggingEventPrivate
 		, const LevelPtr& level1
 		, const LocationInfo& locationInfo1
 		, LogString&& message1
+		, const ThreadSpecificData::NamePairPtr& p = ThreadSpecificData::getCurrentData()->getNames()
 		) :
 		logger(logger1),
 		level(level1),
-		ndc(0),
-		mdcCopy(0),
-		properties(0),
-		ndcLookupRequired(true),
-		mdcCopyLookupRequired(true),
 		message(std::move(message1)),
 		timeStamp(Date::currentTime()),
 		locationInfo(locationInfo1),
-		threadName(getCurrentThreadName()),
-		threadUserName(getCurrentThreadUserName()),
-		chronoTimeStamp(std::chrono::microseconds(timeStamp))
+#if LOG4CXX_ABI_VERSION <= 15
+		threadName(p->idString),
+		threadUserName(p->threadName),
+#endif
+		chronoTimeStamp(std::chrono::microseconds(timeStamp)),
+		pNames(p)
 	{
 	}
 
 	LoggingEventPrivate(
 		const LogString& logger1, const LevelPtr& level1,
-		const LogString& message1, const LocationInfo& locationInfo1) :
+		const LogString& message1, const LocationInfo& locationInfo1,
+		const ThreadSpecificData::NamePairPtr& p = ThreadSpecificData::getCurrentData()->getNames()
+		) :
 		logger(logger1),
 		level(level1),
-		ndc(0),
-		mdcCopy(0),
-		properties(0),
-		ndcLookupRequired(true),
-		mdcCopyLookupRequired(true),
 		message(message1),
 		timeStamp(Date::currentTime()),
 		locationInfo(locationInfo1),
-		threadName(getCurrentThreadName()),
-		threadUserName(getCurrentThreadUserName()),
-		chronoTimeStamp(std::chrono::microseconds(timeStamp))
+#if LOG4CXX_ABI_VERSION <= 15
+		threadName(p->idString),
+		threadUserName(p->threadName),
+#endif
+		chronoTimeStamp(std::chrono::microseconds(timeStamp)),
+		pNames(p)
 	{
 	}
 
 	~LoggingEventPrivate()
 	{
-		delete ndc;
-		delete mdcCopy;
 		delete properties;
 	}
 
 	/**
-	* The logger of the logging event.
+	* The name of the logger used to make the logging request
 	**/
 	LogString logger;
 
-	/** level of logging event. */
+	/** severity level of logging event. */
 	LevelPtr level;
 
-	/** The nested diagnostic context (NDC) of logging event. */
-	mutable LogString* ndc;
+#if LOG4CXX_ABI_VERSION <= 15
+	mutable LogString* ndc{NULL};
 
-	/** The mapped diagnostic context (MDC) of logging event. */
-	mutable MDC::Map* mdcCopy;
+	mutable MDC::Map* mdcCopy{NULL};
+#endif
 
 	/**
 	* A map of String keys and String values.
 	*/
-	std::map<LogString, LogString>* properties;
+	std::map<LogString, LogString>* properties{NULL};
 
-	/** Have we tried to do an NDC lookup? If we did, there is no need
-	*  to do it again.  Note that its value is always false when
-	*  serialized. Thus, a receiving SocketNode will never use it's own
-	*  (incorrect) NDC. See also writeObject method.
-	*/
-	mutable bool ndcLookupRequired;
+#if LOG4CXX_ABI_VERSION <= 15
+	mutable bool ndcLookupRequired{false};
 
-	/**
-	* Have we tried to do an MDC lookup? If we did, there is no need to do it
-	* again.  Note that its value is always false when serialized. See also
-	* the getMDC and getMDCCopy methods.
-	*/
-	mutable bool mdcCopyLookupRequired;
+	mutable bool mdcCopyLookupRequired{false};
+#endif
 
-	/** The application supplied message of logging event. */
+	/** The application supplied message. */
 	LogString message;
 
 
-	/** The number of microseconds elapsed from 01.01.1970 until logging event
-	 was created. */
+	/** The number of microseconds elapsed since 1970-01-01
+	 *  at the time this logging event was created.
+	 */
 	log4cxx_time_t timeStamp;
 
-	/** The is the location where this log statement was written. */
-	const LOG4CXX_NS::spi::LocationInfo locationInfo;
+	/** The source code location where the logging request was made. */
+	const spi::LocationInfo locationInfo;
 
 
-	/** The identifier of thread in which this logging event
-	was generated.
-	*/
+#if LOG4CXX_ABI_VERSION <= 15
 	const LogString& threadName;
 
-	/**
-	 * The user-specified name of the thread(on a per-platform basis).
-	 * This is set using a method such as pthread_setname_np on POSIX
-	 * systems or SetThreadDescription on Windows.
-	 */
 	const LogString& threadUserName;
+#endif
 
 	std::chrono::time_point<std::chrono::system_clock> chronoTimeStamp;
+
+	/**
+	 *  Thread names that remain valid for the lifetime of this LoggingEvent
+	 *  (i.e. even after thread termination).
+	 */
+	ThreadSpecificData::NamePairPtr pNames;
+
+	struct DiagnosticContext
+	{
+		Optional<NDC::DiagnosticContext> ctx;
+		MDC::Map map;
+	};
+	/**
+	 *  Used to hold the diagnostic context when the lifetime
+	 *  of this LoggingEvent exceeds the duration of the logging request.
+	 */
+	mutable std::unique_ptr<DiagnosticContext> dc;
 };
 
 IMPLEMENT_LOG4CXX_OBJECT(LoggingEvent)
@@ -203,100 +194,76 @@ LoggingEvent::~LoggingEvent()
 {
 }
 
-const LogString& LoggingEvent::getThreadUserName() const{
-	return m_priv->threadUserName;
+const LogString& LoggingEvent::getThreadUserName() const
+{
+	return m_priv->pNames->threadName;
 }
 
 bool LoggingEvent::getNDC(LogString& dest) const
 {
-	if (m_priv->ndcLookupRequired)
+	bool result = false;
+	// Use the copy of the diagnostic context if it exists.
+	// Otherwise use the NDC that is associated with the thread.
+	if (m_priv->dc)
 	{
-		m_priv->ndcLookupRequired = false;
-		LogString val;
-
-		if (NDC::get(val))
-		{
-			m_priv->ndc = new LogString(val);
-		}
+		if (result = m_priv->dc->ctx.has_value())
+			dest.append(NDC::getFullMessage(m_priv->dc->ctx.value()));
 	}
-
-	if (m_priv->ndc)
-	{
-		dest.append(*m_priv->ndc);
-		return true;
-	}
-
-	return false;
+	else
+		result = NDC::get(dest);
+	return result;
 }
 
 bool LoggingEvent::getMDC(const LogString& key, LogString& dest) const
 {
-	// Note the mdcCopy is used if it exists. Otherwise we use the MDC
-	// that is associated with the thread.
-	if (m_priv->mdcCopy != 0 && !m_priv->mdcCopy->empty())
+	bool result = false;
+	// Use the copy of the diagnostic context if it exists.
+	// Otherwise use the MDC that is associated with the thread.
+	if (m_priv->dc)
 	{
-		MDC::Map::const_iterator it = m_priv->mdcCopy->find(key);
-
-		if (it != m_priv->mdcCopy->end())
+		auto& map = m_priv->dc->map;
+		auto it = map.find(key);
+		if (it != map.end() && !it->second.empty())
 		{
-			if (!it->second.empty())
-			{
-				dest.append(it->second);
-				return true;
-			}
+			dest.append(it->second);
+			result = true;
 		}
 	}
-
-	return MDC::get(key, dest);
-
+	else
+		result = MDC::get(key, dest);
+	return result;
 }
 
 LoggingEvent::KeySet LoggingEvent::getMDCKeySet() const
 {
-	LoggingEvent::KeySet set;
-
-	if (m_priv->mdcCopy && !m_priv->mdcCopy->empty())
-	{
-		for (auto const& item : *m_priv->mdcCopy)
-		{
-			set.push_back(item.first);
-
-		}
-	}
-	else
+	LoggingEvent::KeySet result;
+	if (m_priv->dc)
 	{
-		ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
-
-		if (data)
-		{
-			for (auto const& item : data->getMap())
-			{
-				set.push_back(item.first);
-			}
-		}
+		for (auto const& item : m_priv->dc->map)
+			result.push_back(item.first);
 	}
+	else for (auto const& item : ThreadSpecificData::getCurrentData()->getMap())
+		result.push_back(item.first);
+	return result;
+}
 
-	return set;
+void LoggingEvent::LoadDC() const
+{
+	m_priv->dc = std::make_unique<LoggingEventPrivate::DiagnosticContext>();
+	auto pData = ThreadSpecificData::getCurrentData();
+	m_priv->dc->map = pData->getMap();
+	auto& stack = pData->getStack();
+	if (!stack.empty())
+		m_priv->dc->ctx = stack.top();
 }
 
+#if LOG4CXX_ABI_VERSION <= 15
 void LoggingEvent::getMDCCopy() const
 {
-	if (m_priv->mdcCopyLookupRequired)
-	{
-		m_priv->mdcCopyLookupRequired = false;
-		// the clone call is required for asynchronous logging.
-		ThreadSpecificData* data = ThreadSpecificData::getCurrentData();
-
-		if (data != 0)
-		{
-			m_priv->mdcCopy = new MDC::Map(data->getMap());
-		}
-		else
-		{
-			m_priv->mdcCopy = new MDC::Map();
-		}
-	}
+	if (!m_priv->dc)
+		LoadDC();
 }
+#endif
 
 bool LoggingEvent::getProperty(const LogString& key, LogString& dest) const
 {
@@ -331,90 +298,6 @@ LoggingEvent::KeySet LoggingEvent::getPropertyKeySet() const
 	return set;
 }
 
-
-const LogString& LoggingEvent::getCurrentThreadName()
-{
-#if LOG4CXX_HAS_THREAD_LOCAL
-	thread_local LogString thread_id_string;
-#else
-	LogString& thread_id_string = ThreadSpecificData::getThreadIdString();
-#endif
-	if ( !thread_id_string.empty() )
-	{
-		return thread_id_string;
-	}
-
-#if LOG4CXX_HAS_PTHREAD_SELF && !(defined(_WIN32) && defined(_LIBCPP_VERSION))
-	// pthread_t encoded in HEX takes needs as many characters
-	// as two times the size of the type, plus an additional null byte.
-	auto threadId = pthread_self();
-	char result[sizeof(pthread_t) * 3 + 10];
-	apr_snprintf(result, sizeof(result), LOG4CXX_APR_THREAD_FMTSPEC, (void*) &threadId);
-	thread_id_string = Transcoder::decode(result);
-#elif defined(_WIN32)
-	char result[20];
-	apr_snprintf(result, sizeof(result), LOG4CXX_WIN32_THREAD_FMTSPEC, GetCurrentThreadId());
-	thread_id_string = Transcoder::decode(result);
-#else
-	std::stringstream ss;
-	ss << std::hex << "0x" << std::this_thread::get_id();
-	thread_id_string = Transcoder::decode(ss.str().c_str());
-#endif
-	return thread_id_string;
-}
-
-const LogString& LoggingEvent::getCurrentThreadUserName()
-{
-#if LOG4CXX_HAS_THREAD_LOCAL
-	thread_local LogString thread_name;
-#else
-	LogString& thread_name = ThreadSpecificData::getThreadName();
-#endif
-	if( !thread_name.empty() ){
-		return thread_name;
-	}
-
-#if LOG4CXX_HAS_PTHREAD_GETNAME && !(defined(_WIN32) && defined(_LIBCPP_VERSION))
-	char result[16];
-	pthread_t current_thread = pthread_self();
-	if (pthread_getname_np(current_thread, result, sizeof(result)) < 0 || 0 == result[0])
-		thread_name = getCurrentThreadName();
-	else
-		thread_name = Transcoder::decode(result);
-#elif defined(_WIN32)
-	typedef HRESULT (WINAPI *TGetThreadDescription)(HANDLE, PWSTR*);
-	static struct initialiser
-	{
-		HMODULE hKernelBase;
-		TGetThreadDescription GetThreadDescription;
-		initialiser()
-			: hKernelBase(GetModuleHandleA("KernelBase.dll"))
-			, GetThreadDescription(nullptr)
-		{
-			if (hKernelBase)
-				GetThreadDescription = reinterpret_cast<TGetThreadDescription>(GetProcAddress(hKernelBase, "GetThreadDescription"));
-		}
-	} win32func;
-	if (win32func.GetThreadDescription)
-	{
-		PWSTR result = 0;
-		HRESULT hr = win32func.GetThreadDescription(GetCurrentThread(), &result);
-		if (SUCCEEDED(hr) && result)
-		{
-			std::wstring wresult = result;
-			LOG4CXX_DECODE_WCHAR(decoded, wresult);
-			LocalFree(result);
-			thread_name = decoded;
-		}
-	}
-	if (thread_name.empty())
-		thread_name = getCurrentThreadName();
-#else
-	thread_name = getCurrentThreadName();
-#endif
-	return thread_name;
-}
-
 void LoggingEvent::setProperty(const LogString& key, const LogString& value)
 {
 	if (m_priv->properties == 0)
@@ -447,7 +330,7 @@ const LogString& LoggingEvent::getRenderedMessage() const
 
 const LogString& LoggingEvent::getThreadName() const
 {
-	return m_priv->threadName;
+	return m_priv->pNames->idString;
 }
 
 log4cxx_time_t LoggingEvent::getTimeStamp() const
diff --git a/src/main/cpp/ndc.cpp b/src/main/cpp/ndc.cpp
index 48c730f2..25d1981b 100644
--- a/src/main/cpp/ndc.cpp
+++ b/src/main/cpp/ndc.cpp
@@ -33,12 +33,12 @@ NDC::~NDC()
 }
 
 
-LogString& NDC::getMessage(NDC::DiagnosticContext& ctx)
+const LogString& NDC::getMessage(const DiagnosticContext& ctx)
 {
 	return ctx.first;
 }
 
-LogString& NDC::getFullMessage(NDC::DiagnosticContext& ctx)
+const LogString& NDC::getFullMessage(const DiagnosticContext& ctx)
 {
 	return ctx.second;
 }
diff --git a/src/main/cpp/smtpappender.cpp b/src/main/cpp/smtpappender.cpp
index a09d6250..752d25db 100644
--- a/src/main/cpp/smtpappender.cpp
+++ b/src/main/cpp/smtpappender.cpp
@@ -644,11 +644,8 @@ void SMTPAppender::append(const spi::LoggingEventPtr& event, Pool& p)
 		return;
 	}
 
-	LogString ndc;
-	event->getNDC(ndc);
-	event->getThreadName();
-	// Get a copy of this thread's MDC.
-	event->getMDCCopy();
+	// Get a copy of this thread's diagnostic context
+	event->LoadDC();
 
 	_priv->cb.add(event);
 
diff --git a/src/main/cpp/threadspecificdata.cpp b/src/main/cpp/threadspecificdata.cpp
index 654fb472..ecd70b70 100644
--- a/src/main/cpp/threadspecificdata.cpp
+++ b/src/main/cpp/threadspecificdata.cpp
@@ -19,10 +19,14 @@
 #include <log4cxx/logstring.h>
 #include <log4cxx/helpers/threadspecificdata.h>
 #include <log4cxx/helpers/exception.h>
+#include <log4cxx/helpers/stringhelper.h>
+#include <log4cxx/helpers/transcoder.h>
 #include <apr_thread_proc.h>
+#include <apr_strings.h>
 #if !defined(LOG4CXX)
 	#define LOG4CXX 1
 #endif
+#include <log4cxx/private/log4cxx_private.h>
 #include <log4cxx/helpers/aprinitializer.h>
 #include <sstream>
 #include <algorithm>
@@ -32,9 +36,17 @@ using namespace LOG4CXX_NS;
 using namespace LOG4CXX_NS::helpers;
 
 struct ThreadSpecificData::ThreadSpecificDataPrivate{
+	ThreadSpecificDataPrivate()
+		: pNamePair(std::make_shared<NamePair>())
+	{
+		setThreadIdName();
+		setThreadUserName();
+	}
 	NDC::Stack ndcStack;
 	MDC::Map mdcMap;
-	LogString str[2];
+
+	std::shared_ptr<NamePair> pNamePair;
+
 #if !LOG4CXX_LOGCHAR_IS_UNICHAR && !LOG4CXX_LOGCHAR_IS_WCHAR
 	std::basic_ostringstream<logchar> logchar_stringstream;
 #endif
@@ -44,8 +56,80 @@ struct ThreadSpecificData::ThreadSpecificDataPrivate{
 #if LOG4CXX_UNICHAR_API || LOG4CXX_LOGCHAR_IS_UNICHAR
 	std::basic_ostringstream<UniChar> unichar_stringstream;
 #endif
+
+	void setThreadIdName();
+	void setThreadUserName();
 };
 
+/* Generate an identifier for the current thread
+*/
+void ThreadSpecificData::ThreadSpecificDataPrivate::setThreadIdName()
+{
+#if LOG4CXX_HAS_PTHREAD_SELF && !(defined(_WIN32) && defined(_LIBCPP_VERSION))
+	// pthread_t encoded in HEX takes needs as many characters
+	// as two times the size of the type, plus an additional null byte.
+	auto threadId = pthread_self();
+	char result[sizeof(pthread_t) * 3 + 10];
+	apr_snprintf(result, sizeof(result), LOG4CXX_APR_THREAD_FMTSPEC, (void*) &threadId);
+	this->pNamePair->idString = Transcoder::decode(result);
+#elif defined(_WIN32)
+	char result[20];
+	apr_snprintf(result, sizeof(result), LOG4CXX_WIN32_THREAD_FMTSPEC, GetCurrentThreadId());
+	this->pNamePair->idString = Transcoder::decode(result);
+#else
+	std::stringstream ss;
+	ss << std::hex << "0x" << std::this_thread::get_id();
+	this->pNamePair->idString = Transcoder::decode(ss.str().c_str());
+#endif
+}
+
+/*
+ * Get the user-specified name of the current thread (on a per-platform basis).
+ * This is set using a method such as pthread_setname_np on POSIX
+ * systems or SetThreadDescription on Windows.
+ */
+void ThreadSpecificData::ThreadSpecificDataPrivate::setThreadUserName()
+{
+#if LOG4CXX_HAS_PTHREAD_GETNAME && !(defined(_WIN32) && defined(_LIBCPP_VERSION))
+	char result[16];
+	pthread_t current_thread = pthread_self();
+	if (pthread_getname_np(current_thread, result, sizeof(result)) < 0 || 0 == result[0])
+		this->pNamePair->threadName = this->pNamePair->idString;
+	else
+		this->pNamePair->threadName = Transcoder::decode(result);
+#elif defined(_WIN32)
+	typedef HRESULT (WINAPI *TGetThreadDescription)(HANDLE, PWSTR*);
+	static struct initialiser
+	{
+		HMODULE hKernelBase;
+		TGetThreadDescription GetThreadDescription;
+		initialiser()
+			: hKernelBase(GetModuleHandleA("KernelBase.dll"))
+			, GetThreadDescription(nullptr)
+		{
+			if (hKernelBase)
+				GetThreadDescription = reinterpret_cast<TGetThreadDescription>(GetProcAddress(hKernelBase, "GetThreadDescription"));
+		}
+	} win32func;
+	if (win32func.GetThreadDescription)
+	{
+		PWSTR result = 0;
+		HRESULT hr = win32func.GetThreadDescription(GetCurrentThread(), &result);
+		if (SUCCEEDED(hr) && result)
+		{
+			std::wstring wresult = result;
+			LOG4CXX_DECODE_WCHAR(decoded, wresult);
+			LocalFree(result);
+			this->pNamePair->threadName = decoded;
+		}
+	}
+	if (this->pNamePair->threadName.empty())
+		this->pNamePair->threadName = this->pNamePair->idString;
+#else
+	this->pNamePair->threadName = this->pNamePair->idString;
+#endif
+}
+
 ThreadSpecificData::ThreadSpecificData()
 	: m_priv(std::make_unique<ThreadSpecificDataPrivate>())
 {
@@ -60,7 +144,6 @@ ThreadSpecificData::~ThreadSpecificData()
 {
 }
 
-
 NDC::Stack& ThreadSpecificData::getStack()
 {
 	return m_priv->ndcStack;
@@ -71,14 +154,9 @@ MDC::Map& ThreadSpecificData::getMap()
 	return m_priv->mdcMap;
 }
 
-LogString& ThreadSpecificData::getThreadIdString()
+auto ThreadSpecificData::getNames() -> NamePairPtr
 {
-	return getCurrentData()->m_priv->str[0];
-}
-
-LogString& ThreadSpecificData::getThreadName()
-{
-	return getCurrentData()->m_priv->str[1];
+	return getCurrentData()->m_priv->pNamePair;
 }
 
 #if !LOG4CXX_LOGCHAR_IS_UNICHAR && !LOG4CXX_LOGCHAR_IS_WCHAR
@@ -104,7 +182,10 @@ std::basic_ostringstream<UniChar>& ThreadSpecificData::getStream(const UniChar&)
 
 ThreadSpecificData* ThreadSpecificData::getCurrentData()
 {
-#if APR_HAS_THREADS
+#if LOG4CXX_HAS_THREAD_LOCAL
+	thread_local ThreadSpecificData data;
+	return &data;
+#elif APR_HAS_THREADS
 	void* pData = NULL;
 	if (APR_SUCCESS == apr_threadkey_private_get(&pData, APRInitializer::getTlsKey())
 		&& !pData)
@@ -118,9 +199,6 @@ ThreadSpecificData* ThreadSpecificData::getCurrentData()
 	}
 	if (pData)
 		return (ThreadSpecificData*) pData;
-#elif LOG4CXX_HAS_THREAD_LOCAL
-	thread_local ThreadSpecificData data;
-	return &data;
 #endif
 
 	// Fallback implementation that is not expected to be used
@@ -138,7 +216,7 @@ ThreadSpecificData* ThreadSpecificData::getCurrentData()
 
 void ThreadSpecificData::recycle()
 {
-#if APR_HAS_THREADS
+#if !LOG4CXX_HAS_THREAD_LOCAL && APR_HAS_THREADS
 	if (m_priv->ndcStack.empty() && m_priv->mdcMap.empty())
 	{
 		void* pData = NULL;
diff --git a/src/main/include/log4cxx/helpers/optional.h b/src/main/include/log4cxx/helpers/optional.h
new file mode 100644
index 00000000..b4a7be72
--- /dev/null
+++ b/src/main/include/log4cxx/helpers/optional.h
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef LOG4CXX_OPTIONAL_HDR_
+#define LOG4CXX_OPTIONAL_HDR_
+
+#ifdef __has_include                           // Check if __has_include is present
+#  if __has_include(<optional>)                // Check for a standard version
+#    include <optional>
+#    if defined(__cpp_lib_optional)            // C++ >= 17
+namespace LOG4CXX_NS { template< class T > using Optional = std::optional<T>; }
+#define LOG4CXX_HAS_STD_OPTIONAL 1
+#    endif
+#  elif __has_include(<experimental/optional>) // Check for an experimental version
+#    include <experimental/optional>
+namespace LOG4CXX_NS { template< class T > using Optional = std::experimental::optional<T>; }
+#define LOG4CXX_HAS_STD_OPTIONAL 1
+#  elif __has_include(<boost/optional.hpp>)    // Try with an external library
+#    include <boost/optional.hpp>
+namespace LOG4CXX_NS { template< class T > using Optional = boost::optional<T>; }
+#define LOG4CXX_HAS_STD_OPTIONAL 1
+#  else                                        // Not found at all
+#define LOG4CXX_HAS_STD_OPTIONAL 0
+#  endif
+#endif
+
+#if !LOG4CXX_HAS_STD_OPTIONAL // Implement a minimal Optional?
+namespace LOG4CXX_NS
+{
+	template< class T >
+class Optional : private std::pair<bool, T>
+{
+	using BaseType = std::pair<bool, T>;
+public:
+	Optional() : BaseType(false, T()) {}
+	Optional& operator=(const T& value)
+	{
+		this->first = true;
+		this->second = value;
+		return *this;
+	}
+	bool has_value() const { return this->first; }
+	const T& value() const { return this->second; }
+};
+} // namespace LOG4CXX_NS
+#endif
+
+#endif // LOG4CXX_OPTIONAL_HDR_
diff --git a/src/main/include/log4cxx/helpers/threadspecificdata.h b/src/main/include/log4cxx/helpers/threadspecificdata.h
index 7fc7e2c7..2b7cf2a4 100644
--- a/src/main/include/log4cxx/helpers/threadspecificdata.h
+++ b/src/main/include/log4cxx/helpers/threadspecificdata.h
@@ -38,29 +38,65 @@ class LOG4CXX_EXPORT ThreadSpecificData
 
 		/**
 		 *  Gets current thread specific data.
-		 *  @return thread specific data, may be null.
+		 *  @return a pointer that is never null.
 		 */
 		static ThreadSpecificData* getCurrentData();
+
 		/**
-		 *  Release this ThreadSpecficData if empty.
+		 *  Remove current thread data from APR if the diagnostic context is empty.
 		 */
 		void recycle();
 
+		/**
+		 *  Add the \c key \c val pair to the mapped diagnostic context of the current thread
+		 */
 		static void put(const LogString& key, const LogString& val);
+
+		/**
+		 *  Add \c val to the nested diagnostic context of the current thread
+		 */
 		static void push(const LogString& val);
-		static void inherit(const LOG4CXX_NS::NDC::Stack& stack);
 
+		/**
+		 *  Use \c stack as the nested diagnostic context of the current thread
+		 */
+		static void inherit(const NDC::Stack& stack);
+
+		/**
+		 *  The nested diagnostic context of the current thread
+		 */
 		NDC::Stack& getStack();
+
+		/**
+		 *  The mapped diagnostic context of the current thread
+		 */
 		MDC::Map& getMap();
 
+		/**
+		 *  A character outpur stream only assessable to the current thread
+		 */
 		template <typename T>
 		static std::basic_ostringstream<T>& getStringStream()
 		{
 			return getStream(T());
 		}
-		static LogString& getThreadIdString();
-		static LogString& getThreadName();
 
+		/**
+		 *  The names assigned to the current thread
+		 */
+		struct NamePair
+		{
+			LogString idString;
+			LogString threadName;
+		};
+		using NamePairPtr = std::shared_ptr<NamePair>;
+		/**
+		 *  A reference counted pointer to the names of the current thread.
+		 *
+		 *  String references will remain valid
+		 *  for the lifetime of this pointer (i.e. even after thread termination).
+		 */
+		static NamePairPtr getNames();
 	private:
 #if !LOG4CXX_LOGCHAR_IS_UNICHAR && !LOG4CXX_LOGCHAR_IS_WCHAR
 		static std::basic_ostringstream<logchar>& getStream(const logchar&);
diff --git a/src/main/include/log4cxx/ndc.h b/src/main/include/log4cxx/ndc.h
index 9535fd55..bc47d2e1 100644
--- a/src/main/include/log4cxx/ndc.h
+++ b/src/main/include/log4cxx/ndc.h
@@ -286,11 +286,11 @@ class LOG4CXX_EXPORT NDC
 		static bool pop(CFStringRef& dst);
 #endif
 
+		static const LogString& getMessage(const DiagnosticContext& ctx);
+		static const LogString& getFullMessage(const DiagnosticContext& ctx);
 	private:
 		NDC(const NDC&);
 		NDC& operator=(const NDC&);
-		static LogString& getMessage(DiagnosticContext& ctx);
-		static LogString& getFullMessage(DiagnosticContext& ctx);
 }; // class NDC;
 }  // namespace log4cxx
 
diff --git a/src/main/include/log4cxx/spi/loggingevent.h b/src/main/include/log4cxx/spi/loggingevent.h
index 97c34bd1..29cf78b6 100644
--- a/src/main/include/log4cxx/spi/loggingevent.h
+++ b/src/main/include/log4cxx/spi/loggingevent.h
@@ -169,11 +169,20 @@ class LOG4CXX_EXPORT LoggingEvent :
 		*/
 		KeySet getMDCKeySet() const;
 
+#if LOG4CXX_ABI_VERSION <= 15
 		/**
 		Obtain a copy of this thread's MDC prior to serialization
 		or asynchronous logging.
 		*/
+		[[ deprecated( "Use LoadDC instead" ) ]]
 		void getMDCCopy() const;
+#endif
+
+		/**
+		Obtain a copy of this thread's diagnostic context prior to serialization
+		or asynchronous logging.
+		*/
+		void LoadDC() const;
 
 		/**
 		* Return a previously set property.
@@ -203,8 +212,6 @@ class LOG4CXX_EXPORT LoggingEvent :
 		//
 		LoggingEvent(const LoggingEvent&);
 		LoggingEvent& operator=(const LoggingEvent&);
-		static const LogString& getCurrentThreadName();
-		static const LogString& getCurrentThreadUserName();
 
 };
 
diff --git a/src/site/markdown/change-report-gh.md b/src/site/markdown/change-report-gh.md
index 320870d1..78f2ad4d 100644
--- a/src/site/markdown/change-report-gh.md
+++ b/src/site/markdown/change-report-gh.md
@@ -57,6 +57,7 @@ The following issues have been addressed:
 
 * MSYS2/MINGW build errors \[[#389](https://github.com/apache/logging-log4cxx/pull/389)\] 
 * `thread_local` problems in MSYS2/MINGW \[[#394](https://github.com/apache/logging-log4cxx/pull/394)\]
+* A potential 'use after free' fault when using AsyncAppender \[[#397](https://github.com/apache/logging-log4cxx/pull/397)\]
 
 ## Release 1.2.0 - 2024-01-01 {#rel_1_2_0}
 
diff --git a/src/test/cpp/asyncappendertestcase.cpp b/src/test/cpp/asyncappendertestcase.cpp
index 33b2f371..bffa5e73 100644
--- a/src/test/cpp/asyncappendertestcase.cpp
+++ b/src/test/cpp/asyncappendertestcase.cpp
@@ -234,7 +234,7 @@ class AsyncAppenderTestCase : public AppenderSkeletonTestCase
 		// this test checks all messages are delivered from multiple threads
 		void testMultiThread()
 		{
-			size_t LEN = 2000; // Larger than default buffer size (128)
+			int LEN = 2000; // Larger than default buffer size (128)
 			int threadCount = 6;
 			auto root = Logger::getRootLogger();
 			auto vectorAppender = std::make_shared<VectorAppender>();
@@ -248,7 +248,7 @@ class AsyncAppenderTestCase : public AppenderSkeletonTestCase
 			{
 				threads.emplace_back([root, LEN]()
 				{
-					for (size_t i = 0; i < LEN; i++)
+					for (int i = 0; i < LEN; i++)
 					{
 						LOG4CXX_DEBUG(root, "message" << i);
 					}
@@ -265,19 +265,24 @@ class AsyncAppenderTestCase : public AppenderSkeletonTestCase
 			asyncAppender->close();
 
 			const std::vector<spi::LoggingEventPtr>& v = vectorAppender->getVector();
-			LOGUNIT_ASSERT_EQUAL(LEN*threadCount, v.size());
-			std::vector<int> count(LEN, 0);
+			LOGUNIT_ASSERT_EQUAL(LEN*threadCount, (int)v.size());
+			std::map<LogString, int> perThreadCount;
+			std::vector<int> msgCount(LEN, 0);
 			for (auto m : v)
 			{
 				auto i = StringHelper::toInt(m->getMessage().substr(7));
 				LOGUNIT_ASSERT(0 <= i);
 				LOGUNIT_ASSERT(i < LEN);
-				++count[i];
+				++msgCount[i];
+				++perThreadCount[m->getThreadName()];
 			}
-			for (size_t i = 0; i < LEN; i++)
+			LOGUNIT_ASSERT_EQUAL(threadCount, (int)perThreadCount.size());
+			for (auto& item : perThreadCount)
 			{
-				LOGUNIT_ASSERT_EQUAL(count[i], threadCount);
+				LOGUNIT_ASSERT_EQUAL(item.second, LEN);
 			}
+			for (size_t i = 0; i < LEN; i++)
+				LOGUNIT_ASSERT_EQUAL(msgCount[i], threadCount);
 		}
 
 		/**
@@ -304,7 +309,7 @@ class AsyncAppenderTestCase : public AppenderSkeletonTestCase
 			asyncAppender->setErrorHandler(errorHandler);
 
 			LOG4CXX_INFO(root, "Message");
-			std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
+			std::this_thread::sleep_for( std::chrono::milliseconds( 30 ) );
 			LOGUNIT_ASSERT(errorHandler->errorReported());
 			LOG4CXX_INFO(root, "Message");
 			auto& v = vectorAppender->getVector();