[Lldb-commits] [PATCH] D154271: [lldb] Fix data race when interacting with python scripts

Med Ismail Bennani via Phabricator via lldb-commits lldb-commits at lists.llvm.org
Sun Jul 2 01:10:19 PDT 2023


mib updated this revision to Diff 536573.
mib added a comment.

Make `DecrementLockCount` actually thread-safe and revert `IncrementLockCount` to its original implementation.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154271/new/

https://reviews.llvm.org/D154271

Files:
  lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h
  lldb/source/Target/Process.cpp


Index: lldb/source/Target/Process.cpp
===================================================================
--- lldb/source/Target/Process.cpp
+++ lldb/source/Target/Process.cpp
@@ -2467,6 +2467,7 @@
 }
 
 void Process::LoadOperatingSystemPlugin(bool flush) {
+  std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
   if (flush)
     m_thread_list.Clear();
   m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Index: lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h
===================================================================
--- lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h
+++ lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPythonImpl.h
@@ -383,9 +383,13 @@
   uint32_t IncrementLockCount() { return ++m_lock_count; }
 
   uint32_t DecrementLockCount() {
-    if (m_lock_count > 0)
-      --m_lock_count;
-    return m_lock_count;
+    // std::atomic::fetch_sub is an atomic post-decrement operation so we need
+    // to subtract 1 from its return value.
+    uint32_t count = m_lock_count.fetch_sub(1, std::memory_order_relaxed) - 1;
+    if (static_cast<int32_t>(count) < 0)
+      // Handle underflow here & reset count to zero.
+      count = 0;
+    return count;
   }
 
   enum ActiveIOHandler {
@@ -421,7 +425,7 @@
   bool m_session_is_active;
   bool m_pty_secondary_is_open;
   bool m_valid_session;
-  uint32_t m_lock_count;
+  std::atomic<uint32_t> m_lock_count;
   PyThreadState *m_command_thread_state;
 };
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D154271.536573.patch
Type: text/x-patch
Size: 1520 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/lldb-commits/attachments/20230702/b0287bd4/attachment.bin>


More information about the lldb-commits mailing list