tags:

views:

70

answers:

3

Hello everyone. I'm trying to debug print an LPCWSTR string, but I get a problem during the sprintf push in the buffer, because it retrieve only the first character from the string. Here is the code:

HANDLE WINAPI hookedCreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
 char buffer[1024];
 sprintf_s(buffer, 1024, "CreateFileW: %s", lpFileName);
 OutputDebugString(buffer); 
 return trueCreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwFlagsAndAttributes, dwCreationDisposition, hTemplateFile);
}

For example I get "CreateFileW: C" or "CreateFileW: \". How do I properly push it in the buffer?

Thank you.

+3  A: 

Use swprintf_s which is the version of sprintf_s which is designed for wide-character strings.

You'll also need an array of wchar_t instead of char and to use OutputDebugStringW()

Also, note you that swprintf_w might not be entierly what you want to call. If it encounters a string that is longer than the size you give it, it executes some sort of assertion. I suggest you test this situation specifically.

shoosh
+1  A: 

Unless you have a concrete reason to target unicode in this single function (and not, say, in your entire project), it might be wise to use charset-agnostic macros wherever possible:

HANDLE WINAPI hookedCreateFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
 TCHAR buffer[1024];
 _stprintf_s(buffer, 1024, _T("CreateFileW: %s"), lpFileName);
 OutputDebugString(buffer); 
 return trueCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwFlagsAndAttributes, dwCreationDisposition, hTemplateFile);
}
Ofek Shilon
+1  A: 

You need to tell sprintf() that you pass a wide character string. Use the %ls specifier:

 sprintf_s(buffer, 1024, "CreateFileW: %ls", lpFileName);
Hans Passant