xref: /freebsd/contrib/llvm-project/lldb/include/lldb/Host/ProcessRunLock.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===-- ProcessRunLock.h ----------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_HOST_PROCESSRUNLOCK_H
10 #define LLDB_HOST_PROCESSRUNLOCK_H
11 
12 #include <cstdint>
13 #include <ctime>
14 
15 #include "lldb/lldb-defines.h"
16 
17 /// Enumerations for broadcasting.
18 namespace lldb_private {
19 
20 /// \class ProcessRunLock ProcessRunLock.h "lldb/Host/ProcessRunLock.h"
21 /// A class used to prevent the process from starting while other
22 /// threads are accessing its data, and prevent access to its data while it is
23 /// running.
24 
25 class ProcessRunLock {
26 public:
27   ProcessRunLock();
28   ~ProcessRunLock();
29 
30   bool ReadTryLock();
31   bool ReadUnlock();
32 
33   /// Set the process to running. Returns true if the process was stopped.
34   /// Return false if the process was running.
35   bool SetRunning();
36 
37   /// Set the process to stopped. Returns true if the process was running.
38   /// Returns false if the process was stopped.
39   bool SetStopped();
40 
41   class ProcessRunLocker {
42   public:
43     ProcessRunLocker() = default;
44 
~ProcessRunLocker()45     ~ProcessRunLocker() { Unlock(); }
46 
47     // Try to lock the read lock, but only do so if there are no writers.
TryLock(ProcessRunLock * lock)48     bool TryLock(ProcessRunLock *lock) {
49       if (m_lock) {
50         if (m_lock == lock)
51           return true; // We already have this lock locked
52         else
53           Unlock();
54       }
55       if (lock) {
56         if (lock->ReadTryLock()) {
57           m_lock = lock;
58           return true;
59         }
60       }
61       return false;
62     }
63 
64   protected:
Unlock()65     void Unlock() {
66       if (m_lock) {
67         m_lock->ReadUnlock();
68         m_lock = nullptr;
69       }
70     }
71 
72     ProcessRunLock *m_lock = nullptr;
73 
74   private:
75     ProcessRunLocker(const ProcessRunLocker &) = delete;
76     const ProcessRunLocker &operator=(const ProcessRunLocker &) = delete;
77   };
78 
79 protected:
80   lldb::rwlock_t m_rwlock;
81   bool m_running = false;
82 
83 private:
84   ProcessRunLock(const ProcessRunLock &) = delete;
85   const ProcessRunLock &operator=(const ProcessRunLock &) = delete;
86 };
87 
88 } // namespace lldb_private
89 
90 #endif // LLDB_HOST_PROCESSRUNLOCK_H
91