diff --git a/libs/mfc/include/afx.h b/libs/mfc/include/afx.h index 250cfcffc..acfe84c23 100644 --- a/libs/mfc/include/afx.h +++ b/libs/mfc/include/afx.h @@ -105,6 +105,7 @@ public: void SetAt(int nIndex, TCHAR ch); // return pointer to const string operator LPCTSTR() const; + LPCTSTR c_str() const { return operator LPCTSTR(); } // overloaded assignment diff --git a/libs/mfc/include/afx.inl b/libs/mfc/include/afx.inl index fc7e76023..7a501db86 100644 --- a/libs/mfc/include/afx.inl +++ b/libs/mfc/include/afx.inl @@ -20,17 +20,17 @@ _AFX_INLINE CFileException::CFileException(int cause, LONG lOsError, _AFX_INLINE CString::CString() { } _AFX_INLINE CString::CString(const unsigned char* lpsz) - { *this = (LPCSTR)lpsz; } + { *this = reinterpret_cast(lpsz); } _AFX_INLINE const CString& CString::operator=(const unsigned char* lpsz) - { *this = (LPCSTR)lpsz; return *this; } + { *this = reinterpret_cast(lpsz); return *this; } _AFX_INLINE const CString& CString::operator+=(char ch) - { *this += (TCHAR)ch; return *this; } + { *this += static_cast(ch); return *this; } _AFX_INLINE const CString& CString::operator=(char ch) - { *this = (TCHAR)ch; return *this; } + { *this = static_cast(ch); return *this; } _AFX_INLINE CString AFXAPI operator+(const CString& string, char ch) - { return string + (TCHAR)ch; } + { return string + static_cast(ch); } _AFX_INLINE CString AFXAPI operator+(char ch, const CString& string) - { return (TCHAR)ch + string; } + { return static_cast(ch) + string; } _AFX_INLINE int CString::GetLength() const { return m_Data.Length(); } diff --git a/libs/mfc/include/atlconv.h b/libs/mfc/include/atlconv.h index 61bee631d..158997222 100644 --- a/libs/mfc/include/atlconv.h +++ b/libs/mfc/include/atlconv.h @@ -35,17 +35,17 @@ LPSTR WINAPI AtlW2AHelper(LPSTR lpa, LPCWSTR lpw, int nChars); #endif #define A2W(lpa) (\ - ((LPCSTR)lpa == NULL) ? NULL : (\ + (static_cast(lpa) == NULL) ? NULL : (\ _convert = (lstrlenA(lpa)+1),\ - ATLA2WHELPER((LPWSTR) alloca(_convert*2), lpa, _convert))) + ATLA2WHELPER(static_cast(alloca(_convert*2)), lpa, _convert))) #define W2A(lpw) (\ - ((LPCWSTR)lpw == NULL) ? NULL : (\ + (static_cast(lpw) == NULL) ? NULL : (\ _convert = (lstrlenW(lpw)+1)*2,\ - ATLW2AHELPER((LPSTR) alloca(_convert), lpw, _convert))) + ATLW2AHELPER(static_cast(alloca(_convert)), lpw, _convert))) -#define A2CW(lpa) ((LPCWSTR)A2W(lpa)) -#define W2CA(lpw) ((LPCSTR)W2A(lpw)) +#define A2CW(lpa) (static_cast(A2W(lpa))) +#define W2CA(lpw) (static_cast(W2A(lpw))) #define T2A W2A #define A2T A2W diff --git a/source/DScpComp.cbproj b/source/DScpComp.cbproj index 12990726e..ba1b05e6e 100644 --- a/source/DScpComp.cbproj +++ b/source/DScpComp.cbproj @@ -49,7 +49,7 @@ true true false - -Wno-ignored-attributes -Wno-zero-as-null-pointer-constant -Wno-c++98-compat-pedantic -Wno-language-extension-token -Wno-missing-prototypes -Wno-old-style-cast -Wno-padded + -Wno-ignored-attributes -Wno-zero-as-null-pointer-constant -Wno-c++98-compat-pedantic -Wno-language-extension-token -Wno-missing-prototypes -Wno-padded -Wno-c99-extensions $(INTERM_PATH)\$(Platform)\$(Config) JPHNE Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace) diff --git a/source/FileZilla.cbproj b/source/FileZilla.cbproj index cec7c5427..9c63defdc 100644 --- a/source/FileZilla.cbproj +++ b/source/FileZilla.cbproj @@ -36,7 +36,7 @@ true filezilla\FileZillaPCH.h false - -Wno-ignored-attributes -Wno-dangling-else -Wno-extra-tokens -Wno-reserved-id-macro -Wno-old-style-cast -Wno-language-extension-token -Wno-global-constructors -Wno-sign-conversion -Wno-zero-as-null-pointer-constant -Wno-c++98-compat-pedantic -Wno-padded -Wno-sign-compare -Wno-deprecated -Wno-cast-align -Wno-shadow -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-format-nonliteral -Wno-implicit-fallthrough + -Wno-ignored-attributes -Wno-dangling-else -Wno-extra-tokens -Wno-reserved-id-macro -Wno-language-extension-token -Wno-global-constructors -Wno-sign-conversion -Wno-zero-as-null-pointer-constant -Wno-c++98-compat-pedantic -Wno-padded -Wno-sign-compare -Wno-deprecated -Wno-cast-align -Wno-shadow -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-format-nonliteral -Wno-implicit-fallthrough -Wno-c99-extensions JPHNE System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace) WINSCP;WIN32;UNICODE;$(Defines) diff --git a/source/My.cbproj b/source/My.cbproj index 3c5924f3f..f214d1e20 100644 --- a/source/My.cbproj +++ b/source/My.cbproj @@ -35,7 +35,7 @@ true true false - -Wno-ignored-attributes -Wno-padded -Wno-language-extension-token -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-old-style-cast -Wno-global-constructors + -Wno-ignored-attributes -Wno-padded -Wno-language-extension-token -Wno-c99-extensions -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-global-constructors $(INTERM_PATH)\$(Platform)\$(Config) JPHNE true diff --git a/source/RScpComp.cbproj b/source/RScpComp.cbproj index 637ed40ee..0c80cd7e2 100644 --- a/source/RScpComp.cbproj +++ b/source/RScpComp.cbproj @@ -36,7 +36,7 @@ true true false - -Wno-ignored-attributes -Wno-zero-as-null-pointer-constant -Wno-c++98-compat-pedantic -Wno-language-extension-token -Wno-missing-prototypes -Wno-old-style-cast -Wno-padded -Wno-float-equal + -Wno-ignored-attributes -Wno-zero-as-null-pointer-constant -Wno-c++98-compat-pedantic -Wno-language-extension-token -Wno-missing-prototypes -Wno-padded -Wno-float-equal -Wno-c99-extensions JPHNE System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace) UNICODE;$(Defines) diff --git a/source/ScpCore.cbproj b/source/ScpCore.cbproj index e9412b831..d2e7d7435 100644 --- a/source/ScpCore.cbproj +++ b/source/ScpCore.cbproj @@ -37,7 +37,7 @@ true core\CorePCH.h false - -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-old-style-cast -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum + -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum -Wno-c99-extensions JPHNE System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace) WINSCP;_WINDOWS;WIN32;WINNT;OPENSSL_NO_DEPRECATED_1_1_0;_CRTIMP=;_LIB;UNICODE;$(BUILD_TYPE);$(Defines) diff --git a/source/ScpForms.cbproj b/source/ScpForms.cbproj index c1ff65cf3..3b71e0438 100644 --- a/source/ScpForms.cbproj +++ b/source/ScpForms.cbproj @@ -32,7 +32,7 @@ true forms\FormsPCH.h false - -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-old-style-cast -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum -Wno-c99-extensions + -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum -Wno-c99-extensions JPHNE System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace) UNICODE;$(Defines) diff --git a/source/ScpResources.cbproj b/source/ScpResources.cbproj index 28e923bcf..19455666f 100644 --- a/source/ScpResources.cbproj +++ b/source/ScpResources.cbproj @@ -31,7 +31,7 @@ true forms\ResourcesPCH.h false - -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-old-style-cast -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum + -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum -Wno-c99-extensions JPHNE System;Xml;Data;Datasnap;Web;Soap;$(DCC_Namespace) UNICODE;$(Defines) diff --git a/source/WinSCP.cbproj b/source/WinSCP.cbproj index a5493fc6c..414fd4533 100644 --- a/source/WinSCP.cbproj +++ b/source/WinSCP.cbproj @@ -57,7 +57,7 @@ true windows\WinPCH.h false - -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-old-style-cast -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum + -Wno-objc-interface-ivars -Wno-return-type-c-linkage -Wno-covered-switch-default -Wno-cast-align -Wno-implicit-fallthrough -Wno-missing-prototypes -Wno-switch -Wno-shadow -Wno-sign-conversion -Wno-global-constructors -Wno-exit-time-destructors -Wno-padded -Wno-c++98-compat-pedantic -Wno-zero-as-null-pointer-constant -Wno-language-extension-token -Wno-ignored-attributes -Wno-float-equal -Wno-switch-enum -Wno-c99-extensions 65001 JPHNE Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;System;Xml;Data;Datasnap;Web;Soap;Vcl;$(DCC_Namespace) diff --git a/source/components/ThemePageControl.cpp b/source/components/ThemePageControl.cpp index ab4431e43..1752c1d7d 100644 --- a/source/components/ThemePageControl.cpp +++ b/source/components/ThemePageControl.cpp @@ -159,7 +159,7 @@ int __fastcall TThemePageControl::GetTabsHeight() // but not on Windows XP TRect Rect = GetClientRect(); - ::SendMessage(Handle, TCM_ADJUSTRECT, FALSE, (LPARAM)&Rect); + ::SendMessage(Handle, TCM_ADJUSTRECT, FALSE, reinterpret_cast(&Rect)); int Result = Rect.Top - 1; // Two different ways to calculate the same, not sure which one is more reliable, @@ -198,7 +198,7 @@ void __fastcall TThemePageControl::PaintWindow(HDC DC) // 1st paint the tab body TRect ClientRect = PageRect; - ::SendMessage(Handle, TCM_ADJUSTRECT, FALSE, (LPARAM)&PageRect); + ::SendMessage(Handle, TCM_ADJUSTRECT, FALSE, reinterpret_cast(&PageRect)); ClientRect.Top = PageRect.Top - 2; DrawThemeBackground(Theme, DC, TABP_PANE, 0, &ClientRect, NULL); @@ -398,7 +398,7 @@ void __fastcall TThemePageControl::DrawTabItem(HDC DC, int Item, TRect Rect, int { SetTextColor(DC, static_cast(ATabTheme->GetItemTextColor(GetItemInfo(State)))); } - HFONT OldFont = (HFONT)SelectObject(DC, Font->Handle); + HGDIOBJ OldFont = SelectObject(DC, Font->Handle); wchar_t * Buf = new wchar_t[static_cast(Text.Length() + 1 + 4)]; wcscpy(Buf, Text.c_str()); TRect TextRect(0, 0, Rect.Width(), 20); diff --git a/source/components/UnixDirView.cpp b/source/components/UnixDirView.cpp index 76c0f4edc..84a2d03ba 100644 --- a/source/components/UnixDirView.cpp +++ b/source/components/UnixDirView.cpp @@ -20,7 +20,7 @@ #pragma package(smart_init) #ifndef DESIGN_ONLY -#define ITEMFILE ((TRemoteFile *)(Item->Data)) +#define ITEMFILE (static_cast(Item->Data)) // noop, previously this tested that the file was in terminal's file listing, // but that cannot be safely checked now the terminal is used in multithreaded // environment @@ -765,8 +765,8 @@ int __stdcall CompareFile(INT_PTR AItem1, INT_PTR AItem2, INT_PTR ADirView) TListItem * Item2 = reinterpret_cast(AItem2); TUnixDirView * DirView = reinterpret_cast(ADirView); DebugAssert((Item1 != NULL) && (Item2 != NULL)); - TRemoteFile * File1 = DebugNotNull((TRemoteFile *)(Item1->Data)); - TRemoteFile * File2 = DebugNotNull((TRemoteFile *)(Item2->Data)); + TRemoteFile * File1 = DebugNotNull(static_cast(Item1->Data)); + TRemoteFile * File2 = DebugNotNull(static_cast(Item2->Data)); int Result; if (File1->IsParentDirectory && !File2->IsParentDirectory) @@ -1049,7 +1049,7 @@ TColor __fastcall TUnixDirView::ItemColor(TListItem * Item) DebugUsedParam(Item); #endif { - return (TColor)clDefaultItemColor; + return clDefaultItemColor; } } //--------------------------------------------------------------------------- diff --git a/source/components/UnixDriveView.cpp b/source/components/UnixDriveView.cpp index 6e2332006..59002e1c1 100644 --- a/source/components/UnixDriveView.cpp +++ b/source/components/UnixDriveView.cpp @@ -730,7 +730,7 @@ bool __fastcall TCustomUnixDriveView::NodePathExists(TTreeNode * /*Node*/) TColor __fastcall TCustomUnixDriveView::NodeColor(TTreeNode * Node) { DebugAssert(Node != NULL); - TColor Result = static_cast(clDefaultItemColor); + TColor Result = clDefaultItemColor; #ifndef DESIGN_ONLY if (FDimmHiddenDirs && !Node->Selected) { diff --git a/source/core/Bookmarks.cpp b/source/core/Bookmarks.cpp index 0d9bf84bd..7a9f6e03a 100644 --- a/source/core/Bookmarks.cpp +++ b/source/core/Bookmarks.cpp @@ -94,7 +94,7 @@ void __fastcall TBookmarks::LoadLevel(THierarchicalStorage * Storage, const Unic else { Directory = L""; // use only in case of malformed config - ShortCut = (TShortCut)Storage->ReadInteger(Name, 0); + ShortCut = static_cast(Storage->ReadInteger(Name, 0)); } TBookmark * Bookmark; if (IsNumber(Name)) diff --git a/source/core/Common.cpp b/source/core/Common.cpp index 228fd47bb..6adca5512 100644 --- a/source/core/Common.cpp +++ b/source/core/Common.cpp @@ -12,6 +12,7 @@ #include #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include #include @@ -344,11 +345,11 @@ UnicodeString ExceptionLogString(Exception *E) DebugAssert(E); if (E->InheritsFrom(__classid(Exception))) { - UnicodeString Msg; - Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message)); - if (E->InheritsFrom(__classid(ExtException))) + UnicodeString Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message)); + ExtException * EE = dynamic_cast(E); + if (EE != nullptr) { - TStrings * MoreMessages = ((ExtException*)E)->MoreMessages; + TStrings * MoreMessages = EE->MoreMessages; if (MoreMessages) { Msg += L"\n" + @@ -1755,7 +1756,7 @@ static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year) HINSTANCE Kernel32 = GetModuleHandle(kernel32); typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi); TGetTimeZoneInformationForYear GetTimeZoneInformationForYear = - (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear"); + reinterpret_cast(GetProcAddress(Kernel32, "GetTimeZoneInformationForYear")); if ((Year == 0) || (GetTimeZoneInformationForYear == NULL)) { @@ -2109,7 +2110,7 @@ FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime, CurrentParams->BaseDifferenceSec; FILETIME Result; - (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL); + *reinterpret_cast<__int64*>(&Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL; return Result; } @@ -2139,7 +2140,7 @@ TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime) __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime, TDSTMode DSTMode) { - __int64 Result = ((*(const __int64*)&(FileTime)) / 10000000LL - 11644473600LL); + __int64 Result = ((*reinterpret_cast(&FileTime)) / 10000000LL - 11644473600LL); if (DSTMode == dstmWin) { @@ -2627,7 +2628,7 @@ TLibModule * __fastcall FindModule(void * Instance) while (CurModule) { - if (CurModule->Instance == (unsigned)Instance) + if (CurModule->Instance == reinterpret_cast(Instance)) { break; } @@ -2659,7 +2660,7 @@ UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength) { TLibModule * MainModule = FindModule(HInstance); DebugAssert(MainModule != NULL); - return DoLoadStrFrom((HINSTANCE)MainModule->ResInstance, Ident, MaxLength); + return DoLoadStrFrom(reinterpret_cast(MainModule->ResInstance), Ident, MaxLength); } //--------------------------------------------------------------------------- UnicodeString __fastcall LoadStrPart(int Ident, int Part) @@ -2979,7 +2980,7 @@ static void NeedUWPData() HINSTANCE Kernel32 = GetModuleHandle(kernel32); typedef LONG WINAPI (* GetCurrentPackageFamilyNameProc)(UINT32 * packageFamilyNameLength, PWSTR packageFamilyName); GetCurrentPackageFamilyNameProc GetCurrentPackageFamilyName = - (GetCurrentPackageFamilyNameProc)GetProcAddress(Kernel32, "GetCurrentPackageFamilyName"); + reinterpret_cast(GetProcAddress(Kernel32, "GetCurrentPackageFamilyName")); UINT32 NameLen = 0; if ((GetCurrentPackageFamilyName != NULL) && (GetCurrentPackageFamilyName(&NameLen, NULL) == ERROR_INSUFFICIENT_BUFFER)) @@ -3324,7 +3325,7 @@ UnicodeString __fastcall FormatVersion(int MajorVersion, int MinorVersion, int R //--------------------------------------------------------------------------- TFormatSettings __fastcall GetEngFormatSettings() { - return TFormatSettings::Create((TLocaleID)1033); + return TFormatSettings::Create(static_cast(1033)); } //--------------------------------------------------------------------------- int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr) diff --git a/source/core/Common.h b/source/core/Common.h index 942d20efe..cbf994a82 100644 --- a/source/core/Common.h +++ b/source/core/Common.h @@ -293,10 +293,8 @@ TStrings * TlsCipherList(); template MethodT __fastcall MakeMethod(void * Data, FuncT Code) { - MethodT Method; - ((TMethod*)&Method)->Data = Data; - ((TMethod*)&Method)->Code = reinterpret_cast(Code); - return Method; + TMethod Method = { .Data = Data, .Code = reinterpret_cast(Code) }; + return *reinterpret_cast(&Method); } //--------------------------------------------------------------------------- enum TAssemblyLanguage { alCSharp, alVBNET, alPowerShell }; diff --git a/source/core/Configuration.cpp b/source/core/Configuration.cpp index 42dd7e3c9..fa169f4ab 100644 --- a/source/core/Configuration.cpp +++ b/source/core/Configuration.cpp @@ -761,7 +761,7 @@ UnicodeString __fastcall TConfiguration::BannerHash(const UnicodeString & Banner Result.SetLength(16); md5checksum( reinterpret_cast(Banner.c_str()), Banner.Length() * sizeof(wchar_t), - (unsigned char*)Result.c_str()); + reinterpret_cast(Result.c_str())); return BytesToHex(Result); } //--------------------------------------------------------------------------- diff --git a/source/core/CopyParam.cpp b/source/core/CopyParam.cpp index a1ed6d9cc..bc632be2f 100644 --- a/source/core/CopyParam.cpp +++ b/source/core/CopyParam.cpp @@ -746,7 +746,7 @@ UnicodeString __fastcall TCopyParamType::GetLogStr() const CaseC[FileNameCase], CharToHex(InvalidCharsReplacement), ResumeC[ResumeSupport], - (int)ResumeThreshold, + static_cast(ResumeThreshold), BooleanToEngStr(CalculateSize), FileMask)) + FORMAT( @@ -867,18 +867,18 @@ void __fastcall TCopyParamType::Load(THierarchicalStorage * Storage) { AddXToDirectories = Storage->ReadBool(L"AddXToDirectories", AddXToDirectories); AsciiFileMask.Masks = Storage->ReadString(L"Masks", AsciiFileMask.Masks); - FileNameCase = (TFileNameCase)Storage->ReadInteger(L"FileNameCase", FileNameCase); + FileNameCase = static_cast(Storage->ReadInteger(L"FileNameCase", FileNameCase)); PreserveReadOnly = Storage->ReadBool(L"PreserveReadOnly", PreserveReadOnly); PreserveTime = Storage->ReadBool(L"PreserveTime", PreserveTime); PreserveTimeDirs = Storage->ReadBool(L"PreserveTimeDirs", PreserveTimeDirs); PreserveRights = Storage->ReadBool(L"PreserveRights", PreserveRights); IgnorePermErrors = Storage->ReadBool(L"IgnorePermErrors", IgnorePermErrors); Rights.Text = Storage->ReadString(L"Text", Rights.Text); - TransferMode = (TTransferMode)Storage->ReadInteger(L"TransferMode", TransferMode); - ResumeSupport = (TResumeSupport)Storage->ReadInteger(L"ResumeSupport", ResumeSupport); + TransferMode = static_cast(Storage->ReadInteger(L"TransferMode", TransferMode)); + ResumeSupport = static_cast(Storage->ReadInteger(L"ResumeSupport", ResumeSupport)); ResumeThreshold = Storage->ReadInt64(L"ResumeThreshold", ResumeThreshold); - InvalidCharsReplacement = (wchar_t)Storage->ReadInteger(L"ReplaceInvalidChars", - (unsigned int)InvalidCharsReplacement); + InvalidCharsReplacement = static_cast(Storage->ReadInteger(L"ReplaceInvalidChars", + static_cast(InvalidCharsReplacement))); LocalInvalidChars = Storage->ReadString(L"LocalInvalidChars", LocalInvalidChars); CalculateSize = Storage->ReadBool(L"CalculateSize", CalculateSize); if (Storage->ValueExists(L"IncludeFileMask")) @@ -947,7 +947,7 @@ void __fastcall TCopyParamType::Save(THierarchicalStorage * Storage, const TCopy WRITE_DATA(Integer, TransferMode); WRITE_DATA(Integer, ResumeSupport); WRITE_DATA(Int64, ResumeThreshold); - #define WRITE_DATA_CONV_FUNC(X) (unsigned int)(X) + #define WRITE_DATA_CONV_FUNC(X) static_cast(X) WRITE_DATA_CONV(Integer, L"ReplaceInvalidChars", InvalidCharsReplacement); WRITE_DATA(String, LocalInvalidChars); WRITE_DATA(Bool, CalculateSize); diff --git a/source/core/Cryptography.cpp b/source/core/Cryptography.cpp index 4df4e8f1a..287ecb580 100644 --- a/source/core/Cryptography.cpp +++ b/source/core/Cryptography.cpp @@ -8,6 +8,7 @@ #include "Exceptions.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include #include @@ -96,6 +97,9 @@ static void hmac_sha1_begin(hmac_ctx cx[1]) memset(cx, 0, sizeof(hmac_ctx)); } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" + /* input the HMAC key (can be called multiple times) */ static void hmac_sha1_key(const unsigned char key[], unsigned long key_len, hmac_ctx cx[1]) { @@ -174,6 +178,8 @@ static void hmac_sha1_end(unsigned char mac[], unsigned long mac_len, hmac_ctx c mac[i] = dig[i]; } +#pragma clang diagnostic pop + #define BLOCK_SIZE 16 void aes_set_encrypt_key(const unsigned char in_key[], unsigned int klen, void * cx) @@ -273,10 +279,10 @@ static void derive_key(const unsigned char pwd[], /* the PASSWORD */ c3->CopyFrom(c2); /* enter additional data for 1st block into uu */ - uu[0] = (unsigned char)((i + 1) >> 24); - uu[1] = (unsigned char)((i + 1) >> 16); - uu[2] = (unsigned char)((i + 1) >> 8); - uu[3] = (unsigned char)(i + 1); + uu[0] = static_cast((i + 1) >> 24); + uu[1] = static_cast((i + 1) >> 16); + uu[2] = static_cast((i + 1) >> 8); + uu[3] = static_cast(i + 1); /* this is the key mixing iteration */ for(j = 0, k = 4; j < iter; ++j) @@ -537,19 +543,19 @@ RawByteString __fastcall ScramblePassword(UnicodeString Password) int P = 0; while ((P <= 0) || (P > 255) || IsDigit(static_cast(P))) { - P = (int)((double)rand() / ((double)RAND_MAX / 256.0)); + P = static_cast(static_cast(rand()) / (static_cast(RAND_MAX) / 256.0)); } - Buf[Index] = (unsigned char)P; + Buf[Index] = static_cast(P); } - Buf[Padding] = (char)('0' + (Len % 10)); - Buf[Padding + 1] = (char)('0' + ((Len / 10) % 10)); - Buf[Padding + 2] = (char)('0' + ((Len / 100) % 10)); + Buf[Padding] = static_cast('0' + (Len % 10)); + Buf[Padding + 1] = static_cast('0' + ((Len / 10) % 10)); + Buf[Padding + 2] = static_cast('0' + ((Len / 100) % 10)); strcpy(Buf + Padding + 3, UtfPassword.c_str()); char * S = Buf; int Last = 31; while (*S != '\0') { - Last = (Last + (unsigned char)*S) % 255 + 1; + Last = (Last + static_cast(*S)) % 255 + 1; *S = ScrambleTable[Last]; S++; } @@ -566,12 +572,12 @@ bool __fastcall UnscramblePassword(RawByteString Scrambled, UnicodeString & Pass int Last = 31; while (*S != '\0') { - int X = (int)UnscrambleTable[(unsigned char)*S] - 1 - (Last % 255); + int X = static_cast(UnscrambleTable[static_cast(*S)] - 1 - (Last % 255)); if (X <= 0) { X += 255; } - *S = (char)X; + *S = static_cast(X); Last = (Last + X) % 255 + 1; S++; } @@ -622,9 +628,9 @@ void __fastcall CryptographyInitialize() UnscrambleTable = new unsigned char[256]; for (int Index = 0; Index < 256; Index++) { - UnscrambleTable[SScrambleTable[Index]] = (unsigned char)Index; + UnscrambleTable[SScrambleTable[Index]] = static_cast(Index); } - srand((unsigned int)time(NULL) ^ (unsigned int)getpid()); + srand(static_cast(time(NULL)) ^ static_cast(getpid())); // The results are partly cached. So when later some OpenSSL function is called, which internally // calls OPENSSL_init_crypto, it will fail, without doing full initialization. So afterwards diff --git a/source/core/FileBuffer.h b/source/core/FileBuffer.h index a6baf826e..24ccfb079 100644 --- a/source/core/FileBuffer.h +++ b/source/core/FileBuffer.h @@ -37,11 +37,11 @@ private: TMemoryStream * FMemory; int FSize; - char * __fastcall GetData() const { return (char *)FMemory->Memory; } + char * __fastcall GetData() const { return static_cast(FMemory->Memory); } char * __fastcall GetPointer() const { return GetData() + GetPosition(); } void NeedSpace(DWORD Size); void __fastcall SetSize(int value); - int __fastcall GetPosition() const { return (int)FMemory->Position; } + int __fastcall GetPosition() const { return static_cast(FMemory->Position); } void __fastcall ProcessRead(DWORD Len, DWORD Result); }; //--------------------------------------------------------------------------- diff --git a/source/core/FileInfo.cpp b/source/core/FileInfo.cpp index e1130b943..35aaca551 100644 --- a/source/core/FileInfo.cpp +++ b/source/core/FileInfo.cpp @@ -42,7 +42,7 @@ PVSFixedFileInfo __fastcall GetFixedFileInfo(void * FileInfo) { UINT Len; PVSFixedFileInfo Result; - if (!VerQueryValue(FileInfo, L"\\", (void**)&Result, &Len)) + if (!VerQueryValue(FileInfo, L"\\", reinterpret_cast(&Result), &Len)) { throw Exception(L"Fixed file info not available"); } @@ -54,7 +54,7 @@ unsigned __fastcall GetTranslationCount(void * FileInfo) { PTranslations P; UINT Len; - if (!VerQueryValue(FileInfo, L"\\VarFileInfo\\Translation", (void**)&P, &Len)) + if (!VerQueryValue(FileInfo, L"\\VarFileInfo\\Translation", reinterpret_cast(&P), &Len)) { throw Exception(L"File info translations not available"); } @@ -67,7 +67,7 @@ TTranslation __fastcall GetTranslation(void * FileInfo, unsigned i) PTranslations P; UINT Len; - if (!VerQueryValue(FileInfo, L"\\VarFileInfo\\Translation", (void**)&P, &Len)) + if (!VerQueryValue(FileInfo, L"\\VarFileInfo\\Translation", reinterpret_cast(&P), &Len)) { throw Exception(L"File info translations not available"); } @@ -89,7 +89,7 @@ UnicodeString __fastcall GetFileInfoString(void * FileInfo, UnicodeString SubBlock = UnicodeString(L"\\StringFileInfo\\") + IntToHex(Translation.Language, 4) + IntToHex(Translation.CharSet, 4) + L"\\" + StringName; - if (!VerQueryValue(FileInfo, SubBlock.c_str(), (void**)&P, &Len)) + if (!VerQueryValue(FileInfo, SubBlock.c_str(), reinterpret_cast(&P), &Len)) { if (!AllowEmpty) { diff --git a/source/core/FileOperationProgress.cpp b/source/core/FileOperationProgress.cpp index e65e6b864..0c7348aa6 100644 --- a/source/core/FileOperationProgress.cpp +++ b/source/core/FileOperationProgress.cpp @@ -263,7 +263,7 @@ int __fastcall TFileOperationProgressType::TransferProgress() int Result; if (TransferSize) { - Result = (int)((TransferredSize * 100)/TransferSize); + Result = static_cast((TransferredSize * 100)/TransferSize); } else { @@ -279,7 +279,7 @@ int __fastcall TFileOperationProgressType::TotalTransferProgress() const int Result; if (FTotalSize > 0) { - Result = (int)(((FPersistence.TotalTransferred - FTotalTransferBase + FTotalSkipped) * 100)/FTotalSize); + Result = static_cast(((FPersistence.TotalTransferred - FTotalTransferBase + FTotalSkipped) * 100)/FTotalSize); } else { @@ -474,7 +474,7 @@ unsigned long __fastcall TFileOperationProgressType::LocalBlockSize() unsigned long Result = TRANSFER_BUF_SIZE; if (LocallyUsed + Result > LocalSize) { - Result = (unsigned long)(LocalSize - LocallyUsed); + Result = static_cast(LocalSize - LocallyUsed); } Result = AdjustToCPSLimit(Result); return Result; @@ -804,7 +804,7 @@ unsigned long __fastcall TFileOperationProgressType::TransferBlockSize() unsigned long Result = TRANSFER_BUF_SIZE; if (TransferredSize + Result > TransferSize) { - Result = (unsigned long)(TransferSize - TransferredSize); + Result = static_cast(TransferSize - TransferredSize); } Result = AdjustToCPSLimit(Result); return Result; @@ -853,7 +853,7 @@ inline static unsigned int CalculateCPS(__int64 Transferred, unsigned int MSecEl } else { - Result = (unsigned int)(Transferred * MSecsPerSec / MSecElapsed); + Result = static_cast(Transferred * MSecsPerSec / MSecElapsed); } return Result; } @@ -891,7 +891,7 @@ TDateTime __fastcall TFileOperationProgressType::TimeExpected() unsigned int CurCps = CPS(); if (CurCps) { - return TDateTime((double)(((double)(TransferSize - TransferredSize)) / CurCps) / SecsPerDay); + return TDateTime(static_cast(static_cast(TransferSize - TransferredSize) / CurCps) / SecsPerDay); } else { @@ -908,7 +908,7 @@ TDateTime __fastcall TFileOperationProgressType::TotalTimeLeft() __int64 Processed = FTotalSkipped + FPersistence.TotalTransferred - FTotalTransferBase; if ((CurCps > 0) && (FTotalSize > Processed)) { - return TDateTime((double)((double)(FTotalSize - Processed) / CurCps) / SecsPerDay); + return TDateTime(static_cast(static_cast(FTotalSize - Processed) / CurCps) / SecsPerDay); } else { diff --git a/source/core/FtpFileSystem.cpp b/source/core/FtpFileSystem.cpp index 8b05ec104..72e4296da 100644 --- a/source/core/FtpFileSystem.cpp +++ b/source/core/FtpFileSystem.cpp @@ -13,8 +13,11 @@ #include "NeonIntf.h" #include "SessionInfo.h" #include "Cryptography.h" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include +#pragma clang diagnostic push //--------------------------------------------------------------------------- #define FILE_OPERATION_LOOP_TERMINAL FTerminal //--------------------------------------------------------------------------- diff --git a/source/core/Http.cpp b/source/core/Http.cpp index 0daaa2598..07edc5ec9 100644 --- a/source/core/Http.cpp +++ b/source/core/Http.cpp @@ -5,9 +5,10 @@ #include "Http.h" #include "NeonIntf.h" #include "Exceptions.h" -#include "ne_request.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wold-style-cast" +#include "ne_request.h" #include #pragma clang diagnostic pop //--------------------------------------------------------------------------- diff --git a/source/core/NamedObjs.cpp b/source/core/NamedObjs.cpp index f91ecd27e..5115685d0 100644 --- a/source/core/NamedObjs.cpp +++ b/source/core/NamedObjs.cpp @@ -78,13 +78,13 @@ __fastcall TNamedObjectList::TNamedObjectList(): //--------------------------------------------------------------------------- TNamedObject * __fastcall TNamedObjectList::AtObject(Integer Index) { - return (TNamedObject *)Items[Index+FHiddenCount]; + return static_cast(Items[Index+FHiddenCount]); } //--------------------------------------------------------------------------- void __fastcall TNamedObjectList::Recount() { int i = 0; - while ((i < TObjectList::Count) && ((TNamedObject *)Items[i])->Hidden) i++; + while ((i < TObjectList::Count) && static_cast(Items[i])->Hidden) i++; FHiddenCount = i; } //--------------------------------------------------------------------------- diff --git a/source/core/NeonIntf.cpp b/source/core/NeonIntf.cpp index 97d44ee98..ad930b17e 100644 --- a/source/core/NeonIntf.cpp +++ b/source/core/NeonIntf.cpp @@ -265,7 +265,7 @@ void SetNeonTlsInit(ne_session * Session, TNeonTlsInit OnNeonTlsInit, TTerminal } // As the OnNeonTlsInit always only calls SetupSsl, we can simplify this with one shared implementation - TMethod & Method = *(TMethod*)&OnNeonTlsInit; + TMethod & Method = *reinterpret_cast(&OnNeonTlsInit); ne_set_session_private(Session, SESSION_TLS_INIT_KEY, Method.Code); ne_set_session_private(Session, SESSION_TLS_INIT_DATA_KEY, Method.Data); } @@ -567,7 +567,7 @@ UnicodeString __fastcall NeonTlsSessionInfo( //--------------------------------------------------------------------------- static int TlsVersionToOpenssl(TTlsVersion TlsVersion) { - TlsVersion = (TTlsVersion)std::min((TTlsVersion)std::max(TlsVersion, tlsMin), tlsMax); + TlsVersion = std::min(std::max(TlsVersion, tlsMin), tlsMax); switch (TlsVersion) { case tls10: return TLS1_VERSION; diff --git a/source/core/NeonIntf.h b/source/core/NeonIntf.h index 657604f53..2d9de41ef 100644 --- a/source/core/NeonIntf.h +++ b/source/core/NeonIntf.h @@ -2,8 +2,11 @@ #ifndef NeonIntfH #define NeonIntfH //--------------------------------------------------------------------------- +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include +#pragma clang diagnostic pop #include //--------------------------------------------------------------------------- #define StrToNeon(S) UTF8String(S).c_str() diff --git a/source/core/PuttyIntf.cpp b/source/core/PuttyIntf.cpp index 6ab1530bb..80eb65771 100644 --- a/source/core/PuttyIntf.cpp +++ b/source/core/PuttyIntf.cpp @@ -206,7 +206,7 @@ static SeatPromptResult get_userpass_input(Seat * seat, prompts_t * p) { S = UnicodeString(AnsiString(Prompt->prompt)); } - Prompts->AddObject(S, (TObject *)(FLAGMASK(Prompt->echo, pupEcho))); + Prompts->AddObject(S, reinterpret_cast(FLAGMASK(Prompt->echo, pupEcho))); // this fails, when new passwords do not match on change password prompt, // and putty retries the prompt DebugAssert(strlen(prompt_get_result_ref(Prompt)) == 0); @@ -621,7 +621,10 @@ char * get_reg_sz_winscp(HKEY Key, const char * Name) else { AnsiString ValueAnsi = AnsiString(Value); + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wold-style-cast" Result = snewn(ValueAnsi.Length() + 1, char); + #pragma clang diagnostic pop strcpy(Result, ValueAnsi.c_str()); } } @@ -704,7 +707,7 @@ TKeyType KeyType(UnicodeString FileName) DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH); UTF8String UtfFileName = UTF8String(FileName); Filename * KeyFile = filename_from_utf8(UtfFileName.c_str()); - TKeyType Result = (TKeyType)key_type(KeyFile); + TKeyType Result = static_cast(key_type(KeyFile)); filename_free(KeyFile); return Result; } @@ -841,6 +844,8 @@ void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment) } //--------------------------------------------------------------------------- // Based on cmdgen.c +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" void AddCertificateToKey(TPrivateKey * PrivateKey, const UnicodeString & CertificateFileName) { struct ssh2_userkey * Ssh2Key = reinterpret_cast(PrivateKey); @@ -1592,6 +1597,7 @@ bool enum_host_ca_next(host_ca_enum * Enum, strbuf * StrBuf) } return Result; } +#pragma clang diagnostic pop //--------------------------------------------------------------------------- void enum_host_ca_finish(host_ca_enum * Enum) { diff --git a/source/core/PuttyIntf.h b/source/core/PuttyIntf.h index 834142703..8d64bdcc4 100644 --- a/source/core/PuttyIntf.h +++ b/source/core/PuttyIntf.h @@ -12,6 +12,7 @@ void __fastcall DontSaveRandomSeed(); #define MPEXT #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wconversion" +#pragma clang diagnostic ignored "-Wold-style-cast" extern "C" { #include diff --git a/source/core/RemoteFiles.cpp b/source/core/RemoteFiles.cpp index d6d9a5961..ec7ac81b1 100644 --- a/source/core/RemoteFiles.cpp +++ b/source/core/RemoteFiles.cpp @@ -867,7 +867,7 @@ void __fastcall TRemoteTokenList::Log(TTerminal * Terminal, const wchar_t * Titl //--------------------------------------------------------------------------- int __fastcall TRemoteTokenList::Count() const { - return (int)FTokens.size(); + return static_cast(FTokens.size()); } //--------------------------------------------------------------------------- const TRemoteToken * __fastcall TRemoteTokenList::Token(int Index) const @@ -1055,7 +1055,7 @@ wchar_t __fastcall TRemoteFile::GetType() const void __fastcall TRemoteFile::SetType(wchar_t AType) { FType = AType; - FIsSymLink = ((wchar_t)towupper(FType) == FILETYPE_SYMLINK); + FIsSymLink = (static_cast(towupper(FType)) == FILETYPE_SYMLINK); } //--------------------------------------------------------------------------- const TRemoteFile * __fastcall TRemoteFile::GetLinkedFile() const @@ -1134,6 +1134,11 @@ UnicodeString __fastcall TRemoteFile::GetRightsStr() return FRights->Unknown ? HumanRights : FRights->Text; } //--------------------------------------------------------------------------- +inline Word StrToWord(const UnicodeString & S) +{ + return static_cast(StrToInt(S)); +} +//--------------------------------------------------------------------------- void __fastcall TRemoteFile::SetListingStr(UnicodeString value) { // Value stored in 'value' can be used for error message @@ -1237,7 +1242,7 @@ void __fastcall TRemoteFile::SetListingStr(UnicodeString value) else { // format dd mmm or mmm dd ? - Day = (Word)StrToIntDef(Col, 0); + Day = static_cast(StrToIntDef(Col, 0)); if (Day > 0) { DayMonthFormat = true; @@ -1252,15 +1257,15 @@ void __fastcall TRemoteFile::SetListingStr(UnicodeString value) // for --full-time format if ((Month == 0) && (Col.Length() == 10) && (Col[5] == L'-') && (Col[8] == L'-')) { - Year = (Word)Col.SubString(1, 4).ToInt(); - Month = (Word)Col.SubString(6, 2).ToInt(); - Day = (Word)Col.SubString(9, 2).ToInt(); + Year = StrToWord(Col.SubString(1, 4)); + Month = StrToWord(Col.SubString(6, 2)); + Day = StrToWord(Col.SubString(9, 2)); GETCOL; - Hour = (Word)Col.SubString(1, 2).ToInt(); - Min = (Word)Col.SubString(4, 2).ToInt(); + Hour = StrToWord(Col.SubString(1, 2)); + Min = StrToWord(Col.SubString(4, 2)); if (Col.Length() >= 8) { - Sec = (Word)StrToInt(Col.SubString(7, 2)); + Sec = StrToWord(StrToInt(Col.SubString(7, 2))); } else { @@ -1293,7 +1298,7 @@ void __fastcall TRemoteFile::SetListingStr(UnicodeString value) if (Day == 0) { GETNCOL; - Day = (Word)StrToInt(Col); + Day = StrToWord(Col); } if ((Day < 1) || (Day > 31)) Abort(); @@ -1306,13 +1311,13 @@ void __fastcall TRemoteFile::SetListingStr(UnicodeString value) { Abort(); } - Hour = (Word)StrToInt(Col.SubString(1, 2)); - Min = (Word)StrToInt(Col.SubString(4, 2)); - Sec = (Word)StrToInt(Col.SubString(7, 2)); + Hour = StrToWord(Col.SubString(1, 2)); + Min = StrToWord(Col.SubString(4, 2)); + Sec = StrToWord(Col.SubString(7, 2)); FModificationFmt = mfFull; // do not trim leading space of filename GETNCOL; - Year = (Word)StrToInt(Col); + Year = StrToWord(Col); } else { @@ -1333,11 +1338,11 @@ void __fastcall TRemoteFile::SetListingStr(UnicodeString value) } // GETNCOL; // We don't want to trim input strings (name with space at beginning???) // Check if we got time (contains :) or year - if ((P = (Word)Col.Pos(L':')) > 0) + if ((P = static_cast(Col.Pos(L':'))) > 0) { Word CurrMonth, CurrDay; - Hour = (Word)StrToInt(Col.SubString(1, P-1)); - Min = (Word)StrToInt(Col.SubString(P+1, Col.Length() - P)); + Hour = StrToWord(Col.SubString(1, P-1)); + Min = StrToWord(Col.SubString(P+1, Col.Length() - P)); if (Hour > 23 || Min > 59) Abort(); // When we don't got year, we assume current year // with exception that the date would be in future @@ -1350,7 +1355,7 @@ void __fastcall TRemoteFile::SetListingStr(UnicodeString value) } else { - Year = (Word)StrToInt(Col); + Year = StrToWord(Col); if (Year > 10000) Abort(); // When we didn't get time we assume midnight Hour = 0; Min = 0; Sec = 0; @@ -1656,7 +1661,7 @@ UnicodeString __fastcall TRemoteFileList::GetFullDirectory() //--------------------------------------------------------------------------- TRemoteFile * __fastcall TRemoteFileList::GetFiles(Integer Index) { - return (TRemoteFile *)Items[Index]; + return static_cast(Items[Index]); } //--------------------------------------------------------------------------- Boolean __fastcall TRemoteFileList::GetIsRoot() @@ -1795,7 +1800,7 @@ void __fastcall TRemoteDirectoryCache::Clear() { for (int Index = 0; Index < Count; Index++) { - delete (TRemoteFileList *)Objects[Index]; + delete static_cast(Objects[Index]); Objects[Index] = NULL; } } @@ -2685,7 +2690,7 @@ TRights TRights::Combine(const TRights & Other) const { TRights Result = (*this); Result |= Other.NumberSet; - Result &= (unsigned short)~Other.NumberUnset; + Result &= static_cast(~Other.NumberUnset); return Result; } //=== TRemoteProperties ------------------------------------------------------- @@ -2753,7 +2758,7 @@ TRemoteProperties __fastcall TRemoteProperties::CommonProperties(TStrings * File TRemoteProperties CommonProperties; for (int Index = 0; Index < FileList->Count; Index++) { - TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]); + TRemoteFile * File = static_cast(FileList->Objects[Index]); DebugAssert(File); if (!Index) { diff --git a/source/core/S3FileSystem.cpp b/source/core/S3FileSystem.cpp index 32e988486..d2c15b1b6 100644 --- a/source/core/S3FileSystem.cpp +++ b/source/core/S3FileSystem.cpp @@ -629,7 +629,7 @@ struct TLibS3CallbackData { TLibS3CallbackData() { - Status = (S3Status)-1; + Status = static_cast(-1); } TS3FileSystem * FileSystem; @@ -1413,8 +1413,8 @@ S3Status TS3FileSystem::LibS3ListBucketCallback( if (Filled == 6) { TDateTime Modification = - EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) + - EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0); + EncodeDateVerbose(static_cast(Year), static_cast(Month), static_cast(Day)) + + EncodeTimeVerbose(static_cast(Hour), static_cast(Min), static_cast(Sec), 0); File->Modification = ConvertTimestampFromUTC(Modification); File->ModificationFmt = mfFull; } diff --git a/source/core/ScpFileSystem.cpp b/source/core/ScpFileSystem.cpp index a7bb51871..802030bd3 100644 --- a/source/core/ScpFileSystem.cpp +++ b/source/core/ScpFileSystem.cpp @@ -263,7 +263,7 @@ TStrings * __fastcall TCommandSet::CreateCommandList() TStrings * CommandList = new TStringList(); for (Integer Index = 0; Index < ShellCommandCount; Index++) { - UnicodeString Cmd = Commands[(TFSCommand)Index]; + UnicodeString Cmd = Commands[static_cast(Index)]; if (!Cmd.IsEmpty()) { Cmd = ExtractCommand(Cmd); @@ -1933,7 +1933,7 @@ void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName, UnicodeString AbsoluteFileName = FTerminal->AbsolutePath(TargetDir + DestFileName, false); DebugAssert(Handle.Handle); - std::unique_ptr Stream(new TSafeHandleStream((THandle)Handle.Handle)); + std::unique_ptr Stream(new TSafeHandleStream(reinterpret_cast(Handle.Handle))); // File is regular file (not directory) FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName))); @@ -2043,7 +2043,7 @@ void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName, // TVarRec don't understand 'unsigned int' -> we use sprintf() Buf.sprintf(L"C%s %Ld %s", Rights.Octal.data(), - (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size : + (OperationProgress->AsciiTransfer ? static_cast<__int64>(AsciiBuf.Size) : OperationProgress->LocalSize), DestFileName.data()); FSecureShell->SendLine(Buf); @@ -2065,7 +2065,7 @@ void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName, { unsigned long BlockSize = OperationProgress->TransferBlockSize(); FSecureShell->Send( - reinterpret_cast(AsciiBuf.Data + (unsigned int)OperationProgress->TransferredSize), + reinterpret_cast(AsciiBuf.Data + static_cast(OperationProgress->TransferredSize)), BlockSize); OperationProgress->AddTransferred(BlockSize); if (OperationProgress->Cancel == csCancelTransfer) @@ -2306,7 +2306,7 @@ void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy, !OperationProgress->Cancel; IFile++) { UnicodeString FileName = FilesToCopy->Strings[IFile]; - TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile]; + TRemoteFile * File = static_cast(FilesToCopy->Objects[IFile]); DebugAssert(File); try @@ -2427,9 +2427,9 @@ void __fastcall TSCPFileSystem::SCPError(const UnicodeString Message, bool Fatal void __fastcall TSCPFileSystem::SCPSendError(const UnicodeString Message, bool Fatal) { DebugUsedParam(Message); - unsigned char ErrorLevel = (char)(Fatal ? 2 : 1); + unsigned char ErrorLevel = Fatal ? 2 : 1; FTerminal->LogEvent(FORMAT(L"Sending SCP error (%d) to remote side:", - ((int)ErrorLevel))); + (static_cast(ErrorLevel)))); FSecureShell->Send(&ErrorLevel, 1); // We don't send exact error message, because some unspecified // characters can terminate remote scp @@ -2694,7 +2694,7 @@ void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir, EXCEPTION; } - FileStream = new TSafeHandleStream((THandle)File); + FileStream = new TSafeHandleStream(reinterpret_cast(File)); } catch (Exception &E) { diff --git a/source/core/Script.cpp b/source/core/Script.cpp index bace5e5bc..7ab4f1776 100644 --- a/source/core/Script.cpp +++ b/source/core/Script.cpp @@ -1334,7 +1334,7 @@ void __fastcall TScript::RmProc(TScriptProcParams * Parameters) bool OnlyFile = Parameters->FindSwitch(L"onlyfile"); TStrings * FileList = CreateFileList( Parameters, 1, Parameters->ParamCount, - (TFileListType)(fltQueryServer | fltMask| FLAGMASK(OnlyFile, fltOnlyFile))); + static_cast(fltQueryServer | fltMask| FLAGMASK(OnlyFile, fltOnlyFile))); try { CheckParams(Parameters); @@ -1476,7 +1476,7 @@ void __fastcall TScript::GetProc(TScriptProcParams * Parameters) OnlyFile = true; } TStrings * FileList = CreateFileList(Parameters, 1, LastFileParam, - (TFileListType)(fltQueryServer | fltMask | FLAGMASK(Latest, fltLatest) | FLAGMASK(OnlyFile, fltOnlyFile))); + static_cast(fltQueryServer | fltMask | FLAGMASK(Latest, fltLatest) | FLAGMASK(OnlyFile, fltOnlyFile))); try { UnicodeString TargetDirectory; @@ -1541,7 +1541,7 @@ void __fastcall TScript::PutProc(TScriptProcParams * Parameters) } else { - FileList = CreateLocalFileList(Parameters, 1, LastFileParam, (TFileListType)(fltMask | FLAGMASK(Latest, fltLatest))); + FileList = CreateLocalFileList(Parameters, 1, LastFileParam, static_cast(fltMask | FLAGMASK(Latest, fltLatest))); } try { @@ -1595,7 +1595,7 @@ TTransferMode __fastcall TScript::ParseTransferModeName(UnicodeString Name) throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (L"transfer", Name))); } - return (TTransferMode)Value; + return static_cast(Value); } //--------------------------------------------------------------------------- void __fastcall TScript::OptionImpl(UnicodeString OptionName, UnicodeString ValueName) @@ -1650,7 +1650,7 @@ void __fastcall TScript::OptionImpl(UnicodeString OptionName, UnicodeString Valu { throw Exception(FMTLOAD(SCRIPT_VALUE_UNKNOWN, (ValueName, OptionName))); } - FBatch = (TBatchMode)Value; + FBatch = static_cast(Value); FInteractiveBatch = FBatch; if (SetValue && (FBatch != BatchOff) && (FSessionReopenTimeout == 0)) @@ -1688,7 +1688,7 @@ void __fastcall TScript::OptionImpl(UnicodeString OptionName, UnicodeString Valu FCopyParam.TransferMode = ParseTransferModeName(ValueName); } - DebugAssert(FCopyParam.TransferMode < (TTransferMode)TransferModeNamesCount); + DebugAssert(FCopyParam.TransferMode < static_cast(TransferModeNamesCount)); const wchar_t * Value = TransferModeNames[FCopyParam.TransferMode]; PrintLine(FORMAT(ListFormat, (Names[Transfer], Value))); } diff --git a/source/core/SecureShell.cpp b/source/core/SecureShell.cpp index b63ddfdf8..6bfe7ac7f 100644 --- a/source/core/SecureShell.cpp +++ b/source/core/SecureShell.cpp @@ -546,10 +546,10 @@ bool __fastcall TSecureShell::TryFtp() Address.sin_family = AF_INET; int Port = FtpPortNumber; Address.sin_port = htons(static_cast(Port)); - Address.sin_addr.s_addr = *((unsigned long *)*HostEntry->h_addr_list); + Address.sin_addr.s_addr = *(reinterpret_cast(*HostEntry->h_addr_list)); HANDLE Event = CreateEvent(NULL, false, false, NULL); - Result = (WSAEventSelect(Socket, (WSAEVENT)Event, FD_CONNECT | FD_CLOSE) != SOCKET_ERROR); + Result = (WSAEventSelect(Socket, static_cast(Event), FD_CONNECT | FD_CLOSE) != SOCKET_ERROR); if (Result) { @@ -1071,8 +1071,8 @@ void __fastcall TSecureShell::FromBackend(const unsigned char * Data, size_t Len if (PendSize < PendLen + Len) { PendSize = PendLen + Len + 4096; - Pending = (unsigned char *) - (Pending ? srealloc(Pending, PendSize) : smalloc(PendSize)); + Pending = static_cast( + Pending ? srealloc(Pending, PendSize) : smalloc(PendSize)); if (!Pending) FatalError(L"Out of memory"); } memmove(Pending + PendLen, p, Len); @@ -1196,7 +1196,7 @@ UnicodeString __fastcall TSecureShell::ReceiveLine() { Index++; } - EOL = (Boolean)(Index && (Pending[Index-1] == '\n')); + EOL = static_cast(Index && (Pending[Index-1] == '\n')); Integer PrevLen = Line.Length(); Line.SetLength(PrevLen + Index); Receive(reinterpret_cast(Line.c_str()) + PrevLen, Index); @@ -1244,7 +1244,7 @@ void __fastcall TSecureShell::SendSpecial(int Code) LogEvent(FORMAT(L"Sending special code: %d", (Code))); } CheckConnection(); - backend_special(FBackendHandle, (SessionSpecialCode)Code, 0); + backend_special(FBackendHandle, static_cast(Code), 0); CheckConnection(); FLastDataSent = Now(); } @@ -1437,7 +1437,7 @@ int __fastcall TSecureShell::TranslatePuttyMessage( size_t OriginalLen = wcslen(Original); size_t PrefixLen = Div - Original; size_t SuffixLen = OriginalLen - PrefixLen - 1; - if (((size_t)Message.Length() >= OriginalLen - 1) && + if ((static_cast(Message.Length()) >= OriginalLen - 1) && (wcsncmp(Message.c_str(), Original, PrefixLen) == 0) && (wcsncmp(Message.c_str() + Message.Length() - SuffixLen, Div + 1, SuffixLen) == 0)) { @@ -1615,7 +1615,7 @@ void __fastcall TSecureShell::SocketEventSelect(SOCKET Socket, HANDLE Event, boo LogEvent(FORMAT(L"Selecting events %d for socket %d", (int(Events), int(Socket)))); } - if (WSAEventSelect(Socket, (WSAEVENT)Event, Events) == SOCKET_ERROR) + if (WSAEventSelect(Socket, static_cast(Event), Events) == SOCKET_ERROR) { if (Configuration->ActualLogProtocol >= 2) { @@ -2027,7 +2027,7 @@ void __fastcall TSecureShell::HandleNetworkEvents(SOCKET Socket, WSANETWORKEVENT #pragma option push -w-prc LPARAM SelectEvent = WSAMAKESELECTREPLY(EventTypes[Event].Mask, Err); #pragma option pop - select_result((WPARAM)Socket, SelectEvent); + select_result(static_cast(Socket), SelectEvent); CheckConnection(); } } diff --git a/source/core/Security.cpp b/source/core/Security.cpp index af3b1f822..289cbb31f 100644 --- a/source/core/Security.cpp +++ b/source/core/Security.cpp @@ -11,7 +11,7 @@ static RawByteString PWALG_SIMPLE_STRING("0123456789ABCDEF"); //--------------------------------------------------------------------------- RawByteString SimpleEncryptChar(unsigned char Ch) { - Ch = (unsigned char)((~Ch) ^ PWALG_SIMPLE_MAGIC); + Ch = static_cast((~Ch) ^ PWALG_SIMPLE_MAGIC); RawByteString Result(".."); Result[1] = PWALG_SIMPLE_STRING[((Ch & 0xF0) >> 4) + 1]; Result[2] = PWALG_SIMPLE_STRING[((Ch & 0x0F) >> 0) + 1]; @@ -22,9 +22,9 @@ unsigned char SimpleDecryptNextChar(RawByteString &Str) { if (Str.Length() > 0) { - unsigned char Result = (unsigned char) + unsigned char Result = static_cast( ~((((PWALG_SIMPLE_STRING.Pos(Str.c_str()[0])-1) << 4) + - ((PWALG_SIMPLE_STRING.Pos(Str.c_str()[1])-1) << 0)) ^ PWALG_SIMPLE_MAGIC); + ((PWALG_SIMPLE_STRING.Pos(Str.c_str()[1])-1) << 0)) ^ PWALG_SIMPLE_MAGIC)); Str.Delete(1, 2); return Result; } @@ -40,31 +40,31 @@ RawByteString EncryptPassword(UnicodeString UnicodePassword, UnicodeString Unico if (!RandSeed) Randomize(); Password = Key + Password; - Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_FLAG); // Flag + Result += SimpleEncryptChar(static_cast(PWALG_SIMPLE_FLAG)); // Flag int Len = Password.Length(); if (Len > std::numeric_limits::max()) { - Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_INTERNAL2); - Result += SimpleEncryptChar((unsigned char)(Len >> 8)); - Result += SimpleEncryptChar((unsigned char)(Len & 0xFF)); + Result += SimpleEncryptChar(static_cast(PWALG_SIMPLE_INTERNAL2)); + Result += SimpleEncryptChar(static_cast(Len >> 8)); + Result += SimpleEncryptChar(static_cast(Len & 0xFF)); } else { - Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_INTERNAL); - Result += SimpleEncryptChar((unsigned char)Len); + Result += SimpleEncryptChar(static_cast(PWALG_SIMPLE_INTERNAL)); + Result += SimpleEncryptChar(static_cast(Len)); } int DataLen = (Result.Length() / 2) + 1 + // Shift Password.Length(); int Shift = (DataLen < PWALG_SIMPLE_MAXLEN) ? random(PWALG_SIMPLE_MAXLEN - DataLen) : 0; - Result += SimpleEncryptChar((unsigned char)Shift); + Result += SimpleEncryptChar(static_cast(Shift)); for (int Index = 0; Index < Shift; Index++) - Result += SimpleEncryptChar((unsigned char)random(256)); + Result += SimpleEncryptChar(static_cast(random(256))); for (int Index = 0; Index < Password.Length(); Index++) Result += SimpleEncryptChar(Password.c_str()[Index]); while (Result.Length() < PWALG_SIMPLE_MAXLEN * 2) - Result += SimpleEncryptChar((unsigned char)random(256)); + Result += SimpleEncryptChar(static_cast(random(256))); return Result; } //--------------------------------------------------------------------------- @@ -96,10 +96,10 @@ UnicodeString DecryptPassword(RawByteString Password, UnicodeString UnicodeKey, UTF8String Result; if (Length >= 0) { - Password.Delete(1, ((Integer)SimpleDecryptNextChar(Password))*2); + Password.Delete(1, static_cast(SimpleDecryptNextChar(Password))*2); for (int Index = 0; Index < Length; Index++) { - Result += (char)SimpleDecryptNextChar(Password); + Result += static_cast(SimpleDecryptNextChar(Password)); } if (Flag == PWALG_SIMPLE_FLAG) { @@ -120,8 +120,8 @@ UnicodeString DecryptPassword(RawByteString Password, UnicodeString UnicodeKey, RawByteString SetExternalEncryptedPassword(RawByteString Password) { RawByteString Result; - Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_FLAG); - Result += SimpleEncryptChar((unsigned char)PWALG_SIMPLE_EXTERNAL); + Result += SimpleEncryptChar(static_cast(PWALG_SIMPLE_FLAG)); + Result += SimpleEncryptChar(static_cast(PWALG_SIMPLE_EXTERNAL)); Result += UTF8String(BytesToHex(reinterpret_cast(Password.c_str()), Password.Length())); return Result; } diff --git a/source/core/SessionData.cpp b/source/core/SessionData.cpp index 5105a26c5..fcd354c95 100644 --- a/source/core/SessionData.cpp +++ b/source/core/SessionData.cpp @@ -232,7 +232,7 @@ void __fastcall TSessionData::DefaultSettings() for (unsigned int Index = 0; Index < std::size(FBugs); Index++) { - Bug[(TSshBug)Index] = asAuto; + Bug[static_cast(Index)] = asAuto; } Special = false; @@ -301,7 +301,7 @@ void __fastcall TSessionData::DefaultSettings() for (unsigned int Index = 0; Index < std::size(FSFTPBugs); Index++) { - SFTPBug[(TSftpBug)Index] = asAuto; + SFTPBug[static_cast(Index)] = asAuto; } Tunnel = false; @@ -481,7 +481,7 @@ void __fastcall TSessionData::NonPersistent() \ for (unsigned int Index = 0; Index < std::size(FBugs); Index++) \ { \ - PROPERTY(Bug[(TSshBug)Index]); \ + PROPERTY(Bug[static_cast(Index)]); \ } \ \ PROPERTY(SftpServer); \ @@ -495,7 +495,7 @@ void __fastcall TSessionData::NonPersistent() \ for (unsigned int Index = 0; Index < std::size(FSFTPBugs); Index++) \ { \ - PROPERTY(SFTPBug[(TSftpBug)Index]); \ + PROPERTY(SFTPBug[static_cast(Index)]); \ } \ \ PROPERTY(Tunnel); \ @@ -549,7 +549,7 @@ void __fastcall TSessionData::Assign(TPersistent * Source) { if (Source && Source->InheritsFrom(__classid(TSessionData))) { - TSessionData * SourceData = (TSessionData *)Source; + TSessionData * SourceData = static_cast(Source); // Master password prompt shows implicitly here, when cloning the session data for a new terminal CopyData(SourceData); FSource = SourceData->FSource; @@ -764,7 +764,7 @@ void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyI RekeyData = Storage->ReadString(L"RekeyBytes", RekeyData); RekeyTime = Storage->ReadInteger(L"RekeyTime", RekeyTime); - FSProtocol = (TFSProtocol)Storage->ReadInteger(L"FSProtocol", FSProtocol); + FSProtocol = static_cast(Storage->ReadInteger(L"FSProtocol", FSProtocol)); LocalDirectory = Storage->ReadString(L"LocalDirectory", LocalDirectory); OtherLocalDirectory = Storage->ReadString(L"OtherLocalDirectory", OtherLocalDirectory); RemoteDirectory = Storage->ReadString(L"RemoteDirectory", RemoteDirectory); @@ -776,7 +776,7 @@ void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyI ResolveSymlinks = Storage->ReadBool(L"ResolveSymlinks", ResolveSymlinks); FollowDirectorySymlinks = Storage->ReadBool(L"FollowDirectorySymlinks", FollowDirectorySymlinks); - DSTMode = (TDSTMode)Storage->ReadInteger(L"ConsiderDST", DSTMode); + DSTMode = static_cast(Storage->ReadInteger(L"ConsiderDST", DSTMode)); Special = Storage->ReadBool(L"Special", Special); if (!Unsafe) { @@ -805,7 +805,7 @@ void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyI ExitCode1IsError = Storage->ReadBool(L"ExitCode1IsError", ExitCode1IsError); LookupUserGroups = Storage->ReadEnum(L"LookupUserGroups2", LookupUserGroups, AutoSwitchMapping); - EOLType = (TEOLType)Storage->ReadInteger(L"EOLType", EOLType); + EOLType = static_cast(Storage->ReadInteger(L"EOLType", EOLType)); TrimVMSVersions = Storage->ReadBool(L"TrimVMSVersions", TrimVMSVersions); VMSAllRevisions = Storage->ReadBool(L"VMSAllRevisions", VMSAllRevisions); NotUtf = Storage->ReadEnum(L"Utf", Storage->ReadEnum(L"SFTPUtfBug", NotUtf), AutoSwitchReversedMapping); @@ -816,7 +816,7 @@ void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyI S3RoleArn = Storage->ReadString(L"S3RoleArn", S3RoleArn); S3RoleSessionName = Storage->ReadString(L"S3RoleSessionName", S3RoleSessionName); S3Profile = Storage->ReadString(L"S3Profile", S3Profile); - S3UrlStyle = (TS3UrlStyle)Storage->ReadInteger(L"S3UrlStyle", S3UrlStyle); + S3UrlStyle = static_cast(Storage->ReadInteger(L"S3UrlStyle", S3UrlStyle)); S3MaxKeys = Storage->ReadEnum(L"S3MaxKeys", S3MaxKeys, AutoSwitchMapping); S3CredentialsEnv = Storage->ReadBool(L"S3CredentialsEnv", S3CredentialsEnv); S3RequesterPays = Storage->ReadBool(L"S3RequesterPays", S3RequesterPays); @@ -2268,7 +2268,7 @@ bool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options, // this can be optimized as the list is sorted for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++) { - TSessionData * AData = (TSessionData *)StoredSessions->Items[Index]; + TSessionData * AData = static_cast(StoredSessions->Items[Index]); if (!AData->IsWorkspace) { bool Match = false; @@ -3071,7 +3071,7 @@ void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultLis if (!AlgoStr.CompareIC(Names[Algo]) && !Used[Algo] && DebugAlwaysTrue(Index < Count)) { - NewList[Index] = (AlgoT)Algo; + NewList[Index] = static_cast(Algo); Used[Algo] = true; Index++; break; @@ -3378,7 +3378,7 @@ void __fastcall TSessionData::SetPingIntervalDT(TDateTime value) unsigned short hour, min, sec, msec; value.DecodeTime(&hour, &min, &sec, &msec); - PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec; + PingInterval = (static_cast(hour))*SecsPerHour + (static_cast(min))*SecsPerMin + sec; } //--------------------------------------------------------------------------- TDateTime __fastcall TSessionData::GetPingIntervalDT() @@ -4830,7 +4830,7 @@ void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage, } else { - SessionData = (TSessionData*)FindByName(SessionName); + SessionData = static_cast(FindByName(SessionName)); } } @@ -4922,7 +4922,7 @@ void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage, DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults); for (int Index = 0; Index < CountIncludingHidden; Index++) { - TSessionData * SessionData = (TSessionData *)Items[Index]; + TSessionData * SessionData = static_cast(Items[Index]); try { DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults); @@ -4990,7 +4990,7 @@ void __fastcall TStoredSessionList::Saved() FDefaultSettings->Modified = false; for (int Index = 0; Index < CountIncludingHidden; Index++) { - ((TSessionData *)Items[Index])->Modified = false; + static_cast(Items[Index])->Modified = false; } } //--------------------------------------------------------------------- @@ -5442,7 +5442,7 @@ int __fastcall TStoredSessionList::IndexOf(TSessionData * Data) TSessionData * __fastcall TStoredSessionList::NewSession( UnicodeString SessionName, TSessionData * Session) { - TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName); + TSessionData * DuplicateSession = static_cast(FindByName(SessionName)); if (!DuplicateSession) { DuplicateSession = new TSessionData(L""); diff --git a/source/core/SessionData.h b/source/core/SessionData.h index 88e9efd8b..a9bd77f1e 100644 --- a/source/core/SessionData.h +++ b/source/core/SessionData.h @@ -770,7 +770,7 @@ public: bool Import(TStoredSessionList * From, bool OnlySelected, TList * Imported); void __fastcall RecryptPasswords(TStrings * RecryptPasswordErrors); TSessionData * __fastcall AtSession(int Index) - { return (TSessionData*)AtObject(Index); } + { return static_cast(AtObject(Index)); } void __fastcall SelectSessionsToImport(TStoredSessionList * Dest, bool SSHOnly); void __fastcall Cleanup(); void __fastcall UpdateStaticUsage(); diff --git a/source/core/SessionInfo.cpp b/source/core/SessionInfo.cpp index 80389f671..9c55b5789 100644 --- a/source/core/SessionInfo.cpp +++ b/source/core/SessionInfo.cpp @@ -49,7 +49,7 @@ UnicodeString __fastcall DoXmlEscape(UnicodeString Str, bool NewLine) case L'\x1D': case L'\x1E': case L'\x1F': - Repl = L"#x" + ByteToHex((unsigned char)Ch) + L";"; + Repl = L"#x" + ByteToHex(static_cast(Ch)) + L";"; break; case L'\xFFFE': @@ -845,7 +845,7 @@ void __fastcall TSessionLog::DoAddToSelf(TLogLineType Type, const UnicodeString } int Writing = UtfLine.Length(); CheckSize(Writing); - FCurrentFileSize += fwrite(UtfLine.c_str(), 1, Writing, (FILE *)FFile); + FCurrentFileSize += fwrite(UtfLine.c_str(), 1, Writing, static_cast(FFile)); } } } @@ -992,7 +992,7 @@ void __fastcall TSessionLog::CloseLogFile() { if (FFile != NULL) { - fclose((FILE *)FFile); + fclose(static_cast(FFile)); FFile = NULL; } FCurrentLogFileName = L""; @@ -1310,7 +1310,7 @@ void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data) UnicodeString Bugs; for (int Index = 0; Index < BUG_COUNT; Index++) { - AddToList(Bugs, EnumName(Data->Bug[(TSshBug)Index], AutoSwitchNames), L","); + AddToList(Bugs, EnumName(Data->Bug[static_cast(Index)], AutoSwitchNames), L","); } ADF(L"SSH Bugs: %s", (Bugs)); ADF(L"Simple channel: %s", (BooleanToEngStr(Data->SshSimple))); @@ -1333,7 +1333,7 @@ void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data) UnicodeString Bugs; for (int Index = 0; Index < SFTP_BUG_COUNT; Index++) { - AddToList(Bugs, EnumName(Data->SFTPBug[(TSftpBug)Index], AutoSwitchNames), L","); + AddToList(Bugs, EnumName(Data->SFTPBug[static_cast(Index)], AutoSwitchNames), L","); } ADF(L"SFTP Bugs: %s", (Bugs)); ADF(L"SFTP Server: %s", ((Data->SftpServer.IsEmpty()? UnicodeString(L"default") : Data->SftpServer))); @@ -1551,7 +1551,7 @@ void __fastcall TActionLog::Add(const UnicodeString & Line) { UTF8String UtfLine = UTF8String(Line); size_t Written = - fwrite(UtfLine.c_str(), 1, UtfLine.Length(), (FILE *)FFile); + fwrite(UtfLine.c_str(), 1, UtfLine.Length(), static_cast(FFile)); if (Written != static_cast(UtfLine.Length())) { throw ECRTExtException(L""); @@ -1559,7 +1559,7 @@ void __fastcall TActionLog::Add(const UnicodeString & Line) #ifdef _DEBUG #endif Written = - fwrite("\n", 1, 1, (FILE *)FFile); + fwrite("\n", 1, 1, static_cast(FFile)); if (Written != 1) { throw ECRTExtException(L""); @@ -1673,7 +1673,7 @@ void __fastcall TActionLog::CloseLogFile() { if (FFile != NULL) { - fclose((FILE *)FFile); + fclose(static_cast(FFile)); FFile = NULL; } FCurrentLogFileName = L""; diff --git a/source/core/SftpFileSystem.cpp b/source/core/SftpFileSystem.cpp index b05563d13..4b41028e1 100644 --- a/source/core/SftpFileSystem.cpp +++ b/source/core/SftpFileSystem.cpp @@ -161,17 +161,18 @@ const int asOpUnsupported = 1 << SSH_FX_OP_UNSUPPORTED; const int asNoSuchFile = 1 << SSH_FX_NO_SUCH_FILE; const int asAll = 0xFFFF; //--------------------------------------------------------------------------- +#define GET_32BITC(cp, i) static_cast(static_cast((cp)[i])) #define GET_32BIT(cp) \ - (((unsigned long)(unsigned char)(cp)[0] << 24) | \ - ((unsigned long)(unsigned char)(cp)[1] << 16) | \ - ((unsigned long)(unsigned char)(cp)[2] << 8) | \ - ((unsigned long)(unsigned char)(cp)[3])) + ((GET_32BITC(cp, 0) << 24) | \ + (GET_32BITC(cp, 1) << 16) | \ + (GET_32BITC(cp, 2) << 8) | \ + (GET_32BITC(cp, 3))) #define PUT_32BIT(cp, value) { \ - (cp)[0] = (unsigned char)((value) >> 24); \ - (cp)[1] = (unsigned char)((value) >> 16); \ - (cp)[2] = (unsigned char)((value) >> 8); \ - (cp)[3] = (unsigned char)(value); } + (cp)[0] = static_cast((value) >> 24); \ + (cp)[1] = static_cast((value) >> 16); \ + (cp)[2] = static_cast((value) >> 8); \ + (cp)[3] = static_cast(value); } //--------------------------------------------------------------------------- #define SFTP_PACKET_ALLOC_DELTA 256 //--------------------------------------------------------------------------- @@ -306,8 +307,8 @@ public: void AddInt64(__int64 Value) { - AddCardinal((unsigned long)(Value >> 32)); - AddCardinal((unsigned long)(Value & 0xFFFFFFFF)); + AddCardinal(static_cast(Value >> 32)); + AddCardinal(static_cast(Value & 0xFFFFFFFF)); } void AddData(const void * Data, int ALength) @@ -466,19 +467,19 @@ public: { if (Properties->Valid.Contains(vpGroup)) { - Valid = (TValid)(Valid | valGroup); + Valid = static_cast(Valid | valGroup); Group = Properties->Group; } if (Properties->Valid.Contains(vpOwner)) { - Valid = (TValid)(Valid | valOwner); + Valid = static_cast(Valid | valOwner); Owner = Properties->Owner; } if (Properties->Valid.Contains(vpRights)) { - Valid = (TValid)(Valid | valRights); + Valid = static_cast(Valid | valRights); TRights Rights = TRights(BaseRights).Combine(Properties->Rights); if (IsDirectory && Properties->AddXToDirectories) { @@ -494,13 +495,13 @@ public: if (Properties->Valid.Contains(vpLastAccess)) { - Valid = (TValid)(Valid | valATime); + Valid = static_cast(Valid | valATime); ATime = Properties->LastAccess; } if (Properties->Valid.Contains(vpModification)) { - Valid = (TValid)(Valid | valMTime); + Valid = static_cast(Valid | valMTime); MTime = Properties->Modification; } } @@ -647,7 +648,7 @@ public: // SSH-2.0-cryptlib returns file type 0 in response to SSH_FXP_LSTAT, // handle this undefined value as "unknown" static const wchar_t * Types = L"U-DLSUOCBF"; - if (FXType > (unsigned char)wcslen(Types)) + if (FXType > static_cast(wcslen(Types))) { throw Exception(FMTLOAD(SFTP_UNKNOWN_FILE_TYPE, (int(FXType)))); } @@ -792,7 +793,7 @@ public: wchar_t Type = FILETYPE_DEFAULT; if (FLAGSET(Flags, SSH_FILEXFER_ATTR_PERMISSIONS)) { - File->Rights->Number = (unsigned short)(Permissions & TRights::rfAllSpecials); + File->Rights->Number = static_cast(Permissions & TRights::rfAllSpecials); if (FLAGSET(Permissions, TRights::rfDirectory)) { Type = FILETYPE_DIRECTORY; @@ -963,7 +964,7 @@ private: { if (FMessageNumber != SFTPNoMessageNumber) { - return (unsigned char)(FMessageNumber & 0xFF); + return static_cast(FMessageNumber & 0xFF); } else { @@ -1539,7 +1540,7 @@ public: FFileName = AFileName; if (OnTransferIn == NULL) { - FStream = new TSafeHandleStream((THandle)AFile); + FStream = new TSafeHandleStream(reinterpret_cast(AFile)); } OperationProgress = AOperationProgress; FHandle = AHandle; @@ -2348,7 +2349,7 @@ void TSFTPFileSystem::LogPacket(const TSFTPPacket * Packet, TLogLineType Type) FTerminal->LogEvent(FORMAT(L"Skipped %s packets", (S))); } FTerminal->Log->Add( - Type, FORMAT(L"Type: %s, Size: %d, Number: %d", (Packet->TypeName, (int)Packet->Length, (int)Packet->MessageNumber))); + Type, FORMAT(L"Type: %s, Size: %d, Number: %d", (Packet->TypeName, static_cast(Packet->Length), static_cast(Packet->MessageNumber)))); if (FTerminal->Configuration->ActualLogProtocol >= 2) { FTerminal->Log->Add(Type, Packet->Dump()); @@ -2488,7 +2489,7 @@ unsigned long __fastcall TSFTPFileSystem::GotStatusPacket( (FTerminal->Configuration->ActualLogProtocol >= 0)) { FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d, Message: %d, Server: %s, Language: %s ", - (int(Code), (int)Packet->MessageNumber, ServerMessage, LanguageTag))); + (int(Code), static_cast(Packet->MessageNumber), ServerMessage, LanguageTag))); } if (!LanguageTag.IsEmpty()) { @@ -2521,7 +2522,7 @@ unsigned long __fastcall TSFTPFileSystem::GotStatusPacket( { if (FTerminal->Configuration->ActualLogProtocol >= 0) { - FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d", ((int)Code))); + FTerminal->Log->Add(llOutput, FORMAT(L"Status code: %d", (static_cast(Code)))); } } return Code; @@ -2534,7 +2535,7 @@ void __fastcall TSFTPFileSystem::RemoveReservation(int Reservation) { FPacketNumbers.PutElement(FPacketNumbers.GetElement(Index), Index-1); } - TSFTPPacket * Packet = (TSFTPPacket *)FPacketReservations->Items[Reservation]; + TSFTPPacket * Packet = static_cast(FPacketReservations->Items[Reservation]); if (Packet) { DebugAssert(Packet->ReservedBy == this); @@ -2632,16 +2633,16 @@ int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet, } if (Reservation < 0 || - Packet->MessageNumber != (unsigned int)FPacketNumbers.GetElement(Reservation)) + Packet->MessageNumber != static_cast(FPacketNumbers.GetElement(Reservation))) { TSFTPPacket * ReservedPacket; unsigned int MessageNumber; for (int Index = 0; Index < FPacketReservations->Count; Index++) { - MessageNumber = (unsigned int)FPacketNumbers.GetElement(Index); + MessageNumber = static_cast(FPacketNumbers.GetElement(Index)); if (MessageNumber == Packet->MessageNumber) { - ReservedPacket = (TSFTPPacket *)FPacketReservations->Items[Index]; + ReservedPacket = static_cast(FPacketReservations->Items[Index]); IsReserved = true; if (ReservedPacket) { @@ -2679,7 +2680,7 @@ int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet, // (and it have not worked anyway until recent fix to UnreserveResponse) if (Reservation >= 0) { - DebugAssert(Packet->MessageNumber == (unsigned int)FPacketNumbers.GetElement(Reservation)); + DebugAssert(Packet->MessageNumber == static_cast(FPacketNumbers.GetElement(Reservation))); RemoveReservation(Reservation); } @@ -2695,7 +2696,7 @@ int __fastcall TSFTPFileSystem::ReceivePacket(TSFTPPacket * Packet, } else if (ExpectedType != Packet->Type) { - FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Packet->Type))); + FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, (static_cast(Packet->Type)))); } } } @@ -2757,7 +2758,7 @@ int __fastcall TSFTPFileSystem::ReceiveResponse( if (MessageNumber != AResponse->MessageNumber) { FTerminal->FatalError(NULL, FMTLOAD(SFTP_MESSAGE_NUMBER, - ((int)AResponse->MessageNumber, (int)MessageNumber))); + (static_cast(AResponse->MessageNumber), static_cast(MessageNumber)))); } } __finally @@ -3199,7 +3200,7 @@ void __fastcall TSFTPFileSystem::DoStartup() { unsigned char Drive = RootsPacket.GetByte(); unsigned char MaybeType = RootsPacket.GetByte(); - FTerminal->LogEvent(FORMAT(L" %s: (type %d)", (static_cast(Drive), (int)MaybeType))); + FTerminal->LogEvent(FORMAT(L" %s: (type %d)", (static_cast(Drive), static_cast(MaybeType)))); FFixedPaths->Add(FORMAT(L"%s:", (static_cast(Drive)))); } } @@ -3652,7 +3653,7 @@ void __fastcall TSFTPFileSystem::ReadDirectory(TRemoteFileList * FileList) } else { - FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, ((int)Response.Type))); + FTerminal->FatalError(NULL, FMTLOAD(SFTP_INVALID_TYPE, (static_cast(Response.Type)))); } } while (!isEOF); @@ -4111,7 +4112,7 @@ void __fastcall TSFTPFileSystem::ChangeFileProperties(const UnicodeString FileNa try { FTerminal->ProcessDirectory(FileName, FTerminal->ChangeFileProperties, - (void*)AProperties); + const_cast(AProperties)); } catch(...) { @@ -4851,7 +4852,7 @@ void __fastcall TSFTPFileSystem::Source( FTerminal->LogEvent(L"Resuming file transfer (append style)."); ResumeOffset = OpenParams.DestFileSize; } - FileSeek((THandle)Handle.Handle, ResumeOffset, soBeginning); + FileSeek(reinterpret_cast(Handle.Handle), ResumeOffset, soBeginning); OperationProgress->AddResumed(ResumeOffset); } @@ -5109,7 +5110,7 @@ RawByteString __fastcall TSFTPFileSystem::SFTPOpenRemoteFile( //--------------------------------------------------------------------------- int __fastcall TSFTPFileSystem::SFTPOpenRemote(void * AOpenParams, void * /*Param2*/) { - TOpenRemoteFileParams * OpenParams = (TOpenRemoteFileParams *)AOpenParams; + TOpenRemoteFileParams * OpenParams = static_cast(AOpenParams); DebugAssert(OpenParams); TFileOperationProgressType * OperationProgress = OpenParams->OperationProgress; @@ -5480,7 +5481,7 @@ void __fastcall TSFTPFileSystem::Sink( else { FTerminal->LogEvent(L"Resuming file transfer."); - FileSeek((THandle)LocalHandle, ResumeOffset, soBeginning); + FileSeek(reinterpret_cast(LocalHandle), ResumeOffset, soBeginning); OperationProgress->AddResumed(ResumeOffset); } } @@ -5576,7 +5577,7 @@ void __fastcall TSFTPFileSystem::Sink( FTerminal->OpenLocalFile(DestFullName, GENERIC_WRITE, NULL, &LocalHandle, NULL, NULL, NULL, NULL); } ResumeAllowed = false; - FileSeek((THandle)LocalHandle, DestFileSize, soBeginning); + FileSeek(reinterpret_cast(LocalHandle), DestFileSize, soBeginning); if (OverwriteMode == omAppend) { FTerminal->LogEvent(L"Appending to file."); @@ -5607,7 +5608,7 @@ void __fastcall TSFTPFileSystem::Sink( DeleteLocalFile = true; - FileStream = new TSafeHandleStream((THandle)LocalHandle); + FileStream = new TSafeHandleStream(reinterpret_cast(LocalHandle)); } // at end of this block queue is discarded diff --git a/source/core/Terminal.cpp b/source/core/Terminal.cpp index c91ce0cee..8df3a5458 100644 --- a/source/core/Terminal.cpp +++ b/source/core/Terminal.cpp @@ -19,6 +19,7 @@ #include #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include #pragma clang diagnostic pop @@ -1961,8 +1962,8 @@ bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind, TStrings * Results = new TStringList; try { - Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho))); - Results->AddObject(Result, (TObject *)MaxLen); + Prompts->AddObject(Prompt, reinterpret_cast(FLAGMASK(Echo, pupEcho))); + Results->AddObject(Result, reinterpret_cast(MaxLen)); AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results); @@ -2033,7 +2034,7 @@ bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kin { if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword) { - Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember); + Prompts->Objects[0] = reinterpret_cast(reinterpret_cast(Prompts->Objects[0]) | pupRemember); } if (OnPromptUser != NULL) @@ -2320,7 +2321,7 @@ void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo) { for (int Index = 0; Index < fcCount; Index++) { - FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index]; + FileSystemInfo.IsCapable[Index] = IsCapable[static_cast(Index)]; } } //--------------------------------------------------------------------------- @@ -2353,7 +2354,7 @@ void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd) bool ChangesDirectory = false; bool ModifiesFiles = false; - switch ((TFSCommand)Cmd) { + switch (static_cast(Cmd)) { case fsChangeDirectory: case fsHomeDirectory: ChangesDirectory = true; @@ -2976,7 +2977,7 @@ void __fastcall TTerminal::SetExceptionOnFail(bool value) //--------------------------------------------------------------------------- bool __fastcall TTerminal::GetExceptionOnFail() const { - return (bool)(FExceptionOnFail > 0); + return (FExceptionOnFail > 0); } //--------------------------------------------------------------------------- void __fastcall TTerminal::FatalAbort() @@ -4176,7 +4177,7 @@ bool __fastcall TTerminal::ProcessFiles(TStrings * FileList, else { // not used anymore - TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile; + TProcessFileEventEx ProcessFileEx = reinterpret_cast(ProcessFile); ProcessFileEx(FileName, File, Param, Index); } Success = true; @@ -4364,7 +4365,7 @@ void __fastcall TTerminal::DeleteFile(UnicodeString FileName, FileName = File->FileName; } StartOperationWithFile(FileName, foDelete); - int Params = (AParams != NULL) ? *((int*)AParams) : 0; + int Params = (AParams != NULL) ? *static_cast(AParams) : 0; bool Recycle = FLAGCLEAR(Params, dfForceDelete) && (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) && @@ -4432,7 +4433,7 @@ void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName, } else { - OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative), Deleted); + OnDeleteLocalFile(FileName, FLAGSET(*static_cast(Params), dfAlternative), Deleted); } AppLogFmt(L"Deleted local file \"%s\"", (FileName)); if (DebugAlwaysTrue((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))) @@ -4449,7 +4450,7 @@ bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params) void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName, const TRemoteFile * File, void * AParams) { - TCustomCommandParams * Params = ((TCustomCommandParams *)AParams); + TCustomCommandParams * Params = static_cast(AParams); if (FileName.IsEmpty() && File) { FileName = File->FileName; @@ -4574,7 +4575,7 @@ bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command) void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName, const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties) { - TRemoteProperties * RProperties = (TRemoteProperties *)Properties; + TRemoteProperties * RProperties = static_cast(Properties); DebugAssert(RProperties && !RProperties->Valid.Empty()); if (FileName.IsEmpty() && File) @@ -4642,7 +4643,7 @@ void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList, TValueRestorer UseBusyCursorRestorer(FUseBusyCursor, false); AnnounceFileListOperation(); - ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties); + ProcessFiles(FileList, foSetProperties, ChangeFileProperties, const_cast(Properties)); } //--------------------------------------------------------------------------- bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList) diff --git a/source/core/WebDAVFileSystem.cpp b/source/core/WebDAVFileSystem.cpp index d7b4c80d7..e9ae74886 100644 --- a/source/core/WebDAVFileSystem.cpp +++ b/source/core/WebDAVFileSystem.cpp @@ -7,6 +7,8 @@ #include #define NE_LFS +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include #include @@ -18,6 +20,7 @@ #include #include #include +#pragma clang diagnostic pop #include "WebDAVFileSystem.h" @@ -1007,8 +1010,8 @@ void __fastcall TWebDAVFileSystem::ParsePropResultSet(TRemoteFile * File, if (Month >= 1) { TDateTime Modification = - EncodeDateVerbose((unsigned short)Year, (unsigned short)Month, (unsigned short)Day) + - EncodeTimeVerbose((unsigned short)Hour, (unsigned short)Min, (unsigned short)Sec, 0); + EncodeDateVerbose(static_cast(Year), static_cast(Month), static_cast(Day)) + + EncodeTimeVerbose(static_cast(Hour), static_cast(Min), static_cast(Sec), 0); File->Modification = ConvertTimestampFromUTC(Modification); // Should use mfYMDHM or mfMDY when appropriate according to Filled File->ModificationFmt = mfFull; @@ -1444,7 +1447,7 @@ void __fastcall TWebDAVFileSystem::Source( { SetFilePointer(Handle.Handle, 0, NULL, FILE_BEGIN); - FD = _open_osfhandle((intptr_t)Handle.Handle, O_BINARY); + FD = _open_osfhandle(reinterpret_cast(Handle.Handle), O_BINARY); if (FD < 0) // can happen only if there are no free slots in handle-FD table { throw ESkipFile(); @@ -1843,7 +1846,7 @@ void __fastcall TWebDAVFileSystem::Sink( int FD = -1; try { - FD = _open_osfhandle((intptr_t)LocalHandle, O_BINARY); + FD = _open_osfhandle(reinterpret_cast(LocalHandle), O_BINARY); if (FD < 0) { throw ESkipFile(); diff --git a/source/core/WebDAVFileSystem.h b/source/core/WebDAVFileSystem.h index aa8f8a4ee..35aa294b5 100644 --- a/source/core/WebDAVFileSystem.h +++ b/source/core/WebDAVFileSystem.h @@ -3,10 +3,13 @@ #define WebDavFileSystemH //------------------------------------------------------------------------------ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include #include #include +#pragma clang diagnostic pop #include //------------------------------------------------------------------------------ struct TNeonCertificateData; diff --git a/source/filezilla/ApiLog.cpp b/source/filezilla/ApiLog.cpp index e0a042ccc..8b55ab68c 100644 --- a/source/filezilla/ApiLog.cpp +++ b/source/filezilla/ApiLog.cpp @@ -70,7 +70,7 @@ void CApiLog::SendLogMessage(int nMessageType, LPCTSTR pMsg) const pStatus->post = TRUE; pStatus->status = pMsg; pStatus->type = nMessageType; - if (!FIntern->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_STATUS, 0), (LPARAM)pStatus)) + if (!FIntern->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_STATUS, 0), reinterpret_cast(pStatus))) delete pStatus; } diff --git a/source/filezilla/AsyncProxySocketLayer.cpp b/source/filezilla/AsyncProxySocketLayer.cpp index 56cfa4521..b436147fa 100644 --- a/source/filezilla/AsyncProxySocketLayer.cpp +++ b/source/filezilla/AsyncProxySocketLayer.cpp @@ -137,7 +137,7 @@ void CAsyncProxySocketLayer::OnReceive(int nErrorCode) int SockAddrLen=sizeof(SockAddr); if (GetPeerName(&SockAddr, &SockAddrLen )) { - ip=((LPSOCKADDR_IN)&SockAddr)->sin_addr.S_un.S_addr; + ip=(reinterpret_cast(&SockAddr))->sin_addr.S_un.S_addr; } else { @@ -149,7 +149,7 @@ void CAsyncProxySocketLayer::OnReceive(int nErrorCode) t_ListenSocketCreatedStruct data; data.ip=ip; data.nPort=port; - DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, PROXYSTATUS_LISTENSOCKETCREATED, (int)&data); + DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, PROXYSTATUS_LISTENSOCKETCREATED, reinterpret_cast(&data)); } ClearBuffer(); } @@ -236,7 +236,7 @@ void CAsyncProxySocketLayer::OnReceive(int nErrorCode) DebugAssert(strlen(lpszAsciiUser)<=255); DebugAssert(strlen(lpszAsciiPass)<=255); unsigned char *buffer = new unsigned char[3 + (lpszAsciiUser?strlen(lpszAsciiUser):0) + (lpszAsciiPass?strlen(lpszAsciiPass):0) + 1]; - sprintf((char *)buffer, " %s %s", lpszAsciiUser?lpszAsciiUser:"", lpszAsciiPass?lpszAsciiPass:""); + sprintf(reinterpret_cast(buffer), " %s %s", lpszAsciiUser?lpszAsciiUser:"", lpszAsciiPass?lpszAsciiPass:""); buffer[0]=1; buffer[1]=static_cast(strlen(lpszAsciiUser)); buffer[2+strlen(lpszAsciiUser)]=static_cast(strlen(lpszAsciiPass)); @@ -416,7 +416,7 @@ void CAsyncProxySocketLayer::OnReceive(int nErrorCode) t_ListenSocketCreatedStruct data; data.ip=ip; data.nPort=port; - DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, PROXYSTATUS_LISTENSOCKETCREATED, (int)&data); + DoLayerCallback(LAYERCALLBACK_LAYERSPECIFIC, PROXYSTATUS_LISTENSOCKETCREATED, reinterpret_cast(&data)); } ClearBuffer(); } @@ -571,7 +571,7 @@ BOOL CAsyncProxySocketLayer::Connect( LPCTSTR lpszHostAddress, UINT nHostPort ) return FALSE; } } - m_nProxyPeerPort = htons((u_short)nHostPort); + m_nProxyPeerPort = htons(static_cast(nHostPort)); m_nProxyPeerIp = 0; delete [] m_pProxyPeerHost; m_pProxyPeerHost = new char[_tcslen(lpszHostAddress)+1]; @@ -592,7 +592,7 @@ BOOL CAsyncProxySocketLayer::Connect( LPCTSTR lpszHostAddress, UINT nHostPort ) LPHOSTENT lphost; lphost = gethostbyname(lpszAscii); if (lphost != NULL) - sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr; + sockAddr.sin_addr.s_addr = reinterpret_cast(lphost->h_addr)->s_addr; else { //Can't resolve hostname @@ -602,8 +602,8 @@ BOOL CAsyncProxySocketLayer::Connect( LPCTSTR lpszHostAddress, UINT nHostPort ) } } - sockAddr.sin_port = htons((u_short)nHostPort); - BOOL res=CAsyncProxySocketLayer::Connect((SOCKADDR*)&sockAddr, sizeof(sockAddr)); + sockAddr.sin_port = htons(static_cast(nHostPort)); + BOOL res=CAsyncProxySocketLayer::Connect(reinterpret_cast(&sockAddr), sizeof(sockAddr)); if (res || WSAGetLastError()==WSAEWOULDBLOCK) { delete [] m_pProxyPeerHost; @@ -836,7 +836,7 @@ BOOL CAsyncProxySocketLayer::Listen( int nConnectionBacklog) } } m_nProxyPeerPort=0; - m_nProxyPeerIp=(unsigned int)nConnectionBacklog; + m_nProxyPeerIp=static_cast(nConnectionBacklog); m_nProxyOpID=PROXYOP_LISTEN; return TRUE; @@ -902,7 +902,7 @@ BOOL CAsyncProxySocketLayer::GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrL BOOL res=GetPeerNameNext(lpSockAddr,lpSockAddrLen); if (res) { - LPSOCKADDR_IN addr=(LPSOCKADDR_IN)lpSockAddr; + LPSOCKADDR_IN addr=reinterpret_cast(lpSockAddr); addr->sin_port=m_nProxyPeerPort; addr->sin_addr.S_un.S_addr=m_nProxyPeerIp; } diff --git a/source/filezilla/AsyncSocketEx.cpp b/source/filezilla/AsyncSocketEx.cpp index d64c281aa..0e016498f 100644 --- a/source/filezilla/AsyncSocketEx.cpp +++ b/source/filezilla/AsyncSocketEx.cpp @@ -60,7 +60,7 @@ public: m_hWnd=CreateWindow(L"CAsyncSocketEx Helper Window", L"CAsyncSocketEx Helper Window", 0, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), 0); DebugAssert(m_hWnd); - SetWindowLongPtr(m_hWnd, GWL_USERDATA, (LONG)this); + SetWindowLongPtr(m_hWnd, GWL_USERDATA, reinterpret_cast(this)); } virtual ~CAsyncSocketExHelperWindow() @@ -168,7 +168,7 @@ public: continue; CAsyncSocketEx *pSocket = m_pAsyncSocketExWindowData[msg.wParam].m_pSocket; - CAsyncSocketExLayer::t_LayerNotifyMsg *pMsg=(CAsyncSocketExLayer::t_LayerNotifyMsg *)msg.lParam; + CAsyncSocketExLayer::t_LayerNotifyMsg *pMsg=reinterpret_cast(msg.lParam); if (!pMsg || !pSocket || pSocket == pOrigSocket || pSocket->m_SocketData.hSocket != pMsg->hSocket) { delete pMsg; @@ -191,7 +191,7 @@ public: DebugAssert(hWnd); if (!hWnd) return 0; - CAsyncSocketExHelperWindow *pWnd=(CAsyncSocketExHelperWindow *)GetWindowLongPtr(hWnd, GWL_USERDATA); + CAsyncSocketExHelperWindow *pWnd=reinterpret_cast(GetWindowLongPtr(hWnd, GWL_USERDATA)); if (message>=WM_SOCKETEX_NOTIFY) { DebugAssert(pWnd); @@ -397,7 +397,7 @@ public: } CAsyncSocketEx *pSocket=pWnd->m_pAsyncSocketExWindowData[wParam].m_pSocket; - CAsyncSocketExLayer::t_LayerNotifyMsg *pMsg=(CAsyncSocketExLayer::t_LayerNotifyMsg *)lParam; + CAsyncSocketExLayer::t_LayerNotifyMsg *pMsg=reinterpret_cast(lParam); if (!pMsg || !pSocket || pSocket->m_SocketData.hSocket != pMsg->hSocket) { delete pMsg; @@ -526,7 +526,7 @@ public: // Verify parameters DebugAssert(hWnd); - CAsyncSocketExHelperWindow *pWnd = (CAsyncSocketExHelperWindow *)GetWindowLongPtr(hWnd, GWL_USERDATA); + CAsyncSocketExHelperWindow *pWnd = reinterpret_cast(GetWindowLongPtr(hWnd, GWL_USERDATA)); DebugAssert(pWnd); CAsyncSocketEx *pSocket = NULL; @@ -534,7 +534,7 @@ public: { pSocket = pWnd->m_pAsyncSocketExWindowData[i].m_pSocket; if (pSocket && pSocket->m_hAsyncGetHostByNameHandle && - pSocket->m_hAsyncGetHostByNameHandle == (HANDLE)wParam) + pSocket->m_hAsyncGetHostByNameHandle == reinterpret_cast(wParam)) break; } if (!pSocket) @@ -550,11 +550,11 @@ public: SOCKADDR_IN sockAddr; memset(&sockAddr,0,sizeof(sockAddr)); sockAddr.sin_family=AF_INET; - sockAddr.sin_addr.s_addr = ((LPIN_ADDR)((LPHOSTENT)pSocket->m_pAsyncGetHostByNameBuffer)->h_addr)->s_addr; + sockAddr.sin_addr.s_addr = reinterpret_cast(reinterpret_cast(pSocket->m_pAsyncGetHostByNameBuffer)->h_addr)->s_addr; sockAddr.sin_port = htons(static_cast(pSocket->m_nAsyncGetHostByNamePort)); - BOOL res = pSocket->Connect((SOCKADDR*)&sockAddr, sizeof(sockAddr)); + BOOL res = pSocket->Connect(reinterpret_cast(&sockAddr), sizeof(sockAddr)); delete [] pSocket->m_pAsyncGetHostByNameBuffer; pSocket->m_pAsyncGetHostByNameBuffer=0; pSocket->m_hAsyncGetHostByNameHandle=0; @@ -821,9 +821,9 @@ BOOL CAsyncSocketEx::Bind(UINT nSocketPort, LPCTSTR lpszSocketAddress) memset(&sockAddr6, 0, sizeof(sockAddr6)); sockAddr6.sin6_family = AF_INET6 ; sockAddr6.sin6_addr = in6addr_any ; - sockAddr6.sin6_port = htons((u_short)nSocketPort); + sockAddr6.sin6_port = htons(static_cast(nSocketPort)); - return BindToAddr((SOCKADDR*)&sockAddr6, sizeof(sockAddr6)); + return BindToAddr(reinterpret_cast(&sockAddr6), sizeof(sockAddr6)); } else if (!lpszAscii && m_SocketData.nFamily == AF_INET) { @@ -832,9 +832,9 @@ BOOL CAsyncSocketEx::Bind(UINT nSocketPort, LPCTSTR lpszSocketAddress) memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = AF_INET ; sockAddr.sin_addr.s_addr = INADDR_ANY ; - sockAddr.sin_port = htons((u_short)nSocketPort); + sockAddr.sin_port = htons(static_cast(nSocketPort)); - return BindToAddr((SOCKADDR*)&sockAddr, sizeof(sockAddr)); + return BindToAddr(reinterpret_cast(&sockAddr), sizeof(sockAddr)); } else return FALSE ; @@ -1016,7 +1016,7 @@ int CAsyncSocketEx::Receive(void* lpBuf, int nBufLen, int nFlags /*=0*/) if (m_pFirstLayer) return m_pFirstLayer->Receive(lpBuf, nBufLen, nFlags); else - return recv(m_SocketData.hSocket, (LPSTR)lpBuf, nBufLen, nFlags); + return recv(m_SocketData.hSocket, static_cast(lpBuf), nBufLen, nFlags); } @@ -1028,7 +1028,7 @@ int CAsyncSocketEx::Send(const void* lpBuf, int nBufLen, int nFlags /*=0*/) } else { - return send(m_SocketData.hSocket, (LPCSTR)lpBuf, nBufLen, nFlags); + return send(m_SocketData.hSocket, static_cast(lpBuf), nBufLen, nFlags); } } @@ -1073,9 +1073,9 @@ BOOL CAsyncSocketEx::Connect(LPCTSTR lpszHostAddress, UINT nHostPort) return FALSE; } - sockAddr.sin_port = htons((u_short)nHostPort); + sockAddr.sin_port = htons(static_cast(nHostPort)); - return CAsyncSocketEx::Connect((SOCKADDR*)&sockAddr, sizeof(sockAddr)); + return CAsyncSocketEx::Connect(reinterpret_cast(&sockAddr), sizeof(sockAddr)); } else { @@ -1434,7 +1434,7 @@ BOOL CAsyncSocketEx::TriggerEvent(long lEvent) pMsg->hSocket = m_SocketData.hSocket; pMsg->lEvent=lEvent%0xFFFF; pMsg->pLayer=0; - BOOL res=PostMessage(GetHelperWindowHandle(), WM_USER, (WPARAM)m_SocketData.nSocketIndex, (LPARAM)pMsg); + BOOL res=PostMessage(GetHelperWindowHandle(), WM_USER, static_cast(m_SocketData.nSocketIndex), reinterpret_cast(pMsg)); if (!res) delete pMsg; return res; @@ -1516,12 +1516,12 @@ BOOL CAsyncSocketEx::IsLayerAttached() const BOOL CAsyncSocketEx::GetSockOpt(int nOptionName, void* lpOptionValue, int* lpOptionLen, int nLevel /*=SOL_SOCKET*/) { - return (SOCKET_ERROR != getsockopt(m_SocketData.hSocket, nLevel, nOptionName, (LPSTR)lpOptionValue, lpOptionLen)); + return (SOCKET_ERROR != getsockopt(m_SocketData.hSocket, nLevel, nOptionName, static_cast(lpOptionValue), lpOptionLen)); } BOOL CAsyncSocketEx::SetSockOpt(int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel /*=SOL_SOCKET*/) { - return (SOCKET_ERROR != setsockopt(m_SocketData.hSocket, nLevel, nOptionName, (LPCSTR)lpOptionValue, nOptionLen)); + return (SOCKET_ERROR != setsockopt(m_SocketData.hSocket, nLevel, nOptionName, static_cast(lpOptionValue), nOptionLen)); } int CAsyncSocketEx::GetState() const @@ -1656,7 +1656,7 @@ void CAsyncSocketEx::AddCallbackNotification(const t_callbackMsg& msg) if(m_pendingCallbacks.size() == 1 && m_SocketData.nSocketIndex != -1) { - PostMessage(GetHelperWindowHandle(), WM_USER + 2, (WPARAM)m_SocketData.nSocketIndex, 0); + PostMessage(GetHelperWindowHandle(), WM_USER + 2, static_cast(m_SocketData.nSocketIndex), 0); } } diff --git a/source/filezilla/AsyncSocketExLayer.cpp b/source/filezilla/AsyncSocketExLayer.cpp index 62370c6d5..bb2a26649 100644 --- a/source/filezilla/AsyncSocketExLayer.cpp +++ b/source/filezilla/AsyncSocketExLayer.cpp @@ -174,7 +174,7 @@ BOOL CAsyncSocketExLayer::TriggerEvent(long lEvent, int nErrorCode, BOOL bPassTh pMsg->hSocket = m_pOwnerSocket->m_SocketData.hSocket; pMsg->lEvent = ( lEvent % 0xffff ) + ( nErrorCode << 16); pMsg->pLayer=bPassThrough?m_pPrevLayer:this; - BOOL res=PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, (LPARAM)pMsg); + BOOL res=PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER, static_cast(m_pOwnerSocket->m_SocketData.nSocketIndex), reinterpret_cast(pMsg)); if (!res) { delete pMsg; @@ -232,7 +232,7 @@ int CAsyncSocketExLayer::SendNext(const void *lpBuf, int nBufLen, int nFlags /*= if (!m_pNextLayer) { DebugAssert(m_pOwnerSocket); - int sent = send(m_pOwnerSocket->GetSocketHandle(), (LPCSTR)lpBuf, nBufLen, nFlags); + int sent = send(m_pOwnerSocket->GetSocketHandle(), static_cast(lpBuf), nBufLen, nFlags); return sent; } else @@ -262,7 +262,7 @@ int CAsyncSocketExLayer::ReceiveNext(void *lpBuf, int nBufLen, int nFlags /*=0*/ if (!m_pNextLayer) { DebugAssert(m_pOwnerSocket); - return recv(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags); + return recv(m_pOwnerSocket->GetSocketHandle(), static_cast(lpBuf), nBufLen, nFlags); } else { @@ -295,7 +295,7 @@ BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort) LPHOSTENT lphost; lphost = gethostbyname(lpszAscii); if (lphost != NULL) - sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr; + sockAddr.sin_addr.s_addr = reinterpret_cast(lphost->h_addr)->s_addr; else { WSASetLastError(WSAEINVAL); @@ -303,9 +303,9 @@ BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort) } } - sockAddr.sin_port = htons((u_short)nHostPort); + sockAddr.sin_port = htons(static_cast(nHostPort)); - res = (SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), (SOCKADDR*)&sockAddr, sizeof(sockAddr)) ); + res = (SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), reinterpret_cast(&sockAddr), sizeof(sockAddr)) ); } else if (m_nFamily == AF_INET6 || m_nFamily == AF_UNSPEC) { @@ -364,7 +364,7 @@ BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort) } } if (m_pOwnerSocket->m_pendingCallbacks.size()) - PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER + 2, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, 0); + PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER + 2, static_cast(m_pOwnerSocket->m_SocketData.nSocketIndex), 0); } if (m_nFamily == AF_UNSPEC) diff --git a/source/filezilla/AsyncSslSocketLayer.cpp b/source/filezilla/AsyncSslSocketLayer.cpp index f7984ee0d..48e5682e0 100644 --- a/source/filezilla/AsyncSslSocketLayer.cpp +++ b/source/filezilla/AsyncSslSocketLayer.cpp @@ -10,9 +10,12 @@ #include "AsyncSslSocketLayer.h" #include "FileZillaTools.h" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include #include #include +#pragma clang diagnostic pop #pragma hdrstop #include "Common.h" @@ -737,7 +740,7 @@ int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode, SSL_CTX_set_session_cache_mode(m_ssl_ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE | SSL_SESS_CACHE_NO_AUTO_CLEAR); SSL_CTX_sess_set_new_cb(m_ssl_ctx, NewSessionCallback); if (!m_CertStorage.IsEmpty() && - CFile::IsValid((LPCTSTR)m_CertStorage)) + CFile::IsValid(m_CertStorage.c_str())) { SSL_CTX_load_verify_locations(m_ssl_ctx, T2CA(m_CertStorage), 0); } @@ -751,6 +754,8 @@ int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode, return SSL_FAILURE_INITSSL; } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" if (clientMode && (host.GetLength() > 0)) { USES_CONVERSION; @@ -770,6 +775,7 @@ int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode, } } #endif +#pragma clang diagnostic pop //Add current instance to list of active instances t_SslLayerList *tmp = m_pSslLayerList; @@ -869,7 +875,7 @@ int CAsyncSslSocketLayer::InitSSLConnection(bool clientMode, } SSL_set_bio(m_ssl, m_ibio, m_ibio); BIO_ctrl(m_sslbio, BIO_C_SET_SSL, BIO_NOCLOSE, m_ssl); - BIO_read(m_sslbio, (void *)1, 0); + BIO_read(m_sslbio, reinterpret_cast(1), 0); // Trigger FD_WRITE so that we can initialize SSL negotiation if (GetLayerState() == connected || GetLayerState() == attached) @@ -1226,7 +1232,7 @@ void CAsyncSslSocketLayer::apps_ssl_info_callback(const SSL *s, int where, int r static bool AsnTimeToValidTime(ASN1_TIME * AsnTime, t_SslCertData::t_validTime & ValidTime) { int i = AsnTime->length; - const char * v = (const char *)AsnTime->data; + const char * v = reinterpret_cast(AsnTime->data); if (i < 10) { @@ -1442,7 +1448,10 @@ BOOL CAsyncSslSocketLayer::GetPeerCertificateData(t_SslCertData &SslCertData, LP { USES_CONVERSION; u_char *data; + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wold-style-cast" int len = BIO_get_mem_data(subjectAltNameBio, &data); + #pragma clang diagnostic pop char * buf = new char[len + 1]; memcpy(buf, data, len); buf[len] = '\0'; @@ -1623,8 +1632,10 @@ int CAsyncSslSocketLayer::verify_callback(int preverify_ok, X509_STORE_CTX *ctx) * Retrieve the pointer to the SSL of the connection currently treated * and the application specific data stored into the SSL object. */ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wold-style-cast" ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); - + #pragma clang diagnostic pop CAsyncSslSocketLayer * pLayer = LookupLayer(ssl); @@ -1683,7 +1694,7 @@ int CAsyncSslSocketLayer::ProvideClientCert( Result = 1; } - Layer->LogSocketMessageRaw(Level, static_cast(Message)); + Layer->LogSocketMessageRaw(Level, Message.c_str()); return Result; } diff --git a/source/filezilla/AsyncSslSocketLayer.h b/source/filezilla/AsyncSslSocketLayer.h index 8523a6287..b3cba4791 100644 --- a/source/filezilla/AsyncSslSocketLayer.h +++ b/source/filezilla/AsyncSslSocketLayer.h @@ -73,7 +73,10 @@ for use in the OpenSSL Toolkit. (https://openssl-library.org/) #define AsyncSslSocketLayerH //--------------------------------------------------------------------------- #include "AsyncSocketExLayer.h" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include +#pragma clang diagnostic pop //--------------------------------------------------------------------------- // Details of SSL certificate, can be used by app to verify if certificate is valid struct t_SslCertData diff --git a/source/filezilla/FileZillaApi.cpp b/source/filezilla/FileZillaApi.cpp index aded7f5a0..151c50c6a 100644 --- a/source/filezilla/FileZillaApi.cpp +++ b/source/filezilla/FileZillaApi.cpp @@ -438,7 +438,7 @@ int CFileZillaApi::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData) case FZ_ASYNCREQUEST_OVERWRITE: break; case FZ_ASYNCREQUEST_VERIFYCERT: - if (!((CVerifyCertRequestData *)pData)->pCertData) + if (!static_cast(pData)->pCertData) { delete pData; return FZ_REPLY_INVALIDPARAM; @@ -463,7 +463,7 @@ int CFileZillaApi::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData) return FZ_REPLY_NOTINITIALIZED; } - m_pMainThread->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_ASYNCREQUESTREPLY, (LPARAM)pData); + m_pMainThread->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_ASYNCREQUESTREPLY, reinterpret_cast(pData)); return FZ_REPLY_OK; } diff --git a/source/filezilla/FileZillaApi.h b/source/filezilla/FileZillaApi.h index 2e1e2feb6..3cc4524a0 100644 --- a/source/filezilla/FileZillaApi.h +++ b/source/filezilla/FileZillaApi.h @@ -65,7 +65,7 @@ typedef struct #define FZ_MSG_OFFSETMASK 0xFFFF #define FZ_MSG_ID(x) ((x >> FZ_MSG_OFFSET) & FZ_MSG_OFFSETMASK) #define FZ_MSG_PARAM(x) ( x & FZ_MSG_OFFSETMASK) -#define FZ_MSG_MAKEMSG(id, param) ((((DWORD)(id & FZ_MSG_OFFSETMASK)) << FZ_MSG_OFFSET) + (param & FZ_MSG_OFFSETMASK) ) +#define FZ_MSG_MAKEMSG(id, param) ((static_cast(id & FZ_MSG_OFFSETMASK) << FZ_MSG_OFFSET) + (param & FZ_MSG_OFFSETMASK)) //--------------------------------------------------------------------------- #define FZ_MSG_REPLY 0 #define FZ_MSG_LISTDATA 1 diff --git a/source/filezilla/FileZillaIntf.cpp b/source/filezilla/FileZillaIntf.cpp index 8ea55eb81..e8b0ff61b 100644 --- a/source/filezilla/FileZillaIntf.cpp +++ b/source/filezilla/FileZillaIntf.cpp @@ -18,7 +18,7 @@ void __fastcall TFileZillaIntf::Finalize() //--------------------------------------------------------------------------- void __fastcall TFileZillaIntf::SetResourceModule(void * ResourceHandle) { - afxCurrentResourceHandle = (HINSTANCE)ResourceHandle; + afxCurrentResourceHandle = static_cast(ResourceHandle); } //--------------------------------------------------------------------------- __fastcall TFileZillaIntf::TFileZillaIntf() : @@ -311,7 +311,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) case FZ_MSG_STATUS: { DebugAssert(FZ_MSG_PARAM(wParam) == 0); - t_ffam_statusmessage * Status = (t_ffam_statusmessage *)lParam; + t_ffam_statusmessage * Status = reinterpret_cast(lParam); DebugAssert(Status->post); Result = HandleStatus(Status->status, Status->type); delete Status; @@ -324,7 +324,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) { int RequestResult; wchar_t FileName1[MAX_PATH]; - COverwriteRequestData * Data = (COverwriteRequestData *)lParam; + COverwriteRequestData * Data = reinterpret_cast(lParam); try { DebugAssert(Data != NULL); @@ -356,7 +356,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) else if (FZ_MSG_PARAM(wParam) == FZ_ASYNCREQUEST_VERIFYCERT) { int RequestResult; - CVerifyCertRequestData * AData = (CVerifyCertRequestData *)lParam; + CVerifyCertRequestData * AData = reinterpret_cast(lParam); try { DebugAssert(AData != NULL); @@ -392,7 +392,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) else if (FZ_MSG_PARAM(wParam) == FZ_ASYNCREQUEST_NEEDPASS) { int RequestResult = 0; - CNeedPassRequestData * AData = (CNeedPassRequestData *)lParam; + CNeedPassRequestData * AData = reinterpret_cast(lParam); try { TNeedPassRequestData Data; @@ -428,7 +428,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) case FZ_MSG_LISTDATA: { DebugAssert(FZ_MSG_PARAM(wParam) == 0); - t_directory * Directory = (t_directory *)lParam; + t_directory * Directory = reinterpret_cast(lParam); CString Path = Directory->path.GetPath(); std::vector Entries(Directory->num); @@ -461,7 +461,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) case FZ_MSG_TRANSFERSTATUS: { DebugAssert(FZ_MSG_PARAM(wParam) == 0); - t_ffam_transferstatus * Status = (t_ffam_transferstatus *)lParam; + t_ffam_transferstatus * Status = reinterpret_cast(lParam); if (Status != NULL) { Result = HandleTransferStatus( @@ -480,7 +480,7 @@ bool __fastcall TFileZillaIntf::HandleMessage(WPARAM wParam, LPARAM lParam) break; case FZ_MSG_CAPABILITIES: - Result = HandleCapabilities((TFTPServerCapabilities *)lParam); + Result = HandleCapabilities(reinterpret_cast(lParam)); break; default: diff --git a/source/filezilla/FilezillaTools.h b/source/filezilla/FilezillaTools.h index 938ca407b..1991bfdd2 100644 --- a/source/filezilla/FilezillaTools.h +++ b/source/filezilla/FilezillaTools.h @@ -5,6 +5,7 @@ #include #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wold-style-cast" #include #pragma clang diagnostic pop //--------------------------------------------------------------------------- diff --git a/source/filezilla/FtpControlSocket.cpp b/source/filezilla/FtpControlSocket.cpp index 0590cc983..a5730e79d 100644 --- a/source/filezilla/FtpControlSocket.cpp +++ b/source/filezilla/FtpControlSocket.cpp @@ -161,7 +161,7 @@ CFtpControlSocket::CFtpControlSocket(CMainThread *pMainThread, CFileZillaTools * m_pTransferSocket=0; m_pDataFile=0; - srand( (unsigned)time( NULL ) ); + srand(static_cast(time(NULL))); m_bKeepAliveActive=FALSE; m_bCheckForTimeout=TRUE; m_bDidRejectCertificate = FALSE; @@ -226,7 +226,7 @@ void CFtpControlSocket::ShowStatus(CString status, int type) const status+=L"*"; } } - LogMessageRaw(type, (LPCTSTR)status); + LogMessageRaw(type, status.c_str()); } void CFtpControlSocket::ShowTimeoutError(UINT nID) const @@ -236,7 +236,7 @@ void CFtpControlSocket::ShowTimeoutError(UINT nID) const CString str2; str2.LoadString(nID); CString message; - message.Format(L"%s (%s)", (LPCTSTR)str1, (LPCTSTR)str2); + message.Format(L"%s (%s)", str1.c_str(), str2.c_str()); ShowStatus(message, FZ_LOG_ERROR); } @@ -509,14 +509,14 @@ void CFtpControlSocket::Connect(t_server &server) temp=fwhost; port=fwport; if(fwport!=21) - fwhost.Format( L"%s:%d", (LPCTSTR)fwhost, fwport); // add port to fwhost (only if port is not 21) + fwhost.Format( L"%s:%d", fwhost.c_str(), fwport); // add port to fwhost (only if port is not 21) } CString hostname = server.host; if(server.port!=21) - hostname.Format( L"%s:%d", (LPCTSTR)hostname, server.port); // add port to hostname (only if port is not 21) + hostname.Format( L"%s:%d", hostname.c_str(), server.port); // add port to hostname (only if port is not 21) CString str; - str.Format(IDS_STATUSMSG_CONNECTING, (LPCTSTR)hostname); + str.Format(IDS_STATUSMSG_CONNECTING, hostname.c_str()); ShowStatus(str, FZ_LOG_STATUS); if (!Connect(temp, port)) @@ -758,7 +758,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) } } } - GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_CAPABILITIES, 0), (LPARAM)&m_serverCapabilities); + GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_CAPABILITIES, 0), reinterpret_cast(&m_serverCapabilities)); if (!m_bAnnouncesUTF8 && !m_CurrentServer.nUTF8) m_bUTF8 = false; if (m_hasClntCmd) @@ -915,7 +915,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) CAsyncRequestData *pData=new CAsyncRequestData; pData->nRequestType=FZ_ASYNCREQUEST_GSS_AUTHFAILED; pData->nRequestID=m_pOwner->GetNextAsyncRequestID(); - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), static_cast(pData))) { delete pData; } @@ -940,7 +940,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) CAsyncRequestData *pData=new CAsyncRequestData; pData->nRequestType = FZ_ASYNCREQUEST_GSS_AUTHFAILED; pData->nRequestID = m_pOwner->GetNextAsyncRequestID(); - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), static_cast(pData))) { delete pData; } @@ -979,7 +979,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) if (logontype) { CString str; - str.Format(IDS_STATUSMSG_FWCONNECT,(LPCTSTR)hostname); + str.Format(IDS_STATUSMSG_FWCONNECT, hostname.c_str()); ShowStatus(str,FZ_LOG_STATUS); } m_Operation.nOpState++; @@ -1017,7 +1017,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) pData->nRequestID = m_pOwner->GetNextAsyncRequestID(); pData->nOldOpState = m_Operation.nOpState; m_Operation.nOpState = CONNECT_GSS_NEEDUSER; - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), (LPARAM)pData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), static_cast(pData))) { delete pData; } @@ -1034,7 +1034,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) pData->nRequestID=m_pOwner->GetNextAsyncRequestID(); pData->nOldOpState = m_Operation.nOpState; m_Operation.nOpState = CONNECT_GSS_NEEDPASS; - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), (LPARAM)pData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), static_cast(pData))) { delete pData; } @@ -1060,7 +1060,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID(); pNeedPassRequestData->nOldOpState = m_Operation.nOpState; m_Operation.nOpState = CONNECT_NEEDPASS; - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), reinterpret_cast(pNeedPassRequestData))) { delete pNeedPassRequestData; ResetOperation(FZ_REPLY_ERROR); @@ -1115,7 +1115,7 @@ void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/) pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID(); pNeedPassRequestData->nOldOpState = m_Operation.nOpState; m_Operation.nOpState = CONNECT_NEEDPASS; - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), reinterpret_cast(pNeedPassRequestData))) { delete pNeedPassRequestData; ResetOperation(FZ_REPLY_ERROR); @@ -1171,7 +1171,7 @@ void CFtpControlSocket::OnReceive(int nErrorCode) } m_MultiLine = ""; CString str; - str.Format(IDS_STATUSMSG_CONNECTEDWITH, (LPCTSTR)m_ServerName); + str.Format(IDS_STATUSMSG_CONNECTEDWITH, m_ServerName.c_str()); ShowStatus(str, FZ_LOG_PROGRESS); m_pOwner->SetConnected(TRUE); } @@ -1237,7 +1237,7 @@ void CFtpControlSocket::OnReceive(int nErrorCode) else { LPWSTR p1 = new WCHAR[len + 1]; - MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1); + MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , p1, len + 1); ShowStatus(W2CT(p1), FZ_LOG_REPLY); delete [] p1; } @@ -1387,7 +1387,7 @@ void CFtpControlSocket::OnConnect(int nErrorCode) CString str; str.Format( m_pSslLayer ? IDS_STATUSMSG_CONNECTEDWITHSSL : IDS_STATUSMSG_CONNECTEDWITH, - (LPCTSTR)m_ServerName); + m_ServerName.c_str()); ShowStatus(str,FZ_LOG_PROGRESS); } } @@ -1396,7 +1396,7 @@ void CFtpControlSocket::OnConnect(int nErrorCode) if (nErrorCode == WSAHOST_NOT_FOUND) { CString str; - str.Format(IDS_ERRORMSG_CANTRESOLVEHOST2, (LPCTSTR)m_ServerName); + str.Format(IDS_ERRORMSG_CANTRESOLVEHOST2, m_ServerName.c_str()); ShowStatus(str, FZ_LOG_ERROR); } else @@ -2111,7 +2111,7 @@ void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath pa { SOCKADDR_IN addr; int len=sizeof(addr); - if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len)) + if (!m_pProxyLayer->GetPeerName(reinterpret_cast(&addr),&len)) { ResetOperation(FZ_REPLY_ERROR); return; @@ -2155,7 +2155,7 @@ void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath pa host = L""; else { - DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr; + DWORD ip = reinterpret_cast(fullname->h_addr)->s_addr; if (ip != INADDR_NONE) host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24); else @@ -2193,7 +2193,7 @@ void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath pa hints.ai_socktype = SOCK_STREAM; if (!getaddrinfo(T2CA(host), "1024", &hints, &res)) { - host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr); + host = Inet6AddrToString(reinterpret_cast(res->ai_addr)->sin6_addr); freeaddrinfo(res); } else @@ -2263,9 +2263,9 @@ void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath pa bool CFtpControlSocket::ConnectTransferSocket(const CString & host, UINT port) { CString hostname; - hostname.Format(L"%s:%d", (LPCTSTR)host, port); + hostname.Format(L"%s:%d", host.c_str(), port); CString str; - str.Format(IDS_STATUSMSG_CONNECTING, (LPCTSTR)hostname); + str.Format(IDS_STATUSMSG_CONNECTING, hostname.c_str()); ShowStatus(str, FZ_LOG_PROGRESS); bool result = true; @@ -2598,7 +2598,7 @@ int CFtpControlSocket::OpenTransferFile(CFileTransferData * pData) wchar_t * Error = m_pTools->LastSysErrorMessage(); //Error opening the file CString str; - str.Format(IDS_ERRORMSG_FILEOPENFAILED,(LPCTSTR)pData->transferfile.localfile); + str.Format(IDS_ERRORMSG_FILEOPENFAILED, pData->transferfile.localfile.c_str()); str += L"\n"; str += Error; free(Error); @@ -2877,7 +2877,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi { CString str; str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART, - transferfile->get ? (LPCTSTR)transferfile->remotepath.FormatFilename(transferfile->remotefile) : (LPCTSTR)transferfile->localfile); + transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile).c_str() : transferfile->localfile.c_str()); ShowStatus(str,FZ_LOG_STATUS); } @@ -3525,7 +3525,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft; LONG low = static_cast(size&0xFFFFFFFF); LONG high = static_cast(size>>32); - if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR) + if (SetFilePointer(m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR) { ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR); nReplyError = FZ_REPLY_ERROR; @@ -3585,7 +3585,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi if (pData->transferfile.get) { pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile); - if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR) + if (SetFilePointer(m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR) { ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR); nReplyError = FZ_REPLY_ERROR; @@ -3692,7 +3692,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi LONG high = 0; if (nOffset >= GetLength64(*m_pDataFile)) { - if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR) + if (SetFilePointer(m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR) { ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR); nReplyError = FZ_REPLY_ERROR; @@ -3702,7 +3702,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi { low=static_cast(nOffset&0xFFFFFFFF); high=static_cast(nOffset>>32); - if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR) + if (SetFilePointer(m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR) { ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR); nReplyError = FZ_REPLY_ERROR; @@ -3834,7 +3834,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi { SOCKADDR_IN addr; int len=sizeof(addr); - if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len)) + if (!m_pProxyLayer->GetPeerName(reinterpret_cast(&addr),&len)) { ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR); bError=TRUE; @@ -3877,7 +3877,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi host = L""; else { - DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr; + DWORD ip = reinterpret_cast(fullname->h_addr)->s_addr; if (ip != INADDR_NONE) host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24); else @@ -3917,7 +3917,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi hints.ai_socktype = SOCK_STREAM; if (!getaddrinfo(T2CA(host), "1024", &hints, &res)) { - host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr); + host = Inet6AddrToString(reinterpret_cast(res->ai_addr)->sin6_addr); freeaddrinfo(res); } else @@ -4028,7 +4028,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi { SOCKADDR_IN addr; int len=sizeof(addr); - if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len)) + if (!m_pProxyLayer->GetPeerName(reinterpret_cast(&addr),&len)) { ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR); bError=TRUE; @@ -4071,7 +4071,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi host = L""; else { - DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr; + DWORD ip = reinterpret_cast(fullname->h_addr)->s_addr; if (ip != INADDR_NONE) host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24); else @@ -4108,7 +4108,7 @@ void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFi hints.ai_socktype = SOCK_STREAM; if (!getaddrinfo(T2CA(host), "1024", &hints, &res)) { - host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr); + host = Inet6AddrToString(reinterpret_cast(res->ai_addr)->sin6_addr); freeaddrinfo(res); } else @@ -4305,7 +4305,7 @@ void CFtpControlSocket::TransferFinished(bool preserveFileTimeForUploads) DebugAlwaysTrue(pData->transferfile.OnTransferOut == NULL)) { m_pTools->PreserveDownloadFileTime( - (HANDLE)m_pDataFile->m_hFile, reinterpret_cast(pData->transferfile.nUserData)); + m_pDataFile->m_hFile, reinterpret_cast(pData->transferfile.nUserData)); } if (!pData->transferfile.get && GetOptionVal(OPTION_MPEXT_PRESERVEUPLOADFILETIME) && preserveFileTimeForUploads && @@ -4316,7 +4316,7 @@ void CFtpControlSocket::TransferFinished(bool preserveFileTimeForUploads) CString filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths); struct tm tm; - if (m_pTools->GetFileModificationTimeInUtc((LPCTSTR)pData->transferfile.localfile, tm)) + if (m_pTools->GetFileModificationTimeInUtc(pData->transferfile.localfile.c_str(), tm)) { CString timestr; timestr.Format(L"%02d%02d%02d%02d%02d%02d", @@ -4411,6 +4411,7 @@ void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/) delete m_pDataFile; m_pDataFile=0; + CFileTransferData * TransferData = static_cast(m_Operation.pData); if (m_Operation.nOpMode) { //Unset busy attribute so that new commands can be executed @@ -4428,12 +4429,12 @@ void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/) //Update remote file entry if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && - (!((CFileTransferData*)m_Operation.pData)->transferfile.get) && + !TransferData->transferfile.get && m_pDirectoryListing && m_Operation.nOpState>=FILETRANSFER_RETRSTOR) { - CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile; - CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath; + CString filename=TransferData->transferfile.remotefile; + CServerPath path=TransferData->transferfile.remotepath; t_directory dir; BOOL res=FALSE; if (m_pDirectoryListing) @@ -4462,9 +4463,9 @@ void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/) if (nSuccessful & FZ_REPLY_ERROR) { dir.direntry[i].bUnsure = TRUE; - if (!((CFileTransferData *)m_Operation.pData)->transferfile.get) + if (!TransferData->transferfile.get) dir.direntry[i].size = -1; - if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size)) + if (!GetLength64(TransferData->transferfile.localfile, dir.direntry[i].size)) dir.direntry[i].size = -1; } dir.direntry[i].date.hasdate = false; @@ -4511,14 +4512,14 @@ void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/) //Transfer aborted by user ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,FZ_LOG_ERROR); else - ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,FZ_LOG_ERROR); + ShowStatus(TransferData->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,FZ_LOG_ERROR); else if (m_Operation.nOpMode&CSMODE_LIST) ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR); else if (m_Operation.nOpMode&CSMODE_LISTFILE) ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR); } else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK) - ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,FZ_LOG_STATUS); + ShowStatus(TransferData->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,FZ_LOG_STATUS); } else { @@ -4593,7 +4594,7 @@ public: int res=GetReplyCode(); if (res==2 || res==3) { //Remove file from cached dirs - CDeleteData *pData=(CDeleteData *)m_Operation.pData; + CDeleteData *pData=static_cast(m_Operation.pData); t_directory dir; BOOL res=FALSE; if (m_pDirectoryListing) @@ -4699,7 +4700,7 @@ public: int res = GetReplyCode(); if (res == 2 || res == 3) { //Remove dir from cached dirs - CRemoveDirData *pData= (CRemoveDirData *)m_Operation.pData; + CRemoveDirData *pData= static_cast(m_Operation.pData); t_directory dir; BOOL res = FALSE; if (m_pDirectoryListing) @@ -4810,7 +4811,7 @@ int CFtpControlSocket::CheckOverwriteFile() return FZ_REPLY_ERROR; } - CFileTransferData *pData = reinterpret_cast(m_Operation.pData); + CFileTransferData *pData = static_cast(m_Operation.pData); int nReplyError = 0; CFileStatus status; @@ -4909,7 +4910,7 @@ int CFtpControlSocket::CheckOverwriteFile() pOverwriteData->localtime = localtime; pOverwriteData->remotetime = remotetime; pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID(); - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), reinterpret_cast(pOverwriteData))) { delete pOverwriteData; nReplyError = FZ_REPLY_ERROR; @@ -4939,7 +4940,7 @@ void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData * if (m_Operation.nOpState != FILETRANSFER_WAIT) return; - CFileTransferData* pTransferData = reinterpret_cast(m_Operation.pData); + CFileTransferData* pTransferData = static_cast(m_Operation.pData); if (!pTransferData) return; @@ -5050,7 +5051,7 @@ void CFtpControlSocket::MakeDir(const CServerPath &path) DebugAssert(m_Operation.nOpMode==CSMODE_MKDIR); DebugAssert(path.IsEmpty()); DebugAssert(m_Operation.pData); - CMakeDirData *pData=(CMakeDirData *)m_Operation.pData; + CMakeDirData *pData=static_cast(m_Operation.pData); int res=GetReplyCode(); if (res==2 || res==3) { @@ -5083,7 +5084,7 @@ void CFtpControlSocket::MakeDir(const CServerPath &path) int res=GetReplyCode(); if (res==2 || res==3) { //Create dir entry in parent dir - CMakeDirData *pData=(CMakeDirData *)m_Operation.pData; + CMakeDirData *pData=static_cast(m_Operation.pData); DebugAssert(!pData->Segments.empty()); @@ -5102,7 +5103,7 @@ void CFtpControlSocket::MakeDir(const CServerPath &path) } else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR) { - CMakeDirData *pData=(CMakeDirData *)m_Operation.pData; + CMakeDirData *pData=static_cast(m_Operation.pData); int res=GetReplyCode(); if (res==2 || res==3 || //Creation successful GetReply() == L"550 Directory already exists")//Creation was successful, although someone else did the work for us @@ -5233,11 +5234,11 @@ void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPa m_Operation.nOpState++; if (pData->newPath.IsEmpty()) { - if (!Send(L"RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName))) + if (!Send(L"RNTO " + pData->path.FormatFilename(pData->newName))) return; } else - if (!Send(L"RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName))) + if (!Send(L"RNTO " + pData->newPath.FormatFilename(pData->newName))) return; } else @@ -5409,7 +5410,7 @@ void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nVa { m_Operation.nOpMode=CSMODE_CHMOD; CString str; - str.Format( L"SITE CHMOD %03d %s", nValue, (LPCTSTR)path.FormatFilename(filename)); + str.Format( L"SITE CHMOD %03d %s", nValue, path.FormatFilename(filename).c_str()); Send(str); } @@ -5418,10 +5419,10 @@ void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pD switch (pData->nRequestType) { case FZ_ASYNCREQUEST_OVERWRITE: - SetFileExistsAction(nAction, (COverwriteRequestData *)pData); + SetFileExistsAction(nAction, static_cast(pData)); break; case FZ_ASYNCREQUEST_VERIFYCERT: - SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData ); + SetVerifyCertResult(nAction, static_cast(pData)->pCertData ); break; case FZ_ASYNCREQUEST_NEEDPASS: if (m_Operation.nOpMode!=CSMODE_CONNECT || @@ -5441,8 +5442,8 @@ void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pD else { m_bCheckForTimeout = TRUE; - m_CurrentServer.pass=((CNeedPassRequestData *)pData)->Password; - m_Operation.nOpState=((CNeedPassRequestData *)pData)->nOldOpState; + m_CurrentServer.pass=static_cast(pData)->Password; + m_Operation.nOpState=static_cast(pData)->nOldOpState; CLogonData *pLogonData = static_cast(m_Operation.pData); pLogonData->waitForAsyncRequest = false; pLogonData->gotPassword = true; @@ -5650,7 +5651,7 @@ int CFtpControlSocket::OnLayerCallback(std::list& callbacks) pRequestData->pCertData = pData; - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), reinterpret_cast(pRequestData))) { delete pRequestData->pCertData; delete pRequestData; @@ -5701,9 +5702,9 @@ _int64 CFtpControlSocket::GetSpeedLimit(int valType, int valValue) int type = GetOptionVal(valType); if ( type == 1) - return ( _int64)GetOptionVal(valValue) * 1024; + return static_cast<_int64>(GetOptionVal(valValue)) * 1024; - return ( _int64)1000000000000; // I hope that when there will be something with 1000GB/s then I'll change it :) + return static_cast<_int64>(1000000000000); // I hope that when there will be something with 1000GB/s then I'll change it :) } _int64 CFtpControlSocket::GetSpeedLimit(enum transferDirection direction) @@ -6042,7 +6043,7 @@ CString CFtpControlSocket::GetReply() else { LPWSTR p1 = new WCHAR[len + 1]; - MultiByteToWideChar(CP_UTF8, 0, line, -1 , (LPWSTR)p1, len + 1); + MultiByteToWideChar(CP_UTF8, 0, line, -1, p1, len + 1); CString reply = W2CT(p1); delete [] p1; return reply; @@ -6161,7 +6162,7 @@ bool CFtpControlSocket::CheckForcePasvIp(CString & host) if (ahost != host) { - LogMessage(FZ_LOG_WARNING, L"Using host address %s instead of the one suggested by the server: %s", (LPCTSTR)ahost, (LPCTSTR)host); + LogMessage(FZ_LOG_WARNING, L"Using host address %s instead of the one suggested by the server: %s", ahost.c_str(), host.c_str()); host = ahost; } break; @@ -6177,7 +6178,7 @@ bool CFtpControlSocket::CheckForcePasvIp(CString & host) } else if (!IsRoutableAddress(host) && IsRoutableAddress(ahost)) { - LogMessage(FZ_LOG_WARNING, L"Server sent passive reply with unroutable address %s, using host address instead.", (LPCTSTR)host); + LogMessage(FZ_LOG_WARNING, L"Server sent passive reply with unroutable address %s, using host address instead.", host.c_str()); host = ahost; } break; diff --git a/source/filezilla/FtpListResult.cpp b/source/filezilla/FtpListResult.cpp index de1c935a0..89925493a 100644 --- a/source/filezilla/FtpListResult.cpp +++ b/source/filezilla/FtpListResult.cpp @@ -411,7 +411,7 @@ void CFtpListResult::SendLineToMessageLog(const RawByteString & Line) Status->post = TRUE; Status->status = Line.c_str(); Status->type = FZ_LOG_INFO; - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_STATUS, 0), (LPARAM)Status)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_STATUS, 0), reinterpret_cast(Status))) { delete Status; } @@ -433,8 +433,8 @@ void CFtpListResult::AddLine(t_directory::t_direntry & direntry) FILETIME ft; SystemTimeToFileTime(&st, &ft); - _int64 nFt = ((_int64)ft.dwHighDateTime << 32) + ft.dwLowDateTime; - nFt += ((_int64)m_server.nTimeZoneOffset) * 10000000 * 60; + _int64 nFt = (static_cast<_int64>(ft.dwHighDateTime) << 32) + ft.dwLowDateTime; + nFt += static_cast<_int64>(m_server.nTimeZoneOffset) * 10000000 * 60; ft.dwHighDateTime = static_cast(nFt >> 32); ft.dwLowDateTime = static_cast(nFt & 0xFFFFFFFF); FileTimeToSystemTime(&ft, &st); @@ -910,7 +910,7 @@ BOOL CFtpListResult::parseAsEPLF(const char *line, const int, t_directory::t_dir dir.size = strntoi64(fact+1, len-1); else if (*fact=='m') { - time_t rawtime = (time_t)strntoi64(fact+1, len-1); + time_t rawtime = static_cast(strntoi64(fact+1, len-1)); TimeTToDate(rawtime, dir.date); } else if (len == 5 && *fact=='u' && *(fact+1)=='p') @@ -1152,14 +1152,14 @@ bool CFtpListResult::parseMlsdDateTime(const CString value, t_directory::t_diren int Year, Month, Day, Hours, Minutes, Seconds; Year=Month=Day=Hours=Minutes=Seconds=0; // Time can include a fraction after a dot, this will ignore the fraction part. - if (swscanf((LPCWSTR)value, L"%4d%2d%2d%2d%2d%2d", &Year, &Month, &Day, &Hours, &Minutes, &Seconds) == 6) + if (swscanf(value.c_str(), L"%4d%2d%2d%2d%2d%2d", &Year, &Month, &Day, &Hours, &Minutes, &Seconds) == 6) { date.hasdate = TRUE; date.hastime = TRUE; date.hasseconds = TRUE; result = TRUE; } - else if (swscanf((LPCWSTR)value, L"%4d%2d%2d", &Year, &Month, &Day) == 3) + else if (swscanf(value.c_str(), L"%4d%2d%2d", &Year, &Month, &Day) == 3) { date.hasdate = TRUE; date.hastime = FALSE; @@ -1633,7 +1633,7 @@ BOOL CFtpListResult::parseAsUnix(const char *line, const int linelen, t_director break; if (i && i < sdaylen) { - if ((unsigned char)sday[i] > 127) + if (static_cast(sday[i]) > 127) sdaylen = i; } @@ -1677,7 +1677,7 @@ BOOL CFtpListResult::parseAsUnix(const char *line, const int linelen, t_director _strlwr(lwr); bool gotYear = false; - int year = (int)strntoi64(smonth, smonthlen); + int year = static_cast(strntoi64(smonth, smonthlen)); if (year > 1000) { gotYear = true; @@ -1699,13 +1699,13 @@ BOOL CFtpListResult::parseAsUnix(const char *line, const int linelen, t_director { return false; } - if ((unsigned char)smonth[i] < 128) + if (static_cast(smonth[i]) < 128) { return false; } smonthlen = i; - direntry.date.month = (int)strntoi64(smonth, smonthlen); + direntry.date.month = static_cast(strntoi64(smonth, smonthlen)); if (!direntry.date.month || direntry.date.month > 12) { return false; @@ -2277,11 +2277,11 @@ void CFtpListResult::copyStr(CString &target, int pos, const char *source, int l else { // convert from UTF-8 to ANSI - int len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)p, -1, NULL, 0); + int len = MultiByteToWideChar(CP_UTF8, 0, static_cast(p), -1, NULL, 0); if (len != 0) { LPWSTR p1 = new WCHAR[len + 1]; - MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)p, -1 , (LPWSTR)p1, len + 1); + MultiByteToWideChar(CP_UTF8, 0, p, -1, p1, len + 1); target = target.Left(pos) + W2CT(p1); delete [] p1; } @@ -2830,7 +2830,7 @@ bool CFtpListResult::ParseSize(const char* str, int len, __int64 &size) const break; case 't': case 'T': - size *= (__int64)1 << 40; + size *= static_cast<__int64>(1) << 40; break; default: return false; diff --git a/source/filezilla/FzApiStructures.h b/source/filezilla/FzApiStructures.h index 7b86d2423..4d4ebe4b5 100644 --- a/source/filezilla/FzApiStructures.h +++ b/source/filezilla/FzApiStructures.h @@ -2,7 +2,10 @@ #ifndef FzApiStructuresH #define FzApiStructuresH //--------------------------------------------------------------------------- +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" #include +#pragma clang diagnostic pop #include //--------------------------------------------------------------------------- class t_server diff --git a/source/filezilla/MFC64bitFix.cpp b/source/filezilla/MFC64bitFix.cpp index 370d2222d..20d20ef45 100644 --- a/source/filezilla/MFC64bitFix.cpp +++ b/source/filezilla/MFC64bitFix.cpp @@ -5,8 +5,8 @@ __int64 GetLength64(CFile &file) { DWORD low; DWORD high; - low=GetFileSize((void *)file.m_hFile, &high); - _int64 size=((_int64)high<<32)+low; + low=GetFileSize(file.m_hFile, &high); + _int64 size=(static_cast<_int64>(high)<<32)+low; return size; } @@ -18,7 +18,7 @@ BOOL GetLength64(CString filename, _int64 &size) return FALSE; DebugCheck(FindClose(hFind)); - size=((_int64)findFileData.nFileSizeHigh<<32)+findFileData.nFileSizeLow; + size=(static_cast<_int64>(findFileData.nFileSizeHigh)<<32)+findFileData.nFileSizeLow; return TRUE; } @@ -34,8 +34,7 @@ BOOL PASCAL GetFileStatus(LPCTSTR lpszFileName, CFileStatus& rStatus) DebugCheck(FindClose(hFind)); // strip attribute of NORMAL bit, our API doesn't have a "normal" bit. - rStatus.m_attribute = (BYTE) - (findFileData.dwFileAttributes & ~FILE_ATTRIBUTE_NORMAL); + rStatus.m_attribute = static_cast(findFileData.dwFileAttributes & ~FILE_ATTRIBUTE_NORMAL); // convert times as appropriate rStatus.m_mtime = CTime(findFileData.ftLastWriteTime); diff --git a/source/filezilla/MainThread.cpp b/source/filezilla/MainThread.cpp index 5e5a3492c..b9c0c52b2 100644 --- a/source/filezilla/MainThread.cpp +++ b/source/filezilla/MainThread.cpp @@ -88,11 +88,11 @@ BOOL CMainThread::OnThreadMessage(UINT Msg, WPARAM wParam, LPARAM lParam) { if (wParam==FZAPI_THREADMSG_COMMAND) { + t_command *pCommand=reinterpret_cast(lParam); if (m_pControlSocket && !m_pControlSocket->IsReady()) - m_pPostKeepAliveCommand=(t_command *)lParam; + m_pPostKeepAliveCommand=pCommand; else { - t_command *pCommand=(t_command *)lParam; switch(pCommand->id) { case FZ_COMMAND_CONNECT: @@ -152,13 +152,13 @@ BOOL CMainThread::OnThreadMessage(UINT Msg, WPARAM wParam, LPARAM lParam) { if (m_pPostKeepAliveCommand) { - PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,(LPARAM)m_pPostKeepAliveCommand); + PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,reinterpret_cast(m_pPostKeepAliveCommand)); m_pPostKeepAliveCommand=0; } } else if (wParam==FZAPI_THREADMSG_ASYNCREQUESTREPLY) { - CAsyncRequestData *pData=(CAsyncRequestData *)lParam; + CAsyncRequestData *pData=reinterpret_cast(lParam); if (pData) { if (pData->nRequestID!=GetAsyncRequestID()) @@ -201,7 +201,7 @@ void CMainThread::Command(const t_command &command) m_bBusy=TRUE; t_command *pCommand=new t_command; *pCommand=command; - DebugCheck(PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,(LPARAM)pCommand)); + DebugCheck(PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,reinterpret_cast(pCommand))); m_LastCommand=command; LCS; } @@ -349,7 +349,7 @@ void CMainThread::SetWorkingDir(t_directory *pWorkingDir) void CMainThread::SendDirectoryListing(t_directory * pDirectoryToSend) { - if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_LISTDATA, 0), (LPARAM)pDirectoryToSend)) + if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_LISTDATA, 0), reinterpret_cast(pDirectoryToSend))) { delete pDirectoryToSend; } @@ -399,7 +399,7 @@ DWORD CMainThread::ResumeThread() DWORD WINAPI CMainThread::ThreadProc(LPVOID lpParameter) { - return ((CMainThread *)lpParameter)->Run(); + return static_cast(lpParameter)->Run(); } DWORD CMainThread::Run() diff --git a/source/filezilla/ServerPath.cpp b/source/filezilla/ServerPath.cpp index 4462879aa..3bd85d7c5 100644 --- a/source/filezilla/ServerPath.cpp +++ b/source/filezilla/ServerPath.cpp @@ -3,7 +3,7 @@ #include "ServerPath.h" #include "structures.h" -#define FTP_MVS_DOUBLE_QUOTA (TCHAR)0xDC +#define FTP_MVS_DOUBLE_QUOTA static_cast(0xDC) ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion diff --git a/source/filezilla/TransferSocket.cpp b/source/filezilla/TransferSocket.cpp index f8845bb44..a51eebc10 100644 --- a/source/filezilla/TransferSocket.cpp +++ b/source/filezilla/TransferSocket.cpp @@ -115,7 +115,7 @@ void CTransferSocket::OnReceive(int nErrorCode) status->bFileTransfer = FALSE; status->transfersize = -1; status->bytes = m_transferdata.transfersize; - GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status); + GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), reinterpret_cast(status)); } if (!numread) { @@ -647,7 +647,7 @@ void CTransferSocket::UpdateStatusBar(bool forceUpdate) status->transfersize = m_transferdata.transfersize; status->bytes=m_transferdata.transfersize-m_transferdata.transferleft; - GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status); + GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), reinterpret_cast(status)); } BOOL CTransferSocket::Create(BOOL bUseSsl) @@ -686,7 +686,7 @@ BOOL CTransferSocket::Create(BOOL bUseSsl) m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR); return FALSE; } - int startport=static_cast(min+((double)rand()*(max-min))/(RAND_MAX+1)); + int startport=static_cast(min+(static_cast(rand())*(max-min))/(RAND_MAX+1)); int port=startport; // Failure to create the socket, calls Close(), which resets the family. We want to keep trying the original faimily with each port. // Only with the specific family set, the Create actually does bind(), without which the port testing does not work. diff --git a/source/forms/About.cpp b/source/forms/About.cpp index df0a64012..94e3e7054 100644 --- a/source/forms/About.cpp +++ b/source/forms/About.cpp @@ -132,7 +132,7 @@ __fastcall TAboutDialog::TAboutDialog(TComponent * AOwner, } int IconSize = ScaleByPixelsPerInch(48, this); - FIconHandle = (HICON)LoadImage(MainInstance, L"MAINICON", IMAGE_ICON, IconSize, IconSize, 0); + FIconHandle = static_cast(LoadImage(MainInstance, L"MAINICON", IMAGE_ICON, IconSize, IconSize, 0)); IconPaintBox->Width = IconSize; IconPaintBox->Height = IconSize; } diff --git a/source/forms/Authenticate.cpp b/source/forms/Authenticate.cpp index 866cb51cd..49066d742 100644 --- a/source/forms/Authenticate.cpp +++ b/source/forms/Authenticate.cpp @@ -344,7 +344,7 @@ bool __fastcall TAuthenticateForm::PromptUser(TPromptKind Kind, UnicodeString Na TCustomEdit * Edit = reinterpret_cast(Edits->Items[Index]); Results->Strings[Index] = Edit->Text; - Prompts->Objects[Index] = (TObject *) + Prompts->Objects[Index] = reinterpret_cast ((int(Prompts->Objects[Index]) & ~pupRemember) | FLAGMASK(((Index == 0) && SessionRememberPasswordCheck->Checked), pupRemember)); } diff --git a/source/forms/Console.cpp b/source/forms/Console.cpp index 255fe9e58..0182552ae 100644 --- a/source/forms/Console.cpp +++ b/source/forms/Console.cpp @@ -35,7 +35,7 @@ __fastcall TConsoleDialog::TConsoleDialog(TComponent* AOwner) FDirectoryChanged = false; FExecuting = false; OutputMemo->Color = clBlack; - OutputMemo->Font->Color = (TColor)0x00BBBBBB; + OutputMemo->Font->Color = static_cast(0x00BBBBBB); FixComboBoxResizeBug(CommandEdit); UseSystemSettings(this); SelectScaledImageList(Images); @@ -276,7 +276,7 @@ void __fastcall TConsoleDialog::DoAdjustWindow() { GetTextMetrics(DC, &TM); - OutputMemo->Perform(EM_GETRECT, 0, ((int)&Rect)); + OutputMemo->Perform(EM_GETRECT, 0, reinterpret_cast(&Rect)); } __finally { diff --git a/source/forms/Custom.cpp b/source/forms/Custom.cpp index 8494cb29f..9761af82b 100644 --- a/source/forms/Custom.cpp +++ b/source/forms/Custom.cpp @@ -615,7 +615,7 @@ void __fastcall SessionNameValidate(const UnicodeString & Text, TSessionData::ValidatePath(Text); DebugAssert(StoredSessions); - TSessionData * Data = (TSessionData *)StoredSessions->FindByName(Text); + TSessionData * Data = static_cast(StoredSessions->FindByName(Text)); if (Data && Data->Special) { MessageDialog(FMTLOAD(CANNOT_OVERWRITE_SPECIAL_SESSION, (Text)), diff --git a/source/forms/CustomScpExplorer.cpp b/source/forms/CustomScpExplorer.cpp index 8e9e058e4..6575afcdd 100644 --- a/source/forms/CustomScpExplorer.cpp +++ b/source/forms/CustomScpExplorer.cpp @@ -836,7 +836,7 @@ void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue, if (QueueItem != NULL) { - QueueItem->UserData = (void*)true; + QueueItem->UserData = reinterpret_cast(true); FQueueItemInvalidated = true; } } @@ -876,9 +876,9 @@ void __fastcall TCustomScpExplorerForm::RefreshQueueItems() FUserActionTimer->Enabled = true; } - if ((bool)QueueItem->UserData) + if (reinterpret_cast(QueueItem->UserData)) { - QueueItem->UserData = (void*)false; + QueueItem->UserData = reinterpret_cast(false); QueueItem->Update(); Updated = true; Update = true; @@ -1898,7 +1898,7 @@ void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender { TTBCustomItem * Item = dynamic_cast(Sender); THistoryItemData Data = *reinterpret_cast(&(Item->Tag)); - HistoryGo((TOperationSide)Data.Side, Data.Index); + HistoryGo(static_cast(Data.Side), Data.Index); } //--------------------------------------------------------------------------- void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side, @@ -4895,7 +4895,7 @@ bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStri { for (int Index = 0; Index < FileList->Count; Index++) { - TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]); + TRemoteFile * File = static_cast(FileList->Objects[Index]); if (CapableGroupChanging) { GroupList->AddUnique(File->Group); @@ -5002,7 +5002,7 @@ void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState { // Note that handling shortcuts on panel (current control) popup menu has precendence over this. // But so far it's not a problem, as it does what we want. - TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index]; + TAction * Action = static_cast(NonVisualDataModule->ExplorerActions->Actions[Index]); if (((Action->ShortCut == KeyShortCut) || (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) && AllowedAction(Action, aaShortCut)) @@ -5097,7 +5097,7 @@ void __fastcall TCustomScpExplorerForm::InitStatusBar() } } - TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar); + TTBXStatusBar * SessionStatusBar = static_cast(GetComponent(fcStatusBar)); int Offset = SessionStatusBar->Panels->Count - SessionPanelCount; @@ -5135,7 +5135,7 @@ void __fastcall TCustomScpExplorerForm::InitStatusBar() //--------------------------------------------------------------------------- void __fastcall TCustomScpExplorerForm::UpdateStatusBar() { - TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar); + TTBXStatusBar * SessionStatusBar = static_cast(GetComponent(fcStatusBar)); DebugAssert(SessionStatusBar != NULL); TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0]; @@ -5696,7 +5696,7 @@ void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors() void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties( TObject *Sender) { - TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL); + TStrings *FileList = static_cast(Sender)->CreateFileList(True, False, NULL); try { SetProperties(osRemote, FileList); @@ -5904,7 +5904,7 @@ void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender, { DebugAssert(Sender && Item && Configuration); DebugAssert(AllowExec); - TCustomDirView * ADirView = (TCustomDirView *)Sender; + TCustomDirView * ADirView = static_cast(Sender); TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal); bool Remote = !IsSideLocalBrowser(Side); @@ -7082,10 +7082,10 @@ void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace( UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path)); if (!ADrive.IsEmpty()) { - __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1)); + __int64 FreeSpace = DiskFree(static_cast(ADrive[1]-'A'+1)); DebugAssert(RequiredSpace >= 0); __int64 RequiredWithReserve; - RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio); + RequiredWithReserve = static_cast<__int64>(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio); if (FreeSpace < RequiredWithReserve) { unsigned int Result; @@ -7314,7 +7314,7 @@ void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Ad if (RemoteDirView->ItemFocused) { DebugAssert(RemoteDirView->ItemFocused->Data); - File = (TRemoteFile *)RemoteDirView->ItemFocused->Data; + File = static_cast(RemoteDirView->ItemFocused->Data); Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks; if (Edit) @@ -7365,7 +7365,7 @@ bool __fastcall TCustomScpExplorerForm::LinkFocused() return !IsSideLocalBrowser(FCurrentSide) && (RemoteDirView->ItemFocused != NULL) && - ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink && + static_cast(RemoteDirView->ItemFocused->Data)->IsSymLink && Terminal->SessionData->ResolveSymlinks; } //--------------------------------------------------------------------------- @@ -8239,7 +8239,7 @@ void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList, FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated); } - FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, + FDDExtMapFile = CreateFileMappingA(reinterpret_cast(0xFFFFFFFF), NULL, PAGE_READWRITE, 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str()); { @@ -10301,7 +10301,7 @@ bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force) // cannot cancel note too early bool NotEarly = (Now() - FNoteShown > - EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0)); + EncodeTimeVerbose(0, 0, static_cast(WinConfiguration->NotificationsStickTime), 0)); if (Force || NotEarly) { FNoteTimer->Enabled = false; diff --git a/source/forms/Editor.cpp b/source/forms/Editor.cpp index 63d3132b2..3b7243768 100644 --- a/source/forms/Editor.cpp +++ b/source/forms/Editor.cpp @@ -267,7 +267,7 @@ int __fastcall TEditorRichEdit::FindText(const UnicodeString SearchStr, int Star FLAGMASK(Options.Contains(stWholeWord), FR_WHOLEWORD) | FLAGMASK(Options.Contains(stMatchCase), FR_MATCHCASE) | FLAGMASK(Down, FR_DOWN); - int Result = SendMessage(Handle, EM_FINDTEXTEX, Flags, (LPARAM)&Find); + int Result = SendMessage(Handle, EM_FINDTEXTEX, Flags, reinterpret_cast(&Find)); return Result; } //--------------------------------------------------------------------------- @@ -490,12 +490,12 @@ void __fastcall TEditorRichEdit::SetTabSize(unsigned int TabSize) // save selection CHARRANGE CharRange; - SendMessage(Handle, EM_EXGETSEL, 0, (LPARAM)&CharRange); + SendMessage(Handle, EM_EXGETSEL, 0, reinterpret_cast(&CharRange)); CHARRANGE CharRangeAll; CharRangeAll.cpMin = 0; CharRangeAll.cpMax = -1; - SendMessage(Handle, EM_EXSETSEL, 0, (LPARAM)&CharRangeAll); + SendMessage(Handle, EM_EXSETSEL, 0, reinterpret_cast(&CharRangeAll)); PARAFORMAT2 ParaFormat; ParaFormat.cbSize = sizeof(ParaFormat); @@ -507,10 +507,10 @@ void __fastcall TEditorRichEdit::SetTabSize(unsigned int TabSize) ParaFormat.rgxTabs[i] = (i + 1) * TabTwips; } - SendMessage(Handle, EM_SETPARAFORMAT, 0, (LPARAM)&ParaFormat); + SendMessage(Handle, EM_SETPARAFORMAT, 0, reinterpret_cast(&ParaFormat)); // restore selection - SendMessage(Handle, EM_EXSETSEL, 0, (LPARAM)&CharRange); + SendMessage(Handle, EM_EXSETSEL, 0, reinterpret_cast(&CharRange)); } //--------------------------------------------------------------------------- bool __stdcall TEditorRichEdit::StreamLoad( @@ -872,7 +872,7 @@ void __fastcall TEditorForm::EditorActionsUpdate(TBasicAction *Action, Action == FindAction || Action == ReplaceAction || Action == GoToLineAction || Action == HelpAction || Action == ColorAction) { - ((TAction *)Action)->Enabled = true; + static_cast(Action)->Enabled = true; } else if (Action == ReloadAction) { @@ -1109,7 +1109,7 @@ void __fastcall TEditorForm::UpdateControls() FCaretPos = ACaretPos; int Count = EditorMemo->Lines->Count; StatusBar->Panels->Items[0]->Caption = FMTLOAD(EDITOR_LINE_STATUS, - ((int)FCaretPos.y+1, Count)); + (static_cast(FCaretPos.y)+1, Count)); int Column = 0; UnicodeString Character; if (FCaretPos.y >= 0 && FCaretPos.y < EditorMemo->Lines->Count) @@ -1531,13 +1531,13 @@ bool __fastcall TEditorForm::CursorInUpperPart() TRect Rect; DC = GetDC(EditorMemo->Handle); - OldFont = (HFONT)SelectObject(DC, EditorMemo->Font->Handle); + OldFont = static_cast(SelectObject(DC, EditorMemo->Font->Handle)); try { GetTextMetrics(DC, &TM); - EditorMemo->Perform(EM_GETRECT, 0, ((int)&Rect)); + EditorMemo->Perform(EM_GETRECT, 0, reinterpret_cast(&Rect)); } __finally { diff --git a/source/forms/FileFind.cpp b/source/forms/FileFind.cpp index fec5e58aa..bc4bca26a 100644 --- a/source/forms/FileFind.cpp +++ b/source/forms/FileFind.cpp @@ -447,7 +447,7 @@ void __fastcall TFileFindDialog::Dispatch(void * Message) TMessage * M = reinterpret_cast(Message); if (M->Msg == CM_DIALOGKEY) { - CMDialogKey(*((TWMKeyDown *)Message)); + CMDialogKey(*static_cast(Message)); } else { diff --git a/source/forms/ImportSessions.cpp b/source/forms/ImportSessions.cpp index 0d09088b2..c1e109a60 100644 --- a/source/forms/ImportSessions.cpp +++ b/source/forms/ImportSessions.cpp @@ -392,7 +392,7 @@ void __fastcall TImportSessionsDialog::CreateHandle() { HINSTANCE User32Library = LoadLibrary(L"user32.dll"); AddClipboardFormatListenerProc AddClipboardFormatListener = - (AddClipboardFormatListenerProc)GetProcAddress(User32Library, "AddClipboardFormatListener"); + reinterpret_cast(GetProcAddress(User32Library, "AddClipboardFormatListener")); if (AddClipboardFormatListener != NULL) { AddClipboardFormatListener(Handle); @@ -406,7 +406,7 @@ void __fastcall TImportSessionsDialog::DestroyHandle() { HINSTANCE User32Library = LoadLibrary(L"user32.dll"); RemoveClipboardFormatListenerProc RemoveClipboardFormatListener = - (RemoveClipboardFormatListenerProc)GetProcAddress(User32Library, "RemoveClipboardFormatListener"); + reinterpret_cast(GetProcAddress(User32Library, "RemoveClipboardFormatListener")); if (RemoveClipboardFormatListener != NULL) { RemoveClipboardFormatListener(Handle); diff --git a/source/forms/LocationProfiles.cpp b/source/forms/LocationProfiles.cpp index 4aa47db63..e7b698f70 100644 --- a/source/forms/LocationProfiles.cpp +++ b/source/forms/LocationProfiles.cpp @@ -257,7 +257,7 @@ bool __fastcall TLocationProfilesDialog::ProfileMatch(TTreeNode * Node) bool Result = false; if (Node->Data) { - TBookmark * Bookmark = (TBookmark *)Node->Data; + TBookmark * Bookmark = static_cast(Node->Data); Result = (Bookmark->Local == LocalDirectory) && (Bookmark->Remote == RemoteDirectory); @@ -491,7 +491,7 @@ bool __fastcall TLocationProfilesDialog::AddAsBookmark(TObject * Sender, bool In if (Selected != NULL) { DebugAssert(!Initial); - SelectedBookmark = (TBookmark *)Selected->Data; + SelectedBookmark = static_cast(Selected->Data); if (SelectedBookmark != NULL) { SelectedNode = SelectedBookmark->Node; @@ -603,7 +603,7 @@ void __fastcall TLocationProfilesDialog::RemoveBookmark(TObject * Sender) TTreeNode * Node = ProfilesView->Selected; if (Node->Data) { - BookmarkList->Delete((TBookmark *)Node->Data); + BookmarkList->Delete(static_cast(Node->Data)); TTreeNode * ParentNode = Node->Parent; Node->Delete(); if (ParentNode && !ParentNode->Count) @@ -622,7 +622,7 @@ void __fastcall TLocationProfilesDialog::RemoveBookmark(TObject * Sender) DebugAssert(Node->Count); for (int i = 0; i < Node->Count; i++) { - BookmarkList->Delete((TBookmark *)Node->Item[i]->Data); + BookmarkList->Delete(static_cast(Node->Item[i]->Data)); } DebugAssert(Folders->IndexOfObject(Node) >= 0); Folders->Delete(Folders->IndexOfObject(Node)); @@ -646,7 +646,7 @@ void __fastcall TLocationProfilesDialog::BookmarkMove(TObject * Sender, DebugAssert(Source && Source->Data); - TBookmark * Bookmark = (TBookmark *)Source->Data; + TBookmark * Bookmark = static_cast(Source->Data); TTreeNode * PrevFolderNode = Source->Parent; if (!Dest || !Dest->Data) @@ -658,7 +658,7 @@ void __fastcall TLocationProfilesDialog::BookmarkMove(TObject * Sender, } else { - TBookmark * DestBookmark = (TBookmark *)Dest->Data; + TBookmark * DestBookmark = static_cast(Dest->Data); Bookmark->Node = DestBookmark->Node; BookmarkList->MoveTo(DestBookmark, Bookmark, @@ -839,8 +839,8 @@ void __fastcall TLocationProfilesDialog::ProfilesViewChange( FChanging = true; try { - LocalDirectoryEdit->Text = ((TBookmark *)Node->Data)->Local; - RemoteDirectoryEdit->Text = ((TBookmark *)Node->Data)->Remote; + LocalDirectoryEdit->Text = static_cast(Node->Data)->Local; + RemoteDirectoryEdit->Text = static_cast(Node->Data)->Remote; } __finally { @@ -859,7 +859,7 @@ void __fastcall TLocationProfilesDialog::BookmarkMoveToButtonClick(TObject * Sen TStringList * Folders = GetFolders(Sender); DebugAssert(ProfilesView->Selected->Data); - TBookmark * Bookmark = (TBookmark *)ProfilesView->Selected->Data; + TBookmark * Bookmark = static_cast(ProfilesView->Selected->Data); TBookmarkFolderDialog * Dialog = new TBookmarkFolderDialog(Folders); try @@ -983,7 +983,7 @@ void __fastcall TLocationProfilesDialog::ProfilesViewEdited( { BookmarkNameValidateName(S); // raises exception in case of duplicate name?? - ((TBookmark *)Node->Data)->Name = S; + static_cast(Node->Data)->Name = S; } else { @@ -1024,7 +1024,7 @@ void __fastcall TLocationProfilesDialog::ProfilesViewEdited( for (int i = 0; i < Node->Count; i++) { - ((TBookmark *)Node->Item[i]->Data)->Node = S; + static_cast(Node->Item[i]->Data)->Node = S; } Node->MakeVisible(); } diff --git a/source/forms/Login.cpp b/source/forms/Login.cpp index 652318afa..15e38d461 100644 --- a/source/forms/Login.cpp +++ b/source/forms/Login.cpp @@ -1719,7 +1719,7 @@ void __fastcall TLoginDialog::Dispatch(void * Message) DebugAssert(M); if (M->Msg == CM_DIALOGKEY) { - CMDialogKey(*((TWMKeyDown *)Message)); + CMDialogKey(*static_cast(Message)); } else if (M->Msg == WM_MANAGES_CAPTION) { diff --git a/source/forms/MessageDlg.cpp b/source/forms/MessageDlg.cpp index 8247f3b8a..7117ba5c7 100644 --- a/source/forms/MessageDlg.cpp +++ b/source/forms/MessageDlg.cpp @@ -38,7 +38,7 @@ void __fastcall TMessageButton::Dispatch(void * Message) TMessage * M = reinterpret_cast(Message); if (M->Msg == WM_GETDLGCODE) { - WMGetDlgCode(*((TWMGetDlgCode *)Message)); + WMGetDlgCode(*static_cast(Message)); } else { @@ -365,7 +365,7 @@ void __fastcall TMessageForm::Dispatch(void * Message) TMessage * M = reinterpret_cast(Message); if (M->Msg == CM_DIALOGKEY) { - CMDialogKey(*((TWMKeyDown *)Message)); + CMDialogKey(*static_cast(Message)); } else if (M->Msg == CM_SHOWINGCHANGED) { diff --git a/source/forms/NonVisual.cpp b/source/forms/NonVisual.cpp index eea2c7247..e1fb1d535 100644 --- a/source/forms/NonVisual.cpp +++ b/source/forms/NonVisual.cpp @@ -38,7 +38,7 @@ TNonVisualDataModule *NonVisualDataModule; ScpExplorer->ComponentVisible[fc ## COMP] = !ScpExplorer->ComponentVisible[fc ## COMP] ) #define EXECOMP(COMP) EXECOMP2(COMP, ) #define COLPROPS(SIDE) \ - ((TCustomDirViewColProperties*)ScpExplorer->DirView(os ## SIDE)->ColProperties) + (static_cast(ScpExplorer->DirView(os ## SIDE)->ColProperties)) #define UPDSORT(SIDE, NAME, LCOL, RCOL, NUM) \ UPDEX(SIDE ## SortBy ## NAME ## Action ## NUM, (AuxInt = (ScpExplorer->IsSideLocalBrowser(os ## SIDE) ? LCOL : RCOL)) >= 0, \ Action->Checked = (COLPROPS(SIDE)->SortColumn == AuxInt), \ @@ -384,7 +384,7 @@ void __fastcall TNonVisualDataModule::ExplorerActionsUpdate( UPDSORT(Current, Rights, dvAttr, uvRights, ) UPDSORT(Current, Owner, -1, uvOwner, ) UPDSORT(Current, Group, -1, uvGroup, ) - #define COLVIEWPROPS ((TCustomDirViewColProperties*)(((TCustomDirView*)(((TListColumns*)(ListColumn->Collection))->Owner()))->ColProperties)) + #define COLVIEWPROPS (static_cast(static_cast(static_cast(ListColumn->Collection)->Owner())->ColProperties)) UPDEX(SortColumnAscendingAction, (ListColumn != NULL), SortColumnAscendingAction->Checked = (COLVIEWPROPS->SortColumn == ListColumn->Index) && COLVIEWPROPS->SortAscending, ) UPDEX(SortColumnDescendingAction, (ListColumn != NULL), SortColumnDescendingAction->Checked = @@ -549,7 +549,7 @@ void __fastcall TNonVisualDataModule::ExplorerActionsExecute( EXE(NewLinkAction, ScpExplorer->AddEditLink(osCurrent, true)) EXE(CurrentRenameAction, ScpExplorer->ExecuteFileOperationCommand(foRename, osCurrent, false)) EXE(CurrentDeleteAction, ScpExplorer->ExecuteFileOperationCommand(foDelete, osCurrent, false)) - EXE(CurrentDeleteAlternativeAction, ScpExplorer->ExecuteFileOperationCommand(foDelete, osCurrent, false, false, (void*)true)) + EXE(CurrentDeleteAlternativeAction, ScpExplorer->ExecuteFileOperationCommand(foDelete, osCurrent, false, false, reinterpret_cast(true))) EXE(CurrentPropertiesAction, ScpExplorer->ExecuteFileOperationCommand(foSetProperties, osCurrent, false)) EXE(CurrentCopyToClipboardAction2, ScpExplorer->CopyFilesToClipboard(osCurrent, false)) EXE(FileListToCommandLineAction, ScpExplorer->PanelExport(osCurrent, peFileList, pedCommandLine)) @@ -631,7 +631,7 @@ void __fastcall TNonVisualDataModule::ExplorerActionsExecute( // style EXE(RemoteCycleStyleAction, if (DirView(osRemote)->DirViewStyle == dvsThumbnail) DirView(osRemote)->DirViewStyle = dvsIcon; - else DirView(osRemote)->DirViewStyle = (TDirViewStyle)(DirView(osRemote)->DirViewStyle + 1); + else DirView(osRemote)->DirViewStyle = static_cast(DirView(osRemote)->DirViewStyle + 1); ScpExplorer->UpdateControls(); ) #define STYLEACTION(SIDE, STYLE) EXE(SIDE ## STYLE ## Action, \ @@ -711,7 +711,7 @@ void __fastcall TNonVisualDataModule::ExplorerActionsExecute( EXE(GoToAddressAction, ScpExplorer->GoToAddress()) EXE(CustomizeToolbarAction, CreateToolbarButtonsList()) - #define COLVIEWPROPS ((TCustomDirViewColProperties*)(((TCustomDirView*)(((TListColumns*)(ListColumn->Collection))->Owner()))->ColProperties)) + #define COLVIEWPROPS (static_cast((static_cast((static_cast(ListColumn->Collection))->Owner()))->ColProperties)) // SORT EXESORTA(Local, 2) #define EXESORTL(NAME, COL, NUM) EXESORT(Local, NAME, COL, COL, NUM) @@ -1503,8 +1503,8 @@ void __fastcall TNonVisualDataModule::SessionFolderThisItemClick(TObject * Sende //--------------------------------------------------------------------------- void __fastcall TNonVisualDataModule::SessionItemClick(TObject * Sender) { - DebugAssert(StoredSessions && (((TTBCustomItem *)Sender)->Tag < StoredSessions->Count)); - ScpExplorer->OpenStoredSession(StoredSessions->Sessions[((TTBCustomItem *)Sender)->Tag]); + DebugAssert(StoredSessions && (static_cast(Sender)->Tag < StoredSessions->Count)); + ScpExplorer->OpenStoredSession(StoredSessions->Sessions[static_cast(Sender)->Tag]); } //--------------------------------------------------------------------------- void __fastcall TNonVisualDataModule::CreateWorkspacesMenu(TAction * Action) @@ -1545,7 +1545,7 @@ TShortCut __fastcall TNonVisualDataModule::OpenSessionShortCut(int Index) { if (Index >= 0 && Index < 10) { - return ShortCut((Word)(Index < 9 ? L'0' + 1 + Index : L'0'), + return ShortCut(static_cast(Index < 9 ? L'0' + 1 + Index : L'0'), TShiftState() << ssAlt); } else @@ -1583,7 +1583,7 @@ void __fastcall TNonVisualDataModule::CreateOpenedSessionListMenu(TAction * Acti //--------------------------------------------------------------------------- void __fastcall TNonVisualDataModule::OpenedSessionItemClick(TObject * Sender) { - TTerminalManager::Instance()->ActiveSession = (TManagedTerminal*)(((TMenuItem *)Sender)->Tag); + TTerminalManager::Instance()->ActiveSession = reinterpret_cast(static_cast(Sender)->Tag); } //--------------------------------------------------------------------------- void __fastcall TNonVisualDataModule::CreateEditorListMenu(TTBCustomItem * Menu, bool OnFocused) diff --git a/source/forms/Preferences.cpp b/source/forms/Preferences.cpp index f1154d00e..7932c467e 100644 --- a/source/forms/Preferences.cpp +++ b/source/forms/Preferences.cpp @@ -922,7 +922,7 @@ void __fastcall TPreferencesDialog::SaveConfiguration() BOOLPROP(ShowTips); // panels - WinConfiguration->DoubleClickAction = (TDoubleClickAction)DoubleClickActionCombo->ItemIndex; + WinConfiguration->DoubleClickAction = static_cast(DoubleClickActionCombo->ItemIndex); BOOLPROP(AutoReadDirectoryAfterOp); BOOLPROP(RefreshRemotePanel); WinConfiguration->RefreshRemotePanelInterval = @@ -2291,15 +2291,15 @@ void __fastcall TPreferencesDialog::Dispatch(void *Message) DebugAssert(M); if (M->Msg == CM_DIALOGKEY) { - CMDialogKey(*((TWMKeyDown *)Message)); + CMDialogKey(*static_cast(Message)); } else if (M->Msg == WM_HELP) { - WMHelp(*((TWMHelp *)Message)); + WMHelp(*static_cast(Message)); } else if (M->Msg == WM_ACTIVATE) { - WMActivate(*((TWMActivate *)Message)); + WMActivate(*static_cast(Message)); } else if (M->Msg == CM_FOCUSCHANGED) { diff --git a/source/forms/Progress.cpp b/source/forms/Progress.cpp index 28f0a6159..11602f18f 100644 --- a/source/forms/Progress.cpp +++ b/source/forms/Progress.cpp @@ -38,7 +38,7 @@ UnicodeString __fastcall TProgressForm::ProgressStr( PROGRESS_SETPROPERTIES, 0, PROGRESS_CUSTOM_COMAND, PROGRESS_CALCULATE_SIZE, PROGRESS_REMOTE_MOVE, PROGRESS_REMOTE_COPY, PROGRESS_GETPROPERTIES, PROGRESS_CALCULATE_CHECKSUM, PROGRESS_LOCK, PROGRESS_UNLOCK }; - DebugAssert((unsigned int)ProgressData->Operation >= 1 && ((unsigned int)ProgressData->Operation - 1) < std::size(Captions)); + DebugAssert(static_cast(ProgressData->Operation) >= 1 && (static_cast(ProgressData->Operation) - 1) < std::size(Captions)); int Id; if (ProgressData->IsTransfer()) { @@ -46,7 +46,7 @@ UnicodeString __fastcall TProgressForm::ProgressStr( } else { - Id = Captions[(int)ProgressData->Operation - 1]; + Id = Captions[static_cast(ProgressData->Operation) - 1]; DebugAssert(Id != 0); } UnicodeString Result = LoadStr(Id); @@ -75,7 +75,7 @@ __fastcall TProgressForm::TProgressForm( : TForm(AOwner), FData() { FLastOperation = foNone; - FLastSide = (TOperationSide)-1; + FLastSide = static_cast(-1); FLastTotalSizeSet = false; FDataGot = false; FDataReceived = false; diff --git a/source/forms/Properties.cpp b/source/forms/Properties.cpp index 191cabe1e..97ae89049 100644 --- a/source/forms/Properties.cpp +++ b/source/forms/Properties.cpp @@ -217,7 +217,7 @@ void __fastcall TPropertiesDialog::LoadInfo() for (int Index = 0; Index < FFileList->Count; Index++) { - TRemoteFile * File = (TRemoteFile *)(FFileList->Objects[Index]); + TRemoteFile * File = static_cast(FFileList->Objects[Index]); if (File->IsDirectory) { Stats.Directories++; @@ -263,7 +263,7 @@ void __fastcall TPropertiesDialog::LoadInfo() if (!FMultiple) { - TRemoteFile * File = (TRemoteFile *)(FFileList->Objects[0]); + TRemoteFile * File = static_cast(FFileList->Objects[0]); DebugAssert(File); UpdateFileImage(); @@ -297,7 +297,7 @@ void __fastcall TPropertiesDialog::UpdateFileImage() FileIconImage->Picture->Bitmap = NULL; - TRemoteFile * File = (TRemoteFile *)(FFileList->Objects[0]); + TRemoteFile * File = static_cast(FFileList->Objects[0]); // shell image list does not have fixed large icon size // (it is probably 32x32 min, but can be larger, on xp it is 48x48 if @@ -346,7 +346,7 @@ void __fastcall TPropertiesDialog::LoadStats(__int64 FilesSize, if (((Stats.Files + Stats.Directories) == 0) && !FMultiple) { - TRemoteFile * File = (TRemoteFile *)(FFileList->Objects[0]); + TRemoteFile * File = static_cast(FFileList->Objects[0]); DebugAssert(File != NULL); FilesStr = File->FileName; } diff --git a/source/forms/Rights.cpp b/source/forms/Rights.cpp index cebfbe2c2..dddadb17c 100644 --- a/source/forms/Rights.cpp +++ b/source/forms/Rights.cpp @@ -142,7 +142,7 @@ TCheckBox * __fastcall TRightsFrame::GetChecks(TRights::TRight Right) if (Controls[Index]->InheritsFrom(__classid(TCheckBox)) && (Controls[Index]->Tag == TRights::RightToFlag(Right))) { - return ((TCheckBox *)Controls[Index]); + return static_cast(Controls[Index]); } } return NULL; @@ -593,19 +593,19 @@ void __fastcall TRightsFrame::Dispatch(void * Message) switch (AMessage.Msg) { case CM_CANCELMODE: - CMCancelMode(*(TCMCancelMode *)Message); + CMCancelMode(*static_cast(Message)); break; case CM_DIALOGKEY: - CMDialogKey(*(TCMDialogKey *)Message); + CMDialogKey(*static_cast(Message)); break; case CM_DIALOGCHAR: - CMDialogChar(*(TCMDialogChar *)Message); + CMDialogChar(*static_cast(Message)); break; case WM_CONTEXTMENU: - WMContextMenu(*(TWMContextMenu *)Message); + WMContextMenu(*static_cast(Message)); break; case CM_DPICHANGED: diff --git a/source/forms/ScpCommander.cpp b/source/forms/ScpCommander.cpp index 9e7715b0f..5a1e3b91f 100644 --- a/source/forms/ScpCommander.cpp +++ b/source/forms/ScpCommander.cpp @@ -156,7 +156,7 @@ void __fastcall TScpCommanderForm::RestorePanelParams( const TScpCommanderPanelConfiguration & PanelConfiguration) { DirView->ColProperties->ParamsStr = PanelConfiguration.DirViewParams; - DirView->DirViewStyle = (TDirViewStyle)PanelConfiguration.ViewStyle; + DirView->DirViewStyle = static_cast(PanelConfiguration.ViewStyle); StatusBar->Visible = PanelConfiguration.StatusBar; DriveControl->Visible = PanelConfiguration.DriveView; if (DriveControl->Align == alTop) @@ -186,7 +186,7 @@ void __fastcall TScpCommanderForm::RestoreParams() RestorePanelParams(LocalDirView, LocalDriveView, LocalStatusBar, WinConfiguration->ScpCommander.LocalPanel); RestorePanelParams(RemoteDirView, RemoteDrivePanel, RemoteStatusBar, WinConfiguration->ScpCommander.RemotePanel); OtherLocalDirView->ColProperties->ParamsStr = WinConfiguration->ScpCommander.OtherLocalPanelDirViewParams; - OtherLocalDirView->DirViewStyle = (TDirViewStyle)WinConfiguration->ScpCommander.OtherLocalPanelViewStyle; + OtherLocalDirView->DirViewStyle = static_cast(WinConfiguration->ScpCommander.OtherLocalPanelViewStyle); FPanelsRestored = true; // just to make sure @@ -452,7 +452,7 @@ void TScpCommanderForm::NewTab(TOperationSide Side, bool AllowReverse) //--------------------------------------------------------------------------- Boolean __fastcall TScpCommanderForm::AllowedAction(TAction * Action, TActionAllowed Allowed) { - #define FLAG ((TActionFlag)(Action->Tag)) + #define FLAG (static_cast(Action->Tag)) return TCustomScpExplorerForm::AllowedAction(Action, Allowed) && // always require Commander flag @@ -1266,7 +1266,7 @@ void __fastcall TScpCommanderForm::FullSynchronizeDirectories() UnicodeString Directory2 = DirView(osOther)->PathName; bool SaveMode = !(GUIConfiguration->SynchronizeModeAuto < 0); TSynchronizeMode Mode = - (SaveMode ? (TSynchronizeMode)GUIConfiguration->SynchronizeModeAuto : + (SaveMode ? static_cast(GUIConfiguration->SynchronizeModeAuto) : ((FCurrentSide == osLocal) ? smRemote : smLocal)); int Params = GUIConfiguration->SynchronizeParams; if (DoFullSynchronizeDirectories(Directory1, Directory2, Mode, Params, SaveMode, -1) >= 0) @@ -1618,7 +1618,7 @@ void __fastcall TScpCommanderForm::AddEditLink(TOperationSide Side, bool Add) if (ADirView->ItemFocused != NULL) { DebugAssert(ADirView->ItemFocused->Data); - PFileRec FileRec = (PFileRec)ADirView->ItemFocused->Data; + PFileRec FileRec = static_cast(ADirView->ItemFocused->Data); Edit = !Add && (UpperCase(FileRec->FileExt) == L"LNK"); if (Edit) @@ -2213,11 +2213,11 @@ void TScpCommanderForm::LocalPathComboUpdateDrives( LocalPathComboBoxPaths->Clear(); Strings->Add(LoadStr(SPECIAL_FOLDER_MY_DOCUMENTS)); LocalPathComboBoxPaths->AddObject( - GetPersonalFolder(), (TObject *)DriveInfo->SpecialFolder[CSIDL_PERSONAL]->ImageIndex); + GetPersonalFolder(), reinterpret_cast(DriveInfo->SpecialFolder[CSIDL_PERSONAL]->ImageIndex)); LocalSpecialPaths++; Strings->Add(LoadStr(SPECIAL_FOLDER_DESKTOP)); LocalPathComboBoxPaths->AddObject( - GetDesktopFolder(), (TObject *)DriveInfo->SpecialFolder[CSIDL_DESKTOP]->ImageIndex); + GetDesktopFolder(), reinterpret_cast(DriveInfo->SpecialFolder[CSIDL_DESKTOP]->ImageIndex)); LocalSpecialPaths++; DebugAssert((FLocalSpecialPaths == 0) || (FLocalSpecialPaths == LocalSpecialPaths)); FLocalSpecialPaths = LocalSpecialPaths; diff --git a/source/forms/ScpExplorer.cpp b/source/forms/ScpExplorer.cpp index 46cc9ee38..32fde3d21 100644 --- a/source/forms/ScpExplorer.cpp +++ b/source/forms/ScpExplorer.cpp @@ -78,7 +78,7 @@ void __fastcall TScpExplorerForm::RestoreParams() bool HadHandleAllocated = RemoteDirView->HandleAllocated(); RemoteDirView->UnixColProperties->ParamsStr = WinConfiguration->ScpExplorer.DirViewParams; RemoteDirView->UnixColProperties->ExtVisible = false; // just to make sure - RemoteDirView->DirViewStyle = (TDirViewStyle)WinConfiguration->ScpExplorer.ViewStyle; + RemoteDirView->DirViewStyle = static_cast(WinConfiguration->ScpExplorer.ViewStyle); if (HadHandleAllocated) { // This is here to make our persistence checks in VerifyControl pass, @@ -186,7 +186,7 @@ bool __fastcall TScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Action->Visible = false; } } - #define FLAG ((TActionFlag)(Action->Tag)) + #define FLAG (static_cast(Action->Tag)) return TCustomScpExplorerForm::AllowedAction(Action, Allowed) && // always require Explorer flag @@ -238,7 +238,7 @@ void __fastcall TScpExplorerForm::FullSynchronizeDirectories() UnicodeString LocalDirectory = WinConfiguration->ScpExplorer.LastLocalTargetDirectory; UnicodeString RemoteDirectory = RemoteDirView->PathName; bool SaveMode = true; - TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode; + TSynchronizeMode Mode = static_cast(GUIConfiguration->SynchronizeMode); int Params = GUIConfiguration->SynchronizeParams; if (DoFullSynchronizeDirectories(LocalDirectory, RemoteDirectory, Mode, Params, SaveMode, -1) >= 0) { diff --git a/source/forms/SiteAdvanced.cpp b/source/forms/SiteAdvanced.cpp index 5ac51670d..92ed9c688 100644 --- a/source/forms/SiteAdvanced.cpp +++ b/source/forms/SiteAdvanced.cpp @@ -256,7 +256,7 @@ void __fastcall TSiteAdvancedDialog::LoadSession() { CipherListBox->Items->AddObject( LoadStr(CIPHER_NAME_WARN+FSessionData->Cipher[Index]), - (TObject*)FSessionData->Cipher[Index]); + reinterpret_cast(FSessionData->Cipher[Index])); } // KEX page @@ -267,7 +267,7 @@ void __fastcall TSiteAdvancedDialog::LoadSession() { KexListBox->Items->AddObject( LoadStr(KEX_NAME_WARN+FSessionData->Kex[Index]), - (TObject*)FSessionData->Kex[Index]); + reinterpret_cast(FSessionData->Kex[Index])); } AuthGSSAPIKEXCheck->Checked = FSessionData->AuthGSSAPIKEX; @@ -425,7 +425,7 @@ void __fastcall TSiteAdvancedDialog::LoadSession() WebDavLiberalEscapingCheck->Checked = FSessionData->WebDavLiberalEscaping; // color - FColor = (TColor)FSessionData->Color; + FColor = static_cast(FSessionData->Color); } EnableControl(PuttyGroup, !DoesSessionExistInPutty(FSessionData->StorageKey)); @@ -672,7 +672,7 @@ void __fastcall TSiteAdvancedDialog::SaveSession(TSessionData * SessionData) SessionData->ProxyTelnetCommand = ProxyTelnetCommandEdit->Text; SessionData->ProxyLocalCommand = ProxyLocalCommandEdit->Text; SessionData->ProxyLocalhost = ProxyLocalhostCheck->Checked; - SessionData->ProxyDNS = (TAutoSwitch)(2 - ProxyDNSCombo->ItemIndex); + SessionData->ProxyDNS = static_cast(2 - ProxyDNSCombo->ItemIndex); // Bugs page #define SAVE_BUG_COMBO(BUG) SessionData->Bug[sb ## BUG] = ComboAutoSwitchSave(Bug ## BUG ## Combo) @@ -1262,11 +1262,11 @@ void __fastcall TSiteAdvancedDialog::Dispatch(void * Message) DebugAssert(M); if (M->Msg == CM_DIALOGKEY) { - CMDialogKey(*((TWMKeyDown *)Message)); + CMDialogKey(*static_cast(Message)); } else if (M->Msg == WM_HELP) { - WMHelp(*((TWMHelp *)Message)); + WMHelp(*static_cast(Message)); } else { @@ -1472,13 +1472,13 @@ TProxyMethod __fastcall TSiteAdvancedDialog::GetProxyMethod() TFSProtocol FSProtocol = FSessionData->FSProtocol; if (FSessionData->UsesSsh) { - Result = (TProxyMethod)SshProxyMethodCombo->ItemIndex; + Result = static_cast(SshProxyMethodCombo->ItemIndex); } else if (FSProtocol == fsFTP) { if (SupportedFtpProxyMethod(FtpProxyMethodCombo->ItemIndex)) { - Result = (TProxyMethod)FtpProxyMethodCombo->ItemIndex; + Result = static_cast(FtpProxyMethodCombo->ItemIndex); } else { @@ -1487,7 +1487,7 @@ TProxyMethod __fastcall TSiteAdvancedDialog::GetProxyMethod() } else if (IsNeon(FSProtocol)) { - Result = (TProxyMethod)NeonProxyMethodCombo->ItemIndex; + Result = static_cast(NeonProxyMethodCombo->ItemIndex); } else { diff --git a/source/packages/filemng/CustomDirView.pas b/source/packages/filemng/CustomDirView.pas index 302781e19..b4acde856 100644 --- a/source/packages/filemng/CustomDirView.pas +++ b/source/packages/filemng/CustomDirView.pas @@ -15,7 +15,7 @@ uses IEListView, PathLabel, SysUtils, PasTools; const - clDefaultItemColor = -(COLOR_ENDCOLORS + 1); + clDefaultItemColor: TColor = -(COLOR_ENDCOLORS + 1); WM_USER_RENAME = WM_USER + 57; WM_USER_INVALIDATEITEM = WM_USER + $2000 + 16; oiNoOverlay = $00; diff --git a/source/windows/GUIConfiguration.cpp b/source/windows/GUIConfiguration.cpp index 256e1212f..550ac5675 100644 --- a/source/windows/GUIConfiguration.cpp +++ b/source/windows/GUIConfiguration.cpp @@ -1047,7 +1047,7 @@ void __fastcall TGUIConfiguration::SetAppliedLocale(LCID AppliedLocale, const Un void __fastcall TGUIConfiguration::FreeResourceModule(HANDLE Instance) { TLibModule * MainModule = FindModule(HInstance); - if ((unsigned)Instance != MainModule->Instance) + if (reinterpret_cast(Instance) != MainModule->Instance) { FreeLibrary(static_cast(Instance)); } @@ -1065,15 +1065,15 @@ HANDLE __fastcall TGUIConfiguration::ChangeResourceModule(HANDLE Instance) Instance = HInstance; } TLibModule * MainModule = FindModule(HInstance); - HANDLE Result = (HANDLE)MainModule->ResInstance; - MainModule->ResInstance = (unsigned)Instance; + HANDLE Result = reinterpret_cast(MainModule->ResInstance); + MainModule->ResInstance = reinterpret_cast(Instance); CoreSetResourceModule(Instance); return Result; } //--------------------------------------------------------------------------- HANDLE __fastcall TGUIConfiguration::GetResourceModule() { - return (HANDLE)FindModule(HInstance)->ResInstance; + return reinterpret_cast(FindModule(HInstance)->ResInstance); } //--------------------------------------------------------------------------- void __fastcall TGUIConfiguration::SetResourceModule(HINSTANCE Instance) @@ -1403,7 +1403,7 @@ TStoredSessionList * __fastcall TGUIConfiguration::SelectPuttySessionsForImport( } TSessionData * PuttySessionData = - (TSessionData *)ImportSessionList->FindByName(PuttySession); + static_cast(ImportSessionList->FindByName(PuttySession)); if (PuttySessionData != NULL) { ImportSessionList->Remove(PuttySessionData); diff --git a/source/windows/GUITools.cpp b/source/windows/GUITools.cpp index fb1f9666a..2aa5c28ea 100644 --- a/source/windows/GUITools.cpp +++ b/source/windows/GUITools.cpp @@ -1396,11 +1396,11 @@ protected: HRESULT Result = S_OK; if (ClassId == IID_IUnknown) { - *Intf = (IUnknown *)this; + *Intf = static_cast(this); } else if (ClassId == ::IID_IDocHostUIHandler) { - *Intf = (::IDocHostUIHandler *)this; + *Intf = static_cast<::IDocHostUIHandler *>(this); } else { @@ -1748,7 +1748,7 @@ void LoadBrowserDocument(TWebBrowserEx * WebBrowser, const UnicodeString & Docum TStreamAdapter * DocumentStreamAdapter = new TStreamAdapter(DocumentStream.get(), soReference); IPersistStreamInit * PersistStreamInit = NULL; if (DebugAlwaysTrue(WebBrowser->Document != NULL) && - SUCCEEDED(WebBrowser->Document->QueryInterface(IID_IPersistStreamInit, (void **)&PersistStreamInit)) && + SUCCEEDED(WebBrowser->Document->QueryInterface(IID_IPersistStreamInit, reinterpret_cast(&PersistStreamInit))) && DebugAlwaysTrue(PersistStreamInit != NULL)) { PersistStreamInit->Load(static_cast<_di_IStream>(*DocumentStreamAdapter)); @@ -1797,7 +1797,7 @@ void __fastcall GetInstrutionsTheme( } if (GetThemeColor(Theme, TEXT_MAININSTRUCTION, 0, TMT_TEXTCOLOR, &AColor) == S_OK) { - MainInstructionColor = (TColor)AColor; + MainInstructionColor = static_cast(AColor); } memset(&AFont, 0, sizeof(AFont)); diff --git a/source/windows/Setup.cpp b/source/windows/Setup.cpp index 2fdcdd4d1..f3e0798d4 100644 --- a/source/windows/Setup.cpp +++ b/source/windows/Setup.cpp @@ -67,7 +67,7 @@ LPTSTR unquote(LPCTSTR str){ last_pos = _tcslen(str) - 1; if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){ new_len= (_tcslen(str) - 1); - ret = (LPTSTR)malloc(new_len * sizeof(TCHAR)); + ret = static_cast(malloc(new_len * sizeof(TCHAR))); lstrcpyn(ret, &str[1], new_len); } else @@ -128,7 +128,7 @@ void path_reg_propagate() { DWORD send_message_result; LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, - (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG, + reinterpret_cast(_T("Environment")), SMTO_ABORTIFHUNG, 5000, &send_message_result); if (ret != ERROR_SUCCESS && GetLastError() != 0) { @@ -160,8 +160,8 @@ BOOL add_path_reg(LPCTSTR path){ RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size); data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already includes '\0'. */ - reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR)); - ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str, + reg_str = static_cast(malloc(data_size * sizeof(TCHAR))); + ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, reinterpret_cast(reg_str), &data_size); if (ret != ERROR_SUCCESS){ err_out_sys(_T("Cannot read \"PATH\" key."), ret); @@ -186,7 +186,7 @@ BOOL add_path_reg(LPCTSTR path){ else { ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ, - (LPBYTE)reg_str, + reinterpret_cast(reg_str), (_tcslen(reg_str) + 1) * sizeof(TCHAR)); if (ret != ERROR_SUCCESS){ err_out_sys(_T("Cannot write \"PATH\" key."), ret); @@ -229,23 +229,23 @@ BOOL remove_path_reg(LPCTSTR path){ RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size); data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already includes '\0'. */ - reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR)); + reg_str = static_cast(malloc(data_size * sizeof(TCHAR))); ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, - (LPBYTE)reg_str, &data_size); + reinterpret_cast(reg_str), &data_size); if (ret != ERROR_SUCCESS){ err_out_sys(_T("Cannot read \"PATH\" key."), ret); func_ret = FALSE; } else{ if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){ - reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR)); + reg_str2 = static_cast(malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR))); *del_part = '\0'; _stprintf(reg_str2, _T("%s%s"), reg_str, next); last_pos = _tcslen(reg_str2) - 1; if (last_pos != -1 && reg_str2[last_pos] == ';') reg_str2[last_pos] = '\0'; ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ, - (LPBYTE)reg_str2, + reinterpret_cast(reg_str2), (_tcslen(reg_str2) + 1) * sizeof(TCHAR)); if (ret != ERROR_SUCCESS){ err_out_sys(_T("Cannot write \"PATH\" key."), ret); @@ -1933,7 +1933,7 @@ void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceName { IShellLink * Link; wchar_t Desc[2048]; - if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) && + if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, reinterpret_cast(&Link))) && SUCCEEDED(Link->GetDescription(Desc, std::size(Desc) - 1))) { Removed->Add(Desc); diff --git a/source/windows/TerminalManager.cpp b/source/windows/TerminalManager.cpp index 71ebee468..b16d1059e 100644 --- a/source/windows/TerminalManager.cpp +++ b/source/windows/TerminalManager.cpp @@ -16,7 +16,7 @@ __fastcall TManagedTerminal::TManagedTerminal(TSessionData * SessionData, TConfiguration * Configuration) : TTerminal(SessionData, Configuration), LocalBrowser(false), LocalExplorerState(NULL), RemoteExplorerState(NULL), OtherLocalExplorerState(NULL), - ReopenStart(0), DirectoryLoaded(Now()), TerminalThread(NULL), Disconnected(false), DisconnectedTemporarily(false), + ReopenStart(), DirectoryLoaded(Now()), TerminalThread(NULL), Disconnected(false), DisconnectedTemporarily(false), ThumbnailsSection(new TCriticalSection()), ThumbnailsEnabled(false), ThumbnailDownloadQueueItem(NULL), ThumbnailVisibleResult(-1) { @@ -374,7 +374,7 @@ void TTerminalManager::ReconnectingTerminal(TManagedTerminal * ManagedTerminal) ManagedTerminal->OrigRemoteDirectory = ManagedTerminal->SessionData->RemoteDirectory; ManagedTerminal->SessionData->RemoteDirectory = ManagedTerminal->StateData->RemoteDirectory; - if ((double)ManagedTerminal->ReopenStart == 0) + if (ManagedTerminal->ReopenStart == TDateTime()) { ManagedTerminal->ReopenStart = Now(); } @@ -385,7 +385,7 @@ void TTerminalManager::ReconnectedTerminal(TManagedTerminal * ManagedTerminal) ManagedTerminal->SessionData->RemoteDirectory = ManagedTerminal->OrigRemoteDirectory; if (ManagedTerminal->Active) { - ManagedTerminal->ReopenStart = 0; + ManagedTerminal->ReopenStart = TDateTime(); ManagedTerminal->Permanent = true; } } @@ -1238,7 +1238,7 @@ void __fastcall TTerminalManager::InitTaskbarButtonCreatedMessage() HINSTANCE User32Library = LoadLibrary(L"user32.dll"); ChangeWindowMessageFilterExProc ChangeWindowMessageFilterEx = - (ChangeWindowMessageFilterExProc)GetProcAddress(User32Library, "ChangeWindowMessageFilterEx"); + reinterpret_cast(GetProcAddress(User32Library, "ChangeWindowMessageFilterEx")); if (ChangeWindowMessageFilterEx != NULL) { diff --git a/source/windows/Tools.cpp b/source/windows/Tools.cpp index 526dc3fc2..d1336ebe6 100644 --- a/source/windows/Tools.cpp +++ b/source/windows/Tools.cpp @@ -59,7 +59,7 @@ TFontStyles __fastcall IntToFontStyles(int value) { if (value & 1) { - Result << (TFontStyle)i; + Result << static_cast(i); } value >>= 1; } @@ -72,7 +72,7 @@ int __fastcall FontStylesToInt(const TFontStyles value) for (int i = fsStrikeOut; i >= fsBold; i--) { Result <<= 1; - if (value.Contains((TFontStyle)i)) + if (value.Contains(static_cast(i))) { Result |= 1; } @@ -229,7 +229,7 @@ void RestoreForm(const UnicodeString & AData, TForm * Form, bool PositionOnly, c { CutToChar(Data, FormDataSep, true); } - TWindowState State = (TWindowState)StrToIntDef(CutToChar(Data, FormDataSep, true), (int)wsNormal); + TWindowState State = static_cast(StrToIntDef(CutToChar(Data, FormDataSep, true), static_cast(wsNormal))); int PixelsPerInch = LoadPixelsPerInch(CutToChar(Data, FormDataSep, true), Form); TRect OriginalBounds = Form->BoundsRect; @@ -338,7 +338,7 @@ UnicodeString __fastcall StoreForm(TForm * Form) FORMAT(L"%d;%d;%d;%d;%d;%s", (SaveDimension(Bounds.Left), SaveDimension(Bounds.Top), SaveDimension(Bounds.Right), SaveDimension(Bounds.Bottom), // we do not want WinSCP to start minimized next time (we cannot handle that anyway). - (int)(Form->WindowState == wsMinimized ? GetWindowStateBeforeMimimize(Form) : Form->WindowState), + static_cast(Form->WindowState == wsMinimized ? GetWindowStateBeforeMimimize(Form) : Form->WindowState), SavePixelsPerInch(Form))); return Result; } @@ -706,7 +706,7 @@ void __fastcall ExitActiveControl(TForm * Form) { if (Form->ActiveControl != NULL) { - TNotifyEvent OnExit = ((TEdit*)Form->ActiveControl)->OnExit; + TNotifyEvent OnExit = static_cast(Form->ActiveControl)->OnExit; if (OnExit != NULL) { OnExit(Form->ActiveControl); @@ -760,8 +760,9 @@ void __fastcall OpenBrowser(UnicodeString URL) //--------------------------------------------------------------------------- void __fastcall OpenFolderInExplorer(const UnicodeString & Path) { - if ((int)ShellExecute(Application->Handle, L"explore", - static_cast(Path.data()), NULL, NULL, SW_SHOWNORMAL) <= 32) + auto PathStr = static_cast(Path.data()); + int Result = reinterpret_cast(ShellExecute(Application->Handle, L"explore", PathStr, NULL, NULL, SW_SHOWNORMAL)); + if (Result <= 32) { throw Exception(FMTLOAD(EXPLORE_LOCAL_DIR_ERROR, (Path))); } @@ -1188,7 +1189,7 @@ static void __fastcall AcquireShutDownPrivileges() Priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process. - Win32Check(AdjustTokenPrivileges(Token, FALSE, &Priv, 0, (PTOKEN_PRIVILEGES)NULL, 0)); + Win32Check(AdjustTokenPrivileges(Token, FALSE, &Priv, 0, nullptr, 0)); } //--------------------------------------------------------------------------- void __fastcall ShutDownWindows() @@ -1453,7 +1454,7 @@ bool __fastcall DetectSystemExternalEditor( else { unsigned int File = FileCreate(ApiPath(TempName)); - if (File == (unsigned int)INVALID_HANDLE_VALUE) + if (File == reinterpret_cast(INVALID_HANDLE_VALUE)) { TryNextTime = true; UsageState = "F"; diff --git a/source/windows/UserInterface.cpp b/source/windows/UserInterface.cpp index f00817325..c78f87e64 100644 --- a/source/windows/UserInterface.cpp +++ b/source/windows/UserInterface.cpp @@ -290,7 +290,7 @@ void __fastcall ShowExtendedExceptionEx(TTerminal * Terminal, TMessageParams Params; if (DebugAlwaysTrue(Manager->ActiveTerminal != NULL) && ((Configuration->SessionReopenTimeout == 0) || - ((double)Manager->ActiveTerminal->ReopenStart == 0) || + (Manager->ActiveTerminal->ReopenStart == TDateTime()) || (int(double(Now() - Manager->ActiveTerminal->ReopenStart) * MSecsPerDay) < Configuration->SessionReopenTimeout))) { Params.Timeout = GUIConfiguration->SessionReopenAutoIdleOn ? GUIConfiguration->SessionReopenAutoIdle : 0; diff --git a/source/windows/VCLCommon.cpp b/source/windows/VCLCommon.cpp index 38044df71..b57061aa4 100644 --- a/source/windows/VCLCommon.cpp +++ b/source/windows/VCLCommon.cpp @@ -276,7 +276,7 @@ void __fastcall EnableControl(TControl * Control, bool Enable) // But we do not use this code anymore for the main window anyway. Color = DarkMode ? GetBtnFaceColor() : clBtnFace; } - ((TEdit*)Control)->Color = Color; + static_cast(Control)->Color = Color; } }; //--------------------------------------------------------------------------- @@ -1573,7 +1573,7 @@ void __fastcall ComboAutoSwitchLoad(TComboBox * ComboBox, TAutoSwitch Value) //--------------------------------------------------------------------------- TAutoSwitch __fastcall ComboAutoSwitchSave(TComboBox * ComboBox) { - return (TAutoSwitch)(2 - ComboBox->ItemIndex); + return static_cast(2 - ComboBox->ItemIndex); } //--------------------------------------------------------------------------- void __fastcall CheckBoxAutoSwitchLoad(TCheckBox * CheckBox, TAutoSwitch Value) @@ -1763,7 +1763,7 @@ void __fastcall InstallPathWordBreakProc(TWinControl * Control) { Wnd = Control->Handle; } - SendMessage(Wnd, EM_SETWORDBREAKPROC, 0, (LPARAM)(EDITWORDBREAKPROC)PathWordBreakProc); + SendMessage(Wnd, EM_SETWORDBREAKPROC, 0, reinterpret_cast(static_cast(PathWordBreakProc))); TPathWordBreakProcComponent * PathWordBreakProcComponent = new TPathWordBreakProcComponent(); PathWordBreakProcComponent->Name = TPathWordBreakProcComponent::QualifiedClassName(); @@ -2307,7 +2307,7 @@ static void __fastcall HintLabelWindowProc(void * Data, TMessage & Message) if (Message.Msg == CM_CANCELMODE) { - TCMCancelMode & CancelMessage = (TCMCancelMode&)Message; + TCMCancelMode & CancelMessage = reinterpret_cast(Message); if ((CancelMessage.Sender != StaticText) && (CancelMessage.Sender != PersistentHintWindow)) { diff --git a/source/windows/WinConfiguration.cpp b/source/windows/WinConfiguration.cpp index d1429a1f6..c49850ae2 100644 --- a/source/windows/WinConfiguration.cpp +++ b/source/windows/WinConfiguration.cpp @@ -177,7 +177,7 @@ void __fastcall TEditorPreferences::Load(THierarchicalStorage * Storage, bool Le { FData.FileMask = Storage->ReadString(L"FileMask", FData.FileMask.Masks); } - FData.Editor = (TEditor)Storage->ReadInteger(L"Editor", FData.Editor); + FData.Editor = static_cast(Storage->ReadInteger(L"Editor", FData.Editor)); FData.ExternalEditor = Storage->ReadString(L"ExternalEditor", FData.ExternalEditor); FData.ExternalEditorText = Storage->ReadBool(L"ExternalEditorText", FData.ExternalEditorText); FData.SDIExternalEditor = Storage->ReadBool(L"SDIExternalEditor", FData.SDIExternalEditor); @@ -3788,7 +3788,7 @@ void __fastcall TCustomCommandList::Load(THierarchicalStorage * Storage) for (int Index = 0; Index < FCommands->Count; Index++) { TCustomCommandType * Command = GetCommand(Index); - Command->ShortCut = (Word)Storage->ReadInteger(Command->Name, Command->ShortCut); + Command->ShortCut = static_cast(Storage->ReadInteger(Command->Name, Command->ShortCut)); } Storage->CloseSubKey(); } diff --git a/source/windows/WinInterface.cpp b/source/windows/WinInterface.cpp index 904836be9..a1466e471 100644 --- a/source/windows/WinInterface.cpp +++ b/source/windows/WinInterface.cpp @@ -201,7 +201,7 @@ TForm * __fastcall CreateMessageDialogEx(const UnicodeString Msg, { NeverAskAgainCaption = !Params->NeverAskAgainTitle.IsEmpty() ? - (UnicodeString)Params->NeverAskAgainTitle : + Params->NeverAskAgainTitle : // qaOK | qaIgnore is used, when custom "non-answer" button is required LoadStr(((ActualAnswers == qaOK) || (ActualAnswers == (qaOK | qaIgnore))) ? NEVER_SHOW_AGAIN : NEVER_ASK_AGAIN); @@ -1518,7 +1518,7 @@ __fastcall ::TTrayIcon::TTrayIcon(unsigned int Id) if (DebugAlwaysTrue(ComCtl32Dll)) { typedef HRESULT WINAPI (* TLoadIconMetric)(HINSTANCE hinst, PCWSTR pszName, int lims, __out HICON *phico); - TLoadIconMetric LoadIconMetric = (TLoadIconMetric)GetProcAddress(ComCtl32Dll, "LoadIconMetric"); + TLoadIconMetric LoadIconMetric = reinterpret_cast(GetProcAddress(ComCtl32Dll, "LoadIconMetric")); if (LoadIconMetric != NULL) { // Prefer not to use Application->Icon->Handle as that shows 32x32 scaled down to 16x16 for some reason @@ -1634,14 +1634,14 @@ void __fastcall ::TTrayIcon::CancelBalloon() //--------------------------------------------------------------------------- bool __fastcall ::TTrayIcon::Notify(unsigned int Message) { - bool Result = SUCCEEDED(Shell_NotifyIcon(Message, (NOTIFYICONDATA*)FTrayIcon)); + bool Result = SUCCEEDED(Shell_NotifyIcon(Message, FTrayIcon)); if (Result && (Message == NIM_ADD)) { UINT Timeout = FTrayIcon->uTimeout; try { FTrayIcon->uVersion = NOTIFYICON_VERSION; - Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, (NOTIFYICONDATA*)FTrayIcon)); + Result = SUCCEEDED(Shell_NotifyIcon(NIM_SETVERSION, FTrayIcon)); } __finally { diff --git a/source/windows/WinMain.cpp b/source/windows/WinMain.cpp index 9ce845c2a..5c6e339e5 100644 --- a/source/windows/WinMain.cpp +++ b/source/windows/WinMain.cpp @@ -246,13 +246,13 @@ void __fastcall FullSynchronize( bool SaveMode = true; // bit ugly - TSynchronizeMode Mode = (TSynchronizeMode)GUIConfiguration->SynchronizeMode; + TSynchronizeMode Mode = static_cast(GUIConfiguration->SynchronizeMode); int Params = GUIConfiguration->SynchronizeParams; // Undocumented syntax for "Start in New Window" if (CommandParams->Count >= 4) { - Mode = (TSynchronizeMode)StrToIntDef(CommandParams->Strings[2], Mode); + Mode = static_cast(StrToIntDef(CommandParams->Strings[2], Mode)); Params = StrToIntDef(CommandParams->Strings[3], Params); }