Skip to content

Commit

Permalink
[win32, svrplus] [win32] Use _countof() instead of ARRAY_SIZE() where…
Browse files Browse the repository at this point in the history
… size_t is needed.

_countof() is an MSVC-specific feature, but it's also available in MinGW.

Fixes PVS-Studio V221 (High): Suspicious sequence of types castings:
pointer -> memsize -> 32-bit integer.
  • Loading branch information
GerbilSoft committed Feb 15, 2020
1 parent 91120fc commit 972e32b
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 56 deletions.
54 changes: 21 additions & 33 deletions src/svrplus/svrplus.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* svrplus.c: Win32 installer for rom-properties. *
* *
* Copyright (c) 2017-2018 by Egor. *
* Copyright (c) 2017-2019 by David Korth. *
* Copyright (c) 2017-2020 by David Korth. *
* SPDX-License-Identifier: GPL-2.0-or-later *
***************************************************************************/

Expand Down Expand Up @@ -41,18 +41,6 @@
#define _MAX_ULTOSTR_BASE10_COUNT (10 + 1)
#endif

/**
* Number of elements in an array.
* (from librpbase/common.h)
*
* Includes a static check for pointers to make sure
* a dynamically-allocated array wasn't specified.
* Reference: http://stackoverflow.com/questions/8018843/macro-definition-array-size
*/
#define ARRAY_SIZE(x) \
(((sizeof(x) / sizeof(x[0]))) / \
(size_t)(!(sizeof(x) % sizeof(x[0]))))

