windows内核LookasiddeList使用

#include<ntifs.h>
#include<ntddk.h>
#include<wdm.h>
#include<intrin.h>

#include"slist.h"


namespace dbg {
	template<typename... types>
	void print(types... args)
	{
		DbgPrintEx(DPFLTR_DEFAULT_ID, DPFLTR_ERROR_LEVEL, args...);
	}

	__inline void dbgbreak() {
		if (*KdDebuggerNotPresent)
			print("breakpoint trigger\n");
		else
			DbgBreakPoint();


	}
}

//
//nonpaged pool 16byte align
//
#pragma(pack,16)
LOOKASIDE_LIST_EX lalist{};


struct test {
	SLIST_ENTRY et;
	int a;
	int b;
	int c;
};

void unload(PDRIVER_OBJECT DriverObject) {
	return;
}

extern "C" NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegPath) {

	NTSTATUS Status = STATUS_SUCCESS;
	int t1 = 0, t2 = 0, t11 = 0, t22 = 0;

	DriverObject->DriverUnload = unload;

	//Ex版本 vista后可用
	Status = ExInitializeLookasideListEx(&lalist, NULL, NULL, NonPagedPool, EX_LOOKASIDE_LIST_EX_FLAGS_RAISE_ON_FAIL,sizeof(test) ,'aaaa', 0);

	if (!NT_SUCCESS(Status))
	{
		return Status;
	}

	slist s1;
	slist s2;
	s1.InitSlist();
	s2.InitSlist();
	
	static int cnt = 0x10000;

	_disable();
	t11 = __rdtsc();
	for (int i = 0; i < cnt; i++)
	{
		test* pt = (test*)ExAllocatePoolWithTag(NonPagedPool, sizeof(test), 'aaaa');
		NT_ASSERT(pt);
		s1.Push(&pt->et);
	}
	t22 = __rdtsc();

	t1 = __rdtsc();
	for (int i = 0; i < cnt; i++)
	{
		test* pt = (test*)ExAllocateFromLookasideListEx(&lalist);
		NT_ASSERT(pt);
		s2.Push(&pt->et);
	}
	t2 = __rdtsc();
	_enable();


	dbg::print("Exalloc time spend %d\n", t22 - t11);
	dbg::print("Lookaside time spend %d\n", t2 - t1);
	
	for (int i = 0; i < cnt; i++) {
		test* t = (test*)s1.Pop();
		ExFreePoolWithTag(t, 'aaaa');
	}

	for (int i = 0; i < cnt; i++) {
		test* t = (test*)s2.Pop();
		ExFreeToLookasideListEx(&lalist, t);
	}
	
	
	ExDeleteLookasideListEx(&lalist);

	

	return STATUS_SUCCESS;
}
1