BSTR.FUNC.REALLOC

Incorrect call to BSTR reallocation function

The BSTR.FUNC.REALLOC checker finds incorrect calls to BSTR reallocation function SysReAllocString or SysReAllocStringLen. The first argument of the functions should be a pointer to a BSTR entity, and the second argument should be a wide char string. Klocwork flags the code when the function's first argument is incorrect or a value of type BSTR is specified as the second argument for the function.

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.

Vulnerable code example

Copy
  void bstr_realloc(wchar_t *ws, BSTR bstr1, BSTR bstr2) {
    SysReAllocString(&ws, L"abc"); 
    SysReAllocString(&bstr1, bstr2);  
  }

Klocwork flags lines 2 and 3 of this example. Klocwork doesn't flag a statement when a value of the wrong type is specified for the second argument, since the compiler usually catches the error, but in line 2 in this case, a value of type BSTR is specified as the first argument, which can pass through the compiler and then cause unexpected results. In line 3, the second argument is of type BSTR, so the length prefix is considered part of the string's value, potentially causing unintended program actions.