Encountered strange situation with references as function parameter - c++

There is this method: SCardListReaders, having such parameters:
LONG WINAPI SCardListReaders(
_In_ SCARDCONTEXT hContext,
_In_opt_ LPCTSTR mszGroups,
_Out_ LPTSTR mszReaders,
_Inout_ LPDWORD pcchReaders
);
And being called like this(from MSDN):
LPTSTR pmszReaders = NULL;
LPTSTR pReader;
LONG lReturn, lReturn2;
DWORD cch = SCARD_AUTOALLOCATE;
// Retrieve the list the readers.
// hSC was set by a previous call to SCardEstablishContext.
lReturn = SCardListReaders(hSC,
NULL,
(LPTSTR)&pmszReaders,
&cch );
...
I am confused by the pmszReaders variable. Particularly, for Unicode builds it is already WCHAR* to my understanding, so why is &pmszReaders passed to the ScardListReaders function above, why not directly pmszReaders? (it is already a pointer right?).

Normally, you pass a pointer to a pre-allocated buffer (a LPTSTR). And that's why mszReaders is declared as LPTSTR.
But note that SCARD_AUTOALLOCATE is passed as last parameter. Only in this case, mszReaders is interpreted as pointer to pointer.
From MSDN:
pcchReaders [in, out]
Length of the mszReaders buffer in characters. This parameter receives the actual length of the multi-string structure, including all trailing null characters. If the buffer length is specified as SCARD_AUTOALLOCATE, then mszReaders is converted to a pointer to a byte pointer, and receives the address of a block of memory containing the multi-string structure. This block of memory must be deallocated with SCardFreeMemory.

From MSDN :
mszReaders [out]
Multi-string that lists the card readers within the supplied reader groups.
If this value is NULL, SCardListReaders ignores the buffer length supplied
in pcchReaders, writes the length of the buffer that would have been
returned if this parameter had not been NULL to pcchReaders,
and returns a success code.
It's a multi-string - as an array of string - so you need to take the address of the first reader as a parameter (pmszReaders being a WCHAR*, in others words a "wstring" ).

It is a bit obtuse to use (LPTSTR)&pmszReaders but according to the function documentation you'll see taht pmszReaders is a Multi-string.
They are giving you an array of LPTSTR by mallocing memory to the LPTSTR pointer you passed in.
The reasoning behind using LPTSTR instead of LPTSTR* is that Microsoft API's don't like using * in their API functions hence LPTSTR's existence in the first place.
To clarify, the LPTSTRyou are returned is in the format:
name1\0name2\0name3\0
Making it an LPTSTR and not an LPTSTR*.
You can safely ignore the _in_ _Out_ parts of code, they are for Microsoft profiling and general helpfulness. They don't have any effect on compiled code.

Related

RegEnumValueA returns 87 ("Invalid Parameter")

