0x00 文档
https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/introduction-to-spin-locks
0x01 相关函数
KeDelayExecutionThread 在指定的时间间隔内将当前线程置于可报警或不可报警的等待状态(sleep)
KeInitializeSpinLock 初始化自旋锁
KeAcquireSpinLock 获得自旋锁,同时将IRQL提升至DPC,文档建议处理时间不超过25为秒
KeReleaseSpinLock 释放自旋锁,并恢复调用者运行的原始IRQL。
PsCreateSystemThread 创建一个以内核模式执行并返回线程句柄的系统线程
PsTerminateSystemThread终止当前系统线程。
0x02 代码
#include <wdm.h>
KSPIN_LOCK spinLock = { 0 };
int product = 0;
VOID DriverUnload(PDRIVER_OBJECT DriverObjecy)
{
DbgPrint("DriverUnload");
}
void producer(PVOID StartContext)
{
KIRQL oldIrql = { 0 };
int producing = 1;
while (producing < 11)
{
KeAcquireSpinLock(&spinLock, &oldIrql); //DISPATCH_LEVEL
if (product == 0)
{
product = producing;
DbgPrint("producing -> %d", producing); //PASSIVE_LEVEL
producing++;
}
KeReleaseSpinLock(&spinLock, oldIrql);
}
PsTerminateSystemThread(STATUS_SUCCESS);
}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObjecy, PUNICODE_STRING RegistryPath)
{
NTSTATUS status = STATUS_SUCCESS;
DriverObjecy->DriverUnload = DriverUnload;
KeInitializeSpinLock(&spinLock);
HANDLE ThreadHandle = NULL;
OBJECT_ATTRIBUTES ObjectAttributes = { 0 };
InitializeObjectAttributes(&ObjectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
status = PsCreateSystemThread(&ThreadHandle, GENERIC_ALL, &ObjectAttributes, NULL, NULL, producer, NULL);
if (!NT_SUCCESS(status))
{
DbgPrint("producer run failed");
return status;
}
ZwClose(ThreadHandle);
KIRQL oldIrql = { 0 };
int buy = 0;
while (product == 0);
while (buy <10)
{
KeAcquireSpinLock(&spinLock, &oldIrql);
if (product != 0)
{
buy = product;
product = 0;
DbgPrint("buy -> %d", buy);
}
KeReleaseSpinLock(&spinLock, oldIrql);
}
return status;
}