内核字符串操作

发布于:2024-10-15 ⋅ 阅读:(82) ⋅ 点赞:(0)

ASCII:

#include <ntddk.h>

VOID UnDirver(PDRIVER_OBJECT pDirverObj)
{
	UNREFERENCED_PARAMETER(pDirverObj);
	DbgPrint("Unload Success!");
}

NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath)
{
	UNREFERENCED_PARAMETER(pRegPath);
	pDriverObj->DriverUnload = UnDirver;
	
	size_t dwlength = strlen("Hello word!") + 1;
	PVOID pBuffer = ExAllocatePoolWithTag(NonPagedPool, dwlength, '123');
	if (pBuffer != NULL)
	{
		RtlZeroMemory(pBuffer, dwlength);
		RtlCopyMemory(pBuffer, "Hello word!", dwlength);
		DbgPrint("%s", (CHAR*)pBuffer);
		ExFreePoolWithTag(pBuffer, '123');
	}
	return STATUS_SUCCESS;
}

Unicode:

#include <ntddk.h>

VOID UnDirver(PDRIVER_OBJECT pDirverObj)
{
	UNREFERENCED_PARAMETER(pDirverObj);
	DbgPrint("Unload Success!");
}

NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath)
{
	UNREFERENCED_PARAMETER(pRegPath);
	pDriverObj->DriverUnload = UnDirver;
	
	size_t dwlength = wcslen(L"Hello word!")*2 + 2;
	PVOID pBuffer = ExAllocatePoolWithTag(NonPagedPool, dwlength, '123');
	if (pBuffer != NULL)
	{
		RtlZeroMemory(pBuffer, dwlength);
		RtlCopyMemory(pBuffer, L"Hello word!", dwlength);
		DbgPrint("%ws", (WCHAR*)pBuffer);
		ExFreePoolWithTag(pBuffer, '123');
	}
	return STATUS_SUCCESS;
}

UNICODE_STRING:

#include <ntddk.h>

VOID UnDirver(PDRIVER_OBJECT pDriverObj) {
	UNREFERENCED_PARAMETER(pDriverObj);
	DbgPrint("Driver Unloaded.\n");
}

NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegPath) {
	UNREFERENCED_PARAMETER(pRegPath);
	pDriverObj->DriverUnload = UnDirver;

	//第一种
	DECLARE_CONST_UNICODE_STRING(obj0, L"Hello word!-0\n");
	DbgPrint("%wZ", &obj0);

	//第二种
	UNICODE_STRING obj1 = RTL_CONSTANT_STRING(L"Hello word!-1\n");
	DbgPrint("%wZ", &obj1);

	//第三种
	UNICODE_STRING obj2 = { 0 };
	RtlInitUnicodeString(&obj2, L"Hello word!-2\n");
	DbgPrint("%wZ", &obj2);

	//第四种
	UNICODE_STRING obj3 = { 0 };
	obj3.Buffer = L"Hello word!-3\n";
	obj3.Length = wcslen(L"Hello word!-3\n") * sizeof(WCHAR);
	obj3.MaximumLength = obj3.Length + 2;
	DbgPrint("%wZ", &obj3);

	//第五种
	UNICODE_STRING obj4 = { 0 };
	ULONG ullength = (wcslen(L"Hello word!-4") * sizeof(WCHAR));
	obj4.Buffer = ExAllocatePool(NonPagedPool, ullength);
	obj4.Length = ullength;
	obj4.MaximumLength = ullength + 2;
	memset(obj4.Buffer, 0, ullength);
	memcpy(obj4.Buffer, L"Hello word!-4", ullength);
	DbgPrint("%wZ", &obj4);

	//字符串拷贝
	UNICODE_STRING obj5 = { 0 };
	WCHAR wcbuffer[256];
	RtlInitEmptyUnicodeString(&obj5, wcbuffer, sizeof(wcbuffer));
	RtlCopyUnicodeString(&obj5, &obj4);
	DbgPrint("%wZ", &obj5);

	//字符串拼接
	RtlAppendUnicodeStringToString(&obj5, &obj5);
	DbgPrint("%wZ", &obj5);

	//字符串对比
	if (RtlCompareUnicodeString(&obj0,&obj1,TRUE) == 0)
	{
		DbgPrint("==");
	}
	else
	{
		DbgPrint("!=");
	}

	ExFreePool(obj4.Buffer);
	return STATUS_SUCCESS;
}