I am currently implementing functions and classes from Borland C++ Builder 5 in Visual Studio 2022. One of the classes is used to handle Windows registry IO, and one of its methods is supposed to return a list of values which the current key contains.
I am using Windows' RegEnumValueA function which, after passing correct arguments, always returns 87 – which stands for "Invalid Parameter".
The method looks as follows:
void __fastcall TRegistry::GetValueNames(TStrings* Strings)
{
HKEY hKey = m_CurrentKey;
DWORD dwIndex = 0;
CHAR cValueName[TREG_MAX_VALUES_BUF_SIZE] = {};
LPSTR lpValueName = cValueName;
DWORD dwValueBufSize = TREG_MAX_VALUES_BUF_SIZE;
LPDWORD lpcchValueName = &dwValueBufSize;
LPDWORD lpType = NULL;
BYTE cData[TREG_MAX_VALUES_BUF_SIZE] = {};
LPBYTE lpData = cData;
LPDWORD lpcbData = NULL;
long res = RegEnumValueA(hKey, dwIndex, lpValueName, lpcchValueName, NULL, lpType, lpData, lpcbData);
while (res != ERROR_NO_MORE_ITEMS)
{
if (res != ERROR_SUCCESS)
{
throw(Exception(AnsiString(res)));
}
else
{
++dwIndex;
res = RegEnumValueA(hKey, dwIndex, lpValueName, lpcchValueName, NULL, lpType, lpData, lpcbData);
}
}
}
As you can see, all the parameters are set correctly. My suspicion is that the NULL passed after lpcchValueName is causing this problem, since I've seen some people having the same issue after looking it up. Unfortunately, these were problems from years ago and were related to system-specific issues on e.g. Windows NT. The call to this method looks as follows:
int main()
{
TRegistry* treg = new TRegistry; // Create a TRegistry object
if (treg->OpenKey(AnsiString("TRegistryTest"), false)) // Open the TRegistryTest key
{
if (treg->OpenKey(AnsiString("subkey1"), true)) // Open the subkey1 key
{
TStringList ts;
treg->GetValueNames(&ts); // Write the value names into a TStringList
}
}
delete treg;
}
TStringList is essentially a container which stores AnsiString values, which in turn are basically glorified std::strings.
I expected the RegEnumValueA function to exit with code 0 as long as there are registry values left to read - in this case, there are 4 values in total in TRegistryTest/subkey1.
Changing TREG_MAX_VALUES_BUF_SIZE does not influence the result at all - it's currently set to a value of 200.
Your lpcbData parameter, which you have set to NULL is invalid. This should be the address of a DWORD that specifies the size (in bytes) of the buffer pointed to by the lpData parameter (i.e. the size of the cData array).
From the documentation:
[in, out, optional] lpcbData
A pointer to a variable that specifies the size of the buffer pointed
to by the lpData parameter, in bytes. When the function returns, the
variable receives the number of bytes stored in the buffer.
This parameter can be NULL only if lpData is NULL.
Also, note that, on success, the values in the variables pointed to by that lpcbData argument and by lpcchValueName (i.e. dwValueBufSize) will be modified to contain the actual sizes of the data/value returned. So, you should reset those before each call. For lpcchValueName, you would use a line like dwValueBufSize = TREG_MAX_VALUES_BUF_SIZE;, with similar code for the lpcbData target, depending on what you call that variable. (And I'm not sure it's an especially good idea to use the same size variable for both, as your comment seems to suggest.)
If you look at C++Builder 5's source code for its TRegistry::GetValueNames() method, you would see that there are two big differences between its approach versus your approach:
BCB5 first calls RegQueryInfoKeyA() to retrieve the number of values in the key, and the length of the longest value name in the key. It then allocates a buffer of that length, and then runs a for loop calling RegEnumValueA() to retrieve the name for each index. But it ignores the return value, which means it could fail if the Registry key is modified mid-loop.
Whereas you are (rightly so) calling RegEnumValueA() in a while loop until it reaches the end of the list or fails. But, you are using a fixed-length buffer to receive the names. 200 should be OK in practice for most systems, but you should use a dynamically allocated buffer and pay attention to RegEnumValueA()'s return value so you can know when it tells you that it needs additional buffer space that you can then allocate.
BCB5 sets the lpType, lpData, and lpcbData parameters of RegEnumValueA() to NULL, since it does not need those data.
Whereas you are setting the lpData parameter to the address of a local buffer, which is wrong (as other comments/answers have already pointed out), and unnecessary anyway since all you really want is each value's name and not its content.

Getting an access violation while trying to store folderpath, possible error in LPSTR / String conversion

I am trying to get the local Appdata folder, and store it in a string. I seem to be doing something wrong with my variables though, since I am getting an access violation when I try to store the folderpath into a string.
Code:
PSTR buffer;
HRESULT hRes = SHGetSpecialFolderPathA(NULL, buffer, CSIDL_APPDATA, FALSE);
std::string executingPathFolder = buffer;
Let's look at MSDN
lpszPath [out]
A pointer to a null-terminated string that receives the drive and path of the specified folder. This buffer must be at least MAX_PATH characters in size.
You must be careful with WinAPI - some methods returning buffers allocates them, some like write to allocated buffer. Please look here how to constructy std::string from LPSTR How do I convert from LPCTSTR to std::string?

