Attempt to get length of non-BSTR string using BSTR function

The BSTR.FUNCL.LEN checker finds SysStringLen or SysStringByteLen functions used in attempts to get the length of non-BSTR strings. The only argument of these functions should be of type BSTR.

Vulnerability and risk

Because the two styles are constructed differently, converting COM-style BSTR strings to and from C-style strings needs care. In some cases, conversions between the two compile well, but still produce unexpected results.

Mitigation and prevention

Unlike C-style strings, BSTR strings have a 4-byte length prefix that contains the number of bytes in the following data string. BSTR strings can also contain embedded null characters, and aren't strongly typed. For these reasons, it's best not to use BSTR in new designs. For existing interfaces, it's important to make conversions and use the Sys*Alloc*, SysFree* and Sys*String* memory allocation functions carefully.

If the first wide char string doesn't contain the length prefix, unexpected results can occur.

Vulnerable code example

  void bstr_len(wchar_t *a) {
    int l = SysStringLen(a);

Klocwork flags line 2, in which the SysStringLen function is used incorrectly. SysStringLen is expecting the BSTR length prefix in the variable, so using it on a non-BSTR variable will cause unexpected results.