windows驱动 - 自旋锁

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值