Why do I need to cast the lpBuffer (LPTSTR) parameter in FormatMessage?

In Windows' FormatMessage() function, the parameter:
_Out_ LPTSTR lpBuffer
Is doing my head in. Following along from Hart's Windows System Programming book, I'm declaring an LPTSTR pointer to be used as the lpBuffer (e.g. LPTSTR errortext;), and then calling the FormatMessage() function.
The correct way to pass in this parameter is: (LPTSTR)&errorText
This works fine. But I don't understand why I need to write (LPTSTR). I understand that's typecasting and I read about it but it doesn't make sense to me, because I'm not changing the variable type or anything, I declared it as an LPTSTR and I'm passing its memory address to the function, the function expects an LPTSTR and I passed it an LPTSTR, so why do I need to put (LPTSTR) as part of the lpBuffer parameter?
The parameter lpBuffer of FormatMessage() is documented as follows:
A pointer to a buffer that receives the null-terminated string that
specifies the formatted message. If dwFlags includes
FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using
the LocalAlloc function, and places the pointer to the buffer at the
address specified in lpBuffer.
So there are 2 different usages of FormatMessage(),
1) Provide your own buffer
const DWORD bufsize = ....;
TCHAR buf[bufsize];
FormatMessage(.... buf, bufsize, ....); // buf is passed as a TCHAR*
2) FormatMessage allocates a buffer for you
const DWORD bufsize = ....;
TCHAR* buf = 0;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | ....,
.... (LPTSTR)&buf, bufsize, ....); // &buf is a TCHAR** so type-cast needed!
....
LocalFree(buf);
In #1, you have to pass the address of the first TCHAR in your buffer, and the function simply fills it the buffer.
In #2, the function needs to tell you where it allocates a new buffer, so you have to tell it where to place that address. You have to pass the address of a pointer variable that receives the address.
In short:
#1 needs a TCHAR* to an existing buffer
#2 needs a TCHAR** that receives a new buffer
That is why the lpBuffer parameter has to be type-casted when using #2.

How do I call the UrlCanonicalize API function correctly?

