affinity mask ZwSetInformationThread

sometimes when setting affinity mask on ZwSetInformationThread its failing for me when setting on first core by using ZwCurrentThread();

KAFFINITY affinity = (1ull << 0);
	last_status = ZwSetInformationThread(
		ZwCurrentThread(),
		ThreadAffinityMask,
		&affinity,
		sizeof(KAFFINITY)
	);

to fix it i open handle by using ObOpenObjectByPointer and lookup for id by using PsLookupThreadByThreadId and thats fix it

PETHREAD pThread;
	HANDLE threadHandle;
	HANDLE threadId = (HANDLE)PsGetCurrentThreadId();
	PsLookupThreadByThreadId((HANDLE)threadId, &pThread);

	ObOpenObjectByPointer(pThread,
		OBJ_KERNEL_HANDLE,
		NULL,
		THREAD_ALL_ACCESS,
		*PsThreadType,
		KernelMode,
		&threadHandle);

	KAFFINITY affinity = (1ull << 0);
	last_status = ZwSetInformationThread(
		threadHandle,
		ThreadAffinityMask,
		&affinity,
		sizeof(KAFFINITY)
	);

make sure to close handle by using ZwClose/ObDereferenceObject to avoid leaks

may i ask why ZwCurrentThread failing ?

Just to ask the obvious question, are you running this in a thread that you have created? You don’t have the authority to change the affinity of any system or user threads.

yes u right using ZwOpenProcess/ZwOpenThread ALL_ACCESS fix that thanks !