diff --git a/src/CE.sln.DotSettings b/src/CE.sln.DotSettings index fa24e7ebd2..692f34a8a2 100644 --- a/src/CE.sln.DotSettings +++ b/src/CE.sln.DotSettings @@ -24,6 +24,7 @@ PID TID VS + WOW <NamingElement Priority="1"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="__interface" /><type Name="class" /><type Name="struct" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="AA_BB" /></Policy></NamingElement> <NamingElement Priority="11"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="class field" /><type Name="struct field" /></Descriptor><Policy Inspect="True" Prefix="m_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="_" Style="aaBb" /></Policy></NamingElement> <NamingElement Priority="12"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="PUBLIC"><type Name="class field" /><type Name="struct field" /></Descriptor><Policy Inspect="True" Prefix="m_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="_" Style="aaBb" /><ExtraRule Prefix="" Suffix="" Style="aaBb" /></Policy></NamingElement> @@ -46,6 +47,8 @@ True True True + True + True True True True @@ -115,6 +118,7 @@ True True True + True True True True @@ -203,6 +207,7 @@ True True True + True True True True @@ -215,6 +220,8 @@ True True True + True + True True True True @@ -227,6 +234,7 @@ True True True + True True True True diff --git a/src/ConEmu/Background.cpp b/src/ConEmu/Background.cpp index 48971de9c7..04e19168fe 100644 --- a/src/ConEmu/Background.cpp +++ b/src/ConEmu/Background.cpp @@ -1252,25 +1252,22 @@ bool CBackgroundInfo::LoadBackgroundFile(bool abShowErrors) if (!pBkImgData) { - wchar_t* exPath = ExpandEnvStr(ms_BgImage); + const CEStr exPath = ExpandEnvStr(ms_BgImage); - if (!exPath || !*exPath) + if (exPath.IsEmpty()) { if (abShowErrors) { - wchar_t szError[MAX_PATH*2]; - DWORD dwErr = GetLastError(); + wchar_t szError[MAX_PATH * 2] = L""; + const DWORD dwErr = GetLastError(); swprintf_c(szError, L"Can't expand environment strings:\r\n%s\r\nError code=0x%08X\r\nImage loading failed", ms_BgImage, dwErr); MBoxA(szError); } - - SafeFree(exPath); return false; } pBkImgData = LoadImageEx(exPath, inf); - SafeFree(exPath); } if (pBkImgData) diff --git a/src/ConEmu/ConEmu.cpp b/src/ConEmu/ConEmu.cpp index 5b251207c8..731680c361 100644 --- a/src/ConEmu/ConEmu.cpp +++ b/src/ConEmu/ConEmu.cpp @@ -693,56 +693,55 @@ void LogFocusInfo(LPCWSTR asInfo, int Level/*=1*/) void CConEmuMain::SetAppID(LPCWSTR asExtraArgs) { - BYTE md5ok = 0; - wchar_t szID[40] = L""; - CEStr lsFull(ms_ConEmuExeDir, asExtraArgs); + BYTE md5Ok = 0; + wchar_t szId[40] = L""; + const CEStr lsFull(ms_ConEmuExeDir, asExtraArgs); if (!lsFull.IsEmpty()) { - wchar_t* pszData = lsFull.ms_Val; - UINT iLen = wcslen(pszData); - CharUpperBuff(pszData, iLen); + const auto iLen = lsFull.GetLen(); + CharUpperBuff(lsFull.data(), iLen); if (gpSet->isLogging()) { - CEStr lsLog(L"Creating AppID from data: `", pszData, L"`"); + const CEStr lsLog(L"Creating AppID from data: `", lsFull, L"`"); LogString(lsLog); } unsigned char data[16] = {}; MD5_CTX ctx = {}; MD5_Init(&ctx); - MD5_Update(&ctx, pszData, iLen*sizeof(pszData[0])); + MD5_Update(&ctx, lsFull.data(), iLen * sizeof(lsFull[0])); MD5_Final(data, &ctx); for (int i = 0; i < 16; i++) { - BYTE bt = (BYTE)data[i]; - md5ok |= bt; - msprintf(szID+i*2, 3, L"%02x", (UINT)bt); + const BYTE bt = static_cast(data[i]); + md5Ok |= bt; + msprintf(szId+i*2, 3, L"%02x", static_cast(bt)); } } - if (!md5ok || (szID[0] == 0)) + if (!md5Ok || (szId[0] == 0)) { - _ASSERTE(md5ok && (szID[0] != 0)); // Must be filled already - lstrcpyn(szID, ms_ConEmuBuild, countof(szID)); + _ASSERTE(md5Ok && (szId[0] != 0)); // Must be filled already + lstrcpyn(szId, ms_ConEmuBuild, countof(szId)); } - wcscpy_c(ms_AppID, szID); + wcscpy_c(ms_AppID, szId); // This suffix isn't passed to Win7+ TaskBar AppModelID, but we need to stored it, // because it's used in Mappings when ConEmu tries to find existing instance for // passing command line in single-instance mode for example... wchar_t szSuffix[64] = L""; - swprintf_c(szSuffix, L"::%u", (UINT)CESERVER_REQ_VER); + swprintf_c(szSuffix, L"::%u", static_cast(CESERVER_REQ_VER)); // hash - 32char, + 5..6 for Protocol ID, quite be enough _ASSERTE((lstrlen(ms_AppID) + lstrlen(szSuffix)) < countof(ms_AppID)); wcscat_c(ms_AppID, szSuffix); if (gpSet->isLogging()) { - CEStr lsLog(L"New AppID: ", ms_AppID); + const CEStr lsLog(L"New AppID: ", ms_AppID); LogString(lsLog); } } @@ -1242,18 +1241,17 @@ LPWSTR CConEmuMain::ConEmuIni() TODO("Хорошо бы еще дать возможность пользователю использовать два файла - системный (предустановки) и пользовательский (настройки)"); // Ищем файл портабельных настроек (возвращаем первый найденный, приоритет...) - LPWSTR pszSearchIni[] = { + CEStr searchIni[] = { ExpandEnvStr(L"%ConEmuDir%\\ConEmu.ini"), ExpandEnvStr(L"%ConEmuBaseDir%\\ConEmu.ini"), ExpandEnvStr(L"%APPDATA%\\ConEmu.ini"), - nullptr }; - for (size_t i = 0; pszSearchIni[i]; i++) + for (const auto& ini : searchIni) { - if (FileExists(pszSearchIni[i])) + if (FileExists(ini)) { - wcscpy_c(ms_ConEmuIni, pszSearchIni[i]); + wcscpy_c(ms_ConEmuIni, ini); goto fin; } } @@ -1262,10 +1260,6 @@ LPWSTR CConEmuMain::ConEmuIni() wcscpy_c(ms_ConEmuIni, ms_ConEmuBaseDir); wcscat_c(ms_ConEmuIni, L"\\ConEmu.ini"); fin: - for (size_t i = 0; i < countof(pszSearchIni); i++) - { - SafeFree(pszSearchIni[i]); - } return ms_ConEmuIni; } @@ -1280,7 +1274,8 @@ LPCWSTR CConEmuMain::ConEmuCExeFull(LPCWSTR asCmdLine/*=nullptr*/) //LPCWSTR pszServer = ms_ConEmuC32Full; bool lbCmd = false, lbFound = false; - int Bits = IsWindows64() ? 64 : 32; + int bits = IsWindows64() ? 64 : 32; + CEStr expanded; if (!asCmdLine || !*asCmdLine) { @@ -1295,7 +1290,6 @@ LPCWSTR CConEmuMain::ConEmuCExeFull(LPCWSTR asCmdLine/*=nullptr*/) // Проверить битность asCmdLine во избежание лишних запусков серверов для Inject // и корректной битности запускаемого процессора по настройке CmdArg szTemp; - wchar_t* pszExpand = nullptr; if (!FileExists(asCmdLine)) { const wchar_t *psz = asCmdLine; @@ -1305,9 +1299,9 @@ LPCWSTR CConEmuMain::ConEmuCExeFull(LPCWSTR asCmdLine/*=nullptr*/) if (wcschr(asCmdLine, L'%')) { - pszExpand = ExpandEnvStr(asCmdLine); - if (pszExpand) - asCmdLine = pszExpand; + expanded = ExpandEnvStr(asCmdLine); + if (expanded) + asCmdLine = expanded.c_str(); } // Если путь указан полностью - берем битность из него, иначе - проверяем "на cmd" @@ -1317,7 +1311,7 @@ LPCWSTR CConEmuMain::ConEmuCExeFull(LPCWSTR asCmdLine/*=nullptr*/) } else { - LPCWSTR pszExt = PointToExt(asCmdLine); + const auto* pszExt = PointToExt(asCmdLine); if (pszExt && (lstrcmpi(pszExt, L".exe") != 0) && (lstrcmpi(pszExt, L".com") != 0)) { // Если указано расширение, и это не .exe и не .com - считаем, что запуск через ComProcessor @@ -1328,72 +1322,71 @@ LPCWSTR CConEmuMain::ConEmuCExeFull(LPCWSTR asCmdLine/*=nullptr*/) CEStr szFind; if (szFind.Set(asCmdLine)) CharUpperBuff(szFind.ms_Val, lstrlen(szFind)); - // По хорошему, нужно бы проверить еще и начало на соответствие в "%WinDir%". Но это не критично. + // We don't care if "%windir% is actual start if (!szFind.IsEmpty() && (wcsstr(szFind, L"\\SYSNATIVE\\") || wcsstr(szFind, L"\\SYSWOW64\\"))) { - // Если "SysNative" - считаем что 32-bit, иначе, 64-битный сервер просто "не увидит" эту папку - // С "SysWow64" все понятно, там только 32-битное - Bits = 32; + // For "SysNative" we need 32-bit server, the 64-bit applications just does not see this folder. + // The "SysWow64" folder contains only 32-bit application. + bits = 32; } else { - MWow64Disable wow; wow.Disable(); - DWORD ImageSubsystem = 0, ImageBits = 0, FileAttrs = 0; - lbFound = GetImageSubsystem(asCmdLine, ImageSubsystem, ImageBits, FileAttrs); - // Если не нашли и путь не был указан - // Даже если указан путь - это может быть путь к файлу без расширения. Его нужно "добавить". - if (!lbFound /*&& !wcschr(asCmdLine, L'\\')*/) + MWow64Disable wow; + wow.Disable(); + DWORD imageSubsystem = 0; + DWORD imageBits = 0; + DWORD fileAttrs = 0; + lbFound = GetImageSubsystem(asCmdLine, imageSubsystem, imageBits, fileAttrs); + // Try to search for the file in any case. + // Moreover, if we didn't found the file, asCmdLine could miss the file extension, try to add it. + if (!lbFound) { - LPCWSTR pszSearchFile = asCmdLine; - LPCWSTR pszSlash = PointToName(asCmdLine); - wchar_t* pszSearchPath = nullptr; - if (pszSlash && (pszSlash > asCmdLine)) + const auto* pszSearchFile = asCmdLine; + const auto* const filePtr = PointToName(asCmdLine); + CEStr pszSearchPath; + if (filePtr && (filePtr > asCmdLine)) { - if ((pszSearchPath = lstrdup(asCmdLine)) != nullptr) + const ssize_t fileNameIndex = filePtr - asCmdLine; + pszSearchPath.Set(asCmdLine); + if (pszSearchPath) { - pszSearchFile = pszSlash; - pszSearchPath[pszSearchFile - asCmdLine] = 0; + pszSearchFile = filePtr; + pszSearchPath.SetAt(fileNameIndex, 0); } } - // попытаемся найти bool bSearchRc = (apiSearchPath(pszSearchPath, pszSearchFile, pszExt ? nullptr : L".exe", szFind) > 0); if (!bSearchRc && !pszSearchPath) { - wchar_t szRoot[MAX_PATH+1]; - wcscpy_c(szRoot, ms_ConEmuExeDir); + const CEStr szRoot(ms_ConEmuExeDir); // One folder above ConEmu's directory - wchar_t* pszRootSlash = wcsrchr(szRoot, L'\\'); + wchar_t* pszRootSlash = wcsrchr(szRoot.data(), L'\\'); if (pszRootSlash) *pszRootSlash = 0; bSearchRc = (apiSearchPath(szRoot, pszSearchFile, pszExt ? nullptr : L".exe", szFind) > 0); } if (bSearchRc) { - lbFound = GetImageSubsystem(szFind, ImageSubsystem, ImageBits, FileAttrs); + lbFound = GetImageSubsystem(szFind, imageSubsystem, imageBits, fileAttrs); } - - SafeFree(pszSearchPath); } if (lbFound) - Bits = ImageBits; + bits = imageBits; } } } - - SafeFree(pszExpand); } if (lbCmd) { if (gpSet->ComSpec.csBits == csb_SameApp) - Bits = WIN3264TEST(32,64); + bits = WIN3264TEST(32,64); else if (gpSet->ComSpec.csBits == csb_x32) - Bits = 32; + bits = 32; } - return (Bits == 64) ? ms_ConEmuC64Full : ms_ConEmuC32Full; + return (bits == 64) ? ms_ConEmuC64Full : ms_ConEmuC32Full; } BOOL CConEmuMain::Init() @@ -3753,23 +3746,25 @@ void CConEmuMain::SetWindowIcon(LPCWSTR asNewIcon) if (gpSet->isTaskbarOverlay) return; - HICON hOldClassIcon = hClassIcon, hOldClassIconSm = hClassIconSm; + auto* hOldClassIcon = hClassIcon; + auto* hOldClassIconSm = hClassIconSm; hClassIcon = nullptr; hClassIconSm = nullptr; - SafeFree(mps_IconPath); - mps_IconPath = ExpandEnvStr(asNewIcon); + + ms_IconPath = ExpandEnvStr(asNewIcon); LoadIcons(); if (hClassIcon) { - SetClassLongPtr(ghWnd, GCLP_HICON, (LONG_PTR)hClassIcon); - SetClassLongPtr(ghWnd, GCLP_HICONSM, (LONG_PTR)hClassIconSm); - SendMessage(ghWnd, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon); - SendMessage(ghWnd, WM_SETICON, ICON_SMALL, (LPARAM)hClassIconSm); + SetClassLongPtr(ghWnd, GCLP_HICON, reinterpret_cast(hClassIcon)); + SetClassLongPtr(ghWnd, GCLP_HICONSM, reinterpret_cast(hClassIconSm)); + SendMessage(ghWnd, WM_SETICON, ICON_BIG, reinterpret_cast(hClassIcon)); + SendMessage(ghWnd, WM_SETICON, ICON_SMALL, reinterpret_cast(hClassIconSm)); } else { - hClassIcon = hOldClassIcon; hClassIconSm = hOldClassIconSm; + hClassIcon = hOldClassIcon; + hClassIconSm = hOldClassIconSm; } } @@ -3779,27 +3774,26 @@ void CConEmuMain::LoadIcons() if (hClassIcon) return; // Уже загружены - wchar_t *lpszExt = nullptr; CEStr szIconPath; CEStr lsLog; - if (mps_IconPath) + if (ms_IconPath) { - if (FileExists(mps_IconPath)) + if (FileExists(ms_IconPath)) { - szIconPath.Set(mps_IconPath); - lsLog.Attach(lstrmerge(L"Loading icon from '/icon' switch `", mps_IconPath, L"`")); + szIconPath.Set(ms_IconPath); + lsLog = CEStr(L"Loading icon from '/icon' switch `", ms_IconPath, L"`"); } else { - if (!apiSearchPath(nullptr, mps_IconPath, nullptr, szIconPath)) + if (!apiSearchPath(nullptr, ms_IconPath, nullptr, szIconPath)) { szIconPath.Clear(); - lsLog.Attach(lstrmerge(L"Icon specified with '/icon' switch `", mps_IconPath, L"` was not found")); + lsLog = CEStr(L"Icon specified with '/icon' switch `", ms_IconPath, L"` was not found"); } else { - lsLog.Attach(lstrmerge(L"Icon specified with '/icon' was found at `", szIconPath, L"`")); + lsLog = CEStr(L"Icon specified with '/icon' was found at `", szIconPath, L"`"); } } } @@ -3816,18 +3810,19 @@ void CConEmuMain::LoadIcons() } } - if (!lsLog.IsEmpty()) LogString(lsLog); + if (!lsLog.IsEmpty()) + LogString(lsLog); if (!szIconPath.IsEmpty()) { - lpszExt = (wchar_t*)PointToExt(szIconPath); + const auto* lpszExt = PointToExt(szIconPath); if (lpszExt && (lstrcmpi(lpszExt, L".ico") == 0)) { - hClassIcon = (HICON)LoadImage(0, szIconPath, IMAGE_ICON, - GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR|LR_LOADFROMFILE); - hClassIconSm = (HICON)LoadImage(0, szIconPath, IMAGE_ICON, - GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR|LR_LOADFROMFILE); + hClassIcon = static_cast(LoadImage(nullptr, szIconPath, IMAGE_ICON, + GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR | LR_LOADFROMFILE)); + hClassIconSm = static_cast(LoadImage(nullptr, szIconPath, IMAGE_ICON, + GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR | LR_LOADFROMFILE)); } else { @@ -6718,7 +6713,7 @@ void CConEmuMain::OnMainCreateFinished() UpdateWin7TaskList(mb_UpdateJumpListOnStartup); mb_UpdateJumpListOnStartup = false; - UINT n = SetKillTimer(true, TIMER_MAIN_ID, TIMER_MAIN_ELAPSE/*gpSet->nMainTimerElapse*/); + UINT_PTR n = SetKillTimer(true, TIMER_MAIN_ID, TIMER_MAIN_ELAPSE/*gpSet->nMainTimerElapse*/); DEBUGTEST(DWORD dw = GetLastError()); n = SetKillTimer(true, TIMER_CONREDRAW_ID, CON_REDRAW_TIMOUT * 2); UNREFERENCED_PARAMETER(n); @@ -7143,7 +7138,7 @@ LRESULT CConEmuMain::OnFocus(HWND hWnd, UINT messg, WPARAM wParam, LPARAM lParam if (messg == WM_SETFOCUS) { lbSetFocus = true; - swprintf_c(szDbg, L"WM_SETFOCUS(From=0x%08X)", (DWORD)wParam); + swprintf_c(szDbg, L"WM_SETFOCUS(From=0x%08X)", LODWORD(wParam)); LogFocusInfo(szDbg); pszMsgName = L"WM_SETFOCUS"; } @@ -7154,7 +7149,7 @@ LRESULT CConEmuMain::OnFocus(HWND hWnd, UINT messg, WPARAM wParam, LPARAM lParam if (LOWORD(wParam)==WA_INACTIVE) { hForeground = GetForegroundWindow(); - hNewFocus = lParam ? (HWND)lParam : hForeground; + hNewFocus = lParam ? reinterpret_cast(lParam) : hForeground; if (CVConGroup::isOurWindow(hNewFocus)) { lbSetFocus = true; // Считать, что фокус мы не теряем! @@ -7164,19 +7159,19 @@ LRESULT CConEmuMain::OnFocus(HWND hWnd, UINT messg, WPARAM wParam, LPARAM lParam if (!CVConGroup::InCreateGroup()) { POINT ptCur = {}; GetCursorPos(&ptCur); - for (size_t i = 0;; i++) + for (int i = 0;; i++) { - CVConGuard VCon; - if (!CVConGroup::GetVCon(i, &VCon)) + CVConGuard vCon; + if (!CVConGroup::GetVCon(i, &vCon)) break; - if (!VCon->isVisible()) + if (!vCon->isVisible()) continue; - HWND hGuiWnd = VCon->GuiWnd(); + HWND hGuiWnd = vCon->GuiWnd(); RECT rcChild = {}; GetWindowRect(hGuiWnd, &rcChild); if (PtInRect(&rcChild, ptCur)) { - Activate(VCon.VCon()); + Activate(vCon.VCon()); } } } @@ -10797,8 +10792,8 @@ LRESULT CConEmuMain::OnMouse_RBtnUp(CVirtualConsole* pVCon, HWND hWnd, UINT mess //держали зажатой <.3 //убьем таймер, кликнем правой кнопкой //KillTimer(hWnd, 1); -- Maximus5, таймер более не используется - DWORD dwCurTick = TimeGetTime(); //GetTickCount(); - DWORD dwDelta=dwCurTick-mouse.RClkTick; + const DWORD dwCurTick = TimeGetTime(); //GetTickCount(); + const DWORD dwDelta = dwCurTick - mouse.RClkTick; // Если держали дольше .3с, но не слишком долго :) if ((gpSet->isRClickSendKey==1) @@ -10823,7 +10818,7 @@ LRESULT CConEmuMain::OnMouse_RBtnUp(CVirtualConsole* pVCon, HWND hWnd, UINT mess // А теперь можно и Apps нажать mouse.bSkipRDblClk=true; // чтобы пока FAR думает в консоль не проскочило мышиное сообщение //POSTMESSAGE(ghConWnd, WM_KEYDOWN, VK_APPS, 0, TRUE); - DWORD dwFarPID = pVCon->RCon()->GetFarPID(); + const DWORD dwFarPID = pVCon->RCon()->GetFarPID(); if (dwFarPID) { @@ -10837,25 +10832,30 @@ LRESULT CConEmuMain::OnMouse_RBtnUp(CVirtualConsole* pVCon, HWND hWnd, UINT mess { //DWORD cbWritten=0; DebugStep(_T("EMenu: Waiting for result (10 sec)")); - int nLen = 0; - int nSize = sizeof(crMouse) + sizeof(wchar_t); + size_t nLen = 0; + unsigned nSize = sizeof(crMouse) + sizeof(wchar_t); - if (gpSet->sRClickMacro && *gpSet->sRClickMacro) + if (gpSet->sRClickMacro && gpSet->sRClickMacro[0]) { - nLen = _tcslen(gpSet->sRClickMacro); - nSize += nLen*2; - // -- заменено на перехват функции ScreenToClient - //pVCon->RCon()->RemoveFromCursor(); + nLen = wcslen(gpSet->sRClickMacro); + if (nLen > 0x8000) + { + const std::wstring errorInfo = L"EMenu: sRClickMacro is too long (" + std::to_wstring(nLen) + L" chars)"; + LogString(errorInfo.c_str()); + } + nSize += nLen * sizeof(gpSet->sRClickMacro[0]); } - LPBYTE pcbData = (LPBYTE)calloc(nSize,1); - _ASSERTE(pcbData); - memmove(pcbData, &crMouse, sizeof(crMouse)); + const std::unique_ptr pcbData(new BYTE[nSize]); + _ASSERTE(pcbData.get() != nullptr); + memmove_s(pcbData.get(), nSize, &crMouse, sizeof(crMouse)); - if (nLen) - lstrcpy((wchar_t*)(pcbData+sizeof(crMouse)), gpSet->sRClickMacro); + if (nLen > 0) + { + wcscpy_s(reinterpret_cast(pcbData.get() + sizeof(crMouse)), nLen + 1, gpSet->sRClickMacro); + } - if (!pipe.Execute(CMD_EMENU, pcbData, nSize)) + if (!pipe.Execute(CMD_EMENU, pcbData.get(), nSize)) { LogString("RightClicked, but pipe.Execute(CMD_EMENU) failed"); } @@ -10882,7 +10882,6 @@ LRESULT CConEmuMain::OnMouse_RBtnUp(CVirtualConsole* pVCon, HWND hWnd, UINT mess } DebugStep(nullptr); - free(pcbData); } else { diff --git a/src/ConEmu/ConEmu.h b/src/ConEmu/ConEmu.h index cf7d43ed62..3436fb2b1b 100644 --- a/src/ConEmu/ConEmu.h +++ b/src/ConEmu/ConEmu.h @@ -166,7 +166,7 @@ class CConEmuMain CEStr ms_PostRConMacro; void AddPostGuiRConMacro(LPCWSTR asGuiMacro); void ExecPostGuiMacro(); - wchar_t *mps_IconPath = nullptr; + CEStr ms_IconPath; HICON mh_TaskbarIcon = nullptr; void SetWindowIcon(LPCWSTR asNewIcon); void SetTaskbarIcon(HICON ahNewIcon); diff --git a/src/ConEmu/ConEmuStart.cpp b/src/ConEmu/ConEmuStart.cpp index 3b4769f4fe..6a2e716634 100644 --- a/src/ConEmu/ConEmuStart.cpp +++ b/src/ConEmu/ConEmuStart.cpp @@ -1151,7 +1151,7 @@ bool CConEmuStart::ParseCommandLine(LPCWSTR pszCmdLine, int& iResult) if (!gpConEmu->opt.IconPrm.Exists && !szNext.IsEmpty()) { gpConEmu->opt.IconPrm = true; - gpConEmu->mps_IconPath = ExpandEnvStr(szNext); + gpConEmu->ms_IconPath = ExpandEnvStr(szNext); } } else if (szArg.IsSwitch(L"-dir")) diff --git a/src/ConEmu/IconList.cpp b/src/ConEmu/IconList.cpp index 41c14cd38c..190586a70d 100644 --- a/src/ConEmu/IconList.cpp +++ b/src/ConEmu/IconList.cpp @@ -226,7 +226,7 @@ int CIconList::CreateTabIcon(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWorkDir int CIconList::CreateTabIconInt(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWorkDir) { - wchar_t* pszExpanded = ExpandEnvStr(asIconDescr); + CEStr pszExpanded = ExpandEnvStr(asIconDescr); // Need to be created! int iIconIdx = -1; @@ -262,7 +262,7 @@ int CIconList::CreateTabIconInt(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWork if (lstrcmpi(lpszExt, L".ico") == 0) { - hFileIcon = (HICON)LoadImage(0, szLoadFile, IMAGE_ICON, mn_CxIcon, mn_CyIcon, LR_DEFAULTCOLOR|LR_LOADFROMFILE); + hFileIcon = static_cast(LoadImage(nullptr, szLoadFile, IMAGE_ICON, mn_CxIcon, mn_CyIcon, LR_DEFAULTCOLOR | LR_LOADFROMFILE)); } else if ((lstrcmpi(lpszExt, L".exe") == 0) || (lstrcmpi(lpszExt, L".dll") == 0)) { @@ -270,19 +270,23 @@ int CIconList::CreateTabIconInt(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWork const UINT extracted = ExtractIconEx(szLoadFile, nIndex, &hIconLarge, &hIconSmall, 1); if (!(hIconLarge || hIconSmall)) { - _ASSERTE(!extracted || (extracted == (UINT)-1)); + _ASSERTE(!extracted || (extracted == static_cast(-1))); CEStr rsFound; - if (SearchAppPaths(szLoadFile, rsFound, false/*abSetPath*/)) + if (SearchAppPaths(szLoadFile, rsFound, false)) + { ExtractIconEx(rsFound, nIndex, &hIconLarge, &hIconSmall, 1); + } } - bool bUseLargeIcon = ((mn_CxIcon > 16) && (hIconLarge != nullptr)) || (hIconSmall == nullptr); + const bool bUseLargeIcon = ((mn_CxIcon > 16) && (hIconLarge != nullptr)) || (hIconSmall == nullptr); + // ReSharper disable once CppLocalVariableMayBeConst HICON hDestroyIcon = bUseLargeIcon ? hIconSmall : hIconLarge; - if (hDestroyIcon) DestroyIcon(hDestroyIcon); + if (hDestroyIcon) + DestroyIcon(hDestroyIcon); hFileIcon = bUseLargeIcon ? hIconLarge : hIconSmall; } else { - //TODO: Shell icons for registered files (cmd, bat, sh, pl, py, ...) + //#TODO: Shell icons for registered files (cmd, bat, sh, pl, py, ...) } if (hFileIcon) @@ -292,29 +296,30 @@ int CIconList::CreateTabIconInt(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWork if (gpSet->isLogging()) { - CEStr lsLog(L"Icon `", asIconDescr, L"` was loaded: ", szIconInfo); + const CEStr lsLog(L"Icon `", asIconDescr, L"` was loaded: ", szIconInfo); gpConEmu->LogString(lsLog); } int iIconIdxAdm = -1; iIconIdx = ImageList_ReplaceIcon(mh_TabIcons, -1, hFileIcon); - TabIconCache NewIcon = {lstrdup(asIconDescr), iIconIdx, false}; - m_Icons.push_back(NewIcon); + const TabIconCache newIcon = {lstrdup(asIconDescr), iIconIdx, false, false}; + m_Icons.push_back(newIcon); if (mn_AdminOverlayIndex >= 0) { + // ReSharper disable once CppLocalVariableMayBeConst HICON hNewIcon = ImageList_GetIcon(mh_TabIcons, iIconIdx, ILD_TRANSPARENT | INDEXTOOVERLAYMASK(mn_AdminOverlayIndex)); if (hNewIcon) { - CEStr lsLog(L"Admin icon `", asIconDescr, L"` was created: ", GetIconInfoStr(hNewIcon, szMergedInfo)); + const CEStr lsLog(L"Admin icon `", asIconDescr, L"` was created: ", GetIconInfoStr(hNewIcon, szMergedInfo)); gpConEmu->LogString(lsLog); iIconIdxAdm = ImageList_ReplaceIcon(mh_TabIcons, -1, hNewIcon); DestroyIcon(hNewIcon); - TabIconCache AdmIcon = {lstrdup(asIconDescr), iIconIdxAdm, true}; - m_Icons.push_back(AdmIcon); + const TabIconCache admIcon = {lstrdup(asIconDescr), iIconIdxAdm, true, false}; + m_Icons.push_back(admIcon); if (bAdmin && (iIconIdxAdm > 0)) { @@ -335,10 +340,9 @@ int CIconList::CreateTabIconInt(LPCWSTR asIconDescr, bool bAdmin, LPCWSTR asWork { gpConEmu->ChangeWorkDir(nullptr); } - SafeFree(pszExpanded); if (gpSet->isLogging() && (iIconIdx < 0)) { - CEStr lsLog(L"Icon `", asIconDescr, L"` loading was failed"); + const CEStr lsLog(L"Icon `", asIconDescr, L"` loading was failed"); gpConEmu->LogString(lsLog); } return iIconIdx; diff --git a/src/ConEmu/OptionsFast.cpp b/src/ConEmu/OptionsFast.cpp index ece92d287d..422d26a23b 100644 --- a/src/ConEmu/OptionsFast.cpp +++ b/src/ConEmu/OptionsFast.cpp @@ -311,12 +311,12 @@ static INT_PTR OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) SettingsStorage Storage = gpSet->GetSettingsType(); // Same priority as in CConEmuMain::ConEmuXml (reverse order) - wchar_t* pszSettingsPlaces[] = { - lstrdup(L"HKEY_CURRENT_USER\\Software\\ConEmu"), + CEStr pszSettingsPlaces[] = { + CEStr(L"HKEY_CURRENT_USER\\Software\\ConEmu"), ExpandEnvStr(L"%APPDATA%\\ConEmu.xml"), GetFullPathNameEx(L"%ConEmuBaseDir%\\ConEmu.xml"), // compact "C:\ConEmu\src\..\Debug\ConEmu.xml" to "C:\ConEmu\Debug\ConEmu.xml" GetFullPathNameEx(L"%ConEmuDir%\\ConEmu.xml"), - nullptr + CEStr() }; // Lets find first allowed item int iAllowed = 0; @@ -334,8 +334,7 @@ static INT_PTR OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) else { // Directly specified with "/LoadCfgFile ..." - SafeFree(pszSettingsPlaces[3]); - pszSettingsPlaces[3] = lstrdup(Storage.File); + pszSettingsPlaces[3].Set(Storage.File); iAllowed = 3; // Most prioritized } } @@ -371,20 +370,13 @@ static INT_PTR OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) } // Populate lbStorageLocation - while (pszSettingsPlaces[iAllowed]) + while (!pszSettingsPlaces[iAllowed].IsEmpty()) { - SendDlgItemMessage(hDlg, lbStorageLocation, CB_ADDSTRING, 0, (LPARAM)pszSettingsPlaces[iAllowed]); + SendDlgItemMessage(hDlg, lbStorageLocation, CB_ADDSTRING, 0, static_cast(pszSettingsPlaces[iAllowed])); iAllowed++; } SendDlgItemMessage(hDlg, lbStorageLocation, CB_SETCURSEL, iDefault, 0); - // Release memory - for (int i = 0; pszSettingsPlaces[i]; i++) - { - SafeFree(pszSettingsPlaces[i]); - } - - // Tasks const CommandTasks* pGrp = nullptr; for (int nGroup = 0; (pGrp = gpSet->CmdTaskGet(nGroup)) != nullptr; nGroup++) @@ -406,7 +398,7 @@ static INT_PTR OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) const ColorPalette* pPal = nullptr; for (int nPal = 0; (pPal = gpSet->PaletteGet(nPal)) != nullptr; nPal++) { - SendDlgItemMessage(hDlg, lbColorSchemeFast, CB_ADDSTRING, 0, (LPARAM)pPal->pszName); + SendDlgItemMessage(hDlg, lbColorSchemeFast, CB_ADDSTRING, 0, reinterpret_cast(pPal->pszName)); } // Show active (default) palette gp_DefaultPalette = gpSet->PaletteFindCurrent(true); @@ -421,7 +413,7 @@ static INT_PTR OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) // Show its colors in box HWND hChild = GetDlgItem(hDlg, stPalettePreviewFast); if (hChild) - gpfn_DefaultColorBoxProc = (WNDPROC)SetWindowLongPtr(hChild, GWLP_WNDPROC, (LONG_PTR)ColorBoxProc); + gpfn_DefaultColorBoxProc = reinterpret_cast(SetWindowLongPtr(hChild, GWLP_WNDPROC, reinterpret_cast(ColorBoxProc))); // Single instance @@ -482,18 +474,18 @@ static INT_PTR OnInitDialog(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) RECT rcGroup, rcBtn, rcWnd; if (GetWindowRect(GetDlgItem(hDlg, gbDisableConImeFast), &rcGroup)) { - int nShift = (rcGroup.bottom-rcGroup.top); + const int nShift = (rcGroup.bottom - rcGroup.top); HWND h = GetDlgItem(hDlg, IDOK); - GetWindowRect(h, &rcBtn); MapWindowPoints(nullptr, hDlg, (LPPOINT)&rcBtn, 2); + GetWindowRect(h, &rcBtn); MapWindowPoints(nullptr, hDlg, reinterpret_cast(&rcBtn), 2); SetWindowPos(h, nullptr, rcBtn.left, rcBtn.top - nShift, 0,0, SWP_NOSIZE|SWP_NOZORDER); h = GetDlgItem(hDlg, IDCANCEL); - GetWindowRect(h, &rcBtn); MapWindowPoints(nullptr, hDlg, (LPPOINT)&rcBtn, 2); + GetWindowRect(h, &rcBtn); MapWindowPoints(nullptr, hDlg, reinterpret_cast(&rcBtn), 2); SetWindowPos(h, nullptr, rcBtn.left, rcBtn.top - nShift, 0,0, SWP_NOSIZE|SWP_NOZORDER); h = GetDlgItem(hDlg, stHomePage); - GetWindowRect(h, &rcBtn); MapWindowPoints(nullptr, hDlg, (LPPOINT)&rcBtn, 2); + GetWindowRect(h, &rcBtn); MapWindowPoints(nullptr, hDlg, reinterpret_cast(&rcBtn), 2); SetWindowPos(h, nullptr, rcBtn.left, rcBtn.top - nShift, 0,0, SWP_NOSIZE|SWP_NOZORDER); SetWindowText(h, gsFirstStart); @@ -1024,7 +1016,6 @@ static size_t FindOnDrives(LPCWSTR asFirstDrive, LPCWSTR asSearchPath, FoundFile { _ASSERTE(foundFiles.size() == 0); bool bFound = false; - wchar_t* pszExpanded = nullptr; wchar_t szDrive[4]; // L"C:" CEStr szTemp; @@ -1133,7 +1124,7 @@ static size_t FindOnDrives(LPCWSTR asFirstDrive, LPCWSTR asSearchPath, FoundFile // Using environment variables? if (wcschr(asSearchPath, L'%')) { - pszExpanded = ExpandEnvStr(asSearchPath); + const CEStr pszExpanded = ExpandEnvStr(asSearchPath); if (pszExpanded && FileExists(pszExpanded)) { foundFiles.Add(asSearchPath, pszExpanded); @@ -1152,7 +1143,7 @@ static size_t FindOnDrives(LPCWSTR asFirstDrive, LPCWSTR asSearchPath, FoundFile bFound = true; } // Search in [HKCU|HKLM]\Software\Microsoft\Windows\CurrentVersion\App Paths - else if (SearchAppPaths(asSearchPath, rsFound, false/*abSetPath*/)) + else if (SearchAppPaths(asSearchPath, rsFound, false)) { // If app exists in "App Paths" we don't need to store its full path foundFiles.Add(asSearchPath, rsFound); @@ -1188,7 +1179,7 @@ static size_t FindOnDrives(LPCWSTR asFirstDrive, LPCWSTR asSearchPath, FoundFile { if ((asFirstDrive && *asFirstDrive) && (lstrcmpi(szDrive, asFirstDrive) == 0)) continue; - UINT nType = GetDriveType(szDrive); + const UINT nType = GetDriveType(szDrive); if (nType != DRIVE_FIXED) continue; rsFound.Attach(JoinPath(szDrive, asSearchPath)); @@ -1201,12 +1192,14 @@ static size_t FindOnDrives(LPCWSTR asFirstDrive, LPCWSTR asSearchPath, FoundFile } wrap: - SafeFree(pszExpanded); _ASSERTE(bFound == (foundFiles.size() != 0)); return foundFiles.size(); } -class CVarDefs + +static class CVarDefs *spVars = nullptr; + +class CVarDefs final { public: struct VarDef @@ -1216,7 +1209,7 @@ class CVarDefs }; MArray Vars; - void Store(wchar_t* asName, wchar_t* psValue) + void Store(wchar_t*&& asName, wchar_t*&& psValue) { if (!asName || !*asName || !psValue || !*psValue) { @@ -1225,42 +1218,43 @@ class CVarDefs } VarDef v = {asName, psValue}; - Vars.push_back(v); + Vars.push_back(std::move(v)); }; void Process(int nBackSteps, LPCWSTR asName) { - wchar_t szName[80] = L"%"; wcscat_c(szName, asName); wcscat_c(szName, L"%"); - wchar_t* psVal = GetEnvVar(asName); - while (psVal && *psVal) + CEStr szName(L"%", asName, L"%"); + const CEStr expanded = GetEnvVar(asName); + while (!expanded.IsEmpty()) { - wchar_t* pszSlash = wcsrchr(psVal, L'\\'); - while (pszSlash && (*(pszSlash+1) == 0)) + wchar_t* pszSlash = wcsrchr(expanded.data(), L'\\'); + while (pszSlash && (*(pszSlash + 1) == 0)) { - _ASSERTE(*(pszSlash+1) != 0 && "Must not be the trailing slash!"); + _ASSERTE(*(pszSlash + 1) != 0 && "Must not be the trailing slash!"); *pszSlash = 0; - pszSlash = wcsrchr(psVal, L'\\'); + pszSlash = wcsrchr(expanded.data(), L'\\'); } - Store(lstrdup(szName), lstrdup(psVal)); + Store(lstrdup(szName), lstrdup(expanded)); + // If we want to try something like "%windir%\.." if ((--nBackSteps) < 0) break; if (!pszSlash) break; *pszSlash = 0; - if (!wcsrchr(psVal, L'\\')) + if (!wcsrchr(expanded, L'\\')) break; - wcscat_c(szName, L"\\.."); + szName = CEStr(szName, L"\\.."); } - SafeFree(psVal); } CVarDefs() { + spVars = this; Process(0, L"ConEmuBaseDir"); - Process(3, L"ConEmuDir"); - Process(0, L"WinDir"); + Process(0, L"ConEmuDir"); + Process(1, L"WinDir"); Process(0, L"ConEmuDrive"); }; @@ -1272,6 +1266,10 @@ class CVarDefs SafeFree(v.pszName); SafeFree(v.pszValue); } + if (spVars == this) + { + spVars = nullptr; + } }; CVarDefs(const CVarDefs&) = delete; @@ -1280,8 +1278,6 @@ class CVarDefs CVarDefs& operator=(CVarDefs&&) = delete; }; -static CVarDefs *spVars = nullptr; - static bool UnExpandEnvStrings(LPCWSTR asSource, wchar_t* rsUnExpanded, INT_PTR cchMax) { // Don't use PathUnExpandEnvStrings because it uses %SystemDrive% instead of %ConEmuDrive%, @@ -1296,7 +1292,7 @@ static bool UnExpandEnvStrings(LPCWSTR asSource, wchar_t* rsUnExpanded, INT_PTR if (!IsFilePath(asSource, true)) return false; - CEStr szTemp((LPCWSTR)asSource); + CEStr szTemp(asSource); wchar_t* ptrSrc = szTemp.ms_Val; if (!ptrSrc) return false; @@ -1366,7 +1362,7 @@ class AppFoundList wchar_t ErrText[512]; DWORD FileAttrs = 0; _ASSERTE(!pszOptFull || *pszOptFull); - LPCWSTR pszPath = pszOptFull ? pszOptFull : szPath; + const auto* pszPath = pszOptFull ? pszOptFull : szPath; // Use GetImageSubsystem as condition because many exe-s may not have VersionInfo at all if (GetImageSubsystem(pszPath, FI.dwSubsystem, FI.dwBits, FileAttrs)) @@ -1378,12 +1374,11 @@ class AppFoundList // App instance found, add it to Installed array? bool bAlready = false; - for (INT_PTR a = 0; a < Installed.size(); a++) + for (auto& ai : Installed) { - AppInfo& ai = Installed[a]; bool path_match = false; if (lstrcmpi(ai.szFullPath, szPath) == 0) - { + { // NOLINT(bugprone-branch-clone) path_match = true; } else if (pszOptFull && (lstrcmpi(ai.szFullPath, pszOptFull) == 0)) @@ -1399,7 +1394,7 @@ class AppFoundList } // Do not add twice same path + args if (path_match - && (lstrcmp(ai.szArgs ? ai.szArgs : L"", asArgs ? asArgs : L"") == 0)) + && (lstrcmp(ai.szArgs ? ai.szArgs : L"", asArgs ? asArgs : L"") == 0)) { bAlready = true; break; } @@ -1410,7 +1405,7 @@ class AppFoundList lstrcpyn(FI.szTaskName, asName, countof(FI.szTaskName)); lstrcpyn(FI.szTaskBaseName, asName, countof(FI.szTaskBaseName)); FI.szFullPath = lstrdup(szPath); - FI.szExpanded = pszOptFull ? lstrdup(pszOptFull) : ExpandEnvStr(szPath); + FI.szExpanded = pszOptFull ? lstrdup(pszOptFull) : ExpandEnvStr(szPath).Detach(); FI.bForceQuot = bForceQuot; FI.szArgs = asArgs ? lstrdup(asArgs) : nullptr; FI.szPrefix = asPrefix ? lstrdup(asPrefix) : nullptr; @@ -2154,19 +2149,19 @@ static void CreateVCTask(AppFoundList& App, LPCWSTR pszPlatform, LPCWSTR pszVer, break; } - int iVer = wcstol(pszVer, nullptr, 10); - CEStr pszPrefix(L"cmd /k \""); + const int iVer = wcstol(pszVer, nullptr, 10); + const CEStr pszPrefix(L"cmd /k \""); CEStr pszSuffix(L"-new_console:t:\"VS ", pszVer, L"\""); - CEStr lsIcon; LPCWSTR pszIconSource = nullptr; + LPCWSTR pszIconSource = nullptr; LPCWSTR pszIconSources[] = { L"%CommonProgramFiles(x86)%\\microsoft shared\\MSEnv\\VSFileHandler.dll", L"%CommonProgramFiles%\\microsoft shared\\MSEnv\\VSFileHandler.dll", nullptr}; for (int i = 0; pszIconSources[i]; i++) { - if (lsIcon.Attach(ExpandEnvStr(pszIconSources[i])) - && FileExists(lsIcon)) + CEStr lsIcon = ExpandEnvStr(pszIconSources[i]); + if (lsIcon && FileExists(lsIcon)) { pszIconSource = pszIconSources[i]; break; @@ -2658,8 +2653,7 @@ void CreateDefaultTasks(SettingsLoadedFlags slfFlags) giCreatIdx++; } - CVarDefs Vars; - spVars = &Vars; + CVarDefs varsToUnexpand; AppFoundList App; diff --git a/src/ConEmu/RealBuffer.cpp b/src/ConEmu/RealBuffer.cpp index 7f4ae52603..a301abacb2 100644 --- a/src/ConEmu/RealBuffer.cpp +++ b/src/ConEmu/RealBuffer.cpp @@ -3170,13 +3170,12 @@ bool CRealBuffer::ProcessFarHyperlink(UINT messg, COORD crFrom, bool bUpdateScre if (bRunOutside) { // Need to check registry for 'App Paths' and set up '%PATH%' - LPCWSTR pszTemp = args.pszSpecialCmd; - CmdArg szExe; + pszTemp = args.pszSpecialCmd; + szExe.Release(); CEnvRestorer szPrevPath; - wchar_t* pszPrevPath = nullptr; if ((pszTemp = NextArg(pszTemp, szExe))) { - if (SearchAppPaths((LPCWSTR)szExe, szExe, true, &szPrevPath)) + if (SearchAppPaths(szExe.c_str(), szExe, true, &szPrevPath)) { wchar_t* pszChanged = MergeCmdLine(szExe, pszTemp); if (pszChanged) diff --git a/src/ConEmu/Recreate.cpp b/src/ConEmu/Recreate.cpp index 956f799ae3..9ba0d2db1e 100644 --- a/src/ConEmu/Recreate.cpp +++ b/src/ConEmu/Recreate.cpp @@ -703,30 +703,24 @@ INT_PTR CRecreateDlg::OnButtonClicked(HWND hDlg, UINT messg, WPARAM wParam, LPAR pArgs->RunAsAdministrator = SendDlgItemMessage(hDlg, cbRunAsAdmin, BM_GETCHECK, 0, 0) ? crb_On : crb_Off; // StartupDir (may be specified as argument) - wchar_t* pszDir = GetDlgItemTextPtr(hDlg, IDC_STARTUP_DIR); - wchar_t* pszExpand = (pszDir && wcschr(pszDir, L'%')) ? ExpandEnvStr(pszDir) : nullptr; - LPCWSTR pszDirResult = pszExpand ? pszExpand : pszDir; + CEStr pszDir = GetDlgItemTextPtr(hDlg, IDC_STARTUP_DIR); + CEStr pszExpand = (pszDir && wcschr(pszDir, L'%')) ? ExpandEnvStr(pszDir) : CEStr(); + const auto* pszDirResult = pszExpand ? pszExpand.c_str() : pszDir.c_str(); // Another user? We may fail with access denied. Check only for "current user" account if (!pArgs->pszUserName && pszDirResult && *pszDirResult && !DirectoryExists(pszDirResult)) { wchar_t* pszErrInfo = lstrmerge(L"Specified directory does not exists!\n", pszDirResult, L"\n" L"Do you want to choose another directory?\n\n"); - DWORD nErr = GetLastError(); - int iDirBtn = DisplayLastError(pszErrInfo, nErr, MB_ICONEXCLAMATION|MB_YESNO, nullptr, hDlg); + const DWORD nErr = GetLastError(); + const int iDirBtn = DisplayLastError(pszErrInfo, nErr, MB_ICONEXCLAMATION|MB_YESNO, nullptr, hDlg); if (iDirBtn == IDYES) { - SafeFree(pszDir); - SafeFree(pszExpand); SafeFree(pszErrInfo); return 1; } // User want to run "as is". Most likely it will fail, but who knows... } SafeFree(pArgs->pszStartupDir); - pArgs->pszStartupDir = pszExpand ? pszExpand : pszDir; - if (pszExpand) - { - SafeFree(pszDir) - } + pArgs->pszStartupDir = pszExpand ? pszExpand.Detach() : pszDir.Detach(); // Command // pszSpecialCmd мог быть передан аргументом - умолчание для строки ввода @@ -754,7 +748,7 @@ INT_PTR CRecreateDlg::OnButtonClicked(HWND hDlg, UINT messg, WPARAM wParam, LPAR && (pArgs->eSplit != RConStartArgsEx::eSplitNone)) { BOOL bOk = FALSE; - int nPercent = GetDlgItemInt(hDlg, tRecreateSplit, &bOk, FALSE); + const int nPercent = GetDlgItemInt(hDlg, tRecreateSplit, &bOk, FALSE); if (bOk && (nPercent >= 1) && (nPercent <= 99)) { pArgs->nSplitValue = (100-nPercent) * 10; diff --git a/src/ConEmu/SetCmdTask.cpp b/src/ConEmu/SetCmdTask.cpp index 4475f204fb..445ba0dc49 100644 --- a/src/ConEmu/SetCmdTask.cpp +++ b/src/ConEmu/SetCmdTask.cpp @@ -172,16 +172,16 @@ void CommandTasks::ParseGuiArgs(RConStartArgsEx* pArgs) const break; if (*szArg) { - wchar_t* pszExpand = nullptr; + CEStr expanded; // e.g. "%USERPROFILE%" if (wcschr(szArg, L'%')) { - pszExpand = ExpandEnvStr(szArg); + expanded = ExpandEnvStr(szArg); } SafeFree(pArgs->pszStartupDir); - pArgs->pszStartupDir = pszExpand ? pszExpand : lstrdup(szArg); + pArgs->pszStartupDir = expanded ? expanded.Detach() : lstrdup(szArg); } } else if (szArg.IsSwitch(L"-icon")) @@ -190,16 +190,16 @@ void CommandTasks::ParseGuiArgs(RConStartArgsEx* pArgs) const break; if (*szArg) { - wchar_t* pszExpand = nullptr; + CEStr expanded; // e.g. "%USERPROFILE%" if (wcschr(szArg, L'%')) { - pszExpand = ExpandEnvStr(szArg); + expanded = ExpandEnvStr(szArg); } SafeFree(pArgs->pszIconFile); - pArgs->pszIconFile = pszExpand ? pszExpand : lstrdup(szArg); + pArgs->pszIconFile = expanded ? expanded.Detach() : lstrdup(szArg); } } else if (szArg.OneOfSwitches(L"-single", L"-reuse")) diff --git a/src/ConEmu/Update.cpp b/src/ConEmu/Update.cpp index f8b8c1c95b..acbe4871f4 100644 --- a/src/ConEmu/Update.cpp +++ b/src/ConEmu/Update.cpp @@ -1811,7 +1811,7 @@ bool CConEmuUpdate::Check7zipInstalled() if (mp_Set->UpdateDownloadSetup() == 1) return true; // Инсталлер, архиватор не требуется! - LPCWSTR pszCmd = mp_Set->UpdateArcCmdLine(); + const auto* pszCmd = mp_Set->UpdateArcCmdLine(); CmdArg sz7zip; if (!NextArg(pszCmd, sz7zip)) { @@ -1819,7 +1819,7 @@ bool CConEmuUpdate::Check7zipInstalled() return false; } - if (FileExistsSearch((LPCWSTR)sz7zip, sz7zip, false)) + if (FileExistsSearch(sz7zip.c_str(), sz7zip, false)) return true; WARNING("TODO: Suggest to download 7zip"); diff --git a/src/ConEmu/all_test.cpp b/src/ConEmu/all_test.cpp index 1b7d4ec20c..c202639a55 100644 --- a/src/ConEmu/all_test.cpp +++ b/src/ConEmu/all_test.cpp @@ -222,20 +222,21 @@ void UnitExpandTest() _ASSERTE(gpConEmu!=nullptr); CEStr szExe; wchar_t szChoc[MAX_PATH] = L"powershell -NoProfile -ExecutionPolicy unrestricted -Command \"iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))\" && SET PATH=%PATH%;%systemdrive%\\chocolatey\\bin"; - wchar_t* pszExpanded = ExpandEnvStr(szChoc); - int nLen = pszExpanded ? lstrlen(pszExpanded) : 0; + const CEStr pszExpanded = ExpandEnvStr(szChoc); + const auto nLen = pszExpanded.GetLen(); BOOL bFound = FileExistsSearch(szChoc, szExe, false); wcscpy_c(szChoc, gpConEmu->ms_ConEmuExeDir); wcscat_c(szChoc, L"\\Tests\\Executables\\abcd"); bFound = FileExistsSearch(szChoc, szExe, false); // TakeCommand - ConEmuComspec tcc = {cst_AutoTccCmd}; + ConEmuComspec tcc = {}; + tcc.csType = cst_AutoTccCmd; FindComspec(&tcc, false); } void UnitModuleTest() { - CEStr pszConEmuCD(gpConEmu->ms_ConEmuBaseDir, L"\\", ConEmuCD_DLL_3264); + const CEStr pszConEmuCD(gpConEmu->ms_ConEmuBaseDir, L"\\", ConEmuCD_DLL_3264); HMODULE hMod, hGetMod; bool bTest; diff --git a/src/ConEmuC/Downloader.cpp b/src/ConEmuC/Downloader.cpp index 62898f97ea..4b50a3cd45 100644 --- a/src/ConEmuC/Downloader.cpp +++ b/src/ConEmuC/Downloader.cpp @@ -1807,7 +1807,7 @@ int DoDownload(LPCWSTR asCmdLine) wchar_t* pszUrl = NULL; size_t iFiles = 0; CEDownloadErrorArg args[4]; - wchar_t* pszExpanded = NULL; + CEStr pszExpanded; wchar_t szFullPath[MAX_PATH*2]; wchar_t szResult[80]; DWORD nFullRc; @@ -1983,11 +1983,11 @@ int DoDownload(LPCWSTR asCmdLine) args[2].uintArg = TRUE; args[2].argType = at_Uint; // May be file name was specified relatively or even with env.vars? - SafeFree(pszExpanded); + pszExpanded.Clear(); if (lstrcmp(szArg, L"-") != 0) { pszExpanded = ExpandEnvStr(szArg); - nFullRc = GetFullPathName((pszExpanded && *pszExpanded) ? pszExpanded : (LPCWSTR)szArg, countof(szFullPath), szFullPath, NULL); + nFullRc = GetFullPathName(!pszExpanded .IsEmpty() ? pszExpanded.c_str() : szArg.c_str(), countof(szFullPath), szFullPath, nullptr); if (nFullRc && nFullRc < countof(szFullPath)) args[1].strArg = szFullPath; } @@ -2024,7 +2024,6 @@ int DoDownload(LPCWSTR asCmdLine) DownloadLog(dc_LogCallback, szResult); // Finalize internet service DownloadCommand(dc_Deinit, 0, NULL); - SafeFree(pszExpanded); for (size_t i = 0; KnownArgs[i].pszArgName; i++) { if (KnownArgs[i].ppszValue) diff --git a/src/ConEmuCD/ConEmuCmd.cpp b/src/ConEmuCD/ConEmuCmd.cpp index 00256d1d53..4eb7d72075 100644 --- a/src/ConEmuCD/ConEmuCmd.cpp +++ b/src/ConEmuCD/ConEmuCmd.cpp @@ -431,23 +431,21 @@ int WorkerComspec::ProcessNewConsoleArg(LPCWSTR asCmdLine) CEnvStrings strs(GetEnvironmentStringsW()); DWORD nCmdLen = lstrlen(asCmdLine) + 1; - CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_NEWCMD, sizeof(CESERVER_REQ_HDR) + sizeof(CESERVER_REQ_NEWCMD) + ((nCmdLen + strs.mcch_Length) * sizeof(wchar_t))); + CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_NEWCMD, sizeof(CESERVER_REQ_HDR) + sizeof(CESERVER_REQ_NEWCMD) + ((nCmdLen + strs.cchLength_) * sizeof(wchar_t))); if (pIn) { pIn->NewCmd.hFromConWnd = hConWnd; // hConWnd may differ from parent process, but ENV_CONEMUDRAW_VAR_W would be inherited - wchar_t* pszDcWnd = GetEnvVar(ENV_CONEMUDRAW_VAR_W); + const CEStr pszDcWnd = GetEnvVar(ENV_CONEMUDRAW_VAR_W); if (pszDcWnd && (pszDcWnd[0] == L'0') && (pszDcWnd[1] == L'x')) { - wchar_t* pszEnd = nullptr; - pIn->NewCmd.hFromDcWnd.u = wcstoul(pszDcWnd + 2, &pszEnd, 16); + pIn->NewCmd.hFromDcWnd.u = wcstoul(pszDcWnd.c_str() + 2, nullptr, 16); } - SafeFree(pszDcWnd); GetCurrentDirectory(countof(pIn->NewCmd.szCurDir), pIn->NewCmd.szCurDir); pIn->NewCmd.SetCommand(asCmdLine); - pIn->NewCmd.SetEnvStrings(strs.ms_Strings, static_cast(strs.mcch_Length)); + pIn->NewCmd.SetEnvStrings(strs.strings_, static_cast(strs.cchLength_)); CESERVER_REQ* pOut = ExecuteGuiCmd(hConEmu, pIn, hConWnd); if (pOut) diff --git a/src/ConEmuCD/ConsoleMain.cpp b/src/ConEmuCD/ConsoleMain.cpp index d482ab6fe0..d56a8384a8 100644 --- a/src/ConEmuCD/ConsoleMain.cpp +++ b/src/ConEmuCD/ConsoleMain.cpp @@ -2308,10 +2308,10 @@ wchar_t* ParseConEmuSubst(LPCWSTR asCmd) asCmd = pszCmdCopy; } - wchar_t* pszExpand = ExpandEnvStr(pszCmdCopy ? pszCmdCopy : asCmd); + CEStr pszExpand = ExpandEnvStr(pszCmdCopy ? pszCmdCopy : asCmd); SafeFree(pszCmdCopy); - return pszExpand; + return pszExpand.Detach(); } BOOL SetTitle(LPCWSTR lsTitle) diff --git a/src/ConEmuCD/DownloaderCall.cpp b/src/ConEmuCD/DownloaderCall.cpp index abec9e9496..71cb7afa2c 100644 --- a/src/ConEmuCD/DownloaderCall.cpp +++ b/src/ConEmuCD/DownloaderCall.cpp @@ -545,13 +545,12 @@ class CDownloader else { // Environment string? Expand it - wchar_t* pszExp = ExpandEnvStr(szCmdStringFormat); + CEStr pszExp = ExpandEnvStr(szCmdStringFormat); // "curl -L %1 -o %2" // "wget %1 -O %2" LPCWSTR Values[] = {asSource, asTarget}; - pszCommand = ExpandMacroValues((pszExp && *pszExp) ? pszExp : szCmdStringFormat, Values, countof(Values)); - SafeFree(pszExp); + pszCommand = ExpandMacroValues(!pszExp.IsEmpty() ? pszExp : szCmdStringFormat, Values, countof(Values)); if (!pszCommand) { diff --git a/src/ConEmuCD/StartEnv.cpp b/src/ConEmuCD/StartEnv.cpp index 619eaf9980..6d331cc26d 100644 --- a/src/ConEmuCD/StartEnv.cpp +++ b/src/ConEmuCD/StartEnv.cpp @@ -159,7 +159,7 @@ void CStartEnv::Set(LPCWSTR asName, LPCWSTR asValue) { CEStr lsNewSuffix; lsNewSuffix.Set(pchName+iSelfLen); - INT_PTR iSLen = lsNewSuffix.GetLen(); + const INT_PTR iSLen = lsNewSuffix.GetLen(); iCmp = (iCurLen >= iSLen && iSLen > 0) ? wcsncmp(lsCurValue.c_str() + iCurLen - iSLen, lsNewSuffix, iSLen) : -1; @@ -176,10 +176,9 @@ void CStartEnv::Set(LPCWSTR asName, LPCWSTR asValue) } // Expand value - wchar_t* pszExpanded = ExpandEnvStr(asValue); - LPCWSTR pszSet = pszExpanded ? pszExpanded : asValue; - SetEnvironmentVariable(asName, (pszSet && *pszSet) ? pszSet : nullptr); - SafeFree(pszExpanded); + const CEStr pszExpanded = ExpandEnvStr(asValue); + const auto pszSet = pszExpanded ? pszExpanded.c_str() : asValue; + SetEnvironmentVariableW(asName, (pszSet && *pszSet) ? pszSet : nullptr); } void CStartEnv::Title(LPCWSTR asTitle) @@ -193,6 +192,6 @@ void CStartEnv::Title(LPCWSTR asTitle) void CStartEnv::Type(LPCWSTR asSwitches, LPCWSTR asFile) { - CEStr lsFull = lstrmerge(asSwitches, (asSwitches && *asSwitches) ? L" " : nullptr, L"\"", asFile, L"\""); + const CEStr lsFull = lstrmerge(asSwitches, (asSwitches && *asSwitches) ? L" " : nullptr, L"\"", asFile, L"\""); DoOutput(ConEmuExecAction::OutType, lsFull); } diff --git a/src/ConEmuDW/ConEmuDw.cpp b/src/ConEmuDW/ConEmuDw.cpp index 6d9fdd3408..ac1be2ac14 100644 --- a/src/ConEmuDW/ConEmuDw.cpp +++ b/src/ConEmuDW/ConEmuDw.cpp @@ -156,7 +156,7 @@ BOOL LoadFarVersion() // Dummy external requirement for FileExistsSearch. // But it's better to splite FileExistsSearch code... -bool SearchAppPaths(wchar_t const *,struct CEStr &,bool,struct CEStr *) +bool SearchAppPaths(wchar_t const*, struct CEStr&, bool, struct CEStr*) { return false; } diff --git a/src/ConEmuPlugin/ConEmuPluginBase.cpp b/src/ConEmuPlugin/ConEmuPluginBase.cpp index 0489bb0cf2..9e41a1b95e 100644 --- a/src/ConEmuPlugin/ConEmuPluginBase.cpp +++ b/src/ConEmuPlugin/ConEmuPluginBase.cpp @@ -158,8 +158,8 @@ DWORD gnSelfPID = 0; //GetCurrentProcessId(); HANDLE ghFarInfoMapping = nullptr; CEFAR_INFO_MAPPING *gpFarInfo = nullptr, *gpFarInfoMapping = nullptr; HANDLE ghFarAliveEvent = nullptr; -PanelViewRegInfo gPanelRegLeft = {nullptr}; -PanelViewRegInfo gPanelRegRight = {nullptr}; +PanelViewRegInfo gPanelRegLeft = {}; +PanelViewRegInfo gPanelRegRight = {}; // Для плагинов PicView & MMView нужно знать, нажат ли CtrlShift при F3 HANDLE ghConEmuCtrlPressed = nullptr, ghConEmuShiftPressed = nullptr; BOOL gbWaitConsoleInputEmpty = FALSE, gbWaitConsoleWrite = FALSE; //, gbWaitConsoleInputPeek = FALSE; @@ -813,7 +813,8 @@ bool CPluginBase::RunExternalProgram(wchar_t* pszCommand) if (wcschr(pszCommand, L'%')) { - szExpand.ms_Val = ExpandEnvStr(pszCommand); + // ReSharper disable once CppJoinDeclarationAndAssignment + szExpand = ExpandEnvStr(pszCommand); if (szExpand.ms_Val) pszCommand = szExpand.ms_Val; } @@ -5331,11 +5332,12 @@ BOOL /*WINAPI*/ CPluginBase::OnConsoleDetaching(HookCallbackArg* pArgs) // Нужно уведомить ТЕКУЩИЙ сервер, что закрываться по окончании команды не нужно if (gdwServerPID == 0) { - _ASSERTE(gdwServerPID != nullptr); + _ASSERTE(gdwServerPID != 0); } else { - CESERVER_REQ In, *pOut = nullptr; + CESERVER_REQ In = {}; + CESERVER_REQ* pOut = nullptr; ExecutePrepareCmd(&In, CECMD_FARDETACHED, sizeof(CESERVER_REQ_HDR)); pOut = ExecuteSrvCmd(gdwServerPID, &In, FarHwnd); diff --git a/src/common/CmdLine.cpp b/src/common/CmdLine.cpp index 1dd31a569c..2f6fe3e87f 100644 --- a/src/common/CmdLine.cpp +++ b/src/common/CmdLine.cpp @@ -602,7 +602,7 @@ bool GetFilePathFromSpaceDelimitedString(const wchar_t* commandLine, CEStr& szEx if (!szTemp.IsEmpty() && ((IsFilePath(szTemp, true) && !wcschr(szTemp, L'%')) // or file/dir may be found via env.var. substitution or searching in %PATH% - || FileExistsSearch(szTemp.c_str(), szTemp)) + || FileExistsSearch(szTemp.c_str(), szTemp, true)) // Than check if it is a FILE (not a directory) && FileExists(szTemp, &nTempSize) && nTempSize) { @@ -732,7 +732,7 @@ bool IsNeedCmd(bool bRootCmd, LPCWSTR asCmdLine, CEStr &szExe, NeedCmdOptions* o CEStr expanded; const wchar_t* exeToCheck = nullptr; // file/dir may be found via env.var. substitution or searching in %PATH% - if (FileExistsSearch(szExe.c_str(), expanded)) + if (FileExistsSearch(szExe.c_str(), expanded, true)) exeToCheck = expanded.IsEmpty() ? szExe.c_str() : expanded.c_str(); // or it's already a full specified file path else if (IsFilePath(szExe, true)) @@ -787,7 +787,7 @@ bool IsNeedCmd(bool bRootCmd, LPCWSTR asCmdLine, CEStr &szExe, NeedCmdOptions* o _ASSERTE(lstrcmpiW(szExe, L"start") != 0); // Expand environment variables and search in the %PATH% - if (FileExistsSearch(szExe.c_str(), szExe)) + if (FileExistsSearch(szExe.c_str(), szExe, true)) { rsArguments = SkipNonPrintable(pwszCopy); } diff --git a/src/common/MAssert.h b/src/common/MAssert.h index d754f01eb1..9f4dad92c5 100644 --- a/src/common/MAssert.h +++ b/src/common/MAssert.h @@ -129,7 +129,7 @@ bool MyAssertSkip(const wchar_t* pszFile, int nLine, const wchar_t* pszTest, boo extern bool gbVerifyStepFailed; extern bool gbVerifyIgnoreAsserts; - #include + #include extern const char* PointToName(const char* asFileOrPath); #define _ASSERT(x) if (!(x) && !gbVerifyIgnoreAsserts) { gbVerifyStepFailed=gbVerifyFailed=true; \ MyAssertSkip(_CRT_WIDE(__FILE__), __LINE__, L"Unit test assertion", true); \ diff --git a/src/common/RConStartArgs.cpp b/src/common/RConStartArgs.cpp index 3c2ab2e492..d820736353 100644 --- a/src/common/RConStartArgs.cpp +++ b/src/common/RConStartArgs.cpp @@ -688,11 +688,11 @@ int RConStartArgs::ProcessNewConArg(bool bForceCurConsole /*= false*/) // For example, "%USERPROFILE%" if (wcschr(pszStartupDir, L'%')) { - wchar_t* pszExpand = nullptr; - if (((pszExpand = ExpandEnvStr(pszStartupDir)) != nullptr)) + CEStr expanded = ExpandEnvStr(pszStartupDir); + if (expanded) { SafeFree(pszStartupDir); - pszStartupDir = pszExpand; + pszStartupDir = expanded.Detach(); } } break; diff --git a/src/common/WFiles.cpp b/src/common/WFiles.cpp index a3608cb861..8ad25ae101 100644 --- a/src/common/WFiles.cpp +++ b/src/common/WFiles.cpp @@ -32,11 +32,12 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "MStrDup.h" #include "WFiles.h" #include "WObjects.h" +#include "WRegistry.h" // Returns true, if application was found in registry: // [HKCU|HKLM]\Software\Microsoft\Windows\CurrentVersion\App Paths -// Also, function may change local process %PATH% variable -bool SearchAppPaths(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath, CEnvRestorer* rpsPathRestore /*= nullptr*/) +// Also, function may change local process %PATH% variable if rpsPathRestore is specified. +bool SearchAppPaths(LPCWSTR asFilePath, CEStr& rsFound, const bool abSetPath, CEnvRestorer* rpsPathRestore /*= nullptr*/) { #if defined(CONEMU_MINIMAL) PRAGMA_ERROR("Must not be included in ConEmuHk"); @@ -48,43 +49,49 @@ bool SearchAppPaths(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath, CEnvRest if (!asFilePath || !*asFilePath) return false; - LPCWSTR pszSearchFile = PointToName(asFilePath); - LPCWSTR pszExt = PointToExt(pszSearchFile); + const auto* pszSearchFile = PointToName(asFilePath); + const auto* pszExt = PointToExt(pszSearchFile); // Lets try find it in "App Paths" // "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\" // "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\" - LPCWSTR pszRoot = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\"; - HKEY hk; LONG lRc; - CEStr lsName(pszRoot, pszSearchFile, pszExt ? nullptr : L".exe"); + wchar_t pszRoot[] = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\"; + HKEY hk; + // ReSharper disable once CppJoinDeclarationAndAssignment + LONG lRc; + const CEStr lsName(pszRoot, pszSearchFile, pszExt ? nullptr : L".exe"); // Seems like 32-bit and 64-bit registry branches are the same now, but just in case - will check both - DWORD nWOW[2] = {WIN3264TEST(KEY_WOW64_32KEY,KEY_WOW64_64KEY), WIN3264TEST(KEY_WOW64_64KEY,KEY_WOW64_32KEY)}; + DWORD nWOW[2] = { WIN3264TEST(KEY_WOW64_32KEY,KEY_WOW64_64KEY), WIN3264TEST(KEY_WOW64_64KEY,KEY_WOW64_32KEY) }; for (int i = 0; i < 3; i++) { bool bFound = false; - DWORD nFlags = ((i && IsWindows64()) ? nWOW[i-1] : 0); + const DWORD nFlags = ((i && IsWindows64()) ? nWOW[i - 1] : 0); if ((i == 2) && !nFlags) break; // This is 32-bit OS lRc = RegOpenKeyEx(i ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER, lsName, 0, KEY_READ|nFlags, &hk); - if (lRc != 0) continue; - wchar_t szVal[MAX_PATH+1] = L""; - DWORD nType, nSize = sizeof(szVal)-sizeof(szVal[0]); - lRc = RegQueryValueEx(hk, nullptr, nullptr, &nType, (LPBYTE)szVal, &nSize); + if (lRc != 0) + continue; + wchar_t szVal[MAX_PATH + 1] = L""; + DWORD nType = 0; + DWORD nSize = sizeof(szVal) - sizeof(szVal[0]); + lRc = RegQueryValueEx(hk, nullptr, nullptr, &nType, reinterpret_cast(szVal), &nSize); if (lRc == 0) { wchar_t *pszCheck = nullptr; + CEStr expanded; if (nType == REG_SZ) { pszCheck = szVal; } else if (nType == REG_EXPAND_SZ) { - pszCheck = ExpandEnvStr(szVal); + expanded = ExpandEnvStr(szVal); + pszCheck = expanded.data(); } // May be quoted - if (pszCheck) + if (pszCheck && *pszCheck) { - LPCWSTR pszPath = Unquote(pszCheck, true); + const auto pszPath = Unquote(pszCheck, true); if (FileExists(pszPath)) { // asFilePath will be invalid after .Set @@ -98,50 +105,39 @@ bool SearchAppPaths(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath, CEnvRest if (abSetPath) { nSize = 0; - lRc = RegQueryValueEx(hk, L"PATH", nullptr, &nType, nullptr, &nSize); - if (lRc == 0 && nSize) + CEStr szAddPath; + const auto iAddLen = RegGetStringValue(hk, nullptr, L"PATH", szAddPath); + if (iAddLen > 0) { - wchar_t* pszCurPath = GetEnvVar(L"PATH"); - wchar_t* pszAddPath = (wchar_t*)calloc(nSize+4,1); - wchar_t* pszNewPath = nullptr; - if (pszAddPath) + CEStr szCurPath = GetEnvVar(L"PATH"); + + // If "%PATH%" does not contain szAddPath (at the beginning) - force add it + const auto iCurLen = szCurPath.GetLen(); + bool bNeedAdd = true; + if ((iCurLen >= iAddLen) && (szCurPath[iAddLen] == L';' || szCurPath[iAddLen] == 0)) + { + const wchar_t ch = szCurPath[iAddLen]; szCurPath.SetAt(iAddLen, 0); + if (szCurPath.Compare(szAddPath) == 0) + bNeedAdd = false; + szCurPath.SetAt(iAddLen, ch); + } + + if (bNeedAdd) { - lRc = RegQueryValueEx(hk, L"PATH", nullptr, &nType, (LPBYTE)pszAddPath, &nSize); - if (lRc == 0 && *pszAddPath) + if (rpsPathRestore) + { + rpsPathRestore->SavePathVar(szCurPath); + } + const CEStr szNewPath(szAddPath, L";", szCurPath); + if (szNewPath) + { + SetEnvironmentVariable(L"PATH", szNewPath); + } + else { - // Если в "%PATH%" этого нет (в начале) - принудительно добавить - int iCurLen = pszCurPath ? lstrlen(pszCurPath) : 0; - int iAddLen = lstrlen(pszAddPath); - bool bNeedAdd = true; - if ((iCurLen >= iAddLen) && (pszCurPath[iAddLen] == L';' || pszCurPath[iAddLen] == 0)) - { - wchar_t ch = pszCurPath[iAddLen]; pszCurPath[iAddLen] = 0; - if (lstrcmpi(pszCurPath, pszAddPath) == 0) - bNeedAdd = false; - pszCurPath[iAddLen] = ch; - } - // Если пути еще нет - if (bNeedAdd) - { - if (rpsPathRestore) - { - rpsPathRestore->SavePathVar(pszCurPath); - } - pszNewPath = lstrmerge(pszAddPath, L";", pszCurPath); - if (pszNewPath) - { - SetEnvironmentVariable(L"PATH", pszNewPath); - } - else - { - _ASSERTE(pszNewPath!=nullptr && "Allocation failed?"); - } - } + _ASSERTE(!szNewPath.IsEmpty() && "Allocation failed?"); } } - SafeFree(pszAddPath); - SafeFree(pszCurPath); - SafeFree(pszNewPath); } } } @@ -160,13 +156,14 @@ bool SearchAppPaths(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath, CEnvRest wchar_t* GetFullPathNameEx(LPCWSTR asPath) { wchar_t* pszResult = nullptr; - wchar_t* pszTemp = nullptr; + CEStr szTemp; if (wcschr(asPath, L'%')) { - if ((pszTemp = ExpandEnvStr(asPath)) != nullptr) + szTemp = ExpandEnvStr(asPath); + if (szTemp) { - asPath = pszTemp; + asPath = szTemp.c_str(); } } @@ -187,7 +184,6 @@ wchar_t* GetFullPathNameEx(LPCWSTR asPath) pszResult = lstrdup(asPath); } - SafeFree(pszTemp); return pszResult; } diff --git a/src/common/WObjects.cpp b/src/common/WObjects.cpp index 8abe8e0831..4b5bfbc657 100644 --- a/src/common/WObjects.cpp +++ b/src/common/WObjects.cpp @@ -144,6 +144,12 @@ int apiSearchPath(LPCWSTR lpPath, LPCWSTR lpFileName, LPCWSTR lpExtension, CEStr } } #endif + + if (!lpFileName || !*lpFileName) + { + _ASSERTE(lpFileName && *lpFileName); + return 0; + } bool bFound = false; wchar_t *pszFilePart = nullptr, *pszBuffer = nullptr; @@ -190,6 +196,12 @@ int apiSearchPath(LPCWSTR lpPath, LPCWSTR lpFileName, LPCWSTR lpExtension, CEStr int apiGetFullPathName(LPCWSTR lpFileName, CEStr& rsPath) { + if (!lpFileName || !*lpFileName) + { + _ASSERTE(lpFileName && *lpFileName); + return 0; + } + int iFoundLen = 0; wchar_t* pszFilePart = nullptr; // ReSharper disable once CppInitializedValueIsAlwaysRewritten @@ -230,6 +242,12 @@ bool FileSearchInDir(LPCWSTR asFilePath, CEStr& rsFound) // a) asFilePath does not contain path, only: "far" // b) asFilePath contains path, but without extension: "C:\\Program Files\\Far\\Far" + if (!asFilePath || !*asFilePath) + { + _ASSERTE(asFilePath && *asFilePath); + return false; + } + LPCWSTR pszSearchFile = asFilePath; const auto* pszSlash = wcsrchr(asFilePath, L'\\'); if (pszSlash) @@ -275,7 +293,7 @@ bool FileSearchInDir(LPCWSTR asFilePath, CEStr& rsFound) SearchAppPaths_t gfnSearchAppPaths = nullptr; -bool FileExistsSearch(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath/*= true*/, bool abRegSearch /*= true*/) +bool FileExistsSearch(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath/*= true*/) { if (!asFilePath || !*asFilePath) { @@ -319,7 +337,7 @@ bool FileExistsSearch(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath/*= true // В ConEmuHk этот блок не активен, потому что может быть "только" перехват CreateProcess, // а о его параметрах должно заботиться вызывающее (текущее) приложение - if (abRegSearch && gfnSearchAppPaths && !wcschr(asFilePath, L'\\')) + if (gfnSearchAppPaths && !wcschr(asFilePath, L'\\')) { // Если в asFilePath НЕ указан путь - искать приложение в реестре, // и там могут быть указаны доп. параметры (пока только добавка в %PATH%) diff --git a/src/common/WObjects.h b/src/common/WObjects.h index 68dfcecc4c..f630341ee6 100644 --- a/src/common/WObjects.h +++ b/src/common/WObjects.h @@ -73,7 +73,7 @@ bool FileSearchInDir(LPCWSTR asFilePath, CEStr& rsFound); class CEnvRestorer; typedef bool (*SearchAppPaths_t)(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath, CEnvRestorer* rpsPathRestore /*= NULL*/); extern SearchAppPaths_t gfnSearchAppPaths /*= NULL*/; -bool FileExistsSearch(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath = true, bool abRegSearch = true); +bool FileExistsSearch(LPCWSTR asFilePath, CEStr& rsFound, bool abSetPath = true); bool GetShortFileName(LPCWSTR asFullPath, int cchShortNameMax, wchar_t* rsShortName/*[MAX_PATH+1]-name only*/, BOOL abFavorLength=FALSE); wchar_t* GetShortFileNameEx(LPCWSTR asLong, BOOL abFavorLength=TRUE); diff --git a/src/common/WUser.cpp b/src/common/WUser.cpp index 41abca0932..803a4caa7f 100644 --- a/src/common/WUser.cpp +++ b/src/common/WUser.cpp @@ -510,27 +510,27 @@ void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/) } else { - wchar_t* pszCur = GetEnvVar(L"PATH"); + CEStr szCur = GetEnvVar(L"PATH"); - if (!pszCur) - pszCur = lstrdup(L""); + if (!szCur) + szCur.Set(L""); - DWORD n = lstrlen(pszCur); - wchar_t* pszUpr = lstrdup(pszCur); - wchar_t* pszDirUpr = (wchar_t*)malloc(MAX_PATH*sizeof(*pszCur)); + const auto curLen = szCur.GetLen(); + const CEStr szUpr(szCur.c_str()); + CEStr szDirUpr; MCHKHEAP; - if (!pszUpr || !pszDirUpr) + if (!szUpr || !szDirUpr.GetBuffer(MAX_PATH)) { - _ASSERTE(pszUpr && pszDirUpr); + _ASSERTE(!szUpr.IsEmpty() && szDirUpr.data()); } else { bool bChanged = false; wchar_t* pszAdd = nullptr; - CharUpperBuff(pszUpr, n); + CharUpperBuff(szUpr.data(), LODWORD(szUpr.GetLen())); for (int i = 0; i <= 1; i++) { @@ -549,41 +549,43 @@ void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/) continue; // второй раз ту же директорию не добавляем pszAdd = pOpt->ConEmuBaseDir; break; + default: + _ASSERTE(FALSE && "should not get here"); + continue; } - int nDirLen = lstrlen(pszAdd); - lstrcpyn(pszDirUpr, pszAdd, MAX_PATH); - CharUpperBuff(pszDirUpr, nDirLen); + const int addDirLen = lstrlen(pszAdd); + szDirUpr.Set(pszAdd); + CharUpperBuff(szDirUpr.data(), addDirLen); MCHKHEAP; // Need to find exact match! bool bFound = false; - LPCWSTR pszFind = wcsstr(pszUpr, pszDirUpr); + LPCWSTR pszFind = wcsstr(szUpr, szDirUpr); while (pszFind) { - if (pszFind[nDirLen] == L';' || pszFind[nDirLen] == 0) + if (pszFind[addDirLen] == L';' || pszFind[addDirLen] == 0) { // OK, found bFound = true; break; } // Next try (may be partial match of subdirs...) - pszFind = wcsstr(pszFind+nDirLen, pszDirUpr); + pszFind = wcsstr(pszFind + addDirLen, szDirUpr); } if (!bFound) { - wchar_t* pszNew = lstrmerge(pszAdd, L";", pszCur); - if (!pszNew) + CEStr szNew(pszAdd, L";", szCur); + if (!szNew) { - _ASSERTE(pszNew && "Failed to reallocate PATH variable"); + _ASSERTE(!szNew.IsEmpty() && "Failed to reallocate PATH variable"); break; } MCHKHEAP; - SafeFree(pszCur); - pszCur = pszNew; + szCur = std::move(szNew); bChanged = true; // Set flag, check next dir } } @@ -592,17 +594,11 @@ void UpdateComspec(ConEmuComspec* pOpt, bool DontModifyPath /*= false*/) if (bChanged) { - SetEnvironmentVariable(L"PATH", pszCur); + SetEnvironmentVariable(L"PATH", szCur); } } MCHKHEAP; - - SafeFree(pszUpr); - SafeFree(pszDirUpr); - - MCHKHEAP; - SafeFree(pszCur); } } }