Someone asked this exact same question before but there's no working answer.
I am writing a little helper string class for the kernel, and want to implement a Format() type function that takes printf specifiers. I can use RtlStringCchVPrintfExW kernel safe string function for formatting, but how do I calculate the size of the buffer to give it in the 1st parameter?
_vscwprintf can do it in user mode, but what shall I use in the kernel?
I can estimate the size, say by adding a page or two, and then repeat if RtlStringCchVPrintfExW fails, but that seems awfully inefficient and wasteful on memory.
OK, I guess there's no way. It's so silly for them not to include it in their ntstrsafe.h.
So I ended up first preallocating a couple of pages of memory via ExAllocatePool2, then calling RtlStringCchVPrintfExW and if it fails with STATUS_BUFFER_OVERFLOW then to increase the allocation size by PAGE_SIZE, call ExFreePoolWithTag on the first memory block and repeat until RtlStringCchVPrintfExW returns STATUS_SUCCESS or some other status code.
It's a shame because this is such a wasteful way of doing it.