HRESULT UrlCanonicalize(
_In_ PCTSTR pszUrl,
_Out_ PTSTR pszCanonicalized,
_Inout_ DWORD *pcchCanonicalized,
DWORD dwFlags
);
Example:
LPCTSTR pszURL = URL.c_str();
LPSTR pszOutPut = new CHAR[ strUrl.length ];
DWORD* dwCount = new DWORD[ strUrl.length ];
hRes = UrlCanonicalize( pszURL, pszOutPut,dwCount, URL_ESCAPE_UNSAFE );
Output:
E_INVALIDARG
This API fails and returns E_INVALIDARG every time I try to call it. Please give me a working code snippet to call the UrlCanonicalize function.
If you know the C++ language, the SDK documentation for the function pretty much tells you everything that you need to know:
You pass it a C-style nul-terminated string that contains your URL.
You pass it pointer to a buffer to receive the output string.
You pass it one or more flags that customize the function's behavior.
And finally, it returns to you an HRESULT value, which is an error code. If it succeeds, that value will be S_OK. If it fails, it will be some other error code.
It works like this:
std::wstring originalURL(L"http://www.example.com/hello/cruel/../world/");
// Allocate a buffer of the appropriate length.
// It needs to be at least as long as the input string.
std::wstring canonicalURL(originalURL.length() + 1, L'\0');
DWORD length = originalURL.length() + 1;
// Call the function to modify the string.
HRESULT hr = UrlCanonicalize(originalURL.c_str(), // input string
&canonicalURL[0], // buffer
&length, // pointer to a DWORD that contains the length of the buffer
URL_UNESCAPE | URL_ESCAPE_UNSAFE);
if (SUCCEEDED(hr))
{
// The function succeeded.
// Your canonicalized URL is in the canonicalURL string.
MessageBox(nullptr, canonicalURL.c_str(), L"The URL is:", MB_OK);
}
else
{
// The function failed.
// The hr variable contains the error code.
throw std::runtime_error("The UrlCanonicalize function failed.");
}
If you want to make sure that the buffer is sufficiently long (and avoid having to handle that error), use the constant INTERNET_MAX_URL_LENGTH (declared in WinInet.h) when allocating it:
std::wstring canonicalURL(INTERNET_MAX_URL_LENGTH, L'\0');
DWORD length = INTERNET_MAX_URL_LENGTH;
The code you tried has a couple of problems:
You've incorrectly initialized the dwCount variable. The function wants a pointer, but that doesn't mean you should declare the variable as a pointer. Nor do you want an array; this is a single DWORD value. So you need to declare it as a regular DWORD, and then use the address-of operator (&) to pass the function a pointer to that variable. Right now, you're passing the function garbage, so it's failing.
You're using C-style strings, which you should avoid in C++ code. Use the C++ string class (std::wstring for Windows code), which is exception safe and manages memory for you. As you already know, the c_str() member function gives you easy access to a C-style nul-terminated string like all C APIs want. This works fine, you do not need to use raw character arrays yourself. Avoid new whenever possible.
Potentially, a third problem is that you're trying to use the C++ string type std::string instead of std::wstring. The former is an 8-bit string type and doesn't support Unicode in a Windows environment. You want std::wstring, which is a wide string with Unicode support. It's what all the Windows API functions expect if you have the UNICODE symbol defined for your project (which it is by default).
Here you go:
LPCTSTR pszURL = URL.c_str();
DWORD nOutputLength = strUrl.length * 2 + 32;
LPTSTR pszOutPut = new TCHAR[nOutputLength];
hRes = UrlCanonicalize( pszURL, pszOutPut, &nOutputLength, URL_ESCAPE_UNSAFE);
On the third parameter you provided garbage instead of pointer to initialized value, so you had API failure back. MSDN has it all for you:
A pointer to a value that, on entry, is set to the number of characters in the pszCanonicalized buffer.

Return a string from Win32 RPC call

I'm trying to make an RPC call which requests 2 numbers and a string from the RPC server, the IDL looks like this:
void GetCurrentStatus([in] handle_t hBinding, [out, ref] DWORD *dwRef1, [out, ref] DWORD *dwRef2, UINT *nLength, [out, size_is(, *nLength)] LPWSTR *pszName);
In the server-side call I do this:
// name = std::wstring
*pszName = (wchar_t*)midl_user_allocate(name.length()+1 * sizeof(wchar_t));
_tcscpy(*pszName, name.c_str());
*nLength = name.length();
But any attempt to call from the client-side results in nothing returned the error The array bounds are invalid.
What is the correct way to return a string from an RPC call?
Thanks,
J
If you have a choice in the matter, use BSTR (i.e. SysAllocString). RPC knows all about this data type and how to copy it and find its length.
Just
[out, retval] BSTR* pstrName
is enough, no separate length parameter needed.
The server is not able to pass string value back to client since it doesn't know how to marshall the string..
When you use BSTR type, the server knows to the length of the string. BSTR must be preceded by a 4-byte length field and terminated by a single null 2-byte character.
Where you have written:
*nLength = name.length();
I believe you need
*nLength = (name.length() + 1) * sizeof(WCHAR);
In particular, if you have an empty (length zero) string, then returning a size_is(0) array is not legal -- so you must add space for the string-terminating NUL (L'\0').
You also want to supply the size in bytes, where each Unicode character uses two bytes -- therefore you must multiply by the character size.