Cast between semantically different integer types: HRESULT to/from a Boolean type.

Closing the gap between Semmle and PreFast.
Covers C6214, C6215, C6216, C6217, C6230
This commit is contained in:
Raul Garcia
2018-09-20 16:16:32 -07:00
parent 6266d8bf01
commit b0ec929aad
7 changed files with 150 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
// winnt.h
typedef long HRESULT;
#define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0)
#define FAILED(hr) (((HRESULT)(hr)) < 0)
// minwindef.h
typedef int BOOL;
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
// winerror.h
#define S_OK ((HRESULT)0L)
#define S_FALSE ((HRESULT)1L)
#define _HRESULT_TYPEDEF_(_sc) ((HRESULT)_sc)
#define E_UNEXPECTED _HRESULT_TYPEDEF_(0x8000FFFFL)
HRESULT HresultFunction()
{
return S_OK;
}
BOOL BoolFunction()
{
return FALSE;
}
HRESULT IncorrectHresultFunction()
{
return BoolFunction(); // BUG
}
void IncorrectTypeConversionTest() {
HRESULT hr = HresultFunction();
if ((BOOL)hr) // BUG
{
// ...
}
if (SUCCEEDED(hr)) // Correct Usage
{
// ...
}
if (SUCCEEDED(BoolFunction())) // BUG
{
// ...
}
if (BoolFunction()) // Correct Usage
{
// ...
}
BOOL b = IncorrectHresultFunction(); // BUG
hr = E_UNEXPECTED;
if (!hr) // BUG
{
// ...
}
if (!FAILED(hr)) // Correct Usage
{
// ...
}
hr = S_FALSE;
if (hr) // Should fail
{
// ...
}
if (SUCCEEDED(hr)) // Correct Usage
{
// ...
}
}

View File

@@ -0,0 +1,6 @@
| IncorrectTypeConversion.cpp:33:9:33:20 | call to BoolFunction | Implicit conversion from BOOL to HRESULT |
| IncorrectTypeConversion.cpp:38:12:38:13 | hr | Explicit conversion from HRESULT to BOOL |
| IncorrectTypeConversion.cpp:47:6:47:30 | (...) | Explicit conversion from BOOL to HRESULT |
| IncorrectTypeConversion.cpp:55:11:55:34 | call to IncorrectHresultFunction | Implicit conversion from HRESULT to BOOL |
| IncorrectTypeConversion.cpp:58:7:58:8 | hr | Implicit conversion from HRESULT to bool |
| IncorrectTypeConversion.cpp:68:6:68:7 | hr | Implicit conversion from HRESULT to bool |

View File

@@ -0,0 +1 @@
Security/CWE/CWE-704/incorrectTypeConversion.ql