// File paths
static const TCHAR str_rp32path[] = _T("i386\\rom-properties.dll");
static const TCHAR str_rp64path[] = _T("amd64\\rom-properties.dll");
Expand Down Expand Up @@ -236,7 +224,7 @@ static bool CheckMsvc(bool is64)
{
// Determine the MSVCRT DLL name.
TCHAR msvcrt_path[MAX_PATH];
int ret = GetSystemDirFilePath(msvcrt_path, ARRAY_SIZE(msvcrt_path), _T("msvcp140.dll"), is64);
int ret = GetSystemDirFilePath(msvcrt_path, _countof(msvcrt_path), _T("msvcp140.dll"), is64);
if (ret <= 0) {
// Unable to get the path.
// Assume the file exists.
Expand Down Expand Up @@ -279,7 +267,7 @@ typedef enum {
static InstallServerResult InstallServer(bool isUninstall, bool is64, DWORD *pErrorCode)
{
TCHAR regsvr32_path[MAX_PATH];
TCHAR args[14 + MAX_PATH + 4 + 3 + ARRAY_SIZE(str_rp64path)] = _T("regsvr32.exe \"");
TCHAR args[14 + MAX_PATH + 4 + 3 + _countof(str_rp64path)] = _T("regsvr32.exe \"");
DWORD szModuleFn;
TCHAR *bs;

Expand All @@ -289,7 +277,7 @@ static InstallServerResult InstallServer(bool isUninstall, bool is64, DWORD *pEr
BOOL bRet;

// Determine the REGSVR32 path.
int ret = GetSystemDirFilePath(regsvr32_path, ARRAY_SIZE(regsvr32_path), _T("regsvr32.exe"), is64);
int ret = GetSystemDirFilePath(regsvr32_path, _countof(regsvr32_path), _T("regsvr32.exe"), is64);
if (ret <= 0) {
// Unable to get the path.
return ISR_FATAL_ERROR;
Expand All @@ -314,14 +302,14 @@ static InstallServerResult InstallServer(bool isUninstall, bool is64, DWORD *pEr

// Remove the EXE filename, then append the DLL relative path.
bs[1] = 0;
_tcscat_s(args, ARRAY_SIZE(args), is64 ? str_rp64path : str_rp32path);
_tcscat_s(args, _countof(args), is64 ? str_rp64path : str_rp32path);
if (!fileExists(&args[14])) {
// File not found.
return ISR_FILE_NOT_FOUND;
}

// Append /s (silent) key, and optionally append /u (uninstall) key.
_tcscat_s(args, ARRAY_SIZE(args), isUninstall ? _T("\" /s /u") : _T("\" /s"));
_tcscat_s(args, _countof(args), isUninstall ? _T("\" /s /u") : _T("\" /s"));

memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
Expand Down Expand Up @@ -426,7 +414,7 @@ static InstallServerResult TryInstallServer(HWND hWnd,
_tcscat_s(sErrBuf, cchErrBuf, _T(" is missing."));
break;
case ISR_CREATEPROCESS_FAILED:
_ultot_s(errorCode, ultot_buf, ARRAY_SIZE(ultot_buf), 10);
_ultot_s(errorCode, ultot_buf, _countof(ultot_buf), 10);
_tcscpy_s(sErrBuf, cchErrBuf, _T("Could not start REGSVR32.exe. (Err:"));
_tcscat_s(sErrBuf, cchErrBuf, ultot_buf);
_tcscat_s(sErrBuf, cchErrBuf, _T(")"));
Expand Down Expand Up @@ -460,7 +448,7 @@ static InstallServerResult TryInstallServer(HWND hWnd,
_tcscat_s(sErrBuf, cchErrBuf, _T("() returned an error."));
break;
default:
_ultot_s(errorCode, ultot_buf, ARRAY_SIZE(ultot_buf), 10);
_ultot_s(errorCode, ultot_buf, _countof(ultot_buf), 10);
_tcscpy_s(sErrBuf, cchErrBuf, _T("REGSVR32 failed: Unknown exit code: "));
_tcscat_s(sErrBuf, cchErrBuf, ultot_buf);
break;
Expand Down Expand Up @@ -494,11 +482,11 @@ static unsigned int WINAPI ThreadProc(LPVOID lpParameter)

// Try to (un)install the 64-bit version.
if (g_is64bit) {
res64 = TryInstallServer(params->hWnd, params->isUninstall, true, msg64, ARRAY_SIZE(msg64));
res64 = TryInstallServer(params->hWnd, params->isUninstall, true, msg64, _countof(msg64));
}

// Try to (un)install the 32-bit version.
res32 = TryInstallServer(params->hWnd, params->isUninstall, false, msg32, ARRAY_SIZE(msg32));
res32 = TryInstallServer(params->hWnd, params->isUninstall, false, msg32, _countof(msg32));

if (res32 == ISR_OK && res64 == ISR_OK) {
// DLL(s) registered successfully.
Expand Down Expand Up @@ -532,16 +520,16 @@ static unsigned int WINAPI ThreadProc(LPVOID lpParameter)

if (res32 != ISR_OK) {
if (g_is64bit) {
_tcscpy_s(msg2, ARRAY_SIZE(msg2), BULLET _T(" 32-bit: "));
_tcscpy_s(msg2, _countof(msg2), BULLET _T(" 32-bit: "));
}
_tcscat_s(msg2, ARRAY_SIZE(msg2), msg32);
_tcscat_s(msg2, _countof(msg2), msg32);
}
if (res64 != ISR_OK) {
if (msg2[0] != _T('\0')) {
_tcscat_s(msg2, ARRAY_SIZE(msg2), _T("\n"));
_tcscat_s(msg2, _countof(msg2), _T("\n"));
}
_tcscat_s(msg2, ARRAY_SIZE(msg2), BULLET _T(" 64-bit: "));
_tcscat_s(msg2, ARRAY_SIZE(msg2), msg64);
_tcscat_s(msg2, _countof(msg2), BULLET _T(" 64-bit: "));
_tcscat_s(msg2, _countof(msg2), msg64);
}

ShowStatusMessage(params->hWnd, msg1, msg2, MB_ICONSTOP);
Expand Down Expand Up @@ -727,9 +715,9 @@ static void HandleInstallUninstall(HWND hDlg, bool isUninstall)
TCHAR ultot_buf[_MAX_ULTOSTR_BASE10_COUNT];

const DWORD lastError = GetLastError();
_ultot_s(lastError, ultot_buf, ARRAY_SIZE(ultot_buf), 10);
_tcscpy_s(threadErr, ARRAY_SIZE(threadErr), BULLET _T(" Win32 error code: "));
_tcscat_s(threadErr, ARRAY_SIZE(threadErr), ultot_buf);
_ultot_s(lastError, ultot_buf, _countof(ultot_buf), 10);
_tcscpy_s(threadErr, _countof(threadErr), BULLET _T(" Win32 error code: "));
_tcscat_s(threadErr, _countof(threadErr), ultot_buf);

ShowStatusMessage(hDlg, _T("An error occurred while starting the worker thread."), threadErr, MB_ICONSTOP);
MessageBeep(MB_ICONSTOP);
Expand Down Expand Up @@ -820,11 +808,11 @@ static INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM l
// ShellExecute() failed.
TCHAR err[128];
TCHAR itot_buf[_MAX_ITOSTR_BASE10_COUNT];
_itot_s((int)ret, itot_buf, ARRAY_SIZE(itot_buf), 10);
_tcscpy_s(err, ARRAY_SIZE(err),
_itot_s((int)ret, itot_buf, _countof(itot_buf), 10);
_tcscpy_s(err, _countof(err),
_T("Could not open the URL.\n\n")
_T("Win32 error code: "));
_tcscat_s(err, ARRAY_SIZE(err), itot_buf);
_tcscat_s(err, _countof(err), itot_buf);
MessageBox(hDlg, err, _T("Could not open URL"), MB_ICONERROR);
}
return TRUE;
Expand Down
14 changes: 7 additions & 7 deletions src/win32/DllMain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
// Get the DLL filename.
SetLastError(ERROR_SUCCESS);
DWORD dwResult = GetModuleFileName(hInstance,
dll_filename, ARRAY_SIZE(dll_filename));
dll_filename, _countof(dll_filename));
if (dwResult == 0 || GetLastError() != ERROR_SUCCESS) {
// Cannot get the DLL filename.
// TODO: Windows XP doesn't SetLastError() if the
Expand Down Expand Up @@ -401,10 +401,10 @@ static tstring GetUserFileAssoc(const tstring &sid, const char *ext)
// - UserChoice: 11 characters
// - Extra: 16 characters
TCHAR regPath[288];
int len = _sntprintf_s(regPath, ARRAY_SIZE(regPath),
int len = _sntprintf_s(regPath, _countof(regPath),
_T("%s\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\%s\\UserChoice"),
sid.c_str(), U82T_c(ext));
if (len <= 0 || len >= ARRAY_SIZE(regPath)) {
if (len <= 0 || len >= _countof(regPath)) {
// Buffer isn't large enough...
return tstring();
}
Expand Down Expand Up @@ -685,10 +685,10 @@ STDAPI DllRegisterServer(void)
hkcr.deleteSubKey(_T("*.vxd"));
for (auto sid_iter = user_SIDs.cbegin(); sid_iter != user_SIDs.cend(); ++sid_iter) {
TCHAR regPath[288];
int len = _sntprintf_s(regPath, ARRAY_SIZE(regPath),
int len = _sntprintf_s(regPath, _countof(regPath),
_T("%s\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts"),
sid_iter->c_str());
if (len <= 0 || len >= ARRAY_SIZE(regPath)) {
if (len <= 0 || len >= _countof(regPath)) {
// Buffer isn't large enough...
continue;
}
Expand Down Expand Up @@ -785,10 +785,10 @@ STDAPI DllUnregisterServer(void)
hkcr.deleteSubKey(_T("*.vxd"));
for (auto sid_iter = user_SIDs.cbegin(); sid_iter != user_SIDs.cend(); ++sid_iter) {
TCHAR regPath[288];
int len = _sntprintf_s(regPath, ARRAY_SIZE(regPath),
int len = _sntprintf_s(regPath, _countof(regPath),
_T("%s\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts"),
sid_iter->c_str());
if (len <= 0 || len >= ARRAY_SIZE(regPath)) {
if (len <= 0 || len >= _countof(regPath)) {
// Buffer isn't large enough...
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion src/win32/RP_ExtractIcon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ IFACEMETHODIMP RP_ExtractIcon::GetIconLocation(UINT uFlags,
return E_INVALIDARG;
}
wchar_t buf[16];
HRESULT hr = GetIconLocation(uFlags, buf, ARRAY_SIZE(buf), piIndex, pwFlags);
HRESULT hr = GetIconLocation(uFlags, buf, _countof(buf), piIndex, pwFlags);
pszIconFile[0] = 0; // Blank it out.
return hr;
}
Expand Down
4 changes: 2 additions & 2 deletions src/win32/RP_ExtractIcon_Fallback.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ LONG RP_ExtractIcon_Private::DoExtractIconW(IExtractIconW *pExtractIconW,
int nIconIndex;
UINT wFlags;
// TODO: Handle S_FALSE with GIL_DEFAULTICON?
hr = pExtractIconW->GetIconLocation(0, szIconFileW, ARRAY_SIZE(szIconFileW), &nIconIndex, &wFlags);
hr = pExtractIconW->GetIconLocation(0, szIconFileW, _countof(szIconFileW), &nIconIndex, &wFlags);
if (FAILED(hr)) {
// GetIconLocation() failed.
return ERROR_FILE_NOT_FOUND;
Expand Down Expand Up @@ -129,7 +129,7 @@ LONG RP_ExtractIcon_Private::DoExtractIconA(IExtractIconA *pExtractIconA,
int nIconIndex;
UINT wFlags;
// TODO: Handle S_FALSE with GIL_DEFAULTICON?
hr = pExtractIconA->GetIconLocation(0, szIconFileA, ARRAY_SIZE(szIconFileA), &nIconIndex, &wFlags);
hr = pExtractIconA->GetIconLocation(0, szIconFileA, _countof(szIconFileA), &nIconIndex, &wFlags);
if (FAILED(hr)) {
// GetIconLocation() failed.
return ERROR_FILE_NOT_FOUND;
Expand Down
2 changes: 1 addition & 1 deletion src/win32/RP_ExtractImage_Fallback.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ HRESULT RP_ExtractImage_Private::Fallback_int(RegKey &hkey_Assoc, HBITMAP *phBmp
wchar_t szPathBuffer[MAX_PATH]; // NOTE: Not actually used.
DWORD dwPriority = IEIT_PRIORITY_NORMAL;
DWORD dwFlags = this->dwFlags;
hr = pExtractImage->GetLocation(szPathBuffer, ARRAY_SIZE(szPathBuffer),
hr = pExtractImage->GetLocation(szPathBuffer, _countof(szPathBuffer),
&dwPriority, &rgSize, dwRecClrDepth, &dwFlags);
if (FAILED(hr) && hr != E_PENDING) {
// Failed to get the image location.
Expand Down
2 changes: 1 addition & 1 deletion src/win32/RP_PropertyStore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ IFACEMETHODIMP RP_PropertyStore::Initialize(IStream *pstream, DWORD grfMode)
// Special handling for System.Image.Dimensions.
if (dimensions.cx != 0 && dimensions.cy != 0) {
wchar_t buf[64];
swprintf(buf, ARRAY_SIZE(buf), L"%ldx%ld", dimensions.cx, dimensions.cy);
swprintf(buf, _countof(buf), L"%ldx%ld", dimensions.cx, dimensions.cy);

PROPVARIANT prop_var;
InitPropVariantFromString(buf, &prop_var);
Expand Down
4 changes: 2 additions & 2 deletions src/win32/RP_PropertyStore_Register.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ LONG RP_PropertyStore::RegisterCLSID(void)

// Get the default "PreviewDetails" and append them
// to the custom "FullDetails".
tstring s_previewDetails(PreviewDetails, ARRAY_SIZE(PreviewDetails)-1);
tstring s_previewDetails(PreviewDetails, _countof(PreviewDetails)-1);
s_reg = hkcr_All.read(_T("PreviewDetails"));
if (s_reg.size() > 5) {
// First 5 characters should be "prop:".
Expand All @@ -123,7 +123,7 @@ LONG RP_PropertyStore::RegisterCLSID(void)
// Prepend with "prop:".
s_infoTip = _T("prop:");
}
s_infoTip.append(InfoTip, ARRAY_SIZE(InfoTip)-1);
s_infoTip.append(InfoTip, _countof(InfoTip)-1);

// Write the registry keys.
RegKey hkey_ProgID(HKEY_CLASSES_ROOT, RP_ProgID, KEY_READ|KEY_WRITE, true);
Expand Down
8 changes: 4 additions & 4 deletions src/win32/RP_ShellPropSheetExt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1615,7 +1615,7 @@ int RP_ShellPropSheetExt_Private::initDateTime(HWND hDlg, HWND hWndTab,
// Format the date/time using the system locale.
TCHAR dateTimeStr[256];
int start_pos = 0;
int cchBuf = ARRAY_SIZE(dateTimeStr);
int cchBuf = _countof(dateTimeStr);

// Convert from Unix time to Win32 SYSTEMTIME.
SYSTEMTIME st;
Expand Down Expand Up @@ -1768,14 +1768,14 @@ int RP_ShellPropSheetExt_Private::initDimensions(HWND hDlg, HWND hWndTab,
TCHAR tbuf[64];
if (dimensions[1] > 0) {
if (dimensions[2] > 0) {
_sntprintf(tbuf, ARRAY_SIZE(tbuf), _T("%dx%dx%d"),
_sntprintf(tbuf, _countof(tbuf), _T("%dx%dx%d"),
dimensions[0], dimensions[1], dimensions[2]);
} else {
_sntprintf(tbuf, ARRAY_SIZE(tbuf), _T("%dx%d"),
_sntprintf(tbuf, _countof(tbuf), _T("%dx%d"),
dimensions[0], dimensions[1]);
}
} else {
_sntprintf(tbuf, ARRAY_SIZE(tbuf), _T("%d"), dimensions[0]);
_sntprintf(tbuf, _countof(tbuf), _T("%d"), dimensions[0]);
}

// Initialize the string field.
Expand Down
4 changes: 2 additions & 2 deletions src/win32/config/AboutTab.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -291,15 +291,15 @@ INT_PTR CALLBACK AboutTabPrivate::dlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, L
ENLINK *pENLink = reinterpret_cast<ENLINK*>(pHdr);
if (pENLink->msg == WM_LBUTTONUP) {
TCHAR urlbuf[256];
if ((pENLink->chrg.cpMax - pENLink->chrg.cpMin) >= ARRAY_SIZE(urlbuf)) {
if ((pENLink->chrg.cpMax - pENLink->chrg.cpMin) >= _countof(urlbuf)) {
// URL is too big.
break;
}
TEXTRANGE range;
range.chrg = pENLink->chrg;
range.lpstrText = urlbuf;
LRESULT lResult = SendMessage(pHdr->hwndFrom, EM_GETTEXTRANGE, 0, (LPARAM)&range);
if (lResult > 0 && lResult < ARRAY_SIZE(urlbuf)) {
if (lResult > 0 && lResult < _countof(urlbuf)) {
ShellExecute(nullptr, _T("open"), urlbuf, nullptr, nullptr, SW_SHOW);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/win32/config/KeyManagerTab.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,7 @@ LRESULT CALLBACK KeyManagerTabPrivate::ListViewSubclassProc(

// Copy the text from the ListView to the EDIT control.
TCHAR szItemText[128];
ListView_GetItemText(hWnd, iItem, lvhti.iSubItem, szItemText, ARRAY_SIZE(szItemText));
ListView_GetItemText(hWnd, iItem, lvhti.iSubItem, szItemText, _countof(szItemText));
SetWindowText(d->hEditBox, szItemText);
// FIXME: ES_AUTOHSCROLL causes some initial scrolling weirdness here,
// but disabling it prevents entering more text than fits onscreen...
Expand Down Expand Up @@ -997,7 +997,7 @@ LRESULT CALLBACK KeyManagerTabPrivate::ListViewEditSubclassProc(
// Save the key.
TCHAR tbuf[128];
tbuf[0] = 0;
GetWindowText(hWnd, tbuf, ARRAY_SIZE(tbuf));
GetWindowText(hWnd, tbuf, _countof(tbuf));
d->keyStore->setKey(d->iEditItem, T2U8(tbuf));

// Item is no longer being edited.
Expand Down Expand Up @@ -1471,7 +1471,7 @@ string KeyManagerTabPrivate::getOpenFileName(const TCHAR *dlgTitle, const TCHAR
ofn.lpstrFilter = ts_filterSpec.c_str();
ofn.lpstrCustomFilter = nullptr;
ofn.lpstrFile = filename;
ofn.nMaxFile = ARRAY_SIZE(filename);
ofn.nMaxFile = _countof(filename);
ofn.lpstrInitialDir = tsKeyFileDir.c_str();
ofn.lpstrTitle = dlgTitle;
ofn.Flags = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
Expand Down

0 comments on commit 972e32b

Please sign in to comment.