Search code examples
kerneldriverunicode-stringwcharwindows-kernel

Convert WCHAR * to UNICODE STRING


First try at windows driver development. How can I convert a WCHAR array (coming from user-space) to a UNICODE_STRING (in kernel mode) assuming that the WCHAR array is not null-terminated?

Should I verify if it ends with null and if it doesn't allocate a new buffer (+2 for the null) and then use the RtlAnsiXXX functions? What is the proper way?

Thanks!


Solution

  • To initialize UNICODE_STRING from wchar array use RtlInitUnicodeString.

    WCHAR array has to be null-terminated.

    So if you checked and wchar-string is not null terminated, you should allocate a new buffer(+sizeof(WCHAR) for null), copy array content and then call RtlInitUnicodeString.

    To check if wchar-string from user-mode is null-terminated I am using:

    BOOLEAN IsStringTerminated(PWCHAR Array, USHORT ArrayLength, USHORT *StringLength)
    {
        BOOLEAN bStringIsTerminated = FALSE;
        USHORT uiIndex = 0;
    
        *StringLength = 0;
    
        while(uiIndex < ArrayLength && bStringIsTerminated == FALSE)
        {
            if(Array[uiIndex] == L'\0')
            {
                *StringLength = uiIndex + 1;
                bStringIsTerminated = TRUE;
            }
            else
            {
                uiIndex++;
            }
        }
    
        return bStringIsTerminated;
    }