HyperDbg Debugger
Loading...
Searching...
No Matches
spinlock.cpp File Reference

This is the implementation for custom spinlock. More...

#include "pch.h"

Functions

BOOLEAN SpinlockTryLock (volatile LONG *Lock)
 Tries to get the lock otherwise returns.
 
void SpinlockLock (volatile LONG *Lock)
 Tries to get the lock and won't return until successfully get the lock.
 
void SpinlockLockWithCustomWait (volatile LONG *Lock, unsigned MaximumWait)
 Tries to get the lock and won't return until successfully get the lock.
 
void SpinlockUnlock (volatile LONG *Lock)
 Release the lock.
 

Detailed Description

This is the implementation for custom spinlock.

Author
Sina Karvandi (sina@.nosp@m.hype.nosp@m.rdbg..nosp@m.org)

This implementation is derived from Hvpp by Petr Benes

  • https://github.com/wbenny/hvpp Based on my benchmarks, this simple implementation beats other (often more complex) spinlock implementations - such as queue spinlocks, ticket spinlocks, MCS locks. The only difference between this implementation and completely naive spinlock is the "backoff".

Also, benefit of this implementation is that we can use it with STL lock guards, e.g.: std::lock_guard.

Look here for more information:

Version
0.1
Date
2022-05-19

Function Documentation

◆ SpinlockLock()

void SpinlockLock ( volatile LONG * Lock)

Tries to get the lock and won't return until successfully get the lock.

Parameters
LONGLock variable
53{
54 unsigned wait = 1;
55
56 while (!SpinlockTryLock(Lock))
57 {
58 for (unsigned i = 0; i < wait; ++i)
59 {
60 _mm_pause();
61 }
62
63 //
64 // Don't call "pause" too many times. If the wait becomes too big,
65 // clamp it to the MaxWait.
66 //
67
68 if (wait * 2 > MaxWait)
69 {
70 wait = MaxWait;
71 }
72 else
73 {
74 wait = wait * 2;
75 }
76 }
77}
BOOLEAN SpinlockTryLock(volatile LONG *Lock)
Tries to get the lock otherwise returns.
Definition spinlock.cpp:41

◆ SpinlockLockWithCustomWait()

void SpinlockLockWithCustomWait ( volatile LONG * Lock,
unsigned MaximumWait )

Tries to get the lock and won't return until successfully get the lock.

Parameters
LONGLock variable
LONGMaxWait Maximum wait (pause) count
87{
88 unsigned wait = 1;
89
90 while (!SpinlockTryLock(Lock))
91 {
92 for (unsigned i = 0; i < wait; ++i)
93 {
94 _mm_pause();
95 }
96
97 //
98 // Don't call "pause" too many times. If the wait becomes too big,
99 // clamp it to the MaxWait.
100 //
101
102 if (wait * 2 > MaximumWait)
103 {
104 wait = MaximumWait;
105 }
106 else
107 {
108 wait = wait * 2;
109 }
110 }
111}

◆ SpinlockTryLock()

BOOLEAN SpinlockTryLock ( volatile LONG * Lock)

Tries to get the lock otherwise returns.

Parameters
LONGLock variable
Returns
BOOLEAN If it was successful on getting the lock
42{
43 return (!(*Lock) && !_interlockedbittestandset(Lock, 0));
44}

◆ SpinlockUnlock()

void SpinlockUnlock ( volatile LONG * Lock)

Release the lock.

Parameters
LONGLock variable
120{
121 *Lock = 0;
122}