From 9ecbbe471bbeb42a732aae8e5f8b04dd424d05c7 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Fri, 14 May 2021 15:38:59 -0600 Subject: [PATCH] Remove lots of unused things from CrySystem (#765) Remove lots of unused things from CrySystem --- Code/CryEngine/CryCommon/ILZ4Decompressor.h | 32 - Code/CryEngine/CryCommon/ISystem.h | 104 - Code/CryEngine/CryCommon/ITextModeConsole.h | 35 - Code/CryEngine/CryCommon/IZLibCompressor.h | 219 - Code/CryEngine/CryCommon/IZStdDecompressor.h | 25 - Code/CryEngine/CryCommon/IZlibDecompressor.h | 94 - Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 35 - Code/CryEngine/CryCommon/ProjectDefines.h | 2 - Code/CryEngine/CryCommon/RenderBus.h | 8 - .../CryEngine/CryCommon/crycommon_files.cmake | 5 - Code/CryEngine/CrySystem/AndroidConsole.cpp | 94 - Code/CryEngine/CrySystem/AndroidConsole.h | 62 - Code/CryEngine/CrySystem/AutoDetectSpec.cpp | 1097 --- Code/CryEngine/CrySystem/AutoDetectSpec.h | 54 - Code/CryEngine/CrySystem/CMakeLists.txt | 63 - Code/CryEngine/CrySystem/CPUDetect.cpp | 1622 ---- Code/CryEngine/CrySystem/CPUDetect.h | 180 - Code/CryEngine/CrySystem/ClientHandler.cpp | 90 - Code/CryEngine/CrySystem/ClientHandler.h | 36 - .../Components/MathConversionTests.cpp | 167 - Code/CryEngine/CrySystem/CompressedFile.cpp | 38 - Code/CryEngine/CrySystem/CryAsyncMemcpy.cpp | 58 - Code/CryEngine/CrySystem/CryDLMalloc.c | 6645 ----------------- Code/CryEngine/CrySystem/CrySystem.rc | 91 - Code/CryEngine/CrySystem/CryWaterMark.h | 34 - Code/CryEngine/CrySystem/HandlerBase.cpp | 131 - Code/CryEngine/CrySystem/HandlerBase.h | 35 - Code/CryEngine/CrySystem/IOSConsole.h | 54 - Code/CryEngine/CrySystem/IOSConsole.mm | 94 - Code/CryEngine/CrySystem/LZ4Decompressor.cpp | 29 - Code/CryEngine/CrySystem/LZ4Decompressor.h | 35 - .../CrySystem/LevelSystem/LevelSystem.cpp | 10 - Code/CryEngine/CrySystem/Log.cpp | 24 +- Code/CryEngine/CrySystem/MobileDetectSpec.cpp | 151 - Code/CryEngine/CrySystem/MobileDetectSpec.h | 35 - .../CrySystem/MobileDetectSpec_Android.cpp | 47 - .../CrySystem/MobileDetectSpec_Ios.cpp | 40 - Code/CryEngine/CrySystem/PhysRenderer.cpp | 18 - Code/CryEngine/CrySystem/PhysRenderer.h | 22 - .../Platform/Android/platform_android.cmake | 16 - .../Android/platform_android_files.cmake | 18 - .../Platform/Linux/platform_linux.cmake | 21 - .../Platform/Linux/platform_linux_files.cmake | 13 - .../CrySystem/Platform/Mac/platform_mac.cmake | 16 - .../Platform/Mac/platform_mac_files.cmake | 10 - .../Platform/Windows/platform_windows.cmake | 16 - .../Windows/platform_windows_files.cmake | 13 - .../CrySystem/Platform/iOS/platform_ios.cmake | 22 - .../Platform/iOS/platform_ios_files.cmake | 18 - Code/CryEngine/CrySystem/SSAPI.DLL | 3 - Code/CryEngine/CrySystem/Sampler.cpp | 287 - Code/CryEngine/CrySystem/Sampler.h | 82 - Code/CryEngine/CrySystem/ServerHandler.cpp | 85 - Code/CryEngine/CrySystem/ServerHandler.h | 36 - Code/CryEngine/CrySystem/ServerThrottle.cpp | 164 - Code/CryEngine/CrySystem/ServerThrottle.h | 48 - Code/CryEngine/CrySystem/SyncLock.cpp | 246 - Code/CryEngine/CrySystem/SyncLock.h | 48 - Code/CryEngine/CrySystem/System.cpp | 162 - Code/CryEngine/CrySystem/System.h | 139 - Code/CryEngine/CrySystem/SystemInit.cpp | 725 +- Code/CryEngine/CrySystem/SystemInit.h | 36 - Code/CryEngine/CrySystem/SystemRender.cpp | 115 - Code/CryEngine/CrySystem/SystemWin32.cpp | 1 - Code/CryEngine/CrySystem/Tests/Test_CLog.cpp | 187 - .../Tests/Test_CommandRegistration.cpp | 282 - .../CrySystem/Tests/Test_CryPrimitives.cpp | 463 -- .../CrySystem/Tests/Test_Localization.cpp | 157 - .../CrySystem/Tests/test_CrySystem.cpp | 54 - Code/CryEngine/CrySystem/Tests/test_Main.cpp | 43 - .../CrySystem/Tests/test_MaterialUtils.cpp | 84 - Code/CryEngine/CrySystem/Timer.h | 2 +- Code/CryEngine/CrySystem/UnixConsole.cpp | 2518 ------- Code/CryEngine/CrySystem/UnixConsole.h | 573 -- Code/CryEngine/CrySystem/Validator.h | 66 - Code/CryEngine/CrySystem/WindowsConsole.cpp | 1153 --- Code/CryEngine/CrySystem/WindowsConsole.h | 245 - .../CrySystem/WindowsErrorReporting.cpp | 151 - Code/CryEngine/CrySystem/ZLibCompressor.cpp | 336 - Code/CryEngine/CrySystem/ZLibCompressor.h | 36 - Code/CryEngine/CrySystem/ZLibDecompressor.cpp | 251 - Code/CryEngine/CrySystem/ZLibDecompressor.h | 35 - Code/CryEngine/CrySystem/ZStdDecompressor.cpp | 26 - Code/CryEngine/CrySystem/ZStdDecompressor.h | 28 - Code/CryEngine/CrySystem/ZipFile.h | 19 - Code/CryEngine/CrySystem/ZipFileFormat_info.h | 76 - Code/CryEngine/CrySystem/crash_face.bmp | 3 - .../CrySystem/crysystem_android_files.cmake | 18 - .../CrySystem/crysystem_dlmalloc_files.cmake | 14 - .../CryEngine/CrySystem/crysystem_files.cmake | 40 - .../CrySystem/crysystem_ios_files.cmake | 16 - .../CrySystem/crysystem_mac_files.cmake | 11 - .../CrySystem/crysystem_test_files.cmake | 22 - Code/CryEngine/CrySystem/resource.h | 38 - .../AzFramework/Thermal}/ThermalInfo.h | 0 .../AzFramework/azframework_files.cmake | 1 + .../Application/Application_Android.cpp | 6 + .../Thermal/ThermalInfo_Android.cpp} | 2 +- .../Thermal/ThermalInfo_Android.h} | 2 +- .../Android/platform_android_files.cmake | 2 + Code/Sandbox/Editor/GameEngine.cpp | 1 - .../Sandbox/Editor/GraphicsSettingsDialog.cpp | 30 - Code/Sandbox/Editor/IEditorImpl.cpp | 9 +- Code/Sandbox/Editor/Util/PathUtil.cpp | 15 - .../Windows/package_filelists/atom.json | 1 - 105 files changed, 15 insertions(+), 20956 deletions(-) delete mode 100644 Code/CryEngine/CryCommon/ILZ4Decompressor.h delete mode 100644 Code/CryEngine/CryCommon/ITextModeConsole.h delete mode 100644 Code/CryEngine/CryCommon/IZLibCompressor.h delete mode 100644 Code/CryEngine/CryCommon/IZStdDecompressor.h delete mode 100644 Code/CryEngine/CryCommon/IZlibDecompressor.h delete mode 100644 Code/CryEngine/CrySystem/AndroidConsole.cpp delete mode 100644 Code/CryEngine/CrySystem/AndroidConsole.h delete mode 100644 Code/CryEngine/CrySystem/AutoDetectSpec.cpp delete mode 100644 Code/CryEngine/CrySystem/AutoDetectSpec.h delete mode 100644 Code/CryEngine/CrySystem/CPUDetect.cpp delete mode 100644 Code/CryEngine/CrySystem/CPUDetect.h delete mode 100644 Code/CryEngine/CrySystem/ClientHandler.cpp delete mode 100644 Code/CryEngine/CrySystem/ClientHandler.h delete mode 100644 Code/CryEngine/CrySystem/Components/MathConversionTests.cpp delete mode 100644 Code/CryEngine/CrySystem/CompressedFile.cpp delete mode 100644 Code/CryEngine/CrySystem/CryAsyncMemcpy.cpp delete mode 100644 Code/CryEngine/CrySystem/CryDLMalloc.c delete mode 100644 Code/CryEngine/CrySystem/CrySystem.rc delete mode 100644 Code/CryEngine/CrySystem/CryWaterMark.h delete mode 100644 Code/CryEngine/CrySystem/HandlerBase.cpp delete mode 100644 Code/CryEngine/CrySystem/HandlerBase.h delete mode 100644 Code/CryEngine/CrySystem/IOSConsole.h delete mode 100644 Code/CryEngine/CrySystem/IOSConsole.mm delete mode 100644 Code/CryEngine/CrySystem/LZ4Decompressor.cpp delete mode 100644 Code/CryEngine/CrySystem/LZ4Decompressor.h delete mode 100644 Code/CryEngine/CrySystem/MobileDetectSpec.cpp delete mode 100644 Code/CryEngine/CrySystem/MobileDetectSpec.h delete mode 100644 Code/CryEngine/CrySystem/MobileDetectSpec_Android.cpp delete mode 100644 Code/CryEngine/CrySystem/MobileDetectSpec_Ios.cpp delete mode 100644 Code/CryEngine/CrySystem/PhysRenderer.cpp delete mode 100644 Code/CryEngine/CrySystem/PhysRenderer.h delete mode 100644 Code/CryEngine/CrySystem/Platform/Android/platform_android.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Android/platform_android_files.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Linux/platform_linux.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Linux/platform_linux_files.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Mac/platform_mac.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Mac/platform_mac_files.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Windows/platform_windows.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/Windows/platform_windows_files.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/iOS/platform_ios.cmake delete mode 100644 Code/CryEngine/CrySystem/Platform/iOS/platform_ios_files.cmake delete mode 100644 Code/CryEngine/CrySystem/SSAPI.DLL delete mode 100644 Code/CryEngine/CrySystem/Sampler.cpp delete mode 100644 Code/CryEngine/CrySystem/Sampler.h delete mode 100644 Code/CryEngine/CrySystem/ServerHandler.cpp delete mode 100644 Code/CryEngine/CrySystem/ServerHandler.h delete mode 100644 Code/CryEngine/CrySystem/ServerThrottle.cpp delete mode 100644 Code/CryEngine/CrySystem/ServerThrottle.h delete mode 100644 Code/CryEngine/CrySystem/SyncLock.cpp delete mode 100644 Code/CryEngine/CrySystem/SyncLock.h delete mode 100644 Code/CryEngine/CrySystem/SystemInit.h delete mode 100644 Code/CryEngine/CrySystem/SystemRender.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/Test_CLog.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/Test_CommandRegistration.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/Test_Localization.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/test_CrySystem.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/test_Main.cpp delete mode 100644 Code/CryEngine/CrySystem/Tests/test_MaterialUtils.cpp delete mode 100644 Code/CryEngine/CrySystem/UnixConsole.cpp delete mode 100644 Code/CryEngine/CrySystem/UnixConsole.h delete mode 100644 Code/CryEngine/CrySystem/Validator.h delete mode 100644 Code/CryEngine/CrySystem/WindowsConsole.cpp delete mode 100644 Code/CryEngine/CrySystem/WindowsConsole.h delete mode 100644 Code/CryEngine/CrySystem/WindowsErrorReporting.cpp delete mode 100644 Code/CryEngine/CrySystem/ZLibCompressor.cpp delete mode 100644 Code/CryEngine/CrySystem/ZLibCompressor.h delete mode 100644 Code/CryEngine/CrySystem/ZLibDecompressor.cpp delete mode 100644 Code/CryEngine/CrySystem/ZLibDecompressor.h delete mode 100644 Code/CryEngine/CrySystem/ZStdDecompressor.cpp delete mode 100644 Code/CryEngine/CrySystem/ZStdDecompressor.h delete mode 100644 Code/CryEngine/CrySystem/ZipFile.h delete mode 100644 Code/CryEngine/CrySystem/ZipFileFormat_info.h delete mode 100644 Code/CryEngine/CrySystem/crash_face.bmp delete mode 100644 Code/CryEngine/CrySystem/crysystem_android_files.cmake delete mode 100644 Code/CryEngine/CrySystem/crysystem_dlmalloc_files.cmake delete mode 100644 Code/CryEngine/CrySystem/crysystem_ios_files.cmake delete mode 100644 Code/CryEngine/CrySystem/crysystem_mac_files.cmake delete mode 100644 Code/CryEngine/CrySystem/crysystem_test_files.cmake delete mode 100644 Code/CryEngine/CrySystem/resource.h rename Code/{CryEngine/CryCommon => Framework/AzFramework/AzFramework/Thermal}/ThermalInfo.h (100%) rename Code/{CryEngine/CrySystem/ThermalInfoAndroid.cpp => Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.cpp} (99%) rename Code/{CryEngine/CrySystem/ThermalInfoAndroid.h => Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.h} (95%) diff --git a/Code/CryEngine/CryCommon/ILZ4Decompressor.h b/Code/CryEngine/CryCommon/ILZ4Decompressor.h deleted file mode 100644 index c136a7518d..0000000000 --- a/Code/CryEngine/CryCommon/ILZ4Decompressor.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Provides the interface for the lz4 hc decompress wrapper - -#ifndef CRYINCLUDE_CRYCOMMON_ILZ4DECOMPRESSOR_H -#define CRYINCLUDE_CRYCOMMON_ILZ4DECOMPRESSOR_H -#pragma once - - -struct ILZ4Decompressor -{ -protected: - virtual ~ILZ4Decompressor() {}; // use Release() - -public: - virtual bool DecompressData(const char* pIn, char* pOut, const uint outputSize) const = 0; - - virtual void Release() = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ILZ4DECOMPRESSOR_H diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 73341dd16f..f863804f3d 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -76,14 +76,9 @@ struct IViewSystem; class ICrySizer; class IXMLBinarySerializer; struct IReadWriteXMLSink; -struct ITextModeConsole; struct IAVI_Reader; class CPNoise3; struct ILocalizationManager; -struct IZLibCompressor; -struct IZLibDecompressor; -struct ILZ4Decompressor; -class IZStdDecompressor; struct IOutputPrintSink; struct IWindowMessageHandler; @@ -524,7 +519,6 @@ struct SSystemInitParams ISystemUserCallback* pUserCallback; const char* sLogFileName; // File name to use for log. bool autoBackupLogs; // if true, logs will be automatically backed up each startup - IValidator* pValidator; // You can specify different validator object to use by System. IOutputPrintSink* pPrintSync; // Print Sync which can be used to catch all output from engine char szSystemCmdLine[2048]; // Command line. @@ -554,7 +548,6 @@ struct SSystemInitParams pUserCallback = NULL; sLogFileName = NULL; autoBackupLogs = true; - pValidator = NULL; pPrintSync = NULL; memset(szSystemCmdLine, 0, sizeof(szSystemCmdLine)); @@ -828,14 +821,6 @@ struct ISystem // Retrieve the name of the user currently logged in to the computer. virtual const char* GetUserName() = 0; - // Summary: - // Gets current supported CPU features flags. (CPUF_SSE, CPUF_SSE2, CPUF_3DNOW, CPUF_MMX) - virtual int GetCPUFlags() = 0; - - // Summary: - // Gets number of CPUs - virtual int GetLogicalCPUCount() = 0; - // Summary: // Quits the application. virtual void Quit() = 0; @@ -852,13 +837,6 @@ struct ISystem virtual bool IsRelaunch() const = 0; - // Summary: - // Displays an error message to display info for certain time - // Arguments: - // acMessage - Message to show - // fTime - Amount of seconds to show onscreen - virtual void DisplayErrorMessage(const char* acMessage, float fTime, const float* pfColor = 0, bool bHardError = true) = 0; - // Description: // Displays error message. // Logs it to console and file and error message box then terminates execution. @@ -889,14 +867,9 @@ struct ISystem // return the related subsystem interface // - virtual IZLibCompressor* GetIZLibCompressor() = 0; - virtual IZLibDecompressor* GetIZLibDecompressor() = 0; - virtual ILZ4Decompressor* GetLZ4Decompressor() = 0; - virtual IZStdDecompressor* GetZStdDecompressor() = 0; virtual IViewSystem* GetIViewSystem() = 0; virtual ILevelSystem* GetILevelSystem() = 0; virtual INameTable* GetINameTable() = 0; - virtual IValidator* GetIValidator() = 0; virtual ICmdLine* GetICmdLine() = 0; virtual ILog* GetILog() = 0; virtual AZ::IO::IArchive* GetIPak() = 0; @@ -917,7 +890,6 @@ struct ISystem virtual bool GetForceNonDevMode() const = 0; virtual bool WasInDevMode() const = 0; virtual bool IsDevMode() const = 0; - virtual bool IsMODValid(const char* szMODName) const = 0; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// @@ -974,13 +946,6 @@ struct ISystem // Gets build version. virtual const SFileVersion& GetBuildVersion() = 0; - // Summary: - // Data compression - //##@{ - virtual bool CompressDataBlock(const void* input, size_t inputSize, void* output, size_t& outputSize, int level = 3) = 0; - virtual bool DecompressDataBlock(const void* input, size_t inputSize, void* output, size_t& outputSize) = 0; - //##@} - ////////////////////////////////////////////////////////////////////////// // Configuration. ////////////////////////////////////////////////////////////////////////// @@ -1002,21 +967,8 @@ struct ISystem // pCallback - 0 means normal LoadConfigVar behaviour is used virtual void LoadConfiguration(const char* sFilename, ILoadConfigurationEntrySink* pSink = 0, bool warnIfMissing = true) = 0; - // Summary: - // Retrieves current configuration specification for client or server. - // Arguments: - // bClient - If true returns local client config spec, if false returns server config spec. - virtual ESystemConfigSpec GetConfigSpec(bool bClient = true) = 0; - virtual ESystemConfigSpec GetMaxConfigSpec() const = 0; - // Summary: - // Changes current configuration specification for client or server. - // Arguments: - // bClient - If true changes client config spec (sys_spec variable changed), - // if false changes only server config spec (as known on the client). - virtual void SetConfigSpec(ESystemConfigSpec spec, ESystemConfigPlatform platform, bool bClient) = 0; - ////////////////////////////////////////////////////////////////////////// // Summary: @@ -1028,10 +980,6 @@ struct ISystem virtual void SetConfigPlatform(ESystemConfigPlatform platform) = 0; ////////////////////////////////////////////////////////////////////////// - // Summary: - // Detects and set optimal spec. - virtual void AutoDetectSpec(bool detectResolution) = 0; - // Summary: // Query if system is now paused. // Pause flag is set when calling system update with pause mode. @@ -1041,8 +989,6 @@ struct ISystem // Retrieves localized strings manager interface. virtual ILocalizationManager* GetLocalizationManager() = 0; - virtual ITextModeConsole* GetITextModeConsole() = 0; - // Summary: // Retrieves the perlin noise singleton instance. virtual CPNoise3* GetNoiseGen() = 0; @@ -1133,22 +1079,10 @@ struct ISystem virtual ESystemGlobalState GetSystemGlobalState(void) = 0; virtual void SetSystemGlobalState(ESystemGlobalState systemGlobalState) = 0; - // Summary: - // Asynchronous memcpy - // Note sync variable will be incremented (in calling thread) before job starts - // and decremented when job finishes. Multiple async copies can therefore be - // tied to the same sync variable, therefore it's advised to wait for completion with - // while(*sync) (yield()); - virtual void AsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync) = 0; - // - #if !defined(_RELEASE) virtual bool IsSavingResourceList() const = 0; #endif - // Initializes Steam if needed and returns if it was successful - virtual bool SteamInit() = 0; - // Summary: // Gets the root window message handler function // The returned pointer is platform-specific: @@ -1752,44 +1686,6 @@ inline void CryLogAlways(const char* format, ...) #endif // EXCLUDE_NORMAL_LOG -/***************************************************** -ASYNC MEMCPY FUNCTIONS -*****************************************************/ - -// Complex delegation required because it is not really easy to -// export a external standalone symbol like a memcpy function when -// building with modules. Dll pay an extra indirection cost for calling this -// function. -#if !defined(AZ_MONOLITHIC_BUILD) -# define CRY_ASYNC_MEMCPY_DELEGATE_TO_CRYSYSTEM -#endif -#define CRY_ASYNC_MEMCPY_API extern "C" - -// Note sync variable will be incremented (in calling thread) before job starts -// and decremented when job finishes. Multiple async copies can therefore be -// tied to the same sync variable, therefore wait for completion with -// while(*sync) (yield()); -#if defined(CRY_ASYNC_MEMCPY_DELEGATE_TO_CRYSYSTEM) -inline void cryAsyncMemcpy( - void* dst - , const void* src - , size_t size - , int nFlags - , volatile int* sync) -{ - GetISystem()->AsyncMemcpy(dst, src, size, nFlags, sync); -} -# else -CRY_ASYNC_MEMCPY_API void cryAsyncMemcpy( - void* dst - , const void* src - , size_t size - , int nFlags - , volatile int* sync); -#endif - - - ////////////////////////////////////////////////////////////////////////// // Additional headers. ////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CryCommon/ITextModeConsole.h b/Code/CryEngine/CryCommon/ITextModeConsole.h deleted file mode 100644 index 026f6d945f..0000000000 --- a/Code/CryEngine/CryCommon/ITextModeConsole.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Allows creation of text mode displays the for dedicated server - - -#ifndef CRYINCLUDE_CRYCOMMON_ITEXTMODECONSOLE_H -#define CRYINCLUDE_CRYCOMMON_ITEXTMODECONSOLE_H -#pragma once - - -struct ITextModeConsole -{ - // - virtual ~ITextModeConsole() {} - virtual Vec2_tpl BeginDraw() = 0; - virtual void PutText(int x, int y, const char* msg) = 0; - virtual void EndDraw() = 0; - virtual void OnShutdown() = 0; - - virtual void SetTitle([[maybe_unused]] const char* title) {} - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ITEXTMODECONSOLE_H diff --git a/Code/CryEngine/CryCommon/IZLibCompressor.h b/Code/CryEngine/CryCommon/IZLibCompressor.h deleted file mode 100644 index df85992eef..0000000000 --- a/Code/CryEngine/CryCommon/IZLibCompressor.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_IZLIBCOMPRESSOR_H -#define CRYINCLUDE_CRYCOMMON_IZLIBCOMPRESSOR_H -#pragma once - - -/* - wrapper interface for the zlib compression / deflate interface - - supports multiple compression streams with an async compatible wrapper - - Gotchas: - the ptr to the input data must remain valid whilst the stream is deflating - the ptr to the output buffer must remain valid whilst the stream is deflating - - **************************************************************************************** - - usage example: - - IZLibCompressor *pComp=GetISystem()->GetIZLibCompressor(); - // see deflateInit2() documentation zlib manual for more info on the parameters here - // this initializes the stream to produce a gzip format block with fairly low memory requirements - IZLibDeflateStream *pStream=pComp->CreateDeflateStream(2,eZMeth_Deflated,24,3,eZStrat_Default,eZFlush_NoFlush); - char *pOutput=new char[512]; // arbitrary size - const char *pInputData="This is an example piece of data that is to be compressed. It can be any arbitrary block of binary data - not just text"; - const int inputBlockSize=16; // to simulate streaming of input, this example provides the input in 16 byte blocks - int totalInput=sizeof(pInputData); - int bytesInput=0; - bool done=false; - FILE *outputFile=fopen("myfile.gz","rb"); - - do - { - EZDeflateState state=pStream->GetState(); - - switch (state) - { - case eZDefState_AwaitingInput: - // 'stream' input data, there is no restriction on the block size you can input, if all the data is available immediately, input all of it at once - { - int inputSize=min(inputBlockSize,totalInput-bytesInput); - - if (inputSize<=0) - { - pStream->EndInput(); - } - else - { - pStream->Input(pInputData+bytesInput,inputSize); - bytesInput+=inputSize; - } - } - break; - - case eZDefState_Deflating: - // do something more interesting... like getting out of this loop and running the rest of your game... - break; - - case eZDefState_ConsumeOutput: - // stream output to a file - { - int bytesToOutput=pStream->GetBytesOutput(); - - if (bytesToOutput>0) - { - fwrite(pOutput,1,bytesToOutput,outputFile); - } - - pStream->SetOutputBuffer(pOutput,sizeof(pOutput)); - } - break; - - case eZDefState_Finished: - case ezDefState_Error: - done=true; - break; - } - - } while (!done); - - fclose(outputFile); - - pStream->Release(); - delete [] pOutput; - -****************************************************************************************/ - -// don't change the order of these zlib wrapping enum values without updating the mapping -// implementation in CZLibCompressorStream -enum EZLibStrategy -{ - eZStrat_Default, // Z_DEFAULT_STRATEGY - eZStrat_Filtered, // Z_FILTERED - eZStrat_HuffmanOnly, // Z_HUFFMAN_ONLY - eZStrat_RLE // Z_RLE -}; -enum EZLibMethod -{ - eZMeth_Deflated // Z_DEFLATED -}; -enum EZLibFlush -{ - eZFlush_NoFlush, // Z_NO_FLUSH - eZFlush_PartialFlush, // Z_PARTIAL_FLUSH - eZFlush_SyncFlush, // Z_SYNC_FLUSH - eZFlush_FullFlush, // Z_FULL_FLUSH -}; - -enum EZDeflateState -{ - eZDefState_AwaitingInput, // caller must call Input() or Finish() to continue - eZDefState_Deflating, // caller must wait - eZDefState_ConsumeOutput, // caller must consume output and then call SetOutputBuffer() to continue - eZDefState_Finished, // stream finished, caller must call Release() to destroy stream - eZDefState_Error // error has occurred and the stream has been closed and will no longer compress -}; - -struct IZLibDeflateStream -{ -protected: - virtual ~IZLibDeflateStream() {}; // use Release() - -public: - struct SStats - { - int bytesInput; - int bytesOutput; - int curMemoryUsed; - int peakMemoryUsed; - }; - - // - // Description: - // Specifies the output buffer for the deflate operation - // Should be set before providing input - // The specified buffer must remain valid (ie do not free) whilst compression is in progress (state == eZDefState_Deflating) - virtual void SetOutputBuffer(char* pInBuffer, int inSize) = 0; - - // Description: - // Returns the number of bytes from the output buffer that are ready to be consumed. After consuming any output, you should call SetOutputBuffer() again to mark the buffer as available - virtual int GetBytesOutput() = 0; - - // Description: - // Begins compressing the source data pInSource of length inSourceSize to a previously specified output buffer - // Only valid to be called if the stream is in state eZDefState_AwaitingInput - // The specified buffer must remain valid (ie do not free) whilst compression is in progress (state == eZDefState_Deflating) - virtual void Input(const char* pInSource, int inSourceSize) = 0; - - // Description: - // Finishes the compression, causing all data to be flushed to the output buffer - // Once called no more data can be input - // After calling the caller must wait until GetState() reutrns eZDefState_Finished - virtual void EndInput() = 0; - - // Description: - // Returns the state of the stream, - virtual EZDeflateState GetState() = 0; - - // Description: - // Gets stats on deflate stream, valid to call at anytime - virtual void GetStats(SStats* pOutStats) = 0; - - // Description: - // Deletes the deflate stream. Will assert if stream is in an invalid state to be released (in state eZDefState_Deflating) - virtual void Release() = 0; - // -}; - -// md5 support structure -struct SMD5Context -{ - uint32 buf[4]; - uint32 bits[2]; - unsigned char in[64]; -}; - -struct IZLibCompressor -{ -protected: - virtual ~IZLibCompressor() {}; // use Release() - -public: - // - // Description: - // Creates a deflate stream to compress data using zlib - // See documentation for zlib deflateInit2() for usage details - // inFlushMethod is passed to calls to zlib deflate(), see zlib docs on deflate() for more details - virtual IZLibDeflateStream* CreateDeflateStream(int inLevel, EZLibMethod inMethod, int inWindowBits, int inMemLevel, EZLibStrategy inStrategy, EZLibFlush inFlushMethod) = 0; - - virtual void Release() = 0; - - // Description: - // Initializes an MD5 context - virtual void MD5Init(SMD5Context* pIOCtx) = 0; - - // Description: - // Digests some data into an existing MD5 context - virtual void MD5Update(SMD5Context* pIOCtx, const char* pInBuff, unsigned int len) = 0; - - // Description: - // Closes the MD5 context and extract the final 16 byte MD5 digest value - virtual void MD5Final(SMD5Context * pIOCtx, char outDigest[16]) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_IZLIBCOMPRESSOR_H - diff --git a/Code/CryEngine/CryCommon/IZStdDecompressor.h b/Code/CryEngine/CryCommon/IZStdDecompressor.h deleted file mode 100644 index b5ab0f3088..0000000000 --- a/Code/CryEngine/CryCommon/IZStdDecompressor.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - - -class IZStdDecompressor -{ -public: - virtual bool DecompressData(const char* pIn, const uint inputSize, char* pOut, const uint outputSize) = 0; - virtual void Release() = 0; - -protected: - virtual ~IZStdDecompressor() = default; // use Release() -}; - diff --git a/Code/CryEngine/CryCommon/IZlibDecompressor.h b/Code/CryEngine/CryCommon/IZlibDecompressor.h deleted file mode 100644 index bd9417c935..0000000000 --- a/Code/CryEngine/CryCommon/IZlibDecompressor.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Provides the interface for the zlib inflate wrapper - - -#ifndef CRYINCLUDE_CRYCOMMON_IZLIBDECOMPRESSOR_H -#define CRYINCLUDE_CRYCOMMON_IZLIBDECOMPRESSOR_H -#pragma once - - -enum EZInflateState -{ - eZInfState_AwaitingInput, // caller must call Input() to continue - eZInfState_Inflating, // caller must wait - eZInfState_ConsumeOutput, // caller must consume output and then call SetOutputBuffer() to continue - eZInfState_Finished, // caller must call Release() - eZInfState_Error // error has occurred and the stream has been closed and will no longer compress -}; - -struct IZLibInflateStream -{ -protected: - virtual ~IZLibInflateStream() {}; // use Release() - -public: - struct SStats - { - int bytesInput; - int bytesOutput; - int curMemoryUsed; - int peakMemoryUsed; - }; - - // Description: - // Specifies the output buffer for the inflate operation - // Should be set before providing input - // The specified buffer must remain valid (ie do not free) whilst compression is in progress (state == eZInfState_Inflating) - virtual void SetOutputBuffer(char* pInBuffer, unsigned int inSize) = 0; - - // Description: - // Returns the number of bytes from the output buffer that are ready to be consumed. After consuming any output, you should call SetOutputBuffer() again to mark the buffer as available - virtual unsigned int GetBytesOutput() = 0; - - // Description: - // Begins decompressing the source data pInSource of length inSourceSize to a previously specified output buffer - // Only valid to be called if the stream is in state eZInfState_AwaitingInput - // The specified buffer must remain valid (ie do not free) whilst compression is in progress (state == eZInfState_Inflating) - virtual void Input(const char* pInSource, unsigned int inSourceSize) = 0; - - // Description: - // Finishes the compression, causing all data to be flushed to the output buffer - // Once called no more data can be input - // After calling the caller must wait until GetState() reuturns eZInfState_Finished - virtual void EndInput() = 0; - - // Description: - // Returns the state of the stream, - virtual EZInflateState GetState() = 0; - - // Description: - // Gets stats on inflate stream, valid to call at anytime - virtual void GetStats(SStats* pOutStats) = 0; - - // Description: - // Deletes the inflate stream. Will assert if stream is in an invalid state to be released (in state eZInfState_Inflating) - virtual void Release() = 0; -}; - -struct IZLibDecompressor -{ -protected: - virtual ~IZLibDecompressor() {}; // use Release() - -public: - // Description: - // Creates a inflate stream to decompress data using zlib - virtual IZLibInflateStream* CreateInflateStream() = 0; - - virtual void Release() = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMON_IZLIBDECOMPRESSOR_H - diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index acd7492398..8c9c98b3ee 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -39,10 +39,6 @@ public: void()); MOCK_METHOD0(GetUserName, const char*()); - MOCK_METHOD0(GetCPUFlags, - int()); - MOCK_METHOD0(GetLogicalCPUCount, - int()); MOCK_METHOD0(Quit, void()); MOCK_METHOD1(Relaunch, @@ -55,8 +51,6 @@ public: int()); MOCK_CONST_METHOD0(IsRelaunch, bool()); - MOCK_METHOD4(DisplayErrorMessage, - void(const char*, float, const float*, bool)); void FatalError([[maybe_unused]] const char* sFormat, ...) override {} void ReportBug([[maybe_unused]] const char* sFormat, ...) override {} @@ -70,22 +64,12 @@ public: int(const char* text, const char* caption, unsigned int uType)); MOCK_METHOD1(CheckLogVerbosity, bool(int verbosity)); - MOCK_METHOD0(GetIZLibCompressor, - IZLibCompressor * ()); - MOCK_METHOD0(GetIZLibDecompressor, - IZLibDecompressor * ()); - MOCK_METHOD0(GetLZ4Decompressor, - ILZ4Decompressor * ()); - MOCK_METHOD0(GetZStdDecompressor, - IZStdDecompressor * ()); MOCK_METHOD0(GetIViewSystem, IViewSystem * ()); MOCK_METHOD0(GetILevelSystem, ILevelSystem * ()); MOCK_METHOD0(GetINameTable, INameTable * ()); - MOCK_METHOD0(GetIValidator, - IValidator * ()); MOCK_METHOD0(GetICmdLine, ICmdLine * ()); MOCK_METHOD0(GetILog, @@ -116,8 +100,6 @@ public: bool()); MOCK_CONST_METHOD0(IsDevMode, bool()); - MOCK_CONST_METHOD1(IsMODValid, - bool(const char* szMODName)); MOCK_METHOD3(CreateXmlNode, XmlNodeRef(const char*, bool, bool)); MOCK_METHOD4(LoadXmlFromBuffer, @@ -147,11 +129,6 @@ public: MOCK_METHOD0(GetBuildVersion, const SFileVersion&()); - MOCK_METHOD5(CompressDataBlock, - bool(const void*, size_t, void*, size_t &, int)); - - MOCK_METHOD4(DecompressDataBlock, - bool(const void* input, size_t inputSize, void* output, size_t & outputSize)); MOCK_METHOD1(AddCVarGroupDirectory, void(const string&)); MOCK_METHOD0(SaveConfiguration, @@ -159,24 +136,16 @@ public: MOCK_METHOD3(LoadConfiguration, void(const char*, ILoadConfigurationEntrySink*, bool)); - MOCK_METHOD1(GetConfigSpec, - ESystemConfigSpec(bool)); MOCK_CONST_METHOD0(GetMaxConfigSpec, ESystemConfigSpec()); - MOCK_METHOD3(SetConfigSpec, - void(ESystemConfigSpec spec, ESystemConfigPlatform platform, bool bClient)); MOCK_CONST_METHOD0(GetConfigPlatform, ESystemConfigPlatform()); MOCK_METHOD1(SetConfigPlatform, void(ESystemConfigPlatform platform)); - MOCK_METHOD1(AutoDetectSpec, - void(bool detectResolution)); MOCK_CONST_METHOD0(IsPaused, bool()); MOCK_METHOD0(GetLocalizationManager, ILocalizationManager * ()); - MOCK_METHOD0(GetITextModeConsole, - ITextModeConsole * ()); MOCK_METHOD0(GetNoiseGen, CPNoise3 * ()); MOCK_METHOD0(GetUpdateCounter, @@ -213,16 +182,12 @@ public: ESystemGlobalState(void)); MOCK_METHOD1(SetSystemGlobalState, void(ESystemGlobalState systemGlobalState)); - MOCK_METHOD5(AsyncMemcpy, - void(void* dst, const void* src, size_t size, int nFlags, volatile int* sync)); #if !defined(_RELEASE) MOCK_CONST_METHOD0(IsSavingResourceList, bool()); #endif - MOCK_METHOD0(SteamInit, - bool()); MOCK_METHOD0(GetRootWindowMessageHandler, void*()); MOCK_METHOD1(RegisterWindowMessageHandler, diff --git a/Code/CryEngine/CryCommon/ProjectDefines.h b/Code/CryEngine/CryCommon/ProjectDefines.h index 67ae58a324..1f151caf2e 100644 --- a/Code/CryEngine/CryCommon/ProjectDefines.h +++ b/Code/CryEngine/CryCommon/ProjectDefines.h @@ -40,8 +40,6 @@ #endif #endif -#define USE_STEAM 0 // Enable this to start using Steam - // The following definitions are used by Sandbox and RC to determine which platform support is needed #define TOOLS_SUPPORT_POWERVR #define TOOLS_SUPPORT_ETC2COMP diff --git a/Code/CryEngine/CryCommon/RenderBus.h b/Code/CryEngine/CryCommon/RenderBus.h index efd004219a..21c56f607c 100644 --- a/Code/CryEngine/CryCommon/RenderBus.h +++ b/Code/CryEngine/CryCommon/RenderBus.h @@ -33,14 +33,6 @@ namespace AZ static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; ////////////////////////////////////////////////////////////////////////// - /** - * This event gets posted at the end of CD3D9Renderer's EF_Scene3D method. - * CSystem (in SystemRenderer.cpp) uses this to render the console, aux geom and UI - * in a manner that will make sure the render calls end up as part of the scene's render. - * This is important or else those render calls won't show up properly in VR. - */ - virtual void OnScene3DEnd() {}; - /** * This event gets posted at the beginning of CD3D9Renderer's FreeResources method, before the resources have been freed. */ diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index 47e57633b4..3c1d1605e7 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -34,7 +34,6 @@ set(FILES LocalizationManagerBus.h LocalizationManagerBus.inl ILog.h - ILZ4Decompressor.h IMaterial.h IMeshBaking.h IMiniLog.h @@ -56,7 +55,6 @@ set(FILES IStereoRenderer.h ISurfaceType.h ISystem.h - ITextModeConsole.h ITexture.h ITimer.h IValidator.h @@ -64,9 +62,6 @@ set(FILES IViewSystem.h IWindowMessageHandler.h IXml.h - IZLibCompressor.h - IZlibDecompressor.h - IZStdDecompressor.h IProximityTriggerSystem.h MicrophoneBus.h physinterface.h diff --git a/Code/CryEngine/CrySystem/AndroidConsole.cpp b/Code/CryEngine/CrySystem/AndroidConsole.cpp deleted file mode 100644 index 2716df3a22..0000000000 --- a/Code/CryEngine/CrySystem/AndroidConsole.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Console implementation for Android, reports back to the main interface. - - -#include "CrySystem_precompiled.h" -#if defined(ANDROID) -#include "AndroidConsole.h" - -#include "android/log.h" -CAndroidConsole::CAndroidConsole() - : m_isInitialized(false) -{ -} - -CAndroidConsole::~CAndroidConsole() -{ -} - -// Interface IOutputPrintSink ///////////////////////////////////////////// -void CAndroidConsole::Print(const char* line) -{ - __android_log_print(ANDROID_LOG_VERBOSE, "CryEngine", "MSG: %s\n", line); -} -// Interface ISystemUserCallback ////////////////////////////////////////// -bool CAndroidConsole::OnError(const char* errorString) -{ - __android_log_print(ANDROID_LOG_ERROR, "CryEngine", "ERR: %s\n", errorString); - return true; -} - -void CAndroidConsole::OnInitProgress(const char* sProgressMsg) -{ - (void) sProgressMsg; - // Do Nothing -} -void CAndroidConsole::OnInit(ISystem* pSystem) -{ - if (!m_isInitialized) - { - IConsole* pConsole = pSystem->GetIConsole(); - if (pConsole != 0) - { - pConsole->AddOutputPrintSink(this); - } - m_isInitialized = true; - } -} -void CAndroidConsole::OnShutdown() -{ - if (m_isInitialized) - { - // remove outputprintsink - m_isInitialized = false; - } -} -void CAndroidConsole::OnUpdate() -{ - // Do Nothing -} -void CAndroidConsole::GetMemoryUsage(ICrySizer* pSizer) -{ - size_t size = sizeof(*this); - - - - pSizer->AddObject(this, size); -} - -// Interface ITextModeConsole ///////////////////////////////////////////// -Vec2_tpl CAndroidConsole::BeginDraw() -{ - return Vec2_tpl(0, 0); -} -void CAndroidConsole::PutText(int x, int y, const char* msg) -{ - __android_log_print(ANDROID_LOG_VERBOSE, "CryEngine", "PUT: %s\n", msg); -} -void CAndroidConsole::EndDraw() -{ - // Do Nothing -} -#endif // ANDROID diff --git a/Code/CryEngine/CrySystem/AndroidConsole.h b/Code/CryEngine/CrySystem/AndroidConsole.h deleted file mode 100644 index af45a68d5e..0000000000 --- a/Code/CryEngine/CrySystem/AndroidConsole.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Console implementation for Android, reports back to the main interface. - - -#ifndef CRYINCLUDE_CRYSYSTEM_ANDROIDCONSOLE_H -#define CRYINCLUDE_CRYSYSTEM_ANDROIDCONSOLE_H -#pragma once - - -#include -#include - - - -class CAndroidConsole - : public ISystemUserCallback - , public IOutputPrintSink - , public ITextModeConsole -{ - CAndroidConsole(const CAndroidConsole&); - CAndroidConsole& operator = (const CAndroidConsole&); - - bool m_isInitialized; -public: - static CryCriticalSectionNonRecursive s_lock; -public: - CAndroidConsole(); - ~CAndroidConsole(); - - // Interface IOutputPrintSink ///////////////////////////////////////////// - DLL_EXPORT virtual void Print(const char* line); - - // Interface ISystemUserCallback ////////////////////////////////////////// - virtual bool OnError(const char* errorString); - virtual bool OnSaveDocument() { return false; } - virtual void OnProcessSwitch() { } - virtual void OnInitProgress(const char* sProgressMsg); - virtual void OnInit(ISystem*); - virtual void OnShutdown(); - virtual void OnUpdate(); - virtual void GetMemoryUsage(ICrySizer* pSizer); - void SetRequireDedicatedServer(bool) {} - void SetHeader(const char*) {} - // Interface ITextModeConsole ///////////////////////////////////////////// - virtual Vec2_tpl BeginDraw(); - virtual void PutText(int x, int y, const char* msg); - virtual void EndDraw(); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_ANDROIDCONSOLE_H diff --git a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp deleted file mode 100644 index aa344684e3..0000000000 --- a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp +++ /dev/null @@ -1,1097 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#if defined(WIN32) || defined(WIN64) - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "System.h" -#include "AutoDetectSpec.h" - -// both function live in CPUDetect.cpp -bool IsAMD(); -bool IsIntel(); - - -static void TrimExcessiveWhiteSpaces(char* pStr) -{ - size_t len(strlen(pStr)); - bool remove(true); - for (size_t i(0); i < len; ++i) - { - if (pStr[i] == ' ' && remove) - { - size_t newlen(len - 1); - - size_t j(i + 1); - for (; j < len && pStr[j] == ' '; ++j) - { - --newlen; - } - - size_t ii(i); - for (; j < len + 1; ++j, ++ii) - { - pStr[ii] = pStr[j]; - } - - assert(newlen == strlen(pStr)); - len = newlen; - remove = false; - } - else - { - remove = pStr[i] == ' '; - } - } - - if (len > 0 && pStr[len - 1] == ' ') - { - pStr[len - 1] = '\0'; - } -} - - -static void GetCPUName(char* pName, size_t bufferSize) -{ - if (!pName || !bufferSize) - { - return; - } - - char name[12 * 4 + 1]; - - int CPUInfo[4]; - __cpuid(CPUInfo, 0x80000000); - if (CPUInfo[0] >= 0x80000004) - { - __cpuid(CPUInfo, 0x80000002); - ((int*)name)[0] = CPUInfo[0]; - ((int*)name)[1] = CPUInfo[1]; - ((int*)name)[2] = CPUInfo[2]; - ((int*)name)[3] = CPUInfo[3]; - - __cpuid(CPUInfo, 0x80000003); - ((int*)name)[4] = CPUInfo[0]; - ((int*)name)[5] = CPUInfo[1]; - ((int*)name)[6] = CPUInfo[2]; - ((int*)name)[7] = CPUInfo[3]; - - __cpuid(CPUInfo, 0x80000004); - ((int*)name)[8] = CPUInfo[0]; - ((int*)name)[9] = CPUInfo[1]; - ((int*)name)[10] = CPUInfo[2]; - ((int*)name)[11] = CPUInfo[3]; - - name[48] = '\0'; - } - else - { - name[0] = '\0'; - } - - int ret(azsnprintf(pName, bufferSize, name)); - if (ret >= bufferSize || ret < 0) - { - pName[bufferSize - 1] = '\0'; - } -} - - -void Win32SysInspect::GetOS(SPlatformInfo::EWinVersion& ver, bool& is64Bit, char* pName, size_t bufferSize) -{ - ver = SPlatformInfo::WinUndetected; - is64Bit = false; - - if (pName && bufferSize) - { - pName[0] = '\0'; - } - - //GetVersionEx was changed to work based on how the application is manifest - //meaning we have to specifically state that this application supports - //Windows 10, Windows 8.1 etc if we want GetVersionEx to return those version numbers. - //RtlGetVersion does not require a manifest. - auto RtlGetVersion = reinterpret_cast(GetProcAddress(GetModuleHandleA("ntdll"), "RtlGetVersion")); - AZ_Assert(RtlGetVersion, "Failed to get address to RtlGetVersion from ntdll.dll"); - - RTL_OSVERSIONINFOEXW sysInfo; - sysInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); - - if (RtlGetVersion(&sysInfo) == 0) - { - if (sysInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) - { - if (sysInfo.dwMajorVersion == 5) - { - if (sysInfo.dwMinorVersion == 0) - { - ver = SPlatformInfo::Win2000; - } - else if (sysInfo.dwMinorVersion == 1) - { - ver = SPlatformInfo::WinXP; - } - else if (sysInfo.dwMinorVersion == 2) - { - if (sysInfo.wProductType == VER_NT_WORKSTATION) - { - ver = SPlatformInfo::WinXP; // 64 bit windows actually but this will be detected later anyway - } - else if (sysInfo.wProductType == VER_NT_SERVER || sysInfo.wProductType == VER_NT_DOMAIN_CONTROLLER) - { - ver = SPlatformInfo::WinSrv2003; - } - } - } - else if (sysInfo.dwMajorVersion == 6) - { - if (sysInfo.dwMinorVersion == 0) - { - ver = SPlatformInfo::WinVista; - } - else if (sysInfo.dwMinorVersion == 1) - { - ver = SPlatformInfo::Win7; - } - else if (sysInfo.dwMinorVersion == 2) - { - ver = SPlatformInfo::Win8; - } - else if (sysInfo.dwMinorVersion == 3) - { - ver = SPlatformInfo::Win81; - } - } - else if (sysInfo.dwMajorVersion == 10) - { - ver = SPlatformInfo::Win10; - } - } - - typedef BOOL (WINAPI * FP_GetSystemWow64Directory)(LPSTR, UINT); - FP_GetSystemWow64Directory pgsw64d((FP_GetSystemWow64Directory) GetProcAddress(GetModuleHandle("kernel32"), "GetSystemWow64DirectoryA")); - if (pgsw64d) - { - char str[MAX_PATH]; - if (!pgsw64d(str, sizeof(str))) - { - is64Bit = GetLastError() != ERROR_CALL_NOT_IMPLEMENTED; - } - else - { - is64Bit = true; - } - } - - if (pName && bufferSize) - { - const char* windowsVersionText(0); - switch (ver) - { - case SPlatformInfo::Win2000: - windowsVersionText = "Windows 2000"; - break; - case SPlatformInfo::WinXP: - windowsVersionText = "Windows XP"; - break; - case SPlatformInfo::WinSrv2003: - windowsVersionText = "Windows Server 2003"; - break; - case SPlatformInfo::WinVista: - windowsVersionText = "Windows Vista"; - break; - case SPlatformInfo::Win7: - windowsVersionText = "Windows 7"; - break; - case SPlatformInfo::Win8: - windowsVersionText = "Windows 8"; - break; - case SPlatformInfo::Win81: - windowsVersionText = "Windows 8.1"; - break; - case SPlatformInfo::Win10: - windowsVersionText = "Windows 10"; - break; - default: - windowsVersionText = "Windows"; - break; - } - - char sptext[32]; - sptext[0] = '\0'; - if (sysInfo.wServicePackMajor > 0) - { - azsnprintf(sptext, sizeof(sptext), "SP %d ", sysInfo.wServicePackMajor); - } - - int ret(azsnprintf(pName, bufferSize, "%s %s %s(build %d.%d.%d)", windowsVersionText, is64Bit ? "64 bit" : "32 bit", - sptext, sysInfo.dwMajorVersion, sysInfo.dwMinorVersion, sysInfo.dwBuildNumber)); - if (ret >= bufferSize || ret < 0) - { - pName[bufferSize - 1] = '\0'; - } - } - } -} - -bool Win32SysInspect::IsVistaKB940105Required() -{ -#if defined(WIN32) && !defined(WIN64) - OSVERSIONINFO osv; - memset(&osv, 0, sizeof(osv)); - osv.dwOSVersionInfoSize = sizeof(osv); - GetVersionEx(&osv); - - if (osv.dwMajorVersion != 6 || osv.dwMinorVersion != 0 || (osv.dwBuildNumber > 6000)) - { - // This QFE only ever applies to Windows Vista RTM. Windows Vista SP1 already has this fix, - // and earlier versions of Windows do not implement WDDM - return false; - } - - //MEMORYSTATUSEX mex; - //memset(&mex, 0, sizeof(mex)); - //mex.dwLength = sizeof(mex); - //GlobalMemoryStatusEx(&mex); - - //if (mex.ullTotalVirtual >= 4294836224) - //{ - // // If there is 4 GB of VA space total for this process, then we are a - // // 32-bit Large Address Aware application running on a Windows 64-bit OS. - - // // We could be a 32-bit Large Address Aware application running on a - // // Windows 32-bit OS and get up to 3 GB, but that has stability implications. - // // Therefore, we recommend the QFE for all 32-bit versions of the OS. - - // // No need for the fix unless the game is pushing 4 GB of VA - // return false; - //} - - const char* sysFile = "dxgkrnl.sys"; - - // Ensure we are checking the system copy of the file - char sysPath[MAX_PATH]; - GetSystemDirectory(sysPath, sizeof(sysPath)); - - cry_strcat(sysPath, "\\drivers\\"); - cry_strcat(sysPath, sysFile); - - char buf[2048]; - if (!GetFileVersionInfo(sysPath, 0, sizeof(buf), buf)) - { - // This should never happen, but we'll assume it's a newer .sys file since we've - // narrowed the test to a Windows Vista RTM OS. - return false; - } - - VS_FIXEDFILEINFO* ver; - UINT size; - if (!VerQueryValue(buf, "\\", (void**) &ver, &size) || size != sizeof(VS_FIXEDFILEINFO) || ver->dwSignature != 0xFEEF04BD) - { - // This should never happen, but we'll assume it's a newer .sys file since we've - // narrowed the test to a Windows Vista RTM OS. - return false; - } - - // File major.minor.build.qfe version comparison - // WORD major = HIWORD( ver->dwFileVersionMS ); WORD minor = LOWORD( ver->dwFileVersionMS ); - // WORD build = HIWORD( ver->dwFileVersionLS ); WORD qfe = LOWORD( ver->dwFileVersionLS ); - - if (ver->dwFileVersionMS > MAKELONG(0, 6) || (ver->dwFileVersionMS == MAKELONG(0, 6) && ver->dwFileVersionLS >= MAKELONG(20648, 6000))) - { - // QFE fix version of dxgkrnl.sys is 6.0.6000.20648 - return false; - } - - return true; -#else - return false; // The QFE is not required for a 64-bit native application as it has 8 TB of VA -#endif -} - - -static void GetSystemMemory(uint64& totSysMem) -{ - typedef BOOL (WINAPI * FP_GlobalMemoryStatusEx)(LPMEMORYSTATUSEX); - FP_GlobalMemoryStatusEx pgmsex((FP_GlobalMemoryStatusEx) GetProcAddress(GetModuleHandle("kernel32"), "GlobalMemoryStatusEx")); - if (pgmsex) - { - MEMORYSTATUSEX memStats; - memStats.dwLength = sizeof(memStats); - if (pgmsex(&memStats)) - { - totSysMem = memStats.ullTotalPhys; - } - else - { - totSysMem = 0; - } - } - else - { - MEMORYSTATUS memStats; - memStats.dwLength = sizeof(memStats); - GlobalMemoryStatus(&memStats); - totSysMem = memStats.dwTotalPhys; - } -} - - -static bool IsVistaOrAbove() -{ - typedef BOOL (WINAPI * FP_VerifyVersionInfo)(LPOSVERSIONINFOEX, DWORD, DWORDLONG); - FP_VerifyVersionInfo pvvi((FP_VerifyVersionInfo) GetProcAddress(GetModuleHandle("kernel32"), "VerifyVersionInfoA")); - - if (pvvi) - { - typedef ULONGLONG (WINAPI * FP_VerSetConditionMask)(ULONGLONG, DWORD, BYTE); - FP_VerSetConditionMask pvscm((FP_VerSetConditionMask) GetProcAddress(GetModuleHandle("kernel32"), "VerSetConditionMask")); - assert(pvscm); - - OSVERSIONINFOEX osvi; - memset(&osvi, 0, sizeof(osvi)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - osvi.dwMajorVersion = 6; - osvi.dwMinorVersion = 0; - osvi.wServicePackMajor = 0; - osvi.wServicePackMinor = 0; - - ULONGLONG mask(0); - mask = pvscm(mask, VER_MAJORVERSION, VER_GREATER_EQUAL); - mask = pvscm(mask, VER_MINORVERSION, VER_GREATER_EQUAL); - mask = pvscm(mask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - mask = pvscm(mask, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); - - if (pvvi(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR, mask)) - { - return true; - } - } - - return false; -} - - -// Preferred solution to determine the number of available CPU cores, works reliably only on WinVista/Win7 32/64 and above -// See http://msdn2.microsoft.com/en-us/library/ms686694.aspx for reasons -static void GetNumCPUCoresGlpi(unsigned int& totAvailToSystem, unsigned int& totAvailToProcess) -{ - typedef BOOL (WINAPI * FP_GetLogicalProcessorInformation)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); - FP_GetLogicalProcessorInformation pglpi((FP_GetLogicalProcessorInformation) GetProcAddress(GetModuleHandle("kernel32"), "GetLogicalProcessorInformation")); - if (pglpi && IsVistaOrAbove()) - { - unsigned long bufferSize(0); - pglpi(0, &bufferSize); - - void* pBuffer(alloca(bufferSize)); - - SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pLogProcInfo((SYSTEM_LOGICAL_PROCESSOR_INFORMATION*) pBuffer); - if (pLogProcInfo && pglpi(pLogProcInfo, &bufferSize)) - { - DWORD_PTR processAffinity, systemAffinity; - GetProcessAffinityMask(GetCurrentProcess(), &processAffinity, &systemAffinity); - - unsigned long numEntries(bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)); - for (unsigned long i(0); i < numEntries; ++i) - { - switch (pLogProcInfo[i].Relationship) - { - case RelationProcessorCore: - { - ++totAvailToSystem; - if (pLogProcInfo[i].ProcessorMask & processAffinity) - { - ++totAvailToProcess; - } - } - break; - - default: - break; - } - } - } - } -} - - -class CApicExtractor -{ -public: - CApicExtractor(unsigned int logProcsPerPkg = 1, unsigned int coresPerPkg = 1) - { - SetPackageTopology(logProcsPerPkg, coresPerPkg); - } - - unsigned char SmtId(unsigned char apicId) const - { - return apicId & m_smtIdMask.mask; - } - - unsigned char CoreId(unsigned char apicId) const - { - return (apicId & m_coreIdMask.mask) >> m_smtIdMask.width; - } - - unsigned char PackageId(unsigned char apicId) const - { - return (apicId & m_pkgIdMask.mask) >> (m_smtIdMask.width + m_coreIdMask.width); - } - - unsigned char PackageCoreId(unsigned char apicId) const - { - return (apicId & (m_pkgIdMask.mask | m_coreIdMask.mask)) >> m_smtIdMask.width; - } - - unsigned int GetLogProcsPerPkg() const - { - return m_logProcsPerPkg; - } - - unsigned int GetCoresPerPkg() const - { - return m_coresPerPkg; - } - - void SetPackageTopology(unsigned int logProcsPerPkg, unsigned int coresPerPkg) - { - m_logProcsPerPkg = (unsigned char) logProcsPerPkg; - m_coresPerPkg = (unsigned char) coresPerPkg; - - m_smtIdMask.width = GetMaskWidth(m_logProcsPerPkg / m_coresPerPkg); - m_coreIdMask.width = GetMaskWidth(m_coresPerPkg); - m_pkgIdMask.width = 8 - (m_smtIdMask.width + m_coreIdMask.width); - - m_pkgIdMask.mask = (unsigned char) (0xFF << (m_smtIdMask.width + m_coreIdMask.width)); - m_coreIdMask.mask = (unsigned char) ((0xFF << m_smtIdMask.width) ^ m_pkgIdMask.mask); - m_smtIdMask.mask = (unsigned char) ~(0xFF << m_smtIdMask.width); - } - -private: - unsigned char GetMaskWidth(unsigned char maxIds) const - { - --maxIds; - unsigned char msbIdx(8); - unsigned char msbMask(0x80); - while (msbMask && !(msbMask & maxIds)) - { - --msbIdx; - msbMask >>= 1; - } - return msbIdx; - } - - struct IdMask - { - unsigned char width; - unsigned char mask; - }; - - unsigned char m_logProcsPerPkg; - unsigned char m_coresPerPkg; - IdMask m_smtIdMask; - IdMask m_coreIdMask; - IdMask m_pkgIdMask; -}; - - -// Fallback solution for WinXP 32/64 -static void GetNumCPUCoresApic(unsigned int& totAvailToSystem, unsigned int& totAvailToProcess) -{ - unsigned int numLogicalPerPhysical(1); - unsigned int numCoresPerPhysical(1); - - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000001); - if ((CPUInfo[3] & 0x10000000) != 0) // Hyperthreading / Multicore bit set - { - numLogicalPerPhysical = (CPUInfo[1] & 0x00FF0000) >> 16; - - if (IsIntel()) - { - __cpuid(CPUInfo, 0x00000000); - if (CPUInfo[0] >= 0x00000004) - { - __cpuidex(CPUInfo, 4, 0); - numCoresPerPhysical = ((CPUInfo[0] & 0xFC000000) >> 26) + 1; - } - } - else if (IsAMD()) - { - __cpuid(CPUInfo, 0x80000000); - if (CPUInfo[0] >= 0x80000008) - { - __cpuid(CPUInfo, 0x80000008); - if (CPUInfo[2] & 0x0000F000) - { - numCoresPerPhysical = 1 << ((CPUInfo[2] & 0x0000F000) >> 12); - } - else - { - numCoresPerPhysical = (CPUInfo[2] & 0xFF) + 1; - } - } - } - } - - HANDLE hCurProcess(GetCurrentProcess()); - HANDLE hCurThread(GetCurrentThread()); - - const int c_maxLogicalProcessors(sizeof(DWORD_PTR) * 8); - unsigned char apicIds[c_maxLogicalProcessors] = { 0 }; - unsigned char items(0); - - DWORD_PTR processAffinity, systemAffinity; - GetProcessAffinityMask(hCurProcess, &processAffinity, &systemAffinity); - - if (systemAffinity == 1) - { - assert(numLogicalPerPhysical == 1); - apicIds[items++] = 0; - } - else - { - if (processAffinity != systemAffinity) - { - SetProcessAffinityMask(hCurProcess, systemAffinity); - } - - DWORD_PTR prevThreadAffinity(0); - for (DWORD_PTR threadAffinity = 1; threadAffinity && threadAffinity <= systemAffinity; threadAffinity <<= 1) - { - if (systemAffinity & threadAffinity) - { - if (!prevThreadAffinity) - { - assert(!items); - prevThreadAffinity = SetThreadAffinityMask(hCurThread, threadAffinity); - } - else - { - assert(items > 0); - SetThreadAffinityMask(hCurThread, threadAffinity); - } - - Sleep(0); - - int CPUInfo2[4]; - __cpuid(CPUInfo2, 0x00000001); - apicIds[items++] = (unsigned char) ((CPUInfo2[1] & 0xFF000000) >> 24); - } - } - - SetProcessAffinityMask(hCurProcess, processAffinity); - SetThreadAffinityMask(hCurThread, prevThreadAffinity); - Sleep(0); - } - - CApicExtractor apicExtractor(numLogicalPerPhysical, numCoresPerPhysical); - - totAvailToSystem = 0; - { - unsigned char pkgCoreIds[c_maxLogicalProcessors] = { 0 }; - for (unsigned int i(0); i < items; ++i) - { - unsigned int j(0); - for (; j < totAvailToSystem; ++j) - { - if (pkgCoreIds[j] == apicExtractor.PackageCoreId(apicIds[i])) - { - break; - } - } - if (j == totAvailToSystem) - { - pkgCoreIds[j] = apicExtractor.PackageCoreId(apicIds[i]); - ++totAvailToSystem; - } - } - } - - totAvailToProcess = 0; - { - unsigned char pkgCoreIds[c_maxLogicalProcessors] = { 0 }; - for (unsigned int i(0); i < items; ++i) - { - if (processAffinity & ((DWORD_PTR) 1 << i)) - { - unsigned int j(0); - for (; j < totAvailToProcess; ++j) - { - if (pkgCoreIds[j] == apicExtractor.PackageCoreId(apicIds[i])) - { - break; - } - } - if (j == totAvailToProcess) - { - pkgCoreIds[j] = apicExtractor.PackageCoreId(apicIds[i]); - ++totAvailToProcess; - } - } - } - } -} - -const char* Win32SysInspect::GetFeatureLevelAsString(Win32SysInspect::DXFeatureLevel featureLevel) -{ - switch (featureLevel) - { - case Win32SysInspect::DXFL_Undefined: - return "unknown"; - case Win32SysInspect::DXFL_9_1: - return "DX9 (SM 2.0)"; - case Win32SysInspect::DXFL_9_2: - return "DX9 (SM 2.0)"; - case Win32SysInspect::DXFL_9_3: - return "DX9 (SM 2.x)"; - case Win32SysInspect::DXFL_10_0: - return "DX10 (SM 4.0)"; - case Win32SysInspect::DXFL_10_1: - return "DX10.1 (SM 4.x)"; - case Win32SysInspect::DXFL_11_0: - default: - return "DX11 (SM 5.0)"; - } -} - -void Win32SysInspect::GetNumCPUCores(unsigned int& totAvailToSystem, unsigned int& totAvailToProcess) -{ - totAvailToSystem = 0; - totAvailToProcess = 0; - - GetNumCPUCoresGlpi(totAvailToSystem, totAvailToProcess); - - if (!totAvailToSystem) - { - GetNumCPUCoresApic(totAvailToSystem, totAvailToProcess); - } -} - - -static Win32SysInspect::DXFeatureLevel GetFeatureLevel(D3D_FEATURE_LEVEL featureLevel) -{ - switch (featureLevel) - { - case D3D_FEATURE_LEVEL_9_1: - return Win32SysInspect::DXFL_9_1; - case D3D_FEATURE_LEVEL_9_2: - return Win32SysInspect::DXFL_9_2; - case D3D_FEATURE_LEVEL_9_3: - return Win32SysInspect::DXFL_9_3; - case D3D_FEATURE_LEVEL_10_0: - return Win32SysInspect::DXFL_10_0; - case D3D_FEATURE_LEVEL_10_1: - return Win32SysInspect::DXFL_10_1; - case D3D_FEATURE_LEVEL_11_0: - default: - return Win32SysInspect::DXFL_11_0; - } -} - -static bool FindGPU(DXGI_ADAPTER_DESC1& adapterDesc, Win32SysInspect::DXFeatureLevel& featureLevel) -{ - memset(&adapterDesc, 0, sizeof(adapterDesc)); - featureLevel = Win32SysInspect::DXFL_Undefined; - - if (!IsVistaOrAbove()) - { - return false; - } - - typedef HRESULT (WINAPI * FP_CreateDXGIFactory1)(REFIID, void**); - FP_CreateDXGIFactory1 pCDXGIF = (FP_CreateDXGIFactory1) GetProcAddress(LoadLibraryA("dxgi.dll"), "CreateDXGIFactory1"); - - IDXGIFactory1* pFactory = 0; - if (pCDXGIF && SUCCEEDED(pCDXGIF(__uuidof(IDXGIFactory1), (void**) &pFactory)) && pFactory) - { - typedef HRESULT (WINAPI * FP_D3D11CreateDevice)(IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT, CONST D3D_FEATURE_LEVEL*, UINT, UINT, ID3D11Device**, D3D_FEATURE_LEVEL*, ID3D11DeviceContext**); - FP_D3D11CreateDevice pD3D11CD = (FP_D3D11CreateDevice) GetProcAddress(LoadLibraryA("d3d11.dll"), "D3D11CreateDevice"); - - if (pD3D11CD) - { - unsigned int nAdapter = 0; - IDXGIAdapter1* pAdapter = 0; - while (pFactory->EnumAdapters1(nAdapter, &pAdapter) != DXGI_ERROR_NOT_FOUND) - { - if (pAdapter) - { - ID3D11Device* pDevice = 0; - D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1}; - D3D_FEATURE_LEVEL deviceFeatureLevel = D3D_FEATURE_LEVEL_9_1; - HRESULT hr = pD3D11CD(pAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, levels, sizeof(levels) / sizeof(levels[0]), D3D11_SDK_VERSION, &pDevice, &deviceFeatureLevel, NULL); - if (SUCCEEDED(hr) && pDevice) - { - IDXGIOutput* pOutput = 0; - const bool displaysConnected = SUCCEEDED(pAdapter->EnumOutputs(0, &pOutput)) && pOutput; - SAFE_RELEASE(pOutput); - - DXGI_ADAPTER_DESC1 ad; - pAdapter->GetDesc1(&ad); - - const Win32SysInspect::DXFeatureLevel fl = GetFeatureLevel(deviceFeatureLevel); - - if (featureLevel < fl && displaysConnected) - { - adapterDesc = ad; - featureLevel = fl; - } - } - - SAFE_RELEASE(pDevice); - SAFE_RELEASE(pAdapter); - } - ++nAdapter; - } - } - } - SAFE_RELEASE(pFactory); - return featureLevel != Win32SysInspect::DXFL_Undefined; -} - - -bool Win32SysInspect::IsDX11Supported() -{ - DXGI_ADAPTER_DESC1 adapterDesc = {}; - DXFeatureLevel featureLevel = Win32SysInspect::DXFL_Undefined; - return FindGPU(adapterDesc, featureLevel) && featureLevel >= DXFL_11_0; -} - - -bool Win32SysInspect::GetGPUInfo(char* pName, size_t bufferSize, unsigned int& vendorID, unsigned int& deviceID, unsigned int& totLocalVidMem, DXFeatureLevel& featureLevel) -{ - if (pName && bufferSize) - { - pName[0] = '\0'; - } - - vendorID = 0; - deviceID = 0; - totLocalVidMem = 0; - featureLevel = Win32SysInspect::DXFL_Undefined; - - DXGI_ADAPTER_DESC1 adapterDesc = {}; - const bool gpuFound = FindGPU(adapterDesc, featureLevel); - if (gpuFound) - { - vendorID = adapterDesc.VendorId; - deviceID = adapterDesc.DeviceId; - - if (pName && bufferSize) - { - sprintf_s(pName, bufferSize, "%s", CryStringUtils::WStrToUTF8(adapterDesc.Description).c_str()); - } - - totLocalVidMem = adapterDesc.DedicatedVideoMemory; - } - - return gpuFound; -} - - -class CGPURating -{ -public: - CGPURating(); - ~CGPURating(); - - int GetRating(unsigned int vendorId, unsigned int deviceId) const; - -private: - struct SGPUID - { - SGPUID(unsigned int vendorId, unsigned int deviceId) - : vendor(vendorId) - , device(deviceId) - { - } - - bool operator < (const SGPUID& rhs) const - { - if (vendor == rhs.vendor) - { - return device < rhs.device; - } - else - { - return vendor < rhs.vendor; - } - } - - unsigned int vendor; - unsigned int device; - }; - - typedef std::map GPURatingMap; - -private: - GPURatingMap m_gpuRatingMap; -}; - - -static size_t SafeReadLine(AZ::IO::IArchive* pPak, AZ::IO::HandleType fileHandle, char* buffer, size_t bufferSize) -{ - assert(buffer && bufferSize); - - memset(buffer, 0, bufferSize); - - size_t bytesRead = pPak->FRead(buffer, bufferSize - 1, fileHandle); - if (!bytesRead) - { - return 0; - } - - char* currentPosition = buffer; - size_t len = 0; - - bool done = false; - int slashRPosition = -1; - do - { - if (*currentPosition != '\r' && *currentPosition != '\n' && len < bufferSize - 1) - { - len++; - currentPosition++; - } - else - { - done = true; - if (*currentPosition == '\r') - { - slashRPosition = len; - } - } - } while (!done); - - // null terminate string - buffer[len] = '\0'; - - ////////////////////////////////////////// - //seek back to the end of the string - int seekback = bytesRead - len - 1; - - // handle CR/LF for file coming from different platforms - if (slashRPosition > -1 && bytesRead > slashRPosition && buffer[slashRPosition + 1] == '\n') - { - seekback--; - } - pPak->FSeek(fileHandle, -seekback, SEEK_CUR); - /////////////////////////////////////////// - - return len; -} - - -#define BUILDPATH_GPURATING(x) "config/gpu/" x - -CGPURating::CGPURating() -{ - auto pPak(gEnv->pCryPak); - - AZ::IO::ArchiveFileIterator h(pPak->FindFirst(BUILDPATH_GPURATING("*.txt"))); - if (h) - { - do - { - char filename[128]; - azsnprintf(filename, sizeof(filename), BUILDPATH_GPURATING("%.*s"), aznumeric_cast(h.m_filename.size()), h.m_filename.data()); - - AZ::IO::HandleType fileHandle = pPak->FOpen(filename, "rb"); - if (fileHandle != AZ::IO::InvalidHandle) - { - size_t lineNr(0); - while (!pPak->FEof(fileHandle)) - { - char line[1024]; - line[0] = '\0'; - size_t len(SafeReadLine(pPak, fileHandle, line, sizeof(line))); - ++lineNr; - - if (len > 2 && line[0] != '/' && line[1] != '/') - { - unsigned int vendorId(0), deviceId(0); - int rating(0); - if (_snscanf_s(line, sizeof(line), "%x,%x,%d", &vendorId, &deviceId, &rating) == 3) - { - GPURatingMap::iterator it(m_gpuRatingMap.find(SGPUID(vendorId, deviceId))); - if (it == m_gpuRatingMap.end()) - { - m_gpuRatingMap.insert(GPURatingMap::value_type(SGPUID(vendorId, deviceId), rating)); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "%s line %d contains a multiple defined GPU rating!", filename, lineNr); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "%s line %d contains incomplete GPU rating!", filename, lineNr); - } - } - } - - pPak->FClose(fileHandle); - } - } while (h = pPak->FindNext(h)); - - pPak->FindClose(h); - } -} - - -CGPURating::~CGPURating() -{ -} - - -int CGPURating::GetRating(unsigned int vendorId, unsigned int deviceId) const -{ - GPURatingMap::const_iterator it(m_gpuRatingMap.find(SGPUID(vendorId, deviceId))); - if (it != m_gpuRatingMap.end()) - { - return (*it).second; - } - else - { - return 0; - } -} - - -int Win32SysInspect::GetGPURating([[maybe_unused]] unsigned int vendorId, [[maybe_unused]] unsigned int deviceId) -{ - return 0; // All GPUs unrated as the database is out of date - - //CGPURating gpuRatingDb; - //return gpuRatingDb.GetRating(vendorId, deviceId); -} - - -static int GetFinalSpecValue(int cpuRating, unsigned int totSysMemMB, int gpuRating, unsigned int totVidMemMB, ESystemConfigSpec maxConfigSpec) -{ - int sysMemRating = 1; - if (totSysMemMB >= Win32SysInspect::SafeMemoryThreshold(12228)) - { - sysMemRating = 3; - } - else if (totSysMemMB >= Win32SysInspect::SafeMemoryThreshold(8192)) - { - sysMemRating = 2; - } - - cpuRating = sysMemRating < cpuRating ? sysMemRating : cpuRating; - - // just a sanity check, GPU should reflect overall GPU perf including memory (higher rated GPUs usually come with enough memory) - if (totVidMemMB < Win32SysInspect::SafeMemoryThreshold(1024)) - { - gpuRating = 1; - } - - int finalRating = cpuRating < gpuRating ? cpuRating : gpuRating; - - return min(finalRating, (int) maxConfigSpec); -} - - -void CSystem::AutoDetectSpec(const bool detectResolution) -{ - CryLogAlways("Running machine spec auto detect (%d bit)...", sizeof(void*) << 3); - - char tempBuf[512]; - - // get OS - SPlatformInfo::EWinVersion winVer(SPlatformInfo::WinUndetected); - bool is64bit(false); - Win32SysInspect::GetOS(winVer, is64bit, tempBuf, sizeof(tempBuf)); - CryLogAlways("- %s", tempBuf); - - // get system memory - uint64 totSysMem(0); - GetSystemMemory(totSysMem); - CryLogAlways("- System memory"); - CryLogAlways("--- %d MB", totSysMem >> 20); - - // get CPU name - GetCPUName(tempBuf, sizeof(tempBuf)); - TrimExcessiveWhiteSpaces(tempBuf); - CryLogAlways("- %s", tempBuf); - - // get number of CPU cores - unsigned int numSysCores(1), numProcCores(1); - Win32SysInspect::GetNumCPUCores(numSysCores, numProcCores); - CryLogAlways("--- Number of available cores: %d (out of %d)", numProcCores, numSysCores); - - // get CPU rating - const int cpuRating = numProcCores >= 4 ? 3 : (numProcCores >= 3 ? 2 : 1); - - // get GPU info - unsigned int gpuVendorId(0), gpuDeviceId(0), totVidMem(0); - Win32SysInspect::DXFeatureLevel featureLevel(Win32SysInspect::DXFL_Undefined); - Win32SysInspect::GetGPUInfo(tempBuf, sizeof(tempBuf), gpuVendorId, gpuDeviceId, totVidMem, featureLevel); - - CryLogAlways("- %s (vendor = 0x%.4x, device = 0x%.4x)", tempBuf, gpuVendorId, gpuDeviceId); - CryLogAlways("--- Dedicated video memory: %d MB", totVidMem >> 20); - CryLogAlways("--- Feature level: %s", GetFeatureLevelAsString(featureLevel)); - - // get GPU rating - const int gpuRating = (totVidMem >> 20) >= Win32SysInspect::SafeMemoryThreshold(4096) ? 3 : ((totVidMem >> 20) >= Win32SysInspect::SafeMemoryThreshold(2048) ? 2 : 1); - - // get final rating - int finalSpecValue(GetFinalSpecValue(cpuRating, totSysMem >> 20, gpuRating, totVidMem >> 20, CONFIG_VERYHIGH_SPEC)); - CryLogAlways("- Final rating: Machine class %d", finalSpecValue); - - m_sys_GraphicsQuality->Set(finalSpecValue); - - if (detectResolution) - { - if ((m_rWidth->GetFlags() & VF_WASINCONFIG) == 0) - { - m_rWidth->Set(GetSystemMetrics(SM_CXFULLSCREEN)); - } - if ((m_rHeight->GetFlags() & VF_WASINCONFIG) == 0) - { - m_rHeight->Set(GetSystemMetrics(SM_CYFULLSCREEN)); - } - if ((m_rFullscreen->GetFlags() & VF_WASINCONFIG) == 0) - { - m_rFullscreen->Set(1); - } - } -} - - -#else - -#include "System.h" - -void CSystem::AutoDetectSpec(const bool detectResolution) -{ - AZ_UNUSED(detectResolution); -} - - -#endif diff --git a/Code/CryEngine/CrySystem/AutoDetectSpec.h b/Code/CryEngine/CrySystem/AutoDetectSpec.h deleted file mode 100644 index a710141668..0000000000 --- a/Code/CryEngine/CrySystem/AutoDetectSpec.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_AUTODETECTSPEC_H -#define CRYINCLUDE_CRYSYSTEM_AUTODETECTSPEC_H -#pragma once - - - -#if defined(WIN32) || defined(WIN64) - -// exposed AutoDetectSpec() helper functions for reuse in CrySystem -namespace Win32SysInspect -{ - enum DXFeatureLevel - { - DXFL_Undefined, - DXFL_9_1, - DXFL_9_2, - DXFL_9_3, - DXFL_10_0, - DXFL_10_1, - DXFL_11_0 - }; - - const char* GetFeatureLevelAsString(DXFeatureLevel featureLevel); - - void GetNumCPUCores(unsigned int& totAvailToSystem, unsigned int& totAvailToProcess); - bool IsDX11Supported(); - bool GetGPUInfo(char* pName, size_t bufferSize, unsigned int& vendorID, unsigned int& deviceID, unsigned int& totLocalVidMem, DXFeatureLevel& featureLevel); - int GetGPURating(unsigned int vendorId, unsigned int deviceId); - void GetOS(SPlatformInfo::EWinVersion& ver, bool& is64Bit, char* pName, size_t bufferSize); - bool IsVistaKB940105Required(); - - inline size_t SafeMemoryThreshold(size_t memMB) - { - return (memMB * 8) / 10; - } -} - -#endif // #if defined(WIN32) || defined(WIN64) - - -#endif // CRYINCLUDE_CRYSYSTEM_AUTODETECTSPEC_H diff --git a/Code/CryEngine/CrySystem/CMakeLists.txt b/Code/CryEngine/CrySystem/CMakeLists.txt index 3261526e8e..5a43051ed7 100644 --- a/Code/CryEngine/CrySystem/CMakeLists.txt +++ b/Code/CryEngine/CrySystem/CMakeLists.txt @@ -9,46 +9,17 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) -ly_get_list_relative_pal_filename(common_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/Common) add_subdirectory(XML) -# The following target is a 'C' file only library to work around an issue in cmake and VS generators that -# will append 'std=c++17' to both C and C++ compiler flags for clang. Do not add any .cpp files to this -# library. -ly_add_target( - NAME CrySystem.DLMalloc.C STATIC - NAMESPACE Legacy - FILES_CMAKE - crysystem_dlmalloc_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - PRIVATE - ${pal_dir} -) - - -ly_get_pal_tool_dirs(pal_tool_dirs ${CMAKE_CURRENT_LIST_DIR}/Platform) - ly_add_target( NAME CrySystem.Static STATIC NAMESPACE Legacy FILES_CMAKE crysystem_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - PLATFORM_INCLUDE_FILES - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake INCLUDE_DIRECTORIES PUBLIC . - ${pal_dir} - PRIVATE - ${common_dir} - ${pal_tool_dirs} BUILD_DEPENDENCIES - PUBLIC - Legacy::CrySystem.DLMalloc.C PRIVATE 3rdParty::expat 3rdParty::lz4 @@ -68,19 +39,11 @@ ly_add_source_properties( VALUES ${LY_PAL_TOOLS_DEFINES} ) -ly_add_source_properties( - SOURCES SystemCFG.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES LY_BUILD=${LY_VERSION_BUILD_NUMBER} -) - ly_add_target( NAME CrySystem ${PAL_TRAIT_MONOLITHIC_DRIVEN_LIBRARY_TYPE} NAMESPACE Legacy FILES_CMAKE crysystem_shared_files.cmake - PLATFORM_INCLUDE_FILES - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake INCLUDE_DIRECTORIES PUBLIC . @@ -90,29 +53,3 @@ ly_add_target( AZ::AzCore Legacy::CryCommon ) - -################################################################################ -# Tests -################################################################################ -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - - ly_add_target( - NAME CrySystem.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Legacy - FILES_CMAKE - crysystem_test_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - . - BUILD_DEPENDENCIES - PRIVATE - AZ::AzTest - Legacy::CryCommon - Legacy::CrySystem.Static - AZ::AzFramework - ) - ly_add_googletest( - NAME Legacy::CrySystem.Tests - ) -endif() - diff --git a/Code/CryEngine/CrySystem/CPUDetect.cpp b/Code/CryEngine/CrySystem/CPUDetect.cpp deleted file mode 100644 index 6d924a1514..0000000000 --- a/Code/CryEngine/CrySystem/CPUDetect.cpp +++ /dev/null @@ -1,1622 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "System.h" -#include "AutoDetectSpec.h" - - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CPUDETECT_CPP_SECTION_1 1 -#define CPUDETECT_CPP_SECTION_2 2 -#endif - -#if defined(WIN32) -#include -#elif defined(LINUX) || defined(APPLE) -#include // setrlimit, getrlimit -#endif - -#if defined(APPLE) -#include -#include // mach_thread_self -#include // Mac OS Thread affinity API -#include -#endif - -#if defined(LINUX) -#ifndef __GNU_SOURCE -#define __GNU_SOURCE -#endif -#include //already includes sched.h -#endif - -/* features */ -#define FPU_FLAG 0x0001 -#define SERIAL_FLAG 0x40000 -#define MMX_FLAG 0x800000 -#define ISSE_FLAG 0x2000000 - -#ifdef __GNUC__ -# define cpuid(op, eax, ebx, ecx, edx) __asm__("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (op) : "cc"); -#endif - -int g_CpuFlags; - -struct SAutoMaxPriority -{ - SAutoMaxPriority() - { - /* get a copy of the current thread and process priorities */ -#if defined(WIN32) - priority_class = GetPriorityClass(GetCurrentProcess()); - thread_priority = GetThreadPriority(GetCurrentThread()); -#elif defined(LINUX) || defined(APPLE) - nice_priority = getpriority(PRIO_PROCESS, 0); - success = nice_priority >= 0 && - pthread_getschedparam(pthread_self(), &thread_policy, &thread_sched_param) == 0; -#endif - - /* make this thread the highest possible priority */ -#if defined(WIN32) - SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); -#elif defined(LINUX) || defined(APPLE) - if (success) - { - setpriority(PRIO_PROCESS, 0, MAX_NICE_PRIORITY); - - sched_param new_sched_param = thread_sched_param; - new_sched_param.sched_priority = sched_get_priority_max(thread_policy); - pthread_setschedparam(pthread_self(), thread_policy, &new_sched_param); - } -#endif - } - - ~SAutoMaxPriority() - { - /* restore the thread priority */ -#if defined(WIN32) - SetPriorityClass(GetCurrentProcess(), priority_class); - SetThreadPriority(GetCurrentThread(), thread_priority); -#elif defined(LINUX) || defined(APPLE) - if (success) - { - pthread_setschedparam(pthread_self(), thread_policy, &thread_sched_param); - setpriority(PRIO_PROCESS, 0, nice_priority); - } -#endif - } - -#if defined(WIN32) - uint32 priority_class; - int thread_priority; -#elif defined(LINUX) || defined(APPLE) - rlimit nice_limit; - int nice_priority; - int thread_policy; - sched_param thread_sched_param; - bool success; - enum - { - MAX_NICE_PRIORITY = 40 - }; -#endif -}; - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_ASM_VOLATILE_CPUID -static inline void __cpuid(int CPUInfo[4], int InfoType) -{ - asm volatile("cpuid" : "=a" (*CPUInfo), "=b" (*(CPUInfo + 1)), "=c" (*(CPUInfo + 2)), "=d" (*(CPUInfo + 3)) : "a" (InfoType)); -} -#endif - -bool IsAMD() -{ -// Broken out for validation support. -#if defined(WIN32) || (defined(LINUX) && !defined(ANDROID)) || defined(MAC) - #define AZ_SUPPORTS_AMD -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CPUDETECT_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(CPUDetect_cpp) -#endif - -#if defined(AZ_SUPPORTS_AMD) - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000000); - - char szCPU[13]; - memset(szCPU, 0, sizeof(szCPU)); - *(int*)&szCPU[0] = CPUInfo[1]; - *(int*)&szCPU[4] = CPUInfo[3]; - *(int*)&szCPU[8] = CPUInfo[2]; - - return (strcmp(szCPU, "AuthenticAMD") == 0); -#else - return false; -#endif -} - -bool IsIntel() -{ -#if defined(WIN32) || (defined(LINUX) && !defined(ANDROID)) || defined(MAC) - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000000); - - char szCPU[13]; - memset(szCPU, 0, sizeof(szCPU)); - *(int*)&szCPU[0] = CPUInfo[1]; - *(int*)&szCPU[4] = CPUInfo[3]; - *(int*)&szCPU[8] = CPUInfo[2]; - - return (strcmp(szCPU, "GenuineIntel") == 0); -#else - return false; -#endif -} - -bool Has64bitExtension() -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HAS64BITEXT - int CPUInfo[4]; - __cpuid(CPUInfo, 0x80000001); // Argument "Processor Signature and AMD Features" - if (CPUInfo[3] & 0x20000000) // Bit 29 in edx is set if 64-bit address extension is supported - { - return true; - } - else - { - return false; - } -#elif defined(WIN64) || defined(LINUX64) || defined(MAC) - return true; -#else - return false; -#endif -} - -bool HTSupported() -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HTSUPPORTED - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000001); - if (CPUInfo[3] & 0x10000000) // Bit 28 in edx is set if HT is supported - { - return true; - } - else - { - return false; - } -#else - return false; -#endif -} - -uint8 LogicalProcPerPhysicalProc() -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000001); - // Bits 16-23 in ebx contain the number of logical processors per physical processor when execute cpuid with eax set to 1 - return (uint8) ((CPUInfo[1] & 0x00FF0000) >> 16); -#else - return 1; -#endif -} - -uint8 GetAPIC_ID() -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000001); - // Bits 24-31 in ebx contain the unique initial APIC ID for the processor this code is running on. Default value = 0xff if HT is not supported. - return (uint8) ((CPUInfo[1] & 0xFF000000) >> 24); -#else - return 0; -#endif -} - -void GetCPUName(char* pName) -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID - if (pName) - { - int CPUInfo[4]; - __cpuid(CPUInfo, 0x80000000); - if (CPUInfo[0] >= 0x80000004) - { - __cpuid(CPUInfo, 0x80000002); - ((int*)pName)[0] = CPUInfo[0]; - ((int*)pName)[1] = CPUInfo[1]; - ((int*)pName)[2] = CPUInfo[2]; - ((int*)pName)[3] = CPUInfo[3]; - - __cpuid(CPUInfo, 0x80000003); - ((int*)pName)[4] = CPUInfo[0]; - ((int*)pName)[5] = CPUInfo[1]; - ((int*)pName)[6] = CPUInfo[2]; - ((int*)pName)[7] = CPUInfo[3]; - - __cpuid(CPUInfo, 0x80000004); - ((int*)pName)[8] = CPUInfo[0]; - ((int*)pName)[9] = CPUInfo[1]; - ((int*)pName)[10] = CPUInfo[2]; - ((int*)pName)[11] = CPUInfo[3]; - } - else - { - pName[0] = '\0'; - } - } -#else - if (pName) - { - pName[0] = '\0'; - } -#endif -} - -bool HasFPUOnChip() -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000001); - // Bit 0 in edx indicates presents of on chip FPU - return (CPUInfo[3] & 0x00000001) != 0; -#else - return false; -#endif -} - -void GetCPUSteppingModelFamily(int& stepping, int& model, int& family) -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID - int CPUInfo[4]; - __cpuid(CPUInfo, 0x00000001); - stepping = CPUInfo[0] & 0xF; // Bit 0-3 in eax specifies stepping - model = (CPUInfo[0] >> 4) & 0xF; // Bit 4-7 in eax specifies model - family = (CPUInfo[0] >> 8) & 0xF; // Bit 8-11 in eax specifies family -#else - stepping = 0; - model = 0; - family = 0; -#endif -} - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID -unsigned long GetCPUFeatureSet() -{ - unsigned long features = 0; - - int CPUInfo[4]; - - __cpuid(CPUInfo, 0); - const int nIds = CPUInfo[0]; - - __cpuid(CPUInfo, 0x80000000); - const unsigned int nExIds = CPUInfo[0]; - - if (nIds > 0) - { - __cpuid(CPUInfo, 0x00000001); - - if (CPUInfo[3] & (1 << 26)) - { - features |= CFI_SSE2; - } - if (CPUInfo[3] & (1 << 25)) - { - features |= CFI_SSE; - } - if (CPUInfo[2] & (1 << 0)) - { - features |= CFI_SSE3; - } - if (CPUInfo[2] & (1 << 29)) - { - features |= CFI_F16C; - } - if (CPUInfo[2] & (1 << 19)) - { - features |= CFI_SSE41; - } - } - - if (nExIds > 0x80000000) - { - __cpuid(CPUInfo, 0x80000001); - if (CPUInfo[3] & (1 << 31)) - { - features |= CFI_3DNOW; - } - } - - return features; -} -#endif - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEFINE_DETECT_PROCESSOR -static unsigned long __stdcall DetectProcessor(void* arg) -{ - const char hex_chars[16] = - { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' - }; - unsigned long signature = 0; - unsigned long cache_temp; - unsigned long cache_eax = 0; - unsigned long cache_ebx = 0; - unsigned long cache_ecx = 0; - unsigned long cache_edx = 0; - unsigned long features_edx = 0; - unsigned long serial_number[3]; - unsigned char cpu_type; - unsigned char fpu_type; - unsigned char CPUID_flag = 0; - unsigned char celeron_flag = 0; - unsigned char pentiumxeon_flag = 0; - unsigned char amd3d_flag = 0; - unsigned char name_flag = 0; - char vendor[13]; - vendor[0] = '\0'; - char name[49]; - name[0] = '\0'; - char* serial; - const char* cpu_string; - const char* cpu_extra_string; - const char* fpu_string; - const char* vendor_string; - SCpu* p = (SCpu*) arg; - - memset(p, 0, sizeof(*p)); - - if (IsAMD() && Has64bitExtension()) - { - p->meVendor = eCVendor_AMD; - p->mFeatures |= GetCPUFeatureSet(); - p->mbSerialPresent = false; - azstrcpy(p->mSerialNumber, AZ_ARRAY_SIZE(p->mSerialNumber), ""); - GetCPUSteppingModelFamily(p->mStepping, p->mModel, p->mFamily); - azstrcpy(p->mVendor, AZ_ARRAY_SIZE(p->mVendor), "AMD"); - GetCPUName(p->mCpuType); - azstrcpy(p->mFpuType, AZ_ARRAY_SIZE(p->mFpuType), HasFPUOnChip() ? "On-Chip" : "Unknown"); - p->mbPhysical = true; - - return 1; - } - else if (IsIntel() && Has64bitExtension()) - { - p->meVendor = eCVendor_Intel; - p->mFeatures |= GetCPUFeatureSet(); - p->mbSerialPresent = false; - azstrcpy(p->mSerialNumber, AZ_ARRAY_SIZE(p->mSerialNumber), ""); - GetCPUSteppingModelFamily(p->mStepping, p->mModel, p->mFamily); - azstrcpy(p->mVendor, AZ_ARRAY_SIZE(p->mVendor), "Intel"); - GetCPUName(p->mCpuType); - azstrcpy(p->mFpuType, AZ_ARRAY_SIZE(p->mFpuType), HasFPUOnChip() ? "On-Chip" : "Unknown"); - - p->mbPhysical = true; - - return 1; - } - - cpu_type = 0xF; - fpu_type = 3; - signature = 0; - - p->mFamily = cpu_type; - p->mModel = (signature >> 4) & 0xf; - p->mStepping = signature & 0xf; - - p->mFeatures = 0; - - p->mFeatures |= amd3d_flag ? CFI_3DNOW : 0; - p->mFeatures |= (features_edx & MMX_FLAG) ? CFI_MMX : 0; - p->mFeatures |= (features_edx & ISSE_FLAG) ? CFI_SSE : 0; - p->mbSerialPresent = ((features_edx & SERIAL_FLAG) != 0); - - if (features_edx & SERIAL_FLAG) - { - serial_number[0] = serial_number[1] = serial_number[2] = 0; - - /* format number */ - serial = p->mSerialNumber; - - serial[0] = hex_chars[(serial_number[2] >> 28) & 0x0f]; - serial[1] = hex_chars[(serial_number[2] >> 24) & 0x0f]; - serial[2] = hex_chars[(serial_number[2] >> 20) & 0x0f]; - serial[3] = hex_chars[(serial_number[2] >> 16) & 0x0f]; - - serial[4] = '-'; - - serial[5] = hex_chars[(serial_number[2] >> 12) & 0x0f]; - serial[6] = hex_chars[(serial_number[2] >> 8) & 0x0f]; - serial[7] = hex_chars[(serial_number[2] >> 4) & 0x0f]; - serial[8] = hex_chars[(serial_number[2] >> 0) & 0x0f]; - - serial[9] = '-'; - - serial[10] = hex_chars[(serial_number[1] >> 28) & 0x0f]; - serial[11] = hex_chars[(serial_number[1] >> 24) & 0x0f]; - serial[12] = hex_chars[(serial_number[1] >> 20) & 0x0f]; - serial[13] = hex_chars[(serial_number[1] >> 16) & 0x0f]; - - serial[14] = '-'; - - serial[15] = hex_chars[(serial_number[1] >> 12) & 0x0f]; - serial[16] = hex_chars[(serial_number[1] >> 8) & 0x0f]; - serial[17] = hex_chars[(serial_number[1] >> 4) & 0x0f]; - serial[18] = hex_chars[(serial_number[1] >> 0) & 0x0f]; - - serial[19] = '-'; - - serial[20] = hex_chars[(serial_number[0] >> 28) & 0x0f]; - serial[21] = hex_chars[(serial_number[0] >> 24) & 0x0f]; - serial[22] = hex_chars[(serial_number[0] >> 20) & 0x0f]; - serial[23] = hex_chars[(serial_number[0] >> 16) & 0x0f]; - - serial[24] = '-'; - - serial[25] = hex_chars[(serial_number[0] >> 12) & 0x0f]; - serial[26] = hex_chars[(serial_number[0] >> 8) & 0x0f]; - serial[27] = hex_chars[(serial_number[0] >> 4) & 0x0f]; - serial[28] = hex_chars[(serial_number[0] >> 0) & 0x0f]; - - serial[29] = 0; - } - - vendor_string = "Unknown"; - cpu_string = "Unknown"; - cpu_extra_string = ""; - fpu_string = "Unknown"; - - if (!CPUID_flag) - { - switch (cpu_type) - { - case 0: - cpu_string = "8086"; - break; - - case 2: - cpu_string = "80286"; - break; - - case 3: - cpu_string = "80386"; - switch (fpu_type) - { - case 2: - fpu_string = "80287"; - break; - - case 1: - fpu_string = "80387"; - break; - - default: - fpu_string = "None"; - break; - } - break; - - case 4: - if (fpu_type) - { - cpu_string = "80486DX, 80486DX2 or 80487SX"; - fpu_string = "on-chip"; - } - else - { - cpu_string = "80486SX"; - } - break; - } - } - else - { /* using CPUID instruction */ - if (!name_flag) - { - if (!strcmp(vendor, "GenuineIntel")) - { - vendor_string = "Intel"; - switch (cpu_type) - { - case 4: - switch (p->mModel) - { - case 0: - case 1: - cpu_string = "80486DX"; - break; - - case 2: - cpu_string = "80486SX"; - break; - - case 3: - cpu_string = "80486DX2"; - break; - - case 4: - cpu_string = "80486SL"; - break; - - case 5: - cpu_string = "80486SX2"; - break; - - case 7: - cpu_string = "Write-Back Enhanced 80486DX2"; - break; - - case 8: - cpu_string = "80486DX4"; - break; - - default: - cpu_string = "80486"; - } - break; - - case 5: - switch (p->mModel) - { - default: - case 1: - case 2: - case 3: - cpu_string = "Pentium"; - break; - - case 4: - cpu_string = "Pentium MMX"; - break; - } - break; - - case 6: - switch (p->mModel) - { - case 1: - cpu_string = "Pentium Pro"; - break; - - case 3: - cpu_string = "Pentium II"; - break; - - case 5: - case 7: - { - cache_temp = cache_eax & 0xFF000000; - if (cache_temp == 0x40000000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44000000) && (cache_temp <= 0x45000000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_eax & 0xFF0000; - if (cache_temp == 0x400000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x440000) && (cache_temp <= 0x450000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_eax & 0xFF00; - if (cache_temp == 0x4000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x4400) && (cache_temp <= 0x4500)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ebx & 0xFF000000; - if (cache_temp == 0x40000000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44000000) && (cache_temp <= 0x45000000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ebx & 0xFF0000; - if (cache_temp == 0x400000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x440000) && (cache_temp <= 0x450000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ebx & 0xFF00; - if (cache_temp == 0x4000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x4400) && (cache_temp <= 0x4500)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ebx & 0xFF; - if (cache_temp == 0x40) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44) && (cache_temp <= 0x45)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ecx & 0xFF000000; - if (cache_temp == 0x40000000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44000000) && (cache_temp <= 0x45000000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ecx & 0xFF0000; - if (cache_temp == 0x400000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x440000) && (cache_temp <= 0x450000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ecx & 0xFF00; - if (cache_temp == 0x4000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x4400) && (cache_temp <= 0x4500)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_ecx & 0xFF; - if (cache_temp == 0x40) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44) && (cache_temp <= 0x45)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_edx & 0xFF000000; - if (cache_temp == 0x40000000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44000000) && (cache_temp <= 0x45000000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_edx & 0xFF0000; - if (cache_temp == 0x400000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x440000) && (cache_temp <= 0x450000)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_edx & 0xFF00; - if (cache_temp == 0x4000) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x4400) && (cache_temp <= 0x4500)) - { - pentiumxeon_flag = 1; - } - cache_temp = cache_edx & 0xFF; - if (cache_temp == 0x40) - { - celeron_flag = 1; - } - if ((cache_temp >= 0x44) && (cache_temp <= 0x45)) - { - pentiumxeon_flag = 1; - } - - if (celeron_flag) - { - cpu_string = "Celeron"; - } - else - { - if (pentiumxeon_flag) - { - if (p->mModel == 5) - { - cpu_string = "Pentium II Xeon"; - } - else - { - cpu_string = "Pentium III Xeon"; - } - } - else - { - if (p->mModel == 5) - { - cpu_string = "Pentium II"; - } - else - { - cpu_string = "Pentium III"; - } - } - } - } - break; - - case 6: - cpu_string = "Celeron"; - break; - - case 8: - cpu_string = "Pentium III"; - break; - } - break; - } - - if (signature & 0x1000) - { - cpu_extra_string = " OverDrive"; - } - else - if (signature & 0x2000) - { - cpu_extra_string = " dual upgrade"; - } - } - else - if (!strcmp(vendor, "CyrixInstead")) - { - vendor_string = "Cyrix"; - switch (p->mFamily) - { - case 4: - switch (p->mModel) - { - case 4: - cpu_string = "MediaGX"; - break; - } - break; - - case 5: - switch (p->mModel) - { - case 2: - cpu_string = "6x86"; - break; - - case 4: - cpu_string = "GXm"; - break; - } - break; - - case 6: - switch (p->mModel) - { - case 0: - cpu_string = "6x86MX"; - break; - } - break; - } - } - else - if (!strcmp(vendor, "AuthenticAMD")) - { - cry_strcpy(p->mVendor, "AMD"); - switch (p->mFamily) - { - case 4: - cpu_string = "Am486 or Am5x86"; - break; - - case 5: - switch (p->mModel) - { - case 0: - case 1: - case 2: - case 3: - cpu_string = "K5"; - break; - - case 4: - case 5: - case 6: - case 7: - cpu_string = "K6"; - break; - - case 8: - cpu_string = "K6-2"; - break; - - case 9: - cpu_string = "K6-III"; - break; - } - break; - - case 6: - cpu_string = "Athlon"; - break; - } - } - else - if (!strcmp(vendor, "CentaurHauls")) - { - vendor_string = "Centaur"; - switch (cpu_type) - { - case 5: - switch (p->mModel) - { - case 4: - cpu_string = "WinChip"; - break; - - case 8: - cpu_string = "WinChip2"; - break; - } - break; - } - } - else - if (!strcmp(vendor, "UMC UMC UMC ")) - { - vendor_string = "UMC"; - } - else - if (!strcmp(vendor, "NexGenDriven")) - { - vendor_string = "NexGen"; - } - } - else - { - vendor_string = vendor; - cpu_string = name; - } - - if (features_edx & FPU_FLAG) - { - fpu_string = "On-Chip"; - } - else - { - fpu_string = "Unknown"; - } - } - - stack_string sCpuType = stack_string(cpu_string) + cpu_extra_string; - - cry_strcpy(p->mCpuType, sCpuType.c_str()); - cry_strcpy(p->mFpuType, fpu_string); - cry_strcpy(p->mVendor, vendor_string); - - if (!azstricmp(vendor_string, "Intel")) - { - p->meVendor = eCVendor_Intel; - } - else - if (!azstricmp(vendor_string, "Cyrix")) - { - p->meVendor = eCVendor_Cyrix; - } - else - if (!azstricmp(vendor_string, "AMD")) - { - p->meVendor = eCVendor_AMD; - } - else - if (!azstricmp(vendor_string, "Centaur")) - { - p->meVendor = eCVendor_Centaur; - } - else - if (!azstricmp(vendor_string, "NexGen")) - { - p->meVendor = eCVendor_NexGen; - } - else - if (!azstricmp(vendor_string, "UMC")) - { - p->meVendor = eCVendor_UMC; - } - else - { - p->meVendor = eCVendor_Unknown; - } - - if (strstr(cpu_string, "8086")) - { - p->meModel = eCpu_8086; - } - else - if (strstr(cpu_string, "80286")) - { - p->meModel = eCpu_80286; - } - else - if (strstr(cpu_string, "80386")) - { - p->meModel = eCpu_80386; - } - else - if (strstr(cpu_string, "80486")) - { - p->meModel = eCpu_80486; - } - else - if (!azstricmp(cpu_string, "Pentium MMX") || !azstricmp(cpu_string, "Pentium")) - { - p->meModel = eCpu_Pentium; - } - else - if (!azstricmp(cpu_string, "Pentium Pro")) - { - p->meModel = eCpu_PentiumPro; - } - else - if (!azstricmp(cpu_string, "Pentium II")) - { - p->meModel = eCpu_Pentium2; - } - else - if (!azstricmp(cpu_string, "Pentium III")) - { - p->meModel = eCpu_Pentium3; - } - else - if (!azstricmp(cpu_string, "Pentium 4")) - { - p->meModel = eCpu_Pentium4; - } - else - if (!azstricmp(cpu_string, "Celeron")) - { - p->meModel = eCpu_Celeron; - } - else - if (!azstricmp(cpu_string, "Pentium II Xeon")) - { - p->meModel = eCpu_Pentium2Xeon; - } - else - if (!azstricmp(cpu_string, "Pentium III Xeon")) - { - p->meModel = eCpu_Pentium3Xeon; - } - else - if (!azstricmp(cpu_string, "MediaGX")) - { - p->meModel = eCpu_CyrixMediaGX; - } - else - if (!azstricmp(cpu_string, "6x86")) - { - p->meModel = eCpu_Cyrix6x86; - } - else - if (!azstricmp(cpu_string, "GXm")) - { - p->meModel = eCpu_CyrixGXm; - } - else - if (!azstricmp(cpu_string, "6x86MX")) - { - p->meModel = eCpu_Cyrix6x86MX; - } - else - if (!azstricmp(cpu_string, "Am486 or Am5x86")) - { - p->meModel = eCpu_Am5x86; - } - else - if (!azstricmp(cpu_string, "K5")) - { - p->meModel = eCpu_AmK5; - } - else - if (!azstricmp(cpu_string, "K6")) - { - p->meModel = eCpu_AmK6; - } - else - if (!azstricmp(cpu_string, "K6-2")) - { - p->meModel = eCpu_AmK6_2; - } - else - if (!azstricmp(cpu_string, "K6-III")) - { - p->meModel = eCpu_AmK6_3; - } - else - if (!azstricmp(cpu_string, "Athlon")) - { - p->meModel = eCpu_AmAthlon; - } - else - if (!azstricmp(cpu_string, "Duron")) - { - p->meModel = eCpu_AmDuron; - } - else - if (!azstricmp(cpu_string, "WinChip")) - { - p->meModel = eCpu_CenWinChip; - } - else - if (!azstricmp(cpu_string, "WinChip2")) - { - p->meModel = eCpu_CenWinChip2; - } - else - { - p->meModel = eCpu_Unknown; - } - - p->mbPhysical = true; - if (!strcmp(vendor_string, "GenuineIntel") && p->mStepping > 4 && HTSupported()) - { - p->mbPhysical = (GetAPIC_ID() & LogicalProcPerPhysicalProc() - 1) == 0; - } - - return 1; -} -#endif //AZ_LEGACY_CRYSYSTEM_TRAIT_DEFINE_DETECT_PROCESSOR - -#if defined(MAC) || (defined(LINUX) && !defined(ANDROID)) -static void* DetectProcessorThreadProc(void* pData) -{ - DetectProcessor(pData); - return NULL; -} -#endif // MAC LINUX - -// #define SQRT_TEST -#ifdef SQRT_TEST -/* ------------------------------------------------------------------------------ */ - -ILINE float CorrectInvSqrt(float fNum, float fInvSqrtEst) -{ - // Newton-Rhapson method for improving estimated inv sqrt. - // f(x) = x^(-1/2) - // f(n) = f(a) + (n-a)f'(a) - // = a^(-1/2) + (n-a)(-1/2)a^(-3/2) - // = a^(-1/2)*3/2 - na^(-3/2)/2 - // = e*3/2 - ne^3/2 - return fInvSqrtEst * (1.5f - fNum * fInvSqrtEst * fInvSqrtEst * 0.5f); -} - - -float Null(float f) { return f; } -float Inv(float f) { return 1.f / f; } - -float Square(float f) { return f * f; } -float InvSquare(float f) { return 1.f / (f * f); } - -float Sqrt(float f) { return sqrtf(f); } -float SqrtT(float f) { return sqrt_tpl(f); } -float SqrtFT(float f) { return sqrt_fast_tpl(f); } - -float InvSqrt(float f) { return 1.f / sqrtf(f); } -float ISqrtT(float f) { return isqrt_tpl(f); } -float ISqrtFT(float f) { return isqrt_fast_tpl(f); } - -float SSEInv(float f) -{ - __m128 s = _mm_rcp_ss(_mm_load_ss(&f)); - float r; - _mm_store_ss(&r, s); - return r; -} -float SSESqrt(float f) -{ - __m128 s = _mm_sqrt_ss(_mm_load_ss(&f)); - float r; - _mm_store_ss(&r, s); - return r; -} -float SSEISqrt(float f) -{ - __m128 s = _mm_sqrt_ss(_mm_load_ss(&f)); - float r; - _mm_store_ss(&r, s); - return 1.f / r; -} -float SSERSqrt(float f) -{ - __m128 s = _mm_rsqrt_ss(_mm_load_ss(&f)); - float r; - _mm_store_ss(&r, s); - return r; -} -float SSERSqrtInv(float f) -{ - __m128 s = _mm_rcp_ss(_mm_rsqrt_ss(_mm_load_ss(&f))); - float r; - _mm_store_ss(&r, s); - return r; -} -float SSERSqrtNR(float f) -{ - __m128 s = _mm_rsqrt_ss(_mm_load_ss(&f)); - float r; - _mm_store_ss(&r, s); - return CorrectInvSqrt(f, r); -} -float SSERISqrtNR(float f) -{ - __m128 s = _mm_rsqrt_ss(_mm_load_ss(&f)); - float r; - _mm_store_ss(&r, s); - return 1.f / CorrectInvSqrt(f, r); -} - -inline float cryISqrtf(float fVal) -{ - unsigned int* n1 = (unsigned int*)&fVal; - unsigned int n = 0x5f3759df - (*n1 >> 1); - float* n2 = (float*)&n; - fVal = (1.5f - (fVal * 0.5f) * *n2 * *n2) * *n2; - return fVal; -} - -float cryISqrtNRf(float f) -{ - return CorrectInvSqrt(f, cryISqrtf(f)); -} - -inline float crySqrtf(float fVal) -{ - return 1.0f / cryISqrtf(fVal); -} - -/* ------------------------------------------------------------------------------ */ -struct SMathTest -{ - typedef int64 TTime; - static inline TTime GetTime() - { - return CryGetTicks(); - } - - static const int T = 100, N = 1000; - float fNullTime; - - float aTestVals[T]; - float aResVals[T]; - - typedef float (* FFloatFunc)(float f); - - float Timer(const char* sName, FFloatFunc func, FFloatFunc finv) - { - for (int i = 0; i < T; i++) - { - aResVals[i] = func(aTestVals[i]); - } - TTime tStart = GetTime(); - for (int r = 0; r < N; r++) - { - for (int i = 0; i < T; i++) - { - aResVals[i] = func(aTestVals[i]); - } - } - float fTime = (GetTime() - tStart) / float(N * T); - - // Error computation. - float fAvgErr = 0.f, fMaxErr = 0.f; - for (int i = 0; i < T; i++) - { - float fErr = abs(finv(aResVals[i]) / aTestVals[i] - 1.f); - fAvgErr += fErr; - fMaxErr = max(fMaxErr, fErr); - } - fAvgErr /= float(T); - - CryLogAlways("%-20s : %5.2f cycles, avg err %.2e, max err %.2e", sName, fTime - fNullTime, fAvgErr, fMaxErr); - - return fTime; - }; - - SMathTest() - { - for (int i = 0; i < T; i++) - { - aTestVals[i] = powf(cry_random(1.f, 2.f), cry_random(-30.f, 30.f)); - } - - CryLogAlways("--- Math Test ---"); - - fNullTime = 0.f; - fNullTime = Timer("(null)", &Null, &Null); - - CryLogAlways("-- Inverse methods"); - Timer("1/f", &Inv, &Inv); - Timer("rcpss", &SSEInv, &Inv); - - CryLogAlways("-- Sqrt methods"); - Timer("sqrtf()", &Sqrt, &Square); - Timer("sqrt_tpl()", &SqrtT, &Square); - Timer("sqrt_fast_tpl()", &SqrtFT, &Square); - Timer("crySqrt()", &crySqrtf, &Square); - - // Timer("sqrtss", &SSESqrt, &Square); - // Timer("rsqrtss,rcpss", &SSERSqrtInv, &Square); - Timer("1/rsqrtss,correction", &SSERISqrtNR, &Square); - - CryLogAlways("-- InvSqrt methods"); - Timer("1/sqrtf()", &InvSqrt, &InvSquare); - Timer("isqrt_tpl()", &ISqrtT, &InvSquare); - Timer("isqrt_fast_tpl()", &ISqrtFT, &InvSquare); - Timer("cryISqrt()", &cryISqrtf, &InvSquare); - - Timer("1/sqrtss", &SSEISqrt, &InvSquare); - // Timer("rsqrtss", &SSERSqrt, &InvSquare); - // Timer("rsqrtss,correction", &SSERSqrtNR, &InvSquare); - Timer("cryISqrt,correction", &cryISqrtNRf, &InvSquare); - - CryLogAlways("--------------------"); - } -}; - -#endif // SQRT_TEST - -#if defined(LINUX) -// collection of functions to read from /proc/cpuinfo - -static bool proc_read_str(char* buffer, char* output, size_t output_length) -{ - if (!buffer || !output || output_length <= 0) - { - return false; - } - while (*buffer && *buffer != ':') - { - ++buffer; - } - if (*buffer == ':') - { - buffer += 2; - cry_strcpy(output, output_length, buffer); - const int len = strlen(output); - if (len > 0 && output[len - 1] == '\n') - { - output[len - 1] = '\0'; - } - return true; - } - return false; -} - - -static bool proc_read_int(char* buffer, int& output) -{ - if (!buffer) - { - return false; - } - while (*buffer && *buffer != ':') - { - ++buffer; - } - if (*buffer == ':') - { - buffer += 2; - output = atoi(buffer); - return true; - } - return false; -} -#endif - -/* ------------------------------------------------------------------------------ */ -void CCpuFeatures::Detect(void) -{ - m_NumSystemProcessors = 1; - m_NumAvailProcessors = 0; - - ////////////////////////////////////////////////////////////////////////// -#if AZ_LEGACY_CRYSYSTEM_TRAIT_HASAFFINITYMASK - CryLogAlways(""); - - DWORD_PTR process_affinity_mask = 1; - - /* get the system info to derive the number of processors within the system. */ - - SYSTEM_INFO sys_info; - DWORD_PTR system_affinity_mask; - GetSystemInfo(&sys_info); - m_NumLogicalProcessors = m_NumSystemProcessors = sys_info.dwNumberOfProcessors; - m_NumAvailProcessors = 0; - GetProcessAffinityMask(GetCurrentProcess(), &process_affinity_mask, &system_affinity_mask); - - for (unsigned char c = 0; c < m_NumSystemProcessors; c++) - { - if (process_affinity_mask & ((DWORD_PTR)1 << c)) - { - m_NumAvailProcessors++; - SetProcessAffinityMask(GetCurrentProcess(), DWORD_PTR(1) << c); - DetectProcessor(&m_Cpu[c]); - m_Cpu[c].mAffinityMask = ((DWORD_PTR)1 << c); - } - } - - SetProcessAffinityMask(GetCurrentProcess(), process_affinity_mask); - - m_bOS_ISSE = false; - m_bOS_ISSE_EXCEPTIONS = false; -#elif defined(LINUX) - // Retrieve information from /proc/cpuinfo - FILE* cpu_info = fopen("/proc/cpuinfo", "r"); - if (!cpu_info) - { - m_NumLogicalProcessors = m_NumSystemProcessors = m_NumAvailProcessors = 1; - CryLogAlways("Could not open /proc/cpuinfo, defaulting values to 1."); - } - else - { - int nCores = 0; - int nCpu = -1; - int index = 0; - char buffer[512]; - while (!feof(cpu_info)) - { - if (nCpu >= MAX_CPU) - { - --nCpu; //Decrement so the sets after the while loop matches the number of CPUs examined - CryLogAlways("Found a higher than expected number of CPUs, defaulting to %d", MAX_CPU); - break; - } - - fgets(buffer, sizeof(buffer), cpu_info); - - if (buffer[0] == '\0' || buffer[0] == '\n') - { - continue; - } - - if (strncmp("processor", buffer, (index = strlen("processor"))) == 0) - { - ++nCpu; - } - else if (strncmp("vendor_id", buffer, (index = strlen("vendor_id"))) == 0) - { - proc_read_str(&buffer[index], m_Cpu[nCpu].mVendor, sizeof(m_Cpu[nCpu].mVendor)); - } - else if (strncmp("model name", buffer, (index = strlen("model name"))) == 0) - { - proc_read_str(&buffer[index], m_Cpu[nCpu].mCpuType, sizeof(m_Cpu[nCpu].mCpuType)); - } - else if (strncmp("cpu cores", buffer, (index = strlen("cpu cores"))) == 0 && nCores == 0) - { - proc_read_int(&buffer[index], nCores); - } - else if (strncmp("fpu", buffer, (index = strlen("fpu"))) == 0) - { - while (buffer[index] != ':' && index < 512) - { - ++index; - } - if (buffer[index] == ':') - { - if (strncmp(&buffer[index + 2], "yes", 3) == 0) - { - snprintf(m_Cpu[nCpu].mFpuType, sizeof(m_Cpu[nCpu].mFpuType), "On-Chip"); - } - else - { - snprintf(m_Cpu[nCpu].mFpuType, sizeof(m_Cpu[nCpu].mFpuType), "Unkown"); - } - } - } - else if (strncmp("cpu family", buffer, (index = strlen("cpu family"))) == 0) - { - proc_read_int(&buffer[index], m_Cpu[nCpu].mFamily); - } - else if (strncmp("model", buffer, (index = strlen("model"))) == 0) - { - proc_read_int(&buffer[index], m_Cpu[nCpu].mModel); - } - else if (strncmp("stepping", buffer, (index = strlen("stepping"))) == 0) - { - proc_read_int(&buffer[index], m_Cpu[nCpu].mStepping); - } - else if (strncmp("flags", buffer, (index = strlen("flags"))) == 0) - { - if (strstr(buffer + index, "mmx")) - { - m_Cpu[nCpu].mFeatures |= CFI_MMX; - } - - if (strstr(buffer + index, "sse")) - { - m_Cpu[nCpu].mFeatures |= CFI_SSE; - } - - if (strstr(buffer + index, "sse2")) - { - m_Cpu[nCpu].mFeatures |= CFI_SSE2; - } - } - } - m_NumLogicalProcessors = m_NumAvailProcessors = nCpu + 1; - m_NumSystemProcessors = nCores; - } - - -#elif defined(APPLE) - size_t len; - unsigned int ncpu; - - len = sizeof(ncpu); - if (sysctlbyname ("hw.physicalcpu_max", &ncpu, &len, NULL, 0) == 0) - { - m_NumSystemProcessors = ncpu; - } - else - { - CryLogAlways("Failed to detect the number of available processors, defaulting to 1"); - m_NumSystemProcessors = 1; - } - - if (sysctlbyname ("hw.logicalcpu_max", &ncpu, &len, NULL, 0) == 0) - { - m_NumAvailProcessors = m_NumLogicalProcessors = ncpu; - } - else - { - CryLogAlways("Failed to detect the number of available logical processors, defaulting to 1"); - m_NumAvailProcessors = m_NumLogicalProcessors = 1; - } - uint64_t cpu_freq; - len = sizeof(cpu_freq); - if (sysctlbyname ("hw.cpufrequency_max", &cpu_freq, &len, NULL, 0) != 0) - { - CryLogAlways("Failed to detect cpu frequency , defaulting to 0"); - cpu_freq = 0; - } - - // On macs, the processors are always the same model, so we can easily - // calculate once and apply the settings for all. - SCpu cpuInfo; -#if !defined(IOS) - DetectProcessor(&cpuInfo); -#endif - for (int c = 0; c < m_NumAvailProcessors; c++) - { - m_Cpu[c] = cpuInfo; - } - -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CPUDETECT_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(CPUDetect_cpp) -#endif - - -#if defined(WIN32) || defined(WIN64) - CryLogAlways("Total number of logical processors: %d", m_NumSystemProcessors); - CryLogAlways("Number of available logical processors: %d", m_NumAvailProcessors); - - unsigned int numSysCores(1), numProcessCores(1); - Win32SysInspect::GetNumCPUCores(numSysCores, numProcessCores); - m_NumSystemProcessors = numSysCores; - m_NumAvailProcessors = numProcessCores; - CryLogAlways("Total number of system cores: %d", m_NumSystemProcessors); - CryLogAlways("Number of cores available to process: %d", m_NumAvailProcessors); - -#else - CryLogAlways("Number of system processors: %d", m_NumSystemProcessors); - CryLogAlways("Number of available processors: %d", m_NumAvailProcessors); -#endif - - if (m_NumAvailProcessors > MAX_CPU) - { - m_NumAvailProcessors = MAX_CPU; - } - - for (int i = 0; i < m_NumAvailProcessors; i++) - { - SCpu* p = &m_Cpu[i]; - - CryLogAlways(" "); - CryLogAlways("Processor %d:", i); - CryLogAlways(" CPU: %s %s", p->mVendor, p->mCpuType); - CryLogAlways(" Family: %d, Model: %d, Stepping: %d", p->mFamily, p->mModel, p->mStepping); - CryLogAlways(" FPU: %s", p->mFpuType); - CryLogAlways(" 3DNow!: %s", (p->mFeatures & CFI_3DNOW) ? "present" : "not present"); - CryLogAlways(" MMX: %s", (p->mFeatures & CFI_MMX) ? "present" : "not present"); - CryLogAlways(" SSE: %s", (p->mFeatures & CFI_SSE) ? "present" : "not present"); - CryLogAlways(" SSE2: %s", (p->mFeatures & CFI_SSE2) ? "present" : "not present"); - CryLogAlways(" SSE3: %s", (p->mFeatures & CFI_SSE3) ? "present" : "not present"); - CryLogAlways(" SSE4.1: %s", (p->mFeatures& CFI_SSE41) ? "present" : "not present"); - if (p->mbSerialPresent) - { - CryLogAlways(" Serial number: %s", p->mSerialNumber); - } - else - { - CryLogAlways(" Serial number not present or disabled"); - } - } - -#ifdef SQRT_TEST - SMathTest test; -#endif - - CryLogAlways(" "); - - //m_NumPhysicsProcessors = m_NumSystemProcessors; - for (int i = m_NumPhysicsProcessors = 0; i < m_NumAvailProcessors; i++) - { - if (m_Cpu[i].mbPhysical) - { - ++m_NumPhysicsProcessors; - } - } - - // Set the cpu flags global variable - g_CpuFlags = 0; - if (hasMMX()) - { - g_CpuFlags |= CPUF_MMX; - } - if (hasSSE()) - { - g_CpuFlags |= CPUF_SSE; - } - if (hasSSE2()) - { - g_CpuFlags |= CPUF_SSE2; - } - if (hasSSE3()) - { - g_CpuFlags |= CPUF_SSE3; - } - if (hasSSE41()) - { - g_CpuFlags |= CPUF_SSE41; - } - if (has3DNow()) - { - g_CpuFlags |= CPUF_3DNOW; - } - if (hasF16C()) - { - g_CpuFlags |= CPUF_F16C; - } -} - diff --git a/Code/CryEngine/CrySystem/CPUDetect.h b/Code/CryEngine/CrySystem/CPUDetect.h deleted file mode 100644 index e2851d5f23..0000000000 --- a/Code/CryEngine/CrySystem/CPUDetect.h +++ /dev/null @@ -1,180 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_CPUDETECT_H -#define CRYINCLUDE_CRYSYSTEM_CPUDETECT_H -#pragma once - - -//------------------------------------------------------- -/// Cpu class -//------------------------------------------------------- -#if defined(WIN64) || defined(LINUX) - #define MAX_CPU 96 -#else - #define MAX_CPU 32 -#endif - -/// Cpu Features -#define CFI_FPUEMULATION 0x01 -#define CFI_MMX 0x02 -#define CFI_3DNOW 0x04 -#define CFI_SSE 0x08 -#define CFI_SSE2 0x10 -#define CFI_SSE3 0x20 -#define CFI_F16C 0x40 -#define CFI_SSE41 0x80 - -/// Type of Cpu Vendor. -enum ECpuVendor -{ - eCVendor_Unknown, - eCVendor_Intel, - eCVendor_Cyrix, - eCVendor_AMD, - eCVendor_Centaur, - eCVendor_NexGen, - eCVendor_UMC, - eCVendor_M68K -}; - -/// Type of Cpu Model. -enum ECpuModel -{ - eCpu_Unknown, - - eCpu_8086, - eCpu_80286, - eCpu_80386, - eCpu_80486, - eCpu_Pentium, - eCpu_PentiumPro, - eCpu_Pentium2, - eCpu_Pentium3, - eCpu_Pentium4, - eCpu_Pentium2Xeon, - eCpu_Pentium3Xeon, - eCpu_Celeron, - eCpu_CeleronA, - - eCpu_Am5x86, - eCpu_AmK5, - eCpu_AmK6, - eCpu_AmK6_2, - eCpu_AmK6_3, - eCpu_AmK6_3D, - eCpu_AmAthlon, - eCpu_AmDuron, - - eCpu_CyrixMediaGX, - eCpu_Cyrix6x86, - eCpu_CyrixGXm, - eCpu_Cyrix6x86MX, - - eCpu_CenWinChip, - eCpu_CenWinChip2, -}; - -struct SCpu -{ - ECpuVendor meVendor; - ECpuModel meModel; - unsigned long mFeatures; - bool mbSerialPresent; - char mSerialNumber[30]; - int mFamily; - int mModel; - int mStepping; - char mVendor[64]; - char mCpuType[64]; - char mFpuType[64]; - bool mbPhysical; // false for hyperthreaded - DWORD_PTR mAffinityMask; - - // constructor - SCpu() - : meVendor(eCVendor_Unknown) - , meModel(eCpu_Unknown) - , mFeatures(0) - , mbSerialPresent(false) - , mFamily(0) - , mModel(0) - , mStepping(0) - , mbPhysical(true) - , mAffinityMask(0) - { - memset(mSerialNumber, 0, sizeof(mSerialNumber)); - memset(mVendor, 0, sizeof(mVendor)); - memset(mCpuType, 0, sizeof(mCpuType)); - memset(mFpuType, 0, sizeof(mFpuType)); - } -}; - -class CCpuFeatures -{ -private: - int m_NumLogicalProcessors; - int m_NumSystemProcessors; - int m_NumAvailProcessors; - int m_NumPhysicsProcessors; - bool m_bOS_ISSE; - bool m_bOS_ISSE_EXCEPTIONS; -public: - - SCpu m_Cpu[MAX_CPU]; - -public: - CCpuFeatures() - { - m_NumLogicalProcessors = 0; - m_NumSystemProcessors = 0; - m_NumAvailProcessors = 0; - m_NumPhysicsProcessors = 0; - m_bOS_ISSE = 0; - m_bOS_ISSE_EXCEPTIONS = 0; - ZeroMemory(m_Cpu, sizeof(m_Cpu)); - } - - void Detect(void); - bool hasSSE() { return (m_Cpu[0].mFeatures & CFI_SSE) != 0; } - bool hasSSE2() { return (m_Cpu[0].mFeatures & CFI_SSE2) != 0; } - bool hasSSE3() { return (m_Cpu[0].mFeatures & CFI_SSE3) != 0; } - bool hasSSE41() { return (m_Cpu[0].mFeatures & CFI_SSE41) != 0; } - bool has3DNow() { return (m_Cpu[0].mFeatures & CFI_3DNOW) != 0; } - bool hasMMX() { return (m_Cpu[0].mFeatures & CFI_MMX) != 0; } - bool hasF16C() { return (m_Cpu[0].mFeatures & CFI_F16C) != 0; } - - unsigned int GetLogicalCPUCount() { return m_NumLogicalProcessors; } - unsigned int GetPhysCPUCount() { return m_NumPhysicsProcessors; } - unsigned int GetCPUCount() { return m_NumAvailProcessors; } - DWORD_PTR GetCPUAffinityMask(unsigned int iCPU) { assert(iCPU < MAX_CPU); return iCPU < GetCPUCount() ? m_Cpu[iCPU].mAffinityMask : 0; } - DWORD_PTR GetPhysCPUAffinityMask(unsigned int iCPU) - { - if (iCPU > GetPhysCPUCount()) - { - return 0; - } - int i; - for (i = 0; (int)iCPU >= 0; i++) - { - if (m_Cpu[i].mbPhysical) - { - --iCPU; - } - } - PREFAST_ASSUME(i > 0 && i < MAX_CPU); - return m_Cpu[i - 1].mAffinityMask; - } -}; - -#endif // CRYINCLUDE_CRYSYSTEM_CPUDETECT_H diff --git a/Code/CryEngine/CrySystem/ClientHandler.cpp b/Code/CryEngine/CrySystem/ClientHandler.cpp deleted file mode 100644 index a708d876f9..0000000000 --- a/Code/CryEngine/CrySystem/ClientHandler.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "ClientHandler.h" - -ClientHandler::ClientHandler(const char* bucket, int affinity, int clientTimeout) - : HandlerBase(bucket, affinity) -{ - m_clientTimeout = clientTimeout; - Reset(); -} - -void ClientHandler::Reset() -{ - m_srvLock.reset(0); - for (int i = 0; i < MAX_CLIENTS_NUM; i++) - { - std::unique_ptr srv(new SSyncLock(m_serverLockName, i, false)); - - // first get the client lock up! - if (!srv->IsValid()) - { - //try to create client lock - m_clientLock.reset(new SSyncLock(m_clientLockName, i, true)); - if (m_clientLock->IsValid()) - { - break; - } - else - { - m_clientLock.reset(0); - } - } - } -} - -bool ClientHandler::ServerIsValid() -{ - if (!m_srvLock.get()) - { - if (m_clientLock.get() && m_clientLock->IsValid()) - { - m_srvLock.reset(new SSyncLock(m_serverLockName, m_clientLock->number, false)); - if (m_srvLock->IsValid()) - { - SetAffinity(); - //got synched - return true; - } - m_srvLock.reset(0); - } - return false; - } - return m_srvLock->IsValid(); -} - -bool ClientHandler::Sync() -{ - if (ServerIsValid()) - { - m_clientLock->Signal();//signal that we're done and - if (m_srvLock->Wait(m_clientTimeout))//wait for server - { - //bla bla, track waiting - return true; - } - else - { - Reset(); - } - } - return false; -} - -#endif // defined(MAP_LOADING_SLICING) diff --git a/Code/CryEngine/CrySystem/ClientHandler.h b/Code/CryEngine/CrySystem/ClientHandler.h deleted file mode 100644 index ce325270ad..0000000000 --- a/Code/CryEngine/CrySystem/ClientHandler.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_CLIENTHANDLER_H -#define CRYINCLUDE_CRYSYSTEM_CLIENTHANDLER_H -#pragma once - -#include "HandlerBase.h" -#include "SyncLock.h" - -struct ClientHandler - : public HandlerBase -{ - ClientHandler(const char* bucket, int affinity, int clientTimeout); - - void Reset(); - bool ServerIsValid(); - bool Sync(); - -private: - int m_clientTimeout; - std::unique_ptr m_clientLock; - std::unique_ptr m_srvLock; -}; - -#endif diff --git a/Code/CryEngine/CrySystem/Components/MathConversionTests.cpp b/Code/CryEngine/CrySystem/Components/MathConversionTests.cpp deleted file mode 100644 index 2ee2bc71f2..0000000000 --- a/Code/CryEngine/CrySystem/Components/MathConversionTests.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" -#include - -#include -#include -#include - -//namespace MathConversionUnitTests -//{ -const float kEpsilon = 0.01f; - -bool IsNearlyEqual(const AZ::Vector3& az, const Vec3& ly) -{ - return fcmp(az.GetX(), ly.x, kEpsilon) - && fcmp(az.GetY(), ly.y, kEpsilon) - && fcmp(az.GetZ(), ly.z, kEpsilon); -} - -bool IsNearlyEqual(const AZ::Quaternion& az, const Quat& ly) -{ - return fcmp(az.GetX(), ly.v.x, kEpsilon) - && fcmp(az.GetY(), ly.v.y, kEpsilon) - && fcmp(az.GetZ(), ly.v.z, kEpsilon) - && fcmp(az.GetW(), ly.w, kEpsilon); -} - -bool IsNearlyEqual(const AZ::Transform& az, const Matrix34& ly) -{ - float azFloats[12]; - const AZ::Matrix3x4 matrix3x4 = AZ::Matrix3x4::CreateFromTransform(az); - matrix3x4.StoreToRowMajorFloat12(azFloats); - - const float* lyFloats = ly.GetData(); - - for (int i = 0; i < 12; ++i) - { - if (!fcmp(azFloats[i], lyFloats[i], kEpsilon)) - { - return false; - } - } - return true; -} - -bool IsNearlyEqual(const AZ::Transform& az, const QuatT& ly) -{ - return IsNearlyEqual(az.GetTranslation(), ly.t) - && IsNearlyEqual(az.GetRotation(), ly.q); -} - -TEST(MathConversionTests, BasicConversions) -{ - { // check vector3 comparisons - AZ::Vector3 az(1.f, 2.f, 3.f); - Vec3 ly(1.f, 2.f, 3.f); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - // reverse XYZ - ly = Vec3(3.f, 2.f, 1.f); - EXPECT_TRUE(!IsNearlyEqual(az, ly)); - - // off by 0.1 - ly = Vec3(1.1f, 2.1f, 3.1f); - EXPECT_TRUE(!IsNearlyEqual(az, ly)); - } - - { // check vector3 conversions - Vec3 ly1(1.f, 2.f, 3.f); - AZ::Vector3 az = LYVec3ToAZVec3(ly1); - EXPECT_TRUE(IsNearlyEqual(az, ly1)); - - Vec3 ly2 = AZVec3ToLYVec3(az); - EXPECT_TRUE(IsNearlyEqual(az, ly1)); - EXPECT_TRUE(ly1.IsEquivalent(ly2)); - } - - { // check quaternion comparisons - AZ::Quaternion az(AZ::Quaternion::CreateIdentity()); - Quat ly(IDENTITY); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - az = AZ::Quaternion(1.f, 2.f, 3.f, 4.f); - ly = Quat(4.f, 1.f, 2.f, 3.f); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - // w in wrong place - ly = Quat(1.f, 2.f, 3.f, 4.f); - EXPECT_TRUE(!IsNearlyEqual(az, ly)); - } - - { // check quaternion conversions - Quat ly1(4.f, 1.f, 2.f, 3.f); - AZ::Quaternion az = LYQuaternionToAZQuaternion(ly1); - EXPECT_TRUE(IsNearlyEqual(az, ly1)); - - Quat ly2 = AZQuaternionToLYQuaternion(az); - EXPECT_TRUE(IsNearlyEqual(az, ly2)); - EXPECT_TRUE(Quat::IsEquivalent(ly1, ly2)); - } - - { // check transform comparisons - AZ::Transform az = AZ::Transform::Identity(); - Matrix34 ly = Matrix34::CreateIdentity(); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - // rotating pi/2 will get us a non-symmetric matrix. - // good for testing that we're not confusing rows & columns - float rotation = gf_PI / 2.f; - - ly = Matrix34::CreateRotationX(rotation, Vec3(1.f, 2.f, 3.f)); - az = AZ::Transform::CreateRotationX(rotation); - az.SetTranslation(1.f, 2.f, 3.f); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - // rotate around different axis - ly = Matrix34::CreateRotationY(rotation, Vec3(1.f, 2.f, 3.f)); - EXPECT_TRUE(!IsNearlyEqual(az, ly)); - } - - { // check transform conversions - Matrix34 ly1 = Matrix34::CreateRotationXYZ(Ang3(0.1f, 0.5f, 0.9f), Vec3(1.f, 2.f, 3.f)); - AZ::Transform az = LYTransformToAZTransform(ly1); - EXPECT_TRUE(IsNearlyEqual(az, ly1)); - - Matrix34 ly2 = AZTransformToLYTransform(az); - EXPECT_TRUE(IsNearlyEqual(az, ly2)); - EXPECT_TRUE(Matrix34::IsEquivalent(ly1, ly2)); - } - - { // check QuatT comparisons - AZ::Transform az = AZ::Transform::Identity(); - QuatT ly(IDENTITY); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - az = AZ::Transform::CreateRotationX(AZ::Constants::HalfPi); - az.SetTranslation(1.f, 2.f, 3.f); - ly.q.SetRotationX(AZ::Constants::HalfPi); - ly.t.Set(1.f, 2.f, 3.f); - EXPECT_TRUE(IsNearlyEqual(az, ly)); - - // off by 0.1 - ly.t.z += 0.1f; - EXPECT_TRUE(!IsNearlyEqual(az, ly)); - } - - { // check QuatT conversions - QuatT ly1(Quat::CreateRotationX(AZ::Constants::HalfPi), Vec3(5.f, 6.f, 7.f)); - AZ::Transform az = LYQuatTToAZTransform(ly1); - EXPECT_TRUE(IsNearlyEqual(az, ly1)); - - QuatT ly2 = AZTransformToLYQuatT(az); - EXPECT_TRUE(IsNearlyEqual(az, ly2)); - EXPECT_TRUE(QuatT::IsEquivalent(ly1, ly2)); - } -} -//} // namespace MathConversionUnitTests diff --git a/Code/CryEngine/CrySystem/CompressedFile.cpp b/Code/CryEngine/CrySystem/CompressedFile.cpp deleted file mode 100644 index 9166466e3d..0000000000 --- a/Code/CryEngine/CrySystem/CompressedFile.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "System.h" -#include "CryZlib.h" - -bool CSystem::CompressDataBlock(const void* input, size_t inputSize, void* output, size_t& outputSize, int level) -{ - uLongf destLen = outputSize; - Bytef* dest = static_cast(output); - uLong sourceLen = inputSize; - const Bytef* source = static_cast(input); - bool ok = Z_OK == compress2(dest, &destLen, source, sourceLen, level); - outputSize = destLen; - return ok; -} - -bool CSystem::DecompressDataBlock(const void* input, size_t inputSize, void* output, size_t& outputSize) -{ - uLongf destLen = outputSize; - Bytef* dest = static_cast(output); - uLong sourceLen = inputSize; - const Bytef* source = static_cast(input); - bool ok = Z_OK == uncompress(dest, &destLen, source, sourceLen); - outputSize = destLen; - return ok; -} diff --git a/Code/CryEngine/CrySystem/CryAsyncMemcpy.cpp b/Code/CryEngine/CrySystem/CryAsyncMemcpy.cpp deleted file mode 100644 index b2aaea1634..0000000000 --- a/Code/CryEngine/CrySystem/CryAsyncMemcpy.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include - -namespace -{ - static void cryAsyncMemcpy_Int( - void* dst - , const void* src - , size_t size - , int nFlags - , volatile int* sync) - { - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); - - cryMemcpy(dst, src, size, nFlags); - if (sync) - { - CryInterlockedDecrement(sync); - } - } -} - -#if !defined(CRY_ASYNC_MEMCPY_DELEGATE_TO_CRYSYSTEM) -CRY_ASYNC_MEMCPY_API void cryAsyncMemcpy( -#else -CRY_ASYNC_MEMCPY_API void cryAsyncMemcpyDelegate( -#endif - void* dst - , const void* src - , size_t size - , int nFlags - , volatile int* sync) -{ - AZ::Job* job = AZ::CreateJobFunction( - [dst, src, size, nFlags, sync]() - { - cryAsyncMemcpy_Int(dst, src, size, nFlags, sync); - }, - true); // Auto-delete - job->Start(); -} - - - diff --git a/Code/CryEngine/CrySystem/CryDLMalloc.c b/Code/CryEngine/CrySystem/CryDLMalloc.c deleted file mode 100644 index bcb835b0d5..0000000000 --- a/Code/CryEngine/CrySystem/CryDLMalloc.c +++ /dev/null @@ -1,6645 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#define DEFAULT_GRANULARITY (64 * 1024) //this gets #undef and redefined in the .inl this has to come before that - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYDLMALLOC_C_SECTION_1 1 -#define CRYDLMALLOC_C_SECTION_2 2 - -#include "../../Framework/AzCore/AzCore/PlatformRestrictedFileDef.h" -#define AZ_RESTRICTED_SECTION CRYDLMALLOC_C_SECTION_1 -#include AZ_RESTRICTED_FILE(CryDLMalloc_c) -#elif defined(_WIN32) || defined(LINUX) || defined(APPLE) -#define TRAIT_ENABLE_DLMALLOC 1 -#endif - -#if defined(BUCKET_SIMULATOR) || TRAIT_ENABLE_DLMALLOC -/* - This is a version (aka dlmalloc) of malloc/free/realloc written by - Doug Lea and released to the public domain, as explained at - http://creativecommons.org/licenses/publicdomain. Send questions, - comments, complaints, performance data, etc to dl@cs.oswego.edu - -* Version 2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) - - Note: There may be an updated version of this malloc obtainable at - ftp://gee.cs.oswego.edu/pub/misc/malloc.c - Check before installing! - -* Quickstart - - This library is all in one file to simplify the most common usage: - ftp it, compile it (-O3), and link it into another program. All of - the compile-time options default to reasonable values for use on - most platforms. You might later want to step through various - compile-time and dynamic tuning options. - - For convenience, an include file for code using this malloc is at: - ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.4.h - You don't really need this .h file unless you call functions not - defined in your system include files. The .h file contains only the - excerpts from this file needed for using this malloc on ANSI C/C++ - systems, so long as you haven't changed compile-time options about - naming and tuning parameters. If you do, then you can create your - own malloc.h that does include all settings by cutting at the point - indicated below. Note that you may already by default be using a C - library containing a malloc that is based on some version of this - malloc (for example in linux). You might still want to use the one - in this file to customize settings or to avoid overheads associated - with library versions. - -* Vital statistics: - - Supported pointer/size_t representation: 4 or 8 bytes - size_t MUST be an unsigned type of the same width as - pointers. (If you are using an ancient system that declares - size_t as a signed type, or need it to be a different width - than pointers, you can use a previous release of this malloc - (e.g. 2.7.2) supporting these.) - - Alignment: 8 bytes (default) - This suffices for nearly all current machines and C compilers. - However, you can define MALLOC_ALIGNMENT to be wider than this - if necessary (up to 128bytes), at the expense of using more space. - - Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) - 8 or 16 bytes (if 8byte sizes) - Each malloced chunk has a hidden word of overhead holding size - and status information, and additional cross-check word - if FOOTERS is defined. - - Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) - 8-byte ptrs: 32 bytes (including overhead) - - Even a request for zero bytes (i.e., malloc(0)) returns a - pointer to something of the minimum allocatable size. - The maximum overhead wastage (i.e., number of extra bytes - allocated than were requested in malloc) is less than or equal - to the minimum size, except for requests >= mmap_threshold that - are serviced via mmap(), where the worst case wastage is about - 32 bytes plus the remainder from a system page (the minimal - mmap unit); typically 4096 or 8192 bytes. - - Security: static-safe; optionally more or less - The "security" of malloc refers to the ability of malicious - code to accentuate the effects of errors (for example, freeing - space that is not currently malloc'ed or overwriting past the - ends of chunks) in code that calls malloc. This malloc - guarantees not to modify any memory locations below the base of - heap, i.e., static variables, even in the presence of usage - errors. The routines additionally detect most improper frees - and reallocs. All this holds as long as the static bookkeeping - for malloc itself is not corrupted by some other means. This - is only one aspect of security -- these checks do not, and - cannot, detect all possible programming errors. - - If FOOTERS is defined nonzero, then each allocated chunk - carries an additional check word to verify that it was malloced - from its space. These check words are the same within each - execution of a program using malloc, but differ across - executions, so externally crafted fake chunks cannot be - freed. This improves security by rejecting frees/reallocs that - could corrupt heap memory, in addition to the checks preventing - writes to statics that are always on. This may further improve - security at the expense of time and space overhead. (Note that - FOOTERS may also be worth using with MSPACES.) - - By default detected errors cause the program to abort (calling - "abort()"). You can override this to instead proceed past - errors by defining PROCEED_ON_ERROR. In this case, a bad free - has no effect, and a malloc that encounters a bad address - caused by user overwrites will ignore the bad address by - dropping pointers and indices to all known memory. This may - be appropriate for programs that should continue if at all - possible in the face of programming errors, although they may - run out of memory because dropped memory is never reclaimed. - - If you don't like either of these options, you can define - CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything - else. And if if you are sure that your program using malloc has - no errors or vulnerabilities, you can define INSECURE to 1, - which might (or might not) provide a small performance improvement. - - Thread-safety: NOT thread-safe unless USE_LOCKS defined - When USE_LOCKS is defined, each public call to malloc, free, - etc is surrounded with either a pthread mutex or a win32 - spinlock (depending on WIN32). This is not especially fast, and - can be a major bottleneck. It is designed only to provide - minimal protection in concurrent environments, and to provide a - basis for extensions. If you are using malloc in a concurrent - program, consider instead using nedmalloc - (http://www.nedprod.com/programs/portable/nedmalloc/) or - ptmalloc (See http://www.malloc.de), which are derived - from versions of this malloc. - - System requirements: Any combination of MORECORE and/or MMAP/MUNMAP - This malloc can use unix sbrk or any emulation (invoked using - the CALL_MORECORE macro) and/or mmap/munmap or any emulation - (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system - memory. On most unix systems, it tends to work best if both - MORECORE and MMAP are enabled. On Win32, it uses emulations - based on VirtualAlloc. It also uses common C library functions - like memset. - - Compliance: I believe it is compliant with the Single Unix Specification - (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably - others as well. - -* Overview of algorithms - - This is not the fastest, most space-conserving, most portable, or - most tunable malloc ever written. However it is among the fastest - while also being among the most space-conserving, portable and - tunable. Consistent balance across these factors results in a good - general-purpose allocator for malloc-intensive programs. - - In most ways, this malloc is a best-fit allocator. Generally, it - chooses the best-fitting existing chunk for a request, with ties - broken in approximately least-recently-used order. (This strategy - normally maintains low fragmentation.) However, for requests less - than 256bytes, it deviates from best-fit when there is not an - exactly fitting available chunk by preferring to use space adjacent - to that used for the previous small request, as well as by breaking - ties in approximately most-recently-used order. (These enhance - locality of series of small allocations.) And for very large requests - (>= 256Kb by default), it relies on system memory mapping - facilities, if supported. (This helps avoid carrying around and - possibly fragmenting memory used only for large chunks.) - - All operations (except malloc_stats and mallinfo) have execution - times that are bounded by a constant factor of the number of bits in - a size_t, not counting any clearing in calloc or copying in realloc, - or actions surrounding MORECORE and MMAP that have times - proportional to the number of non-contiguous regions returned by - system allocation routines, which is often just 1. In real-time - applications, you can optionally suppress segment traversals using - NO_SEGMENT_TRAVERSAL, which assures bounded execution even when - system allocators return non-contiguous spaces, at the typical - expense of carrying around more memory and increased fragmentation. - - The implementation is not very modular and seriously overuses - macros. Perhaps someday all C compilers will do as good a job - inlining modular code as can now be done by brute-force expansion, - but now, enough of them seem not to. - - Some compilers issue a lot of warnings about code that is - dead/unreachable only on some platforms, and also about intentional - uses of negation on unsigned types. All known cases of each can be - ignored. - - For a longer but out of date high-level description, see - http://gee.cs.oswego.edu/dl/html/malloc.html - -* MSPACES - If MSPACES is defined, then in addition to malloc, free, etc., - this file also defines mspace_malloc, mspace_free, etc. These - are versions of malloc routines that take an "mspace" argument - obtained using create_mspace, to control all internal bookkeeping. - If ONLY_MSPACES is defined, only these versions are compiled. - So if you would like to use this allocator for only some allocations, - and your system malloc for others, you can compile with - ONLY_MSPACES and then do something like... - static mspace mymspace = create_mspace(0,0); // for example - #define mymalloc(bytes) mspace_malloc(mymspace, bytes) - - (Note: If you only need one instance of an mspace, you can instead - use "USE_DL_PREFIX" to relabel the global malloc.) - - You can similarly create thread-local allocators by storing - mspaces as thread-locals. For example: - static __thread mspace tlms = 0; - void* tlmalloc(size_t bytes) { - if (tlms == 0) tlms = create_mspace(0, 0); - return mspace_malloc(tlms, bytes); - } - void tlfree(void* mem) { mspace_free(tlms, mem); } - - Unless FOOTERS is defined, each mspace is completely independent. - You cannot allocate from one and free to another (although - conformance is only weakly checked, so usage errors are not always - caught). If FOOTERS is defined, then each chunk carries around a tag - indicating its originating mspace, and frees are directed to their - originating spaces. - - ------------------------- Compile-time options --------------------------- - -Be careful in setting #define values for numerical constants of type -size_t. On some systems, literal values are not automatically extended -to size_t precision unless they are explicitly casted. You can also -use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below. - -WIN32 default: defined if _WIN32 defined - Defining WIN32 sets up defaults for MS environment and compilers. - Otherwise defaults are for unix. Beware that there seem to be some - cases where this malloc might not be a pure drop-in replacement for - Win32 malloc: Random-looking failures from Win32 GDI API's (eg; - SetDIBits()) may be due to bugs in some video driver implementations - when pixel buffers are malloc()ed, and the region spans more than - one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb) - default granularity, pixel buffers may straddle virtual allocation - regions more often than when using the Microsoft allocator. You can - avoid this by using VirtualAlloc() and VirtualFree() for all pixel - buffers rather than using malloc(). If this is not possible, - recompile this malloc with a larger DEFAULT_GRANULARITY. - -MALLOC_ALIGNMENT default: (size_t)8 - Controls the minimum alignment for malloc'ed chunks. It must be a - power of two and at least 8, even on machines for which smaller - alignments would suffice. It may be defined as larger than this - though. Note however that code and data structures are optimized for - the case of 8-byte alignment. - -MSPACES default: 0 (false) - If true, compile in support for independent allocation spaces. - This is only supported if HAVE_MMAP is true. - -ONLY_MSPACES default: 0 (false) - If true, only compile in mspace versions, not regular versions. - -USE_LOCKS default: 0 (false) - Causes each call to each public routine to be surrounded with - pthread or WIN32 mutex lock/unlock. (If set true, this can be - overridden on a per-mspace basis for mspace versions.) If set to a - non-zero value other than 1, locks are used, but their - implementation is left out, so lock functions must be supplied manually, - as described below. - -USE_SPIN_LOCKS default: 1 iff USE_LOCKS and on x86 using gcc or MSC - If true, uses custom spin locks for locking. This is currently - supported only for x86 platforms using gcc or recent MS compilers. - Otherwise, posix locks or win32 critical sections are used. - -FOOTERS default: 0 - If true, provide extra checking and dispatching by placing - information in the footers of allocated chunks. This adds - space and time overhead. - -INSECURE default: 0 - If true, omit checks for usage errors and heap space overwrites. - -USE_DL_PREFIX default: NOT defined - Causes compiler to prefix all public routines with the string 'dl'. - This can be useful when you only want to use this malloc in one part - of a program, using your regular system malloc elsewhere. - -ABORT default: defined as abort() - Defines how to abort on failed checks. On most systems, a failed - check cannot die with an "assert" or even print an informative - message, because the underlying print routines in turn call malloc, - which will fail again. Generally, the best policy is to simply call - abort(). It's not very useful to do more than this because many - errors due to overwriting will show up as address faults (null, odd - addresses etc) rather than malloc-triggered checks, so will also - abort. Also, most compilers know that abort() does not return, so - can better optimize code conditionally calling it. - -PROCEED_ON_ERROR default: defined as 0 (false) - Controls whether detected bad addresses cause them to bypassed - rather than aborting. If set, detected bad arguments to free and - realloc are ignored. And all bookkeeping information is zeroed out - upon a detected overwrite of freed heap space, thus losing the - ability to ever return it from malloc again, but enabling the - application to proceed. If PROCEED_ON_ERROR is defined, the - static variable malloc_corruption_error_count is compiled in - and can be examined to see if errors have occurred. This option - generates slower code than the default abort policy. - -DEBUG default: NOT defined - The DEBUG setting is mainly intended for people trying to modify - this code or diagnose problems when porting to new platforms. - However, it may also be able to better isolate user errors than just - using runtime checks. The assertions in the check routines spell - out in more detail the assumptions and invariants underlying the - algorithms. The checking is fairly extensive, and will slow down - execution noticeably. Calling malloc_stats or mallinfo with DEBUG - set will attempt to check every non-mmapped allocated and free chunk - in the course of computing the summaries. - -ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) - Debugging assertion failures can be nearly impossible if your - version of the assert macro causes malloc to be called, which will - lead to a cascade of further failures, blowing the runtime stack. - ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), - which will usually make debugging easier. - -MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 - The action to take before "return 0" when malloc fails to be able to - return memory because there is none available. - -HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES - True if this system supports sbrk or an emulation of it. - -MORECORE default: sbrk - The name of the sbrk-style system routine to call to obtain more - memory. See below for guidance on writing custom MORECORE - functions. The type of the argument to sbrk/MORECORE varies across - systems. It cannot be size_t, because it supports negative - arguments, so it is normally the signed type of the same width as - size_t (sometimes declared as "intptr_t"). It doesn't much matter - though. Internally, we only call it with arguments less than half - the max value of a size_t, which should work across all reasonable - possibilities, although sometimes generating compiler warnings. - -MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE - If true, take advantage of fact that consecutive calls to MORECORE - with positive arguments always return contiguous increasing - addresses. This is true of unix sbrk. It does not hurt too much to - set it true anyway, since malloc copes with non-contiguities. - Setting it false when definitely non-contiguous saves time - and possibly wasted space it would take to discover this though. - -MORECORE_CANNOT_TRIM default: NOT defined - True if MORECORE cannot release space back to the system when given - negative arguments. This is generally necessary only if you are - using a hand-crafted MORECORE function that cannot handle negative - arguments. - -NO_SEGMENT_TRAVERSAL default: 0 - If non-zero, suppresses traversals of memory segments - returned by either MORECORE or CALL_MMAP. This disables - merging of segments that are contiguous, and selectively - releasing them to the OS if unused, but bounds execution times. - -HAVE_MMAP default: 1 (true) - True if this system supports mmap or an emulation of it. If so, and - HAVE_MORECORE is not true, MMAP is used for all system - allocation. If set and HAVE_MORECORE is true as well, MMAP is - primarily used to directly allocate very large blocks. It is also - used as a backup strategy in cases where MORECORE fails to provide - space from system. Note: A single call to MUNMAP is assumed to be - able to unmap memory that may have be allocated using multiple calls - to MMAP, so long as they are adjacent. - -HAVE_MREMAP default: 1 on linux, else 0 - If true realloc() uses mremap() to re-allocate large blocks and - extend or shrink allocation spaces. - -MMAP_CLEARS default: 1 except on WINCE. - True if mmap clears memory so calloc doesn't need to. This is true - for standard unix mmap using /dev/zero and on WIN32 except for WINCE. - -USE_BUILTIN_FFS default: 0 (i.e., not used) - Causes malloc to use the builtin ffs() function to compute indices. - Some compilers may recognize and intrinsify ffs to be faster than the - supplied C version. Also, the case of x86 using gcc is special-cased - to an asm instruction, so is already as fast as it can be, and so - this setting has no effect. Similarly for Win32 under recent MS compilers. - (On most x86s, the asm version is only slightly faster than the C version.) - -malloc_getpagesize default: derive from system includes, or 4096. - The system page size. To the extent possible, this malloc manages - memory from the system in page-size units. This may be (and - usually is) a function rather than a constant. This is ignored - if WIN32, where page size is determined using getSystemInfo during - initialization. - -USE_DEV_RANDOM default: 0 (i.e., not used) - Causes malloc to use /dev/random to initialize secure magic seed for - stamping footers. Otherwise, the current time is used. - -NO_MALLINFO default: 0 - If defined, don't compile "mallinfo". This can be a simple way - of dealing with mismatches between system declarations and - those in this file. - -MALLINFO_FIELD_TYPE default: size_t - The type of the fields in the mallinfo struct. This was originally - defined as "int" in SVID etc, but is more usefully defined as - size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set - -REALLOC_ZERO_BYTES_FREES default: not defined - This should be set if a call to realloc with zero bytes should - be the same as a call to free. Some people think it should. Otherwise, - since this malloc returns a unique pointer for malloc(0), so does - realloc(p, 0). - -LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H -LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H -LACKS_STDLIB_H default: NOT defined unless on WIN32 - Define these if your system does not have these header files. - You might need to manually insert some of the declarations they provide. - -DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, - system_info.dwAllocationGranularity in WIN32, - otherwise 64K. - Also settable using mallopt(M_GRANULARITY, x) - The unit for allocating and deallocating memory from the system. On - most systems with contiguous MORECORE, there is no reason to - make this more than a page. However, systems with MMAP tend to - either require or encourage larger granularities. You can increase - this value to prevent system allocation functions to be called so - often, especially if they are slow. The value must be at least one - page and must be a power of two. Setting to 0 causes initialization - to either page size or win32 region size. (Note: In previous - versions of malloc, the equivalent of this option was called - "TOP_PAD") - -DEFAULT_TRIM_THRESHOLD default: 2MB - Also settable using mallopt(M_TRIM_THRESHOLD, x) - The maximum amount of unused top-most memory to keep before - releasing via malloc_trim in free(). Automatic trimming is mainly - useful in long-lived programs using contiguous MORECORE. Because - trimming via sbrk can be slow on some systems, and can sometimes be - wasteful (in cases where programs immediately afterward allocate - more large chunks) the value should be high enough so that your - overall system performance would improve by releasing this much - memory. As a rough guide, you might set to a value close to the - average size of a process (program) running on your system. - Releasing this much memory would allow such a process to run in - memory. Generally, it is worth tuning trim thresholds when a - program undergoes phases where several large chunks are allocated - and released in ways that can reuse each other's storage, perhaps - mixed with phases where there are no such chunks at all. The trim - value must be greater than page size to have any useful effect. To - disable trimming completely, you can set to MAX_SIZE_T. Note that the trick - some people use of mallocing a huge space and then freeing it at - program startup, in an attempt to reserve system memory, doesn't - have the intended effect under automatic trimming, since that memory - will immediately be returned to the system. - -DEFAULT_MMAP_THRESHOLD default: 256K - Also settable using mallopt(M_MMAP_THRESHOLD, x) - The request size threshold for using MMAP to directly service a - request. Requests of at least this size that cannot be allocated - using already-existing space will be serviced via mmap. (If enough - normal freed space already exists it is used instead.) Using mmap - segregates relatively large chunks of memory so that they can be - individually obtained and released from the host system. A request - serviced through mmap is never reused by any other request (at least - not directly; the system may just so happen to remap successive - requests to the same locations). Segregating space in this way has - the benefits that: Mmapped space can always be individually released - back to the system, which helps keep the system level memory demands - of a long-lived program low. Also, mapped memory doesn't become - `locked' between other chunks, as can happen with normally allocated - chunks, which means that even trimming via malloc_trim would not - release them. However, it has the disadvantage that the space - cannot be reclaimed, consolidated, and then used to service later - requests, as happens with normal chunks. The advantages of mmap - nearly always outweigh disadvantages for "large" chunks, but the - value of "large" may vary across systems. The default is an - empirically derived value that works well in most systems. You can - disable mmap by setting to MAX_SIZE_T. - -MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP - The number of consolidated frees between checks to release - unused segments when freeing. When using non-contiguous segments, - especially with multiple mspaces, checking only for topmost space - doesn't always suffice to trigger trimming. To compensate for this, - free() will, with a period of MAX_RELEASE_CHECK_RATE (or the - current number of segments, if greater) try to release unused - segments to the OS when freeing chunks that result in - consolidation. The best value for this parameter is a compromise - between slowing down frees with relatively costly checks that - rarely trigger versus holding on to unused memory. To effectively - disable, set to MAX_SIZE_T. This may lead to a very slight speed - improvement at the expense of carrying around more memory. -*/ - -/* Version identifier to allow people to support multiple versions */ - -#ifndef DLMALLOC_VERSION -#define DLMALLOC_VERSION 20804 -#endif /* DLMALLOC_VERSION */ - - -#define MAX_RELEASE_CHECK_RATE 255 -#define REALLOC_ZERO_BYTES_FREES -#define USE_DL_PREFIX 1 - -#define mspace_create_overhead dlmspace_create_overhead -#define create_mspace dlcreate_mspace -#define destroy_mspace dldestroy_mspace -#define create_mspace_with_base dlcreate_mspace_with_base -#define mspace_track_large_chunks dlmspace_track_large_chunks -#define mspace_malloc dlmspace_malloc -#define mspace_free dlmspace_free -#define mspace_realloc dlmspace_realloc -#define mspace_calloc dlmspace_calloc -#define mspace_memalign dlmspace_memalign -#define mspace_independent_calloc dlmspace_independent_calloc -#define mspace_independent_comalloc dlmspace_independent_comalloc -#define mspace_footprint dlmspace_footprint -#define mspace_max_footprint dlmspace_max_footprint -#define mspace_mallinfo dlmspace_mallinfo -#define mspace_usable_size dlmspace_usable_size -#define mspace_malloc_stats dlmspace_malloc_stats -#define mspace_get_used_space dlmspace_get_used_space -#define mspace_trim dlmspace_trim -#define mspace_mallopt dlmspace_mallopt - -// Avoid x64 warnings with size_t converted to int -#pragma warning(disable : 4267) -#pragma warning(disable : 6239) -#pragma warning(disable : 6297) -#pragma warning(disable : 28182) - -// Conditional expression is constant -#pragma warning(disable : 4127) - -#ifdef BUCKET_SIMULATOR - -#define HAVE_MORECORE 0 -#define MORECORE SimSBrk -#define DEFAULT_MMAP_THRESHOLD (1024 * 1024) -#define DEFAULT_TRIM_THRESHOLD (256 * 1024) - -#include -#include -#include -#include /* For size_t */ -#include - -static void* s_sbrkBase; -static void* s_sbrkEnd; -static void* s_sbrkMax; - -extern volatile int dlmallocmapped; - -void* SimSBrk(ptrdiff_t size) -{ - void* ret = NULL; - - if (!s_sbrkBase) - { - s_sbrkBase = VirtualAlloc(NULL, 64 * 1024 * 1024, MEM_RESERVE, PAGE_READWRITE); - s_sbrkEnd = s_sbrkBase; - s_sbrkMax = (LPVOID) ((INT_PTR) s_sbrkBase + 64 * 1024 * 1024); - } - - if (s_sbrkEnd) - { - if (size > 0) - { - INT_PTR end = (INT_PTR) s_sbrkEnd; - INT_PTR newEnd = end + size; - - if (newEnd <= (INT_PTR) s_sbrkMax) - { - ret = VirtualAlloc(s_sbrkEnd, size, MEM_COMMIT, PAGE_READWRITE); - if (ret) - { - s_sbrkEnd = (LPVOID) newEnd; - CryInterlockedAdd(&dlmallocmapped, (LONG) size); - } - } - } - else if (size < 0) - { - INT_PTR end = (INT_PTR) s_sbrkEnd; - INT_PTR newEnd = end + size; - - if (newEnd >= (INT_PTR) s_sbrkBase) - { - VirtualFree((LPVOID) newEnd, -size, MEM_DECOMMIT); - CryInterlockedAdd(&dlmallocmapped, (LONG) size); - } - } - else - { - ret = s_sbrkEnd; - } - } - - if (!ret) - { - ret = (void*) -1; - errno = ENOMEM; - } - - return ret; -} -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#elif defined(_WIN32) - -#define HAVE_MMAP 1 -#define HAVE_MORECORE (!HAVE_MMAP) -#define USE_LOCKS 0 -#define FOOTERS 0 -#define ONLY_MSPACES 1 -#define DEFAULT_MMAP_THRESHOLD (1024 * 1024) -#define DEFAULT_TRIM_THRESHOLD (256 * 1024) - -#define PROT_READ 0 -#define PROT_WRITE 0 -#define MAP_PRIVATE 0 -#define MAP_ANONYMOUS 1 - -#define MALLOC_ALIGNMENT 16 - -#define malloc_getpagesize (64 * 1024) - -#include -#include - -#elif defined(LINUX) || defined(APPLE) -#include -#define HAVE_MMAP 1 -#define HAVE_MORECORE (!HAVE_MMAP) -#define USE_LOCKS 0 -#define FOOTERS 0 -#define ONLY_MSPACES 1 -#define DEFAULT_MMAP_THRESHOLD (16 * 1024 * 1024) -#define DEFAULT_TRIM_THRESHOLD (16 * 1024 * 1024) - -#if !defined(ANDROID) && !defined(LINUX_CROSS_COMPILE) -#define PROT_READ 0 -#define PROT_WRITE 0 -#define MAP_PRIVATE 0 -#define MAP_ANONYMOUS 1 -#endif - -#define MALLOC_ALIGNMENT 16 - -#define malloc_getpagesize (64 * 1024) - -#include - -// ( || ) is always a non-zero constant. -#pragma warning(disable:6285) - -// Potential comparison of a constant with another constant -#pragma warning(disable:6326) - -// Dereferencing NULL pointer -#pragma warning(disable:6011) - -#endif - -#ifndef WIN32 -#ifdef _WIN32 -#define WIN32 1 -#endif /* _WIN32 */ -#ifdef _WIN32_WCE -#define LACKS_FCNTL_H -#define WIN32 1 -#endif /* _WIN32_WCE */ -#endif /* WIN32 */ - -#ifdef WIN32 -#include -#define HAVE_MMAP 1 -#ifndef HAVE_MORECORE -#define HAVE_MORECORE 0 -#endif -#define LACKS_UNISTD_H -#define LACKS_SYS_PARAM_H -#define LACKS_SYS_MMAN_H -#define LACKS_STRING_H -#define LACKS_STRINGS_H -#define LACKS_SYS_TYPES_H -#define LACKS_ERRNO_H -#ifndef MALLOC_FAILURE_ACTION -#define MALLOC_FAILURE_ACTION -#endif /* MALLOC_FAILURE_ACTION */ -#ifdef _WIN32_WCE /* WINCE reportedly does not clear */ -#define MMAP_CLEARS 0 -#else -#define MMAP_CLEARS 1 -#endif /* _WIN32_WCE */ -#endif /* WIN32 */ - -#if defined(DARWIN) || defined(_DARWIN) -/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ -#ifndef HAVE_MORECORE -#define HAVE_MORECORE 0 -#define HAVE_MMAP 1 -/* OSX allocators provide 16 byte alignment */ -#ifndef MALLOC_ALIGNMENT -#define MALLOC_ALIGNMENT ((size_t)16U) -#endif -#endif /* HAVE_MORECORE */ -#endif /* DARWIN */ - -#ifndef LACKS_SYS_TYPES_H -#include /* For size_t */ -#endif /* LACKS_SYS_TYPES_H */ - -#if (defined(__GNUC__) && ((defined(__i386__) || defined(__x86_64__)))) || (defined(_MSC_VER)) -#define SPIN_LOCKS_AVAILABLE 1 -#else -#define SPIN_LOCKS_AVAILABLE 0 -#endif - -/* The maximum possible size_t value has all bits set */ -#define MAX_SIZE_T (~(size_t)0) - -#ifndef ONLY_MSPACES -#define ONLY_MSPACES 0 /* define to a value */ -#else -#define ONLY_MSPACES 1 -#endif /* ONLY_MSPACES */ -#ifndef MSPACES -#if ONLY_MSPACES -#define MSPACES 1 -#else /* ONLY_MSPACES */ -#define MSPACES 0 -#endif /* ONLY_MSPACES */ -#endif /* MSPACES */ -#ifndef MALLOC_ALIGNMENT -#define MALLOC_ALIGNMENT ((size_t)8U) -#endif /* MALLOC_ALIGNMENT */ -#ifndef FOOTERS -#define FOOTERS 0 -#endif /* FOOTERS */ -#ifndef ABORT -#define ABORT abort() -#endif /* ABORT */ -#ifndef ABORT_ON_ASSERT_FAILURE -#define ABORT_ON_ASSERT_FAILURE 1 -#endif /* ABORT_ON_ASSERT_FAILURE */ -#ifndef PROCEED_ON_ERROR -#define PROCEED_ON_ERROR 0 -#endif /* PROCEED_ON_ERROR */ -#ifndef USE_LOCKS -#define USE_LOCKS 0 -#endif /* USE_LOCKS */ -#ifndef USE_SPIN_LOCKS -#if USE_LOCKS && SPIN_LOCKS_AVAILABLE -#define USE_SPIN_LOCKS 1 -#else -#define USE_SPIN_LOCKS 0 -#endif /* USE_LOCKS && SPIN_LOCKS_AVAILABLE. */ -#endif /* USE_SPIN_LOCKS */ -#ifndef INSECURE -#define INSECURE 0 -#endif /* INSECURE */ -#ifndef HAVE_MMAP -#define HAVE_MMAP 1 -#endif /* HAVE_MMAP */ -#ifndef MMAP_CLEARS -#define MMAP_CLEARS 1 -#endif /* MMAP_CLEARS */ -#ifndef HAVE_MREMAP -#ifdef linux -#define HAVE_MREMAP 1 -#else /* linux */ -#define HAVE_MREMAP 0 -#endif /* linux */ -#endif /* HAVE_MREMAP */ -#ifndef MALLOC_FAILURE_ACTION -#define MALLOC_FAILURE_ACTION errno = ENOMEM; -#endif /* MALLOC_FAILURE_ACTION */ -#ifndef HAVE_MORECORE -#if ONLY_MSPACES -#define HAVE_MORECORE 0 -#else /* ONLY_MSPACES */ -#define HAVE_MORECORE 1 -#endif /* ONLY_MSPACES */ -#endif /* HAVE_MORECORE */ -#if !HAVE_MORECORE -#define MORECORE_CONTIGUOUS 0 -#else /* !HAVE_MORECORE */ -#define MORECORE_DEFAULT sbrk -#ifndef MORECORE_CONTIGUOUS -#define MORECORE_CONTIGUOUS 1 -#endif /* MORECORE_CONTIGUOUS */ -#endif /* HAVE_MORECORE */ -#ifndef DEFAULT_GRANULARITY -#if (MORECORE_CONTIGUOUS || defined(WIN32)) -#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ -#else /* MORECORE_CONTIGUOUS */ -#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) -#endif /* MORECORE_CONTIGUOUS */ -#endif /* DEFAULT_GRANULARITY */ -#ifndef DEFAULT_TRIM_THRESHOLD -#ifndef MORECORE_CANNOT_TRIM -#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) -#else /* MORECORE_CANNOT_TRIM */ -#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T -#endif /* MORECORE_CANNOT_TRIM */ -#endif /* DEFAULT_TRIM_THRESHOLD */ -#ifndef DEFAULT_MMAP_THRESHOLD -#if HAVE_MMAP -#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) -#else /* HAVE_MMAP */ -#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T -#endif /* HAVE_MMAP */ -#endif /* DEFAULT_MMAP_THRESHOLD */ -#ifndef MAX_RELEASE_CHECK_RATE -#if HAVE_MMAP -#define MAX_RELEASE_CHECK_RATE 4095 -#else -#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T -#endif /* HAVE_MMAP */ -#endif /* MAX_RELEASE_CHECK_RATE */ -#ifndef USE_BUILTIN_FFS -#define USE_BUILTIN_FFS 0 -#endif /* USE_BUILTIN_FFS */ -#ifndef USE_DEV_RANDOM -#define USE_DEV_RANDOM 0 -#endif /* USE_DEV_RANDOM */ -#ifndef NO_MALLINFO -#define NO_MALLINFO 0 -#endif /* NO_MALLINFO */ -#ifndef MALLINFO_FIELD_TYPE -#define MALLINFO_FIELD_TYPE size_t -#endif /* MALLINFO_FIELD_TYPE */ -#ifndef NO_SEGMENT_TRAVERSAL -#define NO_SEGMENT_TRAVERSAL 0 -#endif /* NO_SEGMENT_TRAVERSAL */ - -/* - mallopt tuning options. SVID/XPG defines four standard parameter - numbers for mallopt, normally defined in malloc.h. None of these - are used in this malloc, so setting them has no effect. But this - malloc does support the following options. -*/ - -#define M_TRIM_THRESHOLD (-1) -#define M_GRANULARITY (-2) -#define M_MMAP_THRESHOLD (-3) - -// --------- Traits -------------- - -#if !defined(AZ_RESTRICTED_PLATFORM) - #if defined(_MSC_VER) - #define TRAIT_HAS_BITSCANFORWARD 1 - #define TRAIT_HAS_BITSCANREVERSE 1 - #endif - #if defined(WIN32) - #define TRAIT_HAS_WIN32_MMAP 1 - #endif - #if defined(WIN32) || defined(WIN64) - #define TRAIT_HAS_GETSYSTEMINFO 1 - #endif - #if defined(_WIN32) - #define TRAIT_USE_QUERYPERFORMANCECOUNTER 1 - #endif -#endif - -/* ------------------------ Mallinfo declarations ------------------------ */ - -#if !NO_MALLINFO -/* - This version of malloc supports the standard SVID/XPG mallinfo - routine that returns a struct containing usage properties and - statistics. It should work on any system that has a - /usr/include/malloc.h defining struct mallinfo. The main - declaration needed is the mallinfo struct that is returned (by-copy) - by mallinfo(). The malloinfo struct contains a bunch of fields that - are not even meaningful in this version of malloc. These fields are - are instead filled by mallinfo() with other numbers that might be of - interest. - - HAVE_USR_INCLUDE_MALLOC_H should be set if you have a - /usr/include/malloc.h file that includes a declaration of struct - mallinfo. If so, it is included; else a compliant version is - declared below. These must be precisely the same for mallinfo() to - work. The original SVID version of this struct, defined on most - systems with mallinfo, declares all fields as ints. But some others - define as unsigned long. If your system defines the fields using a - type of different width than listed here, you MUST #include your - system version and #define HAVE_USR_INCLUDE_MALLOC_H. -*/ - -/* #define HAVE_USR_INCLUDE_MALLOC_H */ - -#ifdef HAVE_USR_INCLUDE_MALLOC_H -#include "/usr/include/malloc.h" -#else /* HAVE_USR_INCLUDE_MALLOC_H */ -#ifndef STRUCT_MALLINFO_DECLARED -#define STRUCT_MALLINFO_DECLARED 1 -struct mallinfo -{ - MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ - MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ - MALLINFO_FIELD_TYPE smblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ - MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ - MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ - MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ - MALLINFO_FIELD_TYPE fordblks; /* total free space */ - MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ -}; -#endif /* STRUCT_MALLINFO_DECLARED */ -#endif /* HAVE_USR_INCLUDE_MALLOC_H */ -#endif /* NO_MALLINFO */ - -/* - Try to persuade compilers to inline. The most critical functions for - inlining are defined as macros, so these aren't used for them. -*/ - -#ifndef FORCEINLINE - #if defined(__GNUC__) -#define FORCEINLINE __inline __attribute__ ((always_inline)) - #elif defined(_MSC_VER) - #define FORCEINLINE __forceinline - #endif -#endif -#ifndef NOINLINE - #if defined(__GNUC__) - #define NOINLINE __attribute__ ((noinline)) - #elif defined(_MSC_VER) - #define NOINLINE __declspec(noinline) - #else - #define NOINLINE - #endif -#endif - -#ifdef __cplusplus -extern "C" { -#ifndef FORCEINLINE - #define FORCEINLINE inline -#endif -#endif /* __cplusplus */ -#ifndef FORCEINLINE - #define FORCEINLINE -#endif - -typedef void* (* dlmmap_handler)(void*, size_t); -typedef int (* dlmunmap_handler)(void*, void*, size_t); - -#if !ONLY_MSPACES - -/* ------------------- Declarations of public routines ------------------- */ - -#ifndef USE_DL_PREFIX -#define dlcalloc calloc -#define dlfree free -#define dlmalloc malloc -#define dlmemalign memalign -#define dlrealloc realloc -#define dlvalloc valloc -#define dlpvalloc pvalloc -#define dlmallinfo mallinfo -#define dlmallopt mallopt -#define dlmalloc_trim malloc_trim -#define dlmalloc_stats malloc_stats -#define dlmalloc_usable_size malloc_usable_size -#define dlmalloc_footprint malloc_footprint -#define dlmalloc_max_footprint malloc_max_footprint -#define dlindependent_calloc independent_calloc -#define dlindependent_comalloc independent_comalloc -#endif /* USE_DL_PREFIX */ - - -/* - malloc(size_t n) - Returns a pointer to a newly allocated chunk of at least n bytes, or - null if no space is available, in which case errno is set to ENOMEM - on ANSI C systems. - - If n is zero, malloc returns a minimum-sized chunk. (The minimum - size is 16 bytes on most 32bit systems, and 32 bytes on 64bit - systems.) Note that size_t is an unsigned type, so calls with - arguments that would be negative if signed are interpreted as - requests for huge amounts of space, which will often fail. The - maximum supported value of n differs across systems, but is in all - cases less than the maximum representable value of a size_t. -*/ -void* dlmalloc(size_t); - -/* - free(void* p) - Releases the chunk of memory pointed to by p, that had been previously - allocated using malloc or a related routine such as realloc. - It has no effect if p is null. If p was not malloced or already - freed, free(p) will by default cause the current program to abort. -*/ -void dlfree(void*); - -/* - calloc(size_t n_elements, size_t element_size); - Returns a pointer to n_elements * element_size bytes, with all locations - set to zero. -*/ -void* dlcalloc(size_t, size_t); - -/* - realloc(void* p, size_t n) - Returns a pointer to a chunk of size n that contains the same data - as does chunk p up to the minimum of (n, p's size) bytes, or null - if no space is available. - - The returned pointer may or may not be the same as p. The algorithm - prefers extending p in most cases when possible, otherwise it - employs the equivalent of a malloc-copy-free sequence. - - If p is null, realloc is equivalent to malloc. - - If space is not available, realloc returns null, errno is set (if on - ANSI) and p is NOT freed. - - if n is for fewer bytes than already held by p, the newly unused - space is lopped off and freed if possible. realloc with a size - argument of zero (re)allocates a minimum-sized chunk. - - The old unix realloc convention of allowing the last-free'd chunk - to be used as an argument to realloc is not supported. -*/ - -void* dlrealloc(void*, size_t); - -/* - memalign(size_t alignment, size_t n); - Returns a pointer to a newly allocated chunk of n bytes, aligned - in accord with the alignment argument. - - The alignment argument should be a power of two. If the argument is - not a power of two, the nearest greater power is used. - 8-byte alignment is guaranteed by normal malloc calls, so don't - bother calling memalign with an argument of 8 or less. - - Overreliance on memalign is a sure way to fragment space. -*/ -void* dlmemalign(size_t, size_t); - -/* - valloc(size_t n); - Equivalent to memalign(pagesize, n), where pagesize is the page - size of the system. If the pagesize is unknown, 4096 is used. -*/ -void* dlvalloc(size_t); - -/* - mallopt(int parameter_number, int parameter_value) - Sets tunable parameters The format is to provide a - (parameter-number, parameter-value) pair. mallopt then sets the - corresponding parameter to the argument value if it can (i.e., so - long as the value is meaningful), and returns 1 if successful else - 0. To workaround the fact that mallopt is specified to use int, - not size_t parameters, the value -1 is specially treated as the - maximum unsigned size_t value. - - SVID/XPG/ANSI defines four standard param numbers for mallopt, - normally defined in malloc.h. None of these are use in this malloc, - so setting them has no effect. But this malloc also supports other - options in mallopt. See below for details. Briefly, supported - parameters are as follows (listed defaults are for "typical" - configurations). - - Symbol param # default allowed param values - M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables) - M_GRANULARITY -2 page size any power of 2 >= page size - M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) -*/ -int dlmallopt(int, int); - -/* - malloc_footprint(); - Returns the number of bytes obtained from the system. The total - number of bytes allocated by malloc, realloc etc., is less than this - value. Unlike mallinfo, this function returns only a precomputed - result, so can be called frequently to monitor memory consumption. - Even if locks are otherwise defined, this function does not use them, - so results might not be up to date. -*/ -size_t dlmalloc_footprint(void); - -/* - malloc_max_footprint(); - Returns the maximum number of bytes obtained from the system. This - value will be greater than current footprint if deallocated space - has been reclaimed by the system. The peak number of bytes allocated - by malloc, realloc etc., is less than this value. Unlike mallinfo, - this function returns only a precomputed result, so can be called - frequently to monitor memory consumption. Even if locks are - otherwise defined, this function does not use them, so results might - not be up to date. -*/ -size_t dlmalloc_max_footprint(void); - -#if !NO_MALLINFO -/* - mallinfo() - Returns (by copy) a struct containing various summary statistics: - - arena: current total non-mmapped bytes allocated from system - ordblks: the number of free chunks - smblks: always zero. - hblks: current number of mmapped regions - hblkhd: total bytes held in mmapped regions - usmblks: the maximum total allocated space. This will be greater - than current total if trimming has occurred. - fsmblks: always zero - uordblks: current total allocated space (normal or mmapped) - fordblks: total free space - keepcost: the maximum number of bytes that could ideally be released - back to system via malloc_trim. ("ideally" means that - it ignores page restrictions etc.) - - Because these fields are ints, but internal bookkeeping may - be kept as longs, the reported values may wrap around zero and - thus be inaccurate. -*/ -struct mallinfo dlmallinfo(void); -#endif /* NO_MALLINFO */ - -/* - independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); - - independent_calloc is similar to calloc, but instead of returning a - single cleared space, it returns an array of pointers to n_elements - independent elements that can hold contents of size elem_size, each - of which starts out cleared, and can be independently freed, - realloc'ed etc. The elements are guaranteed to be adjacently - allocated (this is not guaranteed to occur with multiple callocs or - mallocs), which may also improve cache locality in some - applications. - - The "chunks" argument is optional (i.e., may be null, which is - probably the most typical usage). If it is null, the returned array - is itself dynamically allocated and should also be freed when it is - no longer needed. Otherwise, the chunks array must be of at least - n_elements in length. It is filled in with the pointers to the - chunks. - - In either case, independent_calloc returns this pointer array, or - null if the allocation failed. If n_elements is zero and "chunks" - is null, it returns a chunk representing an array with zero elements - (which should be freed if not wanted). - - Each element must be individually freed when it is no longer - needed. If you'd like to instead be able to free all at once, you - should instead use regular calloc and assign pointers into this - space to represent elements. (In this case though, you cannot - independently free elements.) - - independent_calloc simplifies and speeds up implementations of many - kinds of pools. It may also be useful when constructing large data - structures that initially have a fixed number of fixed-sized nodes, - but the number is not known at compile time, and some of the nodes - may later need to be freed. For example: - - struct Node { int item; struct Node* next; }; - - struct Node* build_list() { - struct Node** pool; - int n = read_number_of_nodes_needed(); - if (n <= 0) return 0; - pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); - if (pool == 0) die(); - // organize into a linked list... - struct Node* first = pool[0]; - for (i = 0; i < n-1; ++i) - pool[i]->next = pool[i+1]; - free(pool); // Can now free the array (or not, if it is needed later) - return first; - } -*/ -void** dlindependent_calloc(size_t, size_t, void**); - -/* - independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); - - independent_comalloc allocates, all at once, a set of n_elements - chunks with sizes indicated in the "sizes" array. It returns - an array of pointers to these elements, each of which can be - independently freed, realloc'ed etc. The elements are guaranteed to - be adjacently allocated (this is not guaranteed to occur with - multiple callocs or mallocs), which may also improve cache locality - in some applications. - - The "chunks" argument is optional (i.e., may be null). If it is null - the returned array is itself dynamically allocated and should also - be freed when it is no longer needed. Otherwise, the chunks array - must be of at least n_elements in length. It is filled in with the - pointers to the chunks. - - In either case, independent_comalloc returns this pointer array, or - null if the allocation failed. If n_elements is zero and chunks is - null, it returns a chunk representing an array with zero elements - (which should be freed if not wanted). - - Each element must be individually freed when it is no longer - needed. If you'd like to instead be able to free all at once, you - should instead use a single regular malloc, and assign pointers at - particular offsets in the aggregate space. (In this case though, you - cannot independently free elements.) - - independent_comallac differs from independent_calloc in that each - element may have a different size, and also that it does not - automatically clear elements. - - independent_comalloc can be used to speed up allocation in cases - where several structs or objects must always be allocated at the - same time. For example: - - struct Head { ... } - struct Foot { ... } - - void send_message(char* msg) { - int msglen = strlen(msg); - size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; - void* chunks[3]; - if (independent_comalloc(3, sizes, chunks) == 0) - die(); - struct Head* head = (struct Head*)(chunks[0]); - char* body = (char*)(chunks[1]); - struct Foot* foot = (struct Foot*)(chunks[2]); - // ... - } - - In general though, independent_comalloc is worth using only for - larger values of n_elements. For small values, you probably won't - detect enough difference from series of malloc calls to bother. - - Overuse of independent_comalloc can increase overall memory usage, - since it cannot reuse existing noncontiguous small chunks that - might be available for some of the elements. -*/ -void** dlindependent_comalloc(size_t, size_t*, void**); - - -/* - pvalloc(size_t n); - Equivalent to valloc(minimum-page-that-holds(n)), that is, - round up n to nearest pagesize. - */ -void* dlpvalloc(size_t); - -/* - malloc_trim(size_t pad); - - If possible, gives memory back to the system (via negative arguments - to sbrk) if there is unused memory at the `high' end of the malloc - pool or in unused MMAP segments. You can call this after freeing - large blocks of memory to potentially reduce the system-level memory - requirements of a program. However, it cannot guarantee to reduce - memory. Under some allocation patterns, some large free blocks of - memory will be locked between two used chunks, so they cannot be - given back to the system. - - The `pad' argument to malloc_trim represents the amount of free - trailing space to leave untrimmed. If this argument is zero, only - the minimum amount of memory to maintain internal data structures - will be left. Non-zero arguments can be supplied to maintain enough - trailing space to service future expected allocations without having - to re-obtain memory from the system. - - Malloc_trim returns 1 if it actually released any memory, else 0. -*/ -int dlmalloc_trim(size_t); - -/* - malloc_stats(); - Prints on stderr the amount of space obtained from the system (both - via sbrk and mmap), the maximum amount (which may be more than - current if malloc_trim and/or munmap got called), and the current - number of bytes allocated via malloc (or realloc, etc) but not yet - freed. Note that this is the number of bytes allocated, not the - number requested. It will be larger than the number requested - because of alignment and bookkeeping overhead. Because it includes - alignment wastage as being in use, this figure may be greater than - zero even when no user-level chunks are allocated. - - The reported current and maximum system memory can be inaccurate if - a program makes other calls to system memory allocation functions - (normally sbrk) outside of malloc. - - malloc_stats prints only the most commonly interesting statistics. - More information can be obtained by calling mallinfo. -*/ -void dlmalloc_stats(void); -void dlmalloc_stats_ret(size_t* sys, size_t* maxSys, size_t* used); - -#endif /* ONLY_MSPACES */ - -/* - malloc_usable_size(void* p); - - Returns the number of bytes you can actually use in - an allocated chunk, which may be more than you requested (although - often not) due to alignment and minimum size constraints. - You can use this many bytes without worrying about - overwriting other allocated objects. This is not a particularly great - programming practice. malloc_usable_size can be more useful in - debugging and assertions, for example: - - p = malloc(n); - assert(malloc_usable_size(p) >= 256); -*/ -size_t dlmalloc_usable_size(void*); - - -#if MSPACES - -/* - mspace is an opaque type representing an independent - region of space that supports mspace_malloc, etc. -*/ -typedef void* mspace; - -/* - mspace_create_overhead returns the number of bytes used by an mspace for - internal tracking. Can be used with the capacity argument when creating - an mspace to allocate an exact amount of space upfront. -*/ -int mspace_create_overhead(void); - -/* - create_mspace creates and returns a new independent space with the - given initial capacity, or, if 0, the default granularity size. It - returns null if there is no system memory available to create the - space. If argument locked is non-zero, the space uses a separate - lock to control access. The capacity of the space will grow - dynamically as needed to service mspace_malloc requests. You can - control the sizes of incremental increases of this space by - compiling with a different DEFAULT_GRANULARITY or dynamically - setting with mallopt(M_GRANULARITY, value). -*/ -mspace create_mspace(size_t capacity, int locked, void* user, dlmmap_handler mmap, dlmunmap_handler munmap); - -/* - destroy_mspace destroys the given space, and attempts to return all - of its memory back to the system, returning the total number of - bytes freed. After destruction, the results of access to all memory - used by the space become undefined. -*/ -size_t destroy_mspace(mspace msp); - -/* - create_mspace_with_base uses the memory supplied as the initial base - of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this - space is used for bookkeeping, so the capacity must be at least this - large. (Otherwise 0 is returned.) When this initial space is - exhausted, additional memory will be obtained from the system. - Destroying this space will deallocate all additionally allocated - space (if possible) but not the initial base. -*/ -mspace create_mspace_with_base(void* base, size_t capacity, int locked); - -/* - mspace_track_large_chunks controls whether requests for large chunks - are allocated in their own untracked mmapped regions, separate from - others in this mspace. By default large chunks are not tracked, - which reduces fragmentation. However, such chunks are not - necessarily released to the system upon destroy_mspace. Enabling - tracking by setting to true may increase fragmentation, but avoids - leakage when relying on destroy_mspace to release all memory - allocated using this space. The function returns the previous - setting. -*/ -int mspace_track_large_chunks(mspace msp, int enable); - - -/* - mspace_malloc behaves as malloc, but operates within - the given space. -*/ -void* mspace_malloc(mspace msp, size_t bytes); - -/* - mspace_free behaves as free, but operates within - the given space. - - If compiled with FOOTERS==1, mspace_free is not actually needed. - free may be called instead of mspace_free because freed chunks from - any space are handled by their originating spaces. -*/ -void mspace_free(mspace msp, void* mem); - -/* - mspace_realloc behaves as realloc, but operates within - the given space. - - If compiled with FOOTERS==1, mspace_realloc is not actually - needed. realloc may be called instead of mspace_realloc because - realloced chunks from any space are handled by their originating - spaces. -*/ -void* mspace_realloc(mspace msp, void* mem, size_t newsize); - -/* - mspace_calloc behaves as calloc, but operates within - the given space. -*/ -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); - -/* - mspace_memalign behaves as memalign, but operates within - the given space. -*/ -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); - -/* - mspace_independent_calloc behaves as independent_calloc, but - operates within the given space. -*/ -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]); - -/* - mspace_independent_comalloc behaves as independent_comalloc, but - operates within the given space. -*/ -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]); - -/* - mspace_footprint() returns the number of bytes obtained from the - system for this space. -*/ -size_t mspace_footprint(mspace msp); - -/* - mspace_max_footprint() returns the peak number of bytes obtained from the - system for this space. -*/ -size_t mspace_max_footprint(mspace msp); - - -#if !NO_MALLINFO -/* - mspace_mallinfo behaves as mallinfo, but reports properties of - the given space. -*/ -struct mallinfo mspace_mallinfo(mspace msp); -#endif /* NO_MALLINFO */ - -/* - malloc_usable_size(void* p) behaves the same as malloc_usable_size; -*/ -size_t mspace_usable_size(void* mem); - -/* - mspace_malloc_stats behaves as malloc_stats, but reports - properties of the given space. -*/ -void mspace_malloc_stats(mspace msp); - -/* - mspace_trim behaves as malloc_trim, but - operates within the given space. -*/ -int mspace_trim(mspace msp, size_t pad); - -/* - An alias for mallopt. -*/ -int mspace_mallopt(int, int); - -#endif /* MSPACES */ - -#ifdef __cplusplus -}; /* end of extern "C" */ -#endif /* __cplusplus */ - -/* - ======================================================================== - To make a fully customizable malloc.h header file, cut everything - above this line, put into file malloc.h, edit to suit, and #include it - on the next line, as well as in programs that use this malloc. - ======================================================================== -*/ - -/* #include "malloc.h" */ - -/*------------------------------ internal #includes ---------------------- */ - -#ifdef WIN32 -#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ -#endif /* WIN32 */ - -#include /* for printing in malloc_stats */ - -#ifndef LACKS_ERRNO_H -#include /* for MALLOC_FAILURE_ACTION */ -#endif /* LACKS_ERRNO_H */ -#if FOOTERS || DEBUG -#include /* for magic initialization */ -#endif /* FOOTERS */ -#ifndef LACKS_STDLIB_H -#include /* for abort() */ -#endif /* LACKS_STDLIB_H */ -#ifdef DEBUG -#if ABORT_ON_ASSERT_FAILURE -#undef assert -#define assert(x) if (!(x)) ABORT -#else /* ABORT_ON_ASSERT_FAILURE */ -#include -#endif /* ABORT_ON_ASSERT_FAILURE */ -#else /* DEBUG */ -#ifndef assert -#define assert(x) -#endif -#define DEBUG 0 -#endif /* DEBUG */ -#ifndef LACKS_STRING_H -#include /* for memset etc */ -#endif /* LACKS_STRING_H */ -#if USE_BUILTIN_FFS -#ifndef LACKS_STRINGS_H -#include /* for ffs */ -#endif /* LACKS_STRINGS_H */ -#endif /* USE_BUILTIN_FFS */ -#if HAVE_MMAP -#ifndef LACKS_SYS_MMAN_H -/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */ -#if (defined(linux) && !defined(__USE_GNU)) -#define __USE_GNU 1 -#include /* for mmap */ -#undef __USE_GNU -#else -#include /* for mmap */ -#endif /* linux */ -#endif /* LACKS_SYS_MMAN_H */ -#ifndef LACKS_FCNTL_H -#include -#endif /* LACKS_FCNTL_H */ -#endif /* HAVE_MMAP */ -#ifndef LACKS_UNISTD_H -#include /* for sbrk, sysconf */ -#else /* LACKS_UNISTD_H */ -#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(_WIN32) -extern void* sbrk(ptrdiff_t); -#endif /* FreeBSD etc */ -#endif /* LACKS_UNISTD_H */ - -/* Declarations for locking */ -#if USE_LOCKS -#ifndef WIN32 -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYDLMALLOC_C_SECTION_2 -#include AZ_RESTRICTED_FILE(CryDLMalloc_c) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -#include -#endif -#if defined (__SVR4) && defined (__sun) /* solaris */ -#include -#endif /* solaris */ -#else -#ifndef _M_AMD64 -/* These are already defined on AMD64 builds */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ -LONG __cdecl _InterlockedCompareExchange(LONG volatile* Dest, LONG Exchange, LONG Comp); -LONG __cdecl _InterlockedExchange(LONG volatile* Target, LONG Value); -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* _M_AMD64 */ -#pragma intrinsic (_InterlockedCompareExchange) -#pragma intrinsic (_InterlockedExchange) -#define interlockedcompareexchange _InterlockedCompareExchange -#define interlockedexchange _InterlockedExchange -#endif /* Win32 */ -#endif /* USE_LOCKS */ - -/* Declarations for bit scanning on win32 */ -#if defined(_MSC_VER) && _MSC_VER >= 1300 -#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ -unsigned char _BitScanForward(unsigned long* index, unsigned long mask); -unsigned char _BitScanReverse(unsigned long* index, unsigned long mask); -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#define BitScanForward _BitScanForward -#define BitScanReverse _BitScanReverse -#pragma intrinsic(_BitScanForward) -#pragma intrinsic(_BitScanReverse) -#endif /* BitScanForward */ -#endif /* defined(_MSC_VER) */ - -#ifndef WIN32 -#ifndef malloc_getpagesize -# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ -# ifndef _SC_PAGE_SIZE -# define _SC_PAGE_SIZE _SC_PAGESIZE -# endif -# endif -# ifdef _SC_PAGE_SIZE -# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) -# else -# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) -extern size_t getpagesize(); -# define malloc_getpagesize getpagesize() -# else -# ifdef WIN32 /* use supplied emulation of getpagesize */ -# define malloc_getpagesize getpagesize() -# else -# ifndef LACKS_SYS_PARAM_H -# include -# endif -# ifdef EXEC_PAGESIZE -# define malloc_getpagesize EXEC_PAGESIZE -# else -# ifdef NBPG -# ifndef CLSIZE -# define malloc_getpagesize NBPG -# else -# define malloc_getpagesize (NBPG * CLSIZE) -# endif -# else -# ifdef NBPC -# define malloc_getpagesize NBPC -# else -# ifdef PAGESIZE -# define malloc_getpagesize PAGESIZE -# else /* just guess */ -# define malloc_getpagesize ((size_t)4096U) -# endif -# endif -# endif -# endif -# endif -# endif -# endif -#endif -#endif - - - -/* ------------------- size_t and alignment properties -------------------- */ - -/* The byte and bit size of a size_t */ -#define SIZE_T_SIZE (sizeof(size_t)) -#define SIZE_T_BITSIZE (sizeof(size_t) << 3) - -/* Some constants coerced to size_t */ -/* Annoying but necessary to avoid errors on some platforms */ -#define SIZE_T_ZERO ((size_t)0) -#define SIZE_T_ONE ((size_t)1) -#define SIZE_T_TWO ((size_t)2) -#define SIZE_T_FOUR ((size_t)4) -#define TWO_SIZE_T_SIZES (SIZE_T_SIZE << 1) -#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE << 2) -#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES + TWO_SIZE_T_SIZES) -#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) - -/* The bit mask value corresponding to MALLOC_ALIGNMENT */ -#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) - -/* True if address a has acceptable alignment */ -#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) - -/* the number of bytes to offset an address to align it */ -#define align_offset(A) \ - ((((size_t)(A) &CHUNK_ALIGN_MASK) == 0) ? 0 : \ - ((MALLOC_ALIGNMENT - ((size_t)(A) &CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) - -/* -------------------------- MMAP preliminaries ------------------------- */ - -/* - If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and - checks to fail so compiler optimizer can delete code rather than - using so many "#if"s. -*/ - - -/* MORECORE and MMAP must return MFAIL on failure */ -#define MFAIL ((void*)(MAX_SIZE_T)) -#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ - -#if HAVE_MMAP - -#if !TRAIT_HAS_WIN32_MMAP -#define MUNMAP_DEFAULT(a, s) munmap((a), (s)) -#define MMAP_PROT (PROT_READ | PROT_WRITE) -#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) -#define MAP_ANONYMOUS MAP_ANON -#endif /* MAP_ANON */ -#ifdef MAP_ANONYMOUS -#define MMAP_FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) -#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) -#else /* MAP_ANONYMOUS */ -/* - Nearly all versions of mmap support MAP_ANONYMOUS, so the following - is unlikely to be needed, but is supplied just in case. -*/ -#define MMAP_FLAGS (MAP_PRIVATE) -static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ -#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \ - (dev_zero_fd = open("/dev/zero", O_RDWR), \ - mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ - mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) -#endif /* MAP_ANONYMOUS */ - -#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s) - -#else /* TRAIT_HAS_WIN32_MMAP */ - -/* Win32 MMAP via VirtualAlloc */ -static FORCEINLINE void* win32mmap(size_t size) -{ - void* ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - return (ptr != 0) ? ptr : MFAIL; -} - -/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ -static FORCEINLINE void* win32direct_mmap(size_t size) -{ - void* ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, - PAGE_READWRITE); - return (ptr != 0) ? ptr : MFAIL; -} - -/* This function supports releasing coalesed segments */ -static FORCEINLINE int win32munmap(void* ptr, size_t size) -{ - MEMORY_BASIC_INFORMATION minfo; - char* cptr = (char*)ptr; - while (size) - { - if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) - { - return -1; - } - if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || - minfo.State != MEM_COMMIT || minfo.RegionSize > size) - { - return -1; - } - if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) - { - return -1; - } - cptr += minfo.RegionSize; - size -= minfo.RegionSize; - } - return 0; -} - -#define MMAP_DEFAULT(s) win32mmap(s) -#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s)) -#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s) -#endif /* TRAIT_HAS_WIN32_MMAP */ -#endif /* HAVE_MMAP */ - -#if HAVE_MREMAP -#ifndef WIN32 -#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) -#endif /* WIN32 */ -#endif /* HAVE_MREMAP */ - - -/** - * Define CALL_MORECORE - */ -#if HAVE_MORECORE - #ifdef MORECORE - #define CALL_MORECORE(S) MORECORE(S) - #else /* MORECORE */ - #define CALL_MORECORE(S) MORECORE_DEFAULT(S) - #endif /* MORECORE */ -#else /* HAVE_MORECORE */ - #define CALL_MORECORE(S) MFAIL -#endif /* HAVE_MORECORE */ - -/** - * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP - */ -#if HAVE_MMAP - #define USE_MMAP_BIT (SIZE_T_ONE) - - #ifdef MMAP - #define CALL_MMAP(s) MMAP(s) - #else /* MMAP */ - #define CALL_MMAP(s) MMAP_DEFAULT(s) - #endif /* MMAP */ - #ifdef MUNMAP - #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) - #else /* MUNMAP */ - #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s)) - #endif /* MUNMAP */ - #ifdef DIRECT_MMAP - #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) - #else /* DIRECT_MMAP */ - #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s) - #endif /* DIRECT_MMAP */ -#else /* HAVE_MMAP */ - #define USE_MMAP_BIT (SIZE_T_ZERO) - - #define MMAP(s) MFAIL - #define MUNMAP(a, s) (-1) - #define DIRECT_MMAP(s) MFAIL - #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) - #define CALL_MMAP(s) MMAP(s) - #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) -#endif /* HAVE_MMAP */ - -/** - * Define CALL_MREMAP - */ -#if HAVE_MMAP && HAVE_MREMAP - #ifdef MREMAP - #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv)) - #else /* MREMAP */ - #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) - #endif /* MREMAP */ -#else /* HAVE_MMAP && HAVE_MREMAP */ - #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL -#endif /* HAVE_MMAP && HAVE_MREMAP */ - -/* mstate bit set if continguous morecore disabled or failed */ -#define USE_NONCONTIGUOUS_BIT (4U) - -/* segment bit set in create_mspace_with_base */ -#define EXTERN_BIT (8U) - - -/* --------------------------- Lock preliminaries ------------------------ */ - -/* - When locks are defined, there is one global lock, plus - one per-mspace lock. - - The global lock_ensures that mparams.magic and other unique - mparams values are initialized only once. It also protects - sequences of calls to MORECORE. In many cases sys_alloc requires - two calls, that should not be interleaved with calls by other - threads. This does not protect against direct calls to MORECORE - by other threads not using this lock, so there is still code to - cope the best we can on interference. - - Per-mspace locks surround calls to malloc, free, etc. To enable use - in layered extensions, per-mspace locks are reentrant. - - Because lock-protected regions generally have bounded times, it is - OK to use the supplied simple spinlocks in the custom versions for - x86. Spinlocks are likely to improve performance for lightly - contended applications, but worsen performance under heavy - contention. - - If USE_LOCKS is > 1, the definitions of lock routines here are - bypassed, in which case you will need to define the type MLOCK_T, - and at least INITIAL_LOCK, ACQUIRE_LOCK, RELEASE_LOCK and possibly - TRY_LOCK (which is not used in this malloc, but commonly needed in - extensions.) You must also declare a - static MLOCK_T malloc_global_mutex = { initialization values };. - -*/ - -#if USE_LOCKS == 1 - -#if USE_SPIN_LOCKS && SPIN_LOCKS_AVAILABLE -#ifndef WIN32 - -/* Custom pthread-style spin locks on x86 and x64 for gcc */ -struct pthread_mlock_t -{ - volatile unsigned int l; - unsigned int c; - pthread_t threadid; -}; -#define MLOCK_T struct pthread_mlock_t -#define CURRENT_THREAD pthread_self() -#define INITIAL_LOCK(sl) ((sl)->threadid = 0, (sl)->l = (sl)->c = 0, 0) -#define ACQUIRE_LOCK(sl) pthread_acquire_lock(sl) -#define RELEASE_LOCK(sl) pthread_release_lock(sl) -#define TRY_LOCK(sl) pthread_try_lock(sl) -#define SPINS_PER_YIELD 63 - -static MLOCK_T malloc_global_mutex = { 0, 0, 0}; - -static FORCEINLINE int pthread_acquire_lock (MLOCK_T* sl) -{ - int spins = 0; - volatile unsigned int* lp = &sl->l; - for (;; ) - { - if (*lp != 0) - { - if (sl->threadid == CURRENT_THREAD) - { - ++sl->c; - return 0; - } - } - else - { - /* place args to cmpxchgl in locals to evade oddities in some gccs */ - int cmp = 0; - int val = 1; - int ret; - __asm__ __volatile__ ("lock; cmpxchgl %1, %2" - : "=a" (ret) - : "r" (val), "m" (*(lp)), "0" (cmp) - : "memory", "cc"); - if (!ret) - { - assert(!sl->threadid); - sl->threadid = CURRENT_THREAD; - sl->c = 1; - return 0; - } - } - if ((++spins & SPINS_PER_YIELD) == 0) - { -#if defined (__SVR4) && defined (__sun) /* solaris */ - thr_yield(); -#else -#if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) - sched_yield(); -#else /* no-op yield on unknown systems */ - ; -#endif /* __linux__ || __FreeBSD__ || __APPLE__ */ -#endif /* solaris */ - } - } -} - -static FORCEINLINE void pthread_release_lock (MLOCK_T* sl) -{ - volatile unsigned int* lp = &sl->l; - assert(*lp != 0); - assert(sl->threadid == CURRENT_THREAD); - if (--sl->c == 0) - { - sl->threadid = 0; - int prev = 0; - int ret; - __asm__ __volatile__ ("lock; xchgl %0, %1" - : "=r" (ret) - : "m" (*(lp)), "0" (prev) - : "memory"); - } -} - -static FORCEINLINE int pthread_try_lock (MLOCK_T* sl) -{ - volatile unsigned int* lp = &sl->l; - if (*lp != 0) - { - if (sl->threadid == CURRENT_THREAD) - { - ++sl->c; - return 1; - } - } - else - { - int cmp = 0; - int val = 1; - int ret; - __asm__ __volatile__ ("lock; cmpxchgl %1, %2" - : "=a" (ret) - : "r" (val), "m" (*(lp)), "0" (cmp) - : "memory", "cc"); - if (!ret) - { - assert(!sl->threadid); - sl->threadid = CURRENT_THREAD; - sl->c = 1; - return 1; - } - } - return 0; -} - - -#else /* WIN32 */ -/* Custom win32-style spin locks on x86 and x64 for MSC */ -struct win32_mlock_t -{ - volatile long l; - unsigned int c; - long threadid; -}; - -#define MLOCK_T struct win32_mlock_t -#define CURRENT_THREAD GetCurrentThreadId() -#define INITIAL_LOCK(sl) ((sl)->threadid = 0, (sl)->l = (sl)->c = 0, 0) -#define ACQUIRE_LOCK(sl) win32_acquire_lock(sl) -#define RELEASE_LOCK(sl) win32_release_lock(sl) -#define TRY_LOCK(sl) win32_try_lock(sl) -#define SPINS_PER_YIELD 63 - -static MLOCK_T malloc_global_mutex = { 0, 0, 0}; - -static FORCEINLINE int win32_acquire_lock (MLOCK_T* sl) -{ - int spins = 0; - for (;; ) - { - if (sl->l != 0) - { - if (sl->threadid == CURRENT_THREAD) - { - ++sl->c; - return 0; - } - } - else - { - if (!interlockedexchange(&sl->l, 1)) - { - assert(!sl->threadid); - sl->threadid = CURRENT_THREAD; - sl->c = 1; - return 0; - } - } - if ((++spins & SPINS_PER_YIELD) == 0) - { - SleepEx(0, FALSE); - } - } -} - -static FORCEINLINE void win32_release_lock (MLOCK_T* sl) -{ - assert(sl->threadid == CURRENT_THREAD); - assert(sl->l != 0); - if (--sl->c == 0) - { - sl->threadid = 0; - interlockedexchange (&sl->l, 0); - } -} - -static FORCEINLINE int win32_try_lock (MLOCK_T* sl) -{ - if (sl->l != 0) - { - if (sl->threadid == CURRENT_THREAD) - { - ++sl->c; - return 1; - } - } - else - { - if (!interlockedexchange(&sl->l, 1)) - { - assert(!sl->threadid); - sl->threadid = CURRENT_THREAD; - sl->c = 1; - return 1; - } - } - return 0; -} - -#endif /* WIN32 */ -#else /* USE_SPIN_LOCKS */ - -#ifndef WIN32 -/* pthreads-based locks */ - -#define MLOCK_T pthread_mutex_t -#define CURRENT_THREAD pthread_self() -#define INITIAL_LOCK(sl) pthread_init_lock(sl) -#define ACQUIRE_LOCK(sl) pthread_mutex_lock(sl) -#define RELEASE_LOCK(sl) pthread_mutex_unlock(sl) -#define TRY_LOCK(sl) (!pthread_mutex_trylock(sl)) - -static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER; - -/* Cope with old-style linux recursive lock initialization by adding */ -/* skipped internal declaration from pthread.h */ -#ifdef linux -#ifndef PTHREAD_MUTEX_RECURSIVE -extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t * __attr, - int __kind)); -#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP -#define pthread_mutexattr_settype(x, y) pthread_mutexattr_setkind_np(x, y) -#endif -#endif - -static int pthread_init_lock (MLOCK_T* sl) -{ - pthread_mutexattr_t attr; - if (pthread_mutexattr_init(&attr)) - { - return 1; - } - if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) - { - return 1; - } - if (pthread_mutex_init(sl, &attr)) - { - return 1; - } - if (pthread_mutexattr_destroy(&attr)) - { - return 1; - } - return 0; -} - -#else /* WIN32 */ -/* Win32 critical sections */ -#define MLOCK_T CRITICAL_SECTION -#define CURRENT_THREAD GetCurrentThreadId() -#define INITIAL_LOCK(s) (!InitializeCriticalSectionAndSpinCount((s), 0x80000000 | 4000)) -#define ACQUIRE_LOCK(s) (EnterCriticalSection(sl), 0) -#define RELEASE_LOCK(s) LeaveCriticalSection(sl) -#define TRY_LOCK(s) TryEnterCriticalSection(sl) -#define NEED_GLOBAL_LOCK_INIT - -static MLOCK_T malloc_global_mutex; -static volatile long malloc_global_mutex_status; - -/* Use spin loop to initialize global lock */ -static void init_malloc_global_mutex() -{ - for (;; ) - { - long stat = malloc_global_mutex_status; - if (stat > 0) - { - return; - } - /* transition to < 0 while initializing, then to > 0) */ - if (stat == 0 && - interlockedcompareexchange(&malloc_global_mutex_status, -1, 0) == 0) - { - InitializeCriticalSection(&malloc_global_mutex); - interlockedexchange(&malloc_global_mutex_status, 1); - return; - } - SleepEx(0, FALSE); - } -} - -#endif /* WIN32 */ -#endif /* USE_SPIN_LOCKS */ -#endif /* USE_LOCKS == 1 */ - -/* ----------------------- User-defined locks ------------------------ */ - -#if USE_LOCKS > 1 -/* Define your own lock implementation here */ -/* #define INITIAL_LOCK(sl) ... */ -/* #define ACQUIRE_LOCK(sl) ... */ -/* #define RELEASE_LOCK(sl) ... */ -/* #define TRY_LOCK(sl) ... */ -/* static MLOCK_T malloc_global_mutex = ... */ -#endif /* USE_LOCKS > 1 */ - -/* ----------------------- Lock-based state ------------------------ */ - -#if USE_LOCKS -#define USE_LOCK_BIT (2U) -#else /* USE_LOCKS */ -#define USE_LOCK_BIT (0U) -#define INITIAL_LOCK(l) -#endif /* USE_LOCKS */ - -#if USE_LOCKS -#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK -#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex); -#endif -#ifndef RELEASE_MALLOC_GLOBAL_LOCK -#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex); -#endif -#else /* USE_LOCKS */ -#define ACQUIRE_MALLOC_GLOBAL_LOCK() -#define RELEASE_MALLOC_GLOBAL_LOCK() -#endif /* USE_LOCKS */ - - -/* ----------------------- Chunk representations ------------------------ */ - -/* - (The following includes lightly edited explanations by Colin Plumb.) - - The malloc_chunk declaration below is misleading (but accurate and - necessary). It declares a "view" into memory allowing access to - necessary fields at known offsets from a given base. - - Chunks of memory are maintained using a `boundary tag' method as - originally described by Knuth. (See the paper by Paul Wilson - ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such - techniques.) Sizes of free chunks are stored both in the front of - each chunk and at the end. This makes consolidating fragmented - chunks into bigger chunks fast. The head fields also hold bits - representing whether chunks are free or in use. - - Here are some pictures to make it clearer. They are "exploded" to - show that the state of a chunk can be thought of as extending from - the high 31 bits of the head field of its header through the - prev_foot and PINUSE_BIT bit of the following chunk header. - - A chunk that's in use looks like: - - chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of previous chunk (if P = 0) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| - | Size of this chunk 1| +-+ - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | | - +- -+ - | | - +- -+ - | : - +- size - sizeof(size_t) available payload bytes -+ - : | - chunk-> +- -+ - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| - | Size of next chunk (may or may not be in use) | +-+ - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - - And if it's free, it looks like this: - - chunk-> +- -+ - | User payload (must be in use, or we would have merged!) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| - | Size of this chunk 0| +-+ - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Next pointer | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Prev pointer | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | : - +- size - sizeof(struct chunk) unused bytes -+ - : | - chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of this chunk | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0| - | Size of next chunk (must be in use, or we would have merged)| +-+ - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | : - +- User payload -+ - : | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |0| - +-+ - Note that since we always merge adjacent free chunks, the chunks - adjacent to a free chunk must be in use. - - Given a pointer to a chunk (which can be derived trivially from the - payload pointer) we can, in O(1) time, find out whether the adjacent - chunks are free, and if so, unlink them from the lists that they - are on and merge them with the current chunk. - - Chunks always begin on even word boundaries, so the mem portion - (which is returned to the user) is also on an even word boundary, and - thus at least double-word aligned. - - The P (PINUSE_BIT) bit, stored in the unused low-order bit of the - chunk size (which is always a multiple of two words), is an in-use - bit for the *previous* chunk. If that bit is *clear*, then the - word before the current chunk size contains the previous chunk - size, and can be used to find the front of the previous chunk. - The very first chunk allocated always has this bit set, preventing - access to non-existent (or non-owned) memory. If pinuse is set for - any given chunk, then you CANNOT determine the size of the - previous chunk, and might even get a memory addressing fault when - trying to do so. - - The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of - the chunk size redundantly records whether the current chunk is - inuse (unless the chunk is mmapped). This redundancy enables usage - checks within free and realloc, and reduces indirection when freeing - and consolidating chunks. - - Each freshly allocated chunk must have both cinuse and pinuse set. - That is, each allocated chunk borders either a previously allocated - and still in-use chunk, or the base of its memory arena. This is - ensured by making all allocations from the the `lowest' part of any - found chunk. Further, no free chunk physically borders another one, - so each free chunk is known to be preceded and followed by either - inuse chunks or the ends of memory. - - Note that the `foot' of the current chunk is actually represented - as the prev_foot of the NEXT chunk. This makes it easier to - deal with alignments etc but can be very confusing when trying - to extend or adapt this code. - - The exceptions to all this are - - 1. The special chunk `top' is the top-most available chunk (i.e., - the one bordering the end of available memory). It is treated - specially. Top is never included in any bin, is used only if - no other chunk is available, and is released back to the - system if it is very large (see M_TRIM_THRESHOLD). In effect, - the top chunk is treated as larger (and thus less well - fitting) than any other available chunk. The top chunk - doesn't update its trailing size field since there is no next - contiguous chunk that would have to index off it. However, - space is still allocated for it (TOP_FOOT_SIZE) to enable - separation or merging when space is extended. - - 3. Chunks allocated via mmap, have both cinuse and pinuse bits - cleared in their head fields. Because they are allocated - one-by-one, each must carry its own prev_foot field, which is - also used to hold the offset this chunk has within its mmapped - region, which is needed to preserve alignment. Each mmapped - chunk is trailed by the first two fields of a fake next-chunk - for sake of usage checks. - -*/ - -struct malloc_chunk -{ - size_t prev_foot;/* Size of previous chunk (if free). */ - size_t head; /* Size and inuse bits. */ - struct malloc_chunk* fd; /* double links -- used only if free. */ - struct malloc_chunk* bk; -}; - -typedef struct malloc_chunk mchunk; -typedef struct malloc_chunk* mchunkptr; -typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ -typedef unsigned int bindex_t; /* Described below */ -typedef unsigned int binmap_t; /* Described below */ -typedef unsigned int flag_t; /* The type of various bit flag sets */ - -/* ------------------- Chunks sizes and alignments ----------------------- */ - -#define MCHUNK_SIZE (sizeof(mchunk)) - -#if FOOTERS -#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) -#else /* FOOTERS */ -#define CHUNK_OVERHEAD (SIZE_T_SIZE) -#endif /* FOOTERS */ - -/* MMapped chunks need a second word of overhead ... */ -#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) -/* ... and additional padding for fake next-chunk at foot */ -#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) - -/* The smallest size we can malloc is an aligned minimal chunk */ -#define MIN_CHUNK_SIZE \ - ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) - -/* conversion from malloc headers to user pointers, and back */ -#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) -#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) -/* chunk associated with aligned address A */ -#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) - -/* Bounds on request (not chunk) sizes. */ -#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) -#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) - -/* pad request bytes into a usable size */ -#define pad_request(req) \ - (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) - -/* pad request, checking for minimum (but not maximum) */ -#define request2size(req) \ - (((req) < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(req)) - - -/* ------------------ Operations on head and foot fields ----------------- */ - -/* - The head field of a chunk is or'ed with PINUSE_BIT when previous - adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in - use, unless mmapped, in which case both bits are cleared. - - FLAG4_BIT is not used by this malloc, but might be useful in extensions. -*/ - -#define PINUSE_BIT (SIZE_T_ONE) -#define CINUSE_BIT (SIZE_T_TWO) -#define FLAG4_BIT (SIZE_T_FOUR) -#define INUSE_BITS (PINUSE_BIT | CINUSE_BIT) -#define FLAG_BITS (PINUSE_BIT | CINUSE_BIT | FLAG4_BIT) - -/* Head value for fenceposts */ -#define FENCEPOST_HEAD (INUSE_BITS | SIZE_T_SIZE) - -/* extraction of fields from head words */ -#define cinuse(p) ((p)->head & CINUSE_BIT) -#define pinuse(p) ((p)->head & PINUSE_BIT) -#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT) -#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0) - -#define chunksize(p) ((p)->head & ~(FLAG_BITS)) - -#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) - -/* Treat space at ptr +/- offset as a chunk */ -#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) -#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) - -/* Ptr to next or previous physical malloc_chunk. */ -#define next_chunk(p) ((mchunkptr)(((char*)(p)) + ((p)->head & ~FLAG_BITS))) -#define prev_chunk(p) ((mchunkptr)(((char*)(p)) - ((p)->prev_foot))) - -/* extract next chunk's pinuse bit */ -#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) - -/* Get/set size at footer */ -#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) -#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) - -/* Set size, pinuse bit, and foot */ -#define set_size_and_pinuse_of_free_chunk(p, s) \ - ((p)->head = (s | PINUSE_BIT), set_foot(p, s)) - -/* Set size, pinuse bit, foot, and clear next pinuse */ -#define set_free_with_pinuse(p, s, n) \ - (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) - -/* Get the internal overhead associated with chunk p */ -#define overhead_for(p) \ - (is_mmapped(p) ? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) - -/* Return true if malloced space is not necessarily cleared */ -#if MMAP_CLEARS -#define calloc_must_clear(p) (!is_mmapped(p)) -#else /* MMAP_CLEARS */ -#define calloc_must_clear(p) (1) -#endif /* MMAP_CLEARS */ - -/* ---------------------- Overlaid data structures ----------------------- */ - -/* - When chunks are not in use, they are treated as nodes of either - lists or trees. - - "Small" chunks are stored in circular doubly-linked lists, and look - like this: - - chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of previous chunk | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - `head:' | Size of chunk, in bytes |P| - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Forward pointer to next chunk in list | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Back pointer to previous chunk in list | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Unused space (may be 0 bytes long) . - . . - . | -nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - `foot:' | Size of chunk, in bytes | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - - Larger chunks are kept in a form of bitwise digital trees (aka - tries) keyed on chunksizes. Because malloc_tree_chunks are only for - free chunks greater than 256 bytes, their size doesn't impose any - constraints on user chunk sizes. Each node looks like: - - chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Size of previous chunk | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - `head:' | Size of chunk, in bytes |P| - mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Forward pointer to next chunk of same size | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Back pointer to previous chunk of same size | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Pointer to left child (child[0]) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Pointer to right child (child[1]) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Pointer to parent | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | bin index of this chunk | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Unused space . - . | -nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - `foot:' | Size of chunk, in bytes | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - - Each tree holding treenodes is a tree of unique chunk sizes. Chunks - of the same size are arranged in a circularly-linked list, with only - the oldest chunk (the next to be used, in our FIFO ordering) - actually in the tree. (Tree members are distinguished by a non-null - parent pointer.) If a chunk with the same size an an existing node - is inserted, it is linked off the existing node using pointers that - work in the same way as fd/bk pointers of small chunks. - - Each tree contains a power of 2 sized range of chunk sizes (the - smallest is 0x100 <= x < 0x180), which is is divided in half at each - tree level, with the chunks in the smaller half of the range (0x100 - <= x < 0x140 for the top nose) in the left subtree and the larger - half (0x140 <= x < 0x180) in the right subtree. This is, of course, - done by inspecting individual bits. - - Using these rules, each node's left subtree contains all smaller - sizes than its right subtree. However, the node at the root of each - subtree has no particular ordering relationship to either. (The - dividing line between the subtree sizes is based on trie relation.) - If we remove the last chunk of a given size from the interior of the - tree, we need to replace it with a leaf node. The tree ordering - rules permit a node to be replaced by any leaf below it. - - The smallest chunk in a tree (a common operation in a best-fit - allocator) can be found by walking a path to the leftmost leaf in - the tree. Unlike a usual binary tree, where we follow left child - pointers until we reach a null, here we follow the right child - pointer any time the left one is null, until we reach a leaf with - both child pointers null. The smallest chunk in the tree will be - somewhere along that path. - - The worst case number of steps to add, find, or remove a node is - bounded by the number of bits differentiating chunks within - bins. Under current bin calculations, this ranges from 6 up to 21 - (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case - is of course much better. -*/ - -struct malloc_tree_chunk -{ - /* The first four fields must be compatible with malloc_chunk */ - size_t prev_foot; - size_t head; - struct malloc_tree_chunk* fd; - struct malloc_tree_chunk* bk; - - struct malloc_tree_chunk* child[2]; - struct malloc_tree_chunk* parent; - bindex_t index; -}; - -typedef struct malloc_tree_chunk tchunk; -typedef struct malloc_tree_chunk* tchunkptr; -typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ - -/* A little helper macro for trees */ -#define leftmost_child(t) ((t)->child[0] != 0 ? (t)->child[0] : (t)->child[1]) - -/* ----------------------------- Segments -------------------------------- */ - -/* - Each malloc space may include non-contiguous segments, held in a - list headed by an embedded malloc_segment record representing the - top-most space. Segments also include flags holding properties of - the space. Large chunks that are directly allocated by mmap are not - included in this list. They are instead independently created and - destroyed without otherwise keeping track of them. - - Segment management mainly comes into play for spaces allocated by - MMAP. Any call to MMAP might or might not return memory that is - adjacent to an existing segment. MORECORE normally contiguously - extends the current space, so this space is almost always adjacent, - which is simpler and faster to deal with. (This is why MORECORE is - used preferentially to MMAP when both are available -- see - sys_alloc.) When allocating using MMAP, we don't use any of the - hinting mechanisms (inconsistently) supported in various - implementations of unix mmap, or distinguish reserving from - committing memory. Instead, we just ask for space, and exploit - contiguity when we get it. It is probably possible to do - better than this on some systems, but no general scheme seems - to be significantly better. - - Management entails a simpler variant of the consolidation scheme - used for chunks to reduce fragmentation -- new adjacent memory is - normally prepended or appended to an existing segment. However, - there are limitations compared to chunk consolidation that mostly - reflect the fact that segment processing is relatively infrequent - (occurring only when getting memory from system) and that we - don't expect to have huge numbers of segments: - - * Segments are not indexed, so traversal requires linear scans. (It - would be possible to index these, but is not worth the extra - overhead and complexity for most programs on most platforms.) - * New segments are only appended to old ones when holding top-most - memory; if they cannot be prepended to others, they are held in - different segments. - - Except for the top-most segment of an mstate, each segment record - is kept at the tail of its segment. Segments are added by pushing - segment records onto the list headed by &mstate.seg for the - containing mstate. - - Segment flags control allocation/merge/deallocation policies: - * If EXTERN_BIT set, then we did not allocate this segment, - and so should not try to deallocate or merge with others. - (This currently holds only for the initial segment passed - into create_mspace_with_base.) - * If USE_MMAP_BIT set, the segment may be merged with - other surrounding mmapped segments and trimmed/de-allocated - using munmap. - * If neither bit is set, then the segment was obtained using - MORECORE so can be merged with surrounding MORECORE'd segments - and deallocated/trimmed using MORECORE with negative arguments. -*/ - -struct malloc_segment -{ - char* base; /* base address */ - size_t size; /* allocated size */ - struct malloc_segment* next; /* ptr to next segment */ - flag_t sflags; /* mmap and extern flag */ -}; - -#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT) -#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) - -typedef struct malloc_segment msegment; -typedef struct malloc_segment* msegmentptr; - -/* ---------------------------- malloc_state ----------------------------- */ - -/* - A malloc_state holds all of the bookkeeping for a space. - The main fields are: - - Top - The topmost chunk of the currently active segment. Its size is - cached in topsize. The actual size of topmost space is - topsize+TOP_FOOT_SIZE, which includes space reserved for adding - fenceposts and segment records if necessary when getting more - space from the system. The size at which to autotrim top is - cached from mparams in trim_check, except that it is disabled if - an autotrim fails. - - Designated victim (dv) - This is the preferred chunk for servicing small requests that - don't have exact fits. It is normally the chunk split off most - recently to service another small request. Its size is cached in - dvsize. The link fields of this chunk are not maintained since it - is not kept in a bin. - - SmallBins - An array of bin headers for free chunks. These bins hold chunks - with sizes less than MIN_LARGE_SIZE bytes. Each bin contains - chunks of all the same size, spaced 8 bytes apart. To simplify - use in double-linked lists, each bin header acts as a malloc_chunk - pointing to the real first node, if it exists (else pointing to - itself). This avoids special-casing for headers. But to avoid - waste, we allocate only the fd/bk pointers of bins, and then use - repositioning tricks to treat these as the fields of a chunk. - - TreeBins - Treebins are pointers to the roots of trees holding a range of - sizes. There are 2 equally spaced treebins for each power of two - from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything - larger. - - Bin maps - There is one bit map for small bins ("smallmap") and one for - treebins ("treemap). Each bin sets its bit when non-empty, and - clears the bit when empty. Bit operations are then used to avoid - bin-by-bin searching -- nearly all "search" is done without ever - looking at bins that won't be selected. The bit maps - conservatively use 32 bits per map word, even if on 64bit system. - For a good description of some of the bit-based techniques used - here, see Henry S. Warren Jr's book "Hacker's Delight" (and - supplement at http://hackersdelight.org/). Many of these are - intended to reduce the branchiness of paths through malloc etc, as - well as to reduce the number of memory locations read or written. - - Segments - A list of segments headed by an embedded malloc_segment record - representing the initial space. - - Address check support - The least_addr field is the least address ever obtained from - MORECORE or MMAP. Attempted frees and reallocs of any address less - than this are trapped (unless INSECURE is defined). - - Magic tag - A cross-check field that should always hold same value as mparams.magic. - - Flags - Bits recording whether to use MMAP, locks, or contiguous MORECORE - - Statistics - Each space keeps track of current and maximum system memory - obtained via MORECORE or MMAP. - - Trim support - Fields holding the amount of unused topmost memory that should trigger - timming, and a counter to force periodic scanning to release unused - non-topmost segments. - - Locking - If USE_LOCKS is defined, the "mutex" lock is acquired and released - around every public call using this mspace. - - Extension support - A void* pointer and a size_t field that can be used to help implement - extensions to this malloc. -*/ - -/* Bin types, widths and sizes */ -#define NSMALLBINS (32U) -#define NTREEBINS (32U) -#define SMALLBIN_SHIFT (3U) -#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) -#define TREEBIN_SHIFT (8U) -#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) -#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) -#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) - -struct malloc_state -{ - binmap_t smallmap; - binmap_t treemap; - size_t dvsize; - size_t topsize; - char* least_addr; - mchunkptr dv; - mchunkptr top; - size_t trim_check; - size_t release_checks; - size_t magic; - mchunkptr smallbins[(NSMALLBINS + 1) * 2]; - tbinptr treebins[NTREEBINS]; - size_t footprint; - size_t max_footprint; - flag_t mflags; -#if USE_LOCKS - MLOCK_T mutex; /* locate lock among fields that rarely change */ -#endif /* USE_LOCKS */ - msegment seg; - void* extp; /* Unused but available for extensions */ - size_t exts; - dlmmap_handler mmap; - dlmunmap_handler munmap; -}; - -typedef struct malloc_state* mstate; - -/* ------------- Global malloc_state and malloc_params ------------------- */ - -/* - malloc_params holds global properties, including those that can be - dynamically set using mallopt. There is a single instance, mparams, - initialized in init_mparams. Note that the non-zeroness of "magic" - also serves as an initialization flag. -*/ - -struct malloc_params -{ - volatile size_t magic; - size_t page_size; - size_t granularity; - size_t mmap_threshold; - size_t trim_threshold; - flag_t default_mflags; -}; - -static struct malloc_params mparams; - -/* Ensure mparams initialized */ -#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams()) - -#if !ONLY_MSPACES - -/* The global malloc_state used for all non-"mspace" calls */ -static struct malloc_state _gm_; -#define gm (&_gm_) -#define is_global(M) ((M) == &_gm_) - -#endif /* !ONLY_MSPACES */ - -#define is_initialized(M) ((M)->top != 0) - -/* -------------------------- system alloc setup ------------------------- */ - -/* Operations on mflags */ - -#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) -#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) -#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) - -#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) -#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) -#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) - -#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) -#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) - -#define set_lock(M, L) \ - ((M)->mflags = (L) ? \ - ((M)->mflags | USE_LOCK_BIT) : \ - ((M)->mflags & ~USE_LOCK_BIT)) - -/* page-align a size */ -#define page_align(S) \ - (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE)) - -/* granularity-align a size */ -#define granularity_align(S) \ - (((S) + (mparams.granularity - SIZE_T_ONE)) \ - & ~(mparams.granularity - SIZE_T_ONE)) - - -/* For mmap, use granularity alignment on windows, else page-align */ -#ifdef WIN32 -#define mmap_align(S) granularity_align(S) -#else -#define mmap_align(S) page_align(S) -#endif - -/* For sys_alloc, enough padding to ensure can malloc request on success */ -#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT) - -#define is_page_aligned(S) \ - (((size_t)(S) &(mparams.page_size - SIZE_T_ONE)) == 0) -#define is_granularity_aligned(S) \ - (((size_t)(S) &(mparams.granularity - SIZE_T_ONE)) == 0) - -/* True if segment S holds address A */ -#define segment_holds(S, A) \ - ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) - -/* Return segment holding given address */ -static msegmentptr segment_holding(mstate m, char* addr) -{ - msegmentptr sp = &m->seg; - for (;; ) - { - if (addr >= sp->base && addr < sp->base + sp->size) - { - return sp; - } - if ((sp = sp->next) == 0) - { - return 0; - } - } -} - -/* Return true if segment contains a segment link */ -static int has_segment_link(mstate m, msegmentptr ss) -{ - msegmentptr sp = &m->seg; - for (;; ) - { - if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) - { - return 1; - } - if ((sp = sp->next) == 0) - { - return 0; - } - } -} - -#ifndef MORECORE_CANNOT_TRIM -#define should_trim(M, s) ((s) > (M)->trim_check) -#else /* MORECORE_CANNOT_TRIM */ -#define should_trim(M, s) (0) -#endif /* MORECORE_CANNOT_TRIM */ - -/* - TOP_FOOT_SIZE is padding at the end of a segment, including space - that may be needed to place segment records and fenceposts when new - noncontiguous segments are added. -*/ -#define TOP_FOOT_SIZE \ - (align_offset(chunk2mem(0)) + pad_request(sizeof(struct malloc_segment)) + MIN_CHUNK_SIZE) - - -/* ------------------------------- Hooks -------------------------------- */ - -/* - PREACTION should be defined to return 0 on success, and nonzero on - failure. If you are not using locking, you can redefine these to do - anything you like. -*/ - -#if USE_LOCKS - -#define PREACTION(M) ((use_lock(M)) ? ACQUIRE_LOCK(&(M)->mutex) : 0) -#define POSTACTION(M) { if (use_lock(M)) {RELEASE_LOCK(&(M)->mutex); } \ -} -#else /* USE_LOCKS */ - -#ifndef PREACTION -#define PREACTION(M) (0) -#endif /* PREACTION */ - -#ifndef POSTACTION -#define POSTACTION(M) -#endif /* POSTACTION */ - -#endif /* USE_LOCKS */ - -/* - CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses. - USAGE_ERROR_ACTION is triggered on detected bad frees and - reallocs. The argument p is an address that might have triggered the - fault. It is ignored by the two predefined actions, but might be - useful in custom actions that try to help diagnose errors. -*/ - -#if PROCEED_ON_ERROR - -/* A count of the number of corruption errors causing resets */ -int malloc_corruption_error_count; - -/* default corruption action */ -static void reset_on_error(mstate m); - -#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) -#define USAGE_ERROR_ACTION(m, p) - -#else /* PROCEED_ON_ERROR */ - -#ifndef CORRUPTION_ERROR_ACTION -#define CORRUPTION_ERROR_ACTION(m) ABORT -#endif /* CORRUPTION_ERROR_ACTION */ - -#ifndef USAGE_ERROR_ACTION -#define USAGE_ERROR_ACTION(m, p) ABORT -#endif /* USAGE_ERROR_ACTION */ - -#endif /* PROCEED_ON_ERROR */ - -/* -------------------------- Debugging setup ---------------------------- */ - -#if !DEBUG - -#define check_free_chunk(M, P) -#define check_inuse_chunk(M, P) -#define check_malloced_chunk(M, P, N) -#define check_mmapped_chunk(M, P) -#define check_malloc_state(M) -#define check_top_chunk(M, P) - -#else /* DEBUG */ -#define check_free_chunk(M, P) do_check_free_chunk(M, P) -#define check_inuse_chunk(M, P) do_check_inuse_chunk(M, P) -#define check_top_chunk(M, P) do_check_top_chunk(M, P) -#define check_malloced_chunk(M, P, N) do_check_malloced_chunk(M, P, N) -#define check_mmapped_chunk(M, P) do_check_mmapped_chunk(M, P) -#define check_malloc_state(M) do_check_malloc_state(M) - -static void do_check_any_chunk(mstate m, mchunkptr p); -static void do_check_top_chunk(mstate m, mchunkptr p); -static void do_check_mmapped_chunk(mstate m, mchunkptr p); -static void do_check_inuse_chunk(mstate m, mchunkptr p); -static void do_check_free_chunk(mstate m, mchunkptr p); -static void do_check_malloced_chunk(mstate m, void* mem, size_t s); -static void do_check_tree(mstate m, tchunkptr t); -static void do_check_treebin(mstate m, bindex_t i); -static void do_check_smallbin(mstate m, bindex_t i); -static void do_check_malloc_state(mstate m); -static int bin_find(mstate m, mchunkptr x); -static size_t traverse_and_check(mstate m); -#endif /* DEBUG */ - -/* ---------------------------- Indexing Bins ---------------------------- */ - -#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) -#define small_index(s) ((s) >> SMALLBIN_SHIFT) -#define small_index2size(i) ((i) << SMALLBIN_SHIFT) -#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) - -/* addressing by index. See above about smallbin repositioning */ -#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i) << 1]))) -#define treebin_at(M, i) (&((M)->treebins[i])) - -/* assign tree index for size S to variable I. Use x86 asm if possible */ -#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) -#define compute_tree_index(S, I) \ - { \ - unsigned int X = S >> TREEBIN_SHIFT; \ - if (X == 0) { \ - I = 0; } \ - else if (X > 0xFFFF) { \ - I = NTREEBINS - 1; } \ - else { \ - unsigned int K; \ - __asm__("bsrl\t%1, %0\n\t" : "=r" (K) : "g" (X)); \ - I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT - 1)) & 1))); \ - } \ - } - -#elif defined (__INTEL_COMPILER) -#define compute_tree_index(S, I) \ - { \ - size_t X = S >> TREEBIN_SHIFT; \ - if (X == 0) { \ - I = 0; } \ - else if (X > 0xFFFF) { \ - I = NTREEBINS - 1; } \ - else { \ - unsigned int K = _bit_scan_reverse (X); \ - I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT - 1)) & 1))); \ - } \ - } - -#elif TRAIT_HAS_BITSCANREVERSE -#define compute_tree_index(S, I) \ - { \ - size_t X = S >> TREEBIN_SHIFT; \ - if (X == 0) { \ - I = 0; } \ - else if (X > 0xFFFF) { \ - I = NTREEBINS - 1; } \ - else { \ - unsigned int K; \ - _BitScanReverse((DWORD*) &K, X); \ - I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT - 1)) & 1))); \ - } \ - } - -#else /* GNUC */ -#define compute_tree_index(S, I) \ - { \ - size_t X = S >> TREEBIN_SHIFT; \ - if (X == 0) { \ - I = 0; } \ - else if (X > 0xFFFF) { \ - I = NTREEBINS - 1; } \ - else { \ - unsigned int Y = (unsigned int)X; \ - unsigned int N = ((Y - 0x100) >> 16) & 8; \ - unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4; \ - N += K; \ - N += K = (((Y <<= K) - 0x4000) >> 16) & 2; \ - K = 14 - N + ((Y <<= K) >> 15); \ - I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT - 1)) & 1)); \ - } \ - } -#endif /* GNUC */ - -/* Bit representing maximum resolved size in a treebin at i */ -#define bit_for_tree_index(i) \ - (i == NTREEBINS - 1) ? (SIZE_T_BITSIZE - 1) : (((i) >> 1) + TREEBIN_SHIFT - 2) - -/* Shift placing maximum resolved bit in a treebin at i as sign bit */ -#define leftshift_for_tree_index(i) \ - ((i == NTREEBINS - 1) ? 0 : \ - ((SIZE_T_BITSIZE - SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) - -/* The size of the smallest chunk held in bin with index i */ -#define minsize_for_tree_index(i) \ - ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ - (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) - - -/* ------------------------ Operations on bin maps ----------------------- */ - -/* bit corresponding to given index */ -#define idx2bit(i) ((binmap_t)(1) << (i)) - -/* Mark/Clear bits with given index */ -#define mark_smallmap(M, i) ((M)->smallmap |= idx2bit(i)) -#define clear_smallmap(M, i) ((M)->smallmap &= ~idx2bit(i)) -#define smallmap_is_marked(M, i) ((M)->smallmap & idx2bit(i)) - -#define mark_treemap(M, i) ((M)->treemap |= idx2bit(i)) -#define clear_treemap(M, i) ((M)->treemap &= ~idx2bit(i)) -#define treemap_is_marked(M, i) ((M)->treemap & idx2bit(i)) - -/* isolate the least set bit of a bitmap */ -#define least_bit(x) ((x) & - (x)) - -/* mask with all bits to left of least bit of x on */ -#define left_bits(x) ((x << 1) | -(x << 1)) - -/* mask with all bits to left of or equal to least bit of x on */ -#define same_or_left_bits(x) ((x) | -(x)) - -/* index corresponding to given bit. Use x86 asm if possible */ - -#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) -#define compute_bit2idx(X, I) \ - { \ - unsigned int J; \ - __asm__("bsfl\t%1, %0\n\t" : "=r" (J) : "g" (X)); \ - I = (bindex_t)J; \ - } - -#elif defined (__INTEL_COMPILER) -#define compute_bit2idx(X, I) \ - { \ - unsigned int J; \ - J = _bit_scan_forward (X); \ - I = (bindex_t)J; \ - } - -#elif TRAIT_HAS_BITSCANFORWARD -#define compute_bit2idx(X, I) \ - { \ - unsigned int J; \ - _BitScanForward((DWORD*) &J, X); \ - I = (bindex_t)J; \ - } - -#elif USE_BUILTIN_FFS -#define compute_bit2idx(X, I) I = ffs(X) - 1 - -#else -#define compute_bit2idx(X, I) \ - { \ - unsigned int Y = X - 1; \ - unsigned int K = Y >> (16 - 4) & 16; \ - unsigned int N = K; Y >>= K; \ - N += K = Y >> (8 - 3) & 8; Y >>= K; \ - N += K = Y >> (4 - 2) & 4; Y >>= K; \ - N += K = Y >> (2 - 1) & 2; Y >>= K; \ - N += K = Y >> (1 - 0) & 1; Y >>= K; \ - I = (bindex_t)(N + Y); \ - } -#endif /* GNUC */ - - -/* ----------------------- Runtime Check Support ------------------------- */ - -/* - For security, the main invariant is that malloc/free/etc never - writes to a static address other than malloc_state, unless static - malloc_state itself has been corrupted, which cannot occur via - malloc (because of these checks). In essence this means that we - believe all pointers, sizes, maps etc held in malloc_state, but - check all of those linked or offsetted from other embedded data - structures. These checks are interspersed with main code in a way - that tends to minimize their run-time cost. - - When FOOTERS is defined, in addition to range checking, we also - verify footer fields of inuse chunks, which can be used guarantee - that the mstate controlling malloc/free is intact. This is a - streamlined version of the approach described by William Robertson - et al in "Run-time Detection of Heap-based Overflows" LISA'03 - http://www.usenix.org/events/lisa03/tech/robertson.html The footer - of an inuse chunk holds the xor of its mstate and a random seed, - that is checked upon calls to free() and realloc(). This is - (probablistically) unguessable from outside the program, but can be - computed by any code successfully malloc'ing any chunk, so does not - itself provide protection against code that has already broken - security through some other means. Unlike Robertson et al, we - always dynamically check addresses of all offset chunks (previous, - next, etc). This turns out to be cheaper than relying on hashes. -*/ - -#if !INSECURE -/* Check if address a is at least as high as any from MORECORE or MMAP */ -#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) -/* Check if address of next chunk n is higher than base chunk p */ -#define ok_next(p, n) ((char*)(p) < (char*)(n)) -/* Check if p has inuse status */ -#define ok_inuse(p) is_inuse(p) -/* Check if p has its pinuse bit on */ -#define ok_pinuse(p) pinuse(p) - -#else /* !INSECURE */ -#define ok_address(M, a) (1) -#define ok_next(b, n) (1) -#define ok_inuse(p) (1) -#define ok_pinuse(p) (1) -#endif /* !INSECURE */ - -#if (FOOTERS && !INSECURE) -/* Check if (alleged) mstate m has expected magic field */ -#define ok_magic(M) ((M)->magic == mparams.magic) -#else /* (FOOTERS && !INSECURE) */ -#define ok_magic(M) (1) -#endif /* (FOOTERS && !INSECURE) */ - - -/* In gcc, use __builtin_expect to minimize impact of checks */ -#if !INSECURE -#if defined(__GNUC__) && __GNUC__ >= 3 -#define RTCHECK(e) __builtin_expect(e, 1) -#else /* GNUC */ -#define RTCHECK(e) (e) -#endif /* GNUC */ -#else /* !INSECURE */ -#define RTCHECK(e) (1) -#endif /* !INSECURE */ - -/* macros to set up inuse chunks with or without footers */ - -#if !FOOTERS - -#define mark_inuse_foot(M, p, s) - -/* Macros for setting head/foot of non-mmapped chunks */ - -/* Set cinuse bit and pinuse bit of next chunk */ -#define set_inuse(M, p, s) \ - ((p)->head = (((p)->head & PINUSE_BIT) | s | CINUSE_BIT), \ - ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) - -/* Set cinuse and pinuse of this chunk and pinuse of next chunk */ -#define set_inuse_and_pinuse(M, p, s) \ - ((p)->head = (s | PINUSE_BIT | CINUSE_BIT), \ - ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) - -/* Set size, cinuse and pinuse bit of this chunk */ -#define set_size_and_pinuse_of_inuse_chunk(M, p, s) \ - ((p)->head = (s | PINUSE_BIT | CINUSE_BIT)) - -#else /* FOOTERS */ - -/* Set foot of inuse chunk to be xor of mstate and seed */ -#define mark_inuse_foot(M, p, s) \ - (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) - -#define get_mstate_for(p) \ - ((mstate)(((mchunkptr)((char*)(p) + \ - (chunksize(p))))->prev_foot ^ mparams.magic)) - -#define set_inuse(M, p, s) \ - ((p)->head = (((p)->head & PINUSE_BIT) | s | CINUSE_BIT), \ - (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ - mark_inuse_foot(M, p, s)) - -#define set_inuse_and_pinuse(M, p, s) \ - ((p)->head = (s | PINUSE_BIT | CINUSE_BIT), \ - (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ - mark_inuse_foot(M, p, s)) - -#define set_size_and_pinuse_of_inuse_chunk(M, p, s) \ - ((p)->head = (s | PINUSE_BIT | CINUSE_BIT), \ - mark_inuse_foot(M, p, s)) - -#endif /* !FOOTERS */ - -/* ---------------------------- setting mparams -------------------------- */ - -/* Initialize mparams */ -int init_mparams(void) -{ -#ifdef NEED_GLOBAL_LOCK_INIT - if (malloc_global_mutex_status <= 0) - { - init_malloc_global_mutex(); - } -#endif - - ACQUIRE_MALLOC_GLOBAL_LOCK(); - if (mparams.magic == 0) - { - size_t magic; - size_t psize; - size_t gsize; - -#if TRAIT_HAS_GETSYSTEMINFO - { - SYSTEM_INFO system_info; - GetSystemInfo(&system_info); - psize = system_info.dwPageSize; - gsize = ((DEFAULT_GRANULARITY != 0) ? - DEFAULT_GRANULARITY : system_info.dwAllocationGranularity); - } -#else - psize = malloc_getpagesize; - gsize = ((DEFAULT_GRANULARITY != 0) ? DEFAULT_GRANULARITY : psize); -#endif //#if TRAIT_HAS_GETSYSTEMINFO - - /* Sanity-check configuration: - size_t must be unsigned and as wide as pointer type. - ints must be at least 4 bytes. - alignment must be at least 8. - Alignment, min chunk size, and page size must all be powers of 2. - */ - if ((sizeof(size_t) != sizeof(char*)) || - (MAX_SIZE_T < MIN_CHUNK_SIZE) || - (sizeof(int) < 4) || - (MALLOC_ALIGNMENT < (size_t)8U) || - ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - SIZE_T_ONE)) != 0) || - ((MCHUNK_SIZE & (MCHUNK_SIZE - SIZE_T_ONE)) != 0) || - ((gsize & (gsize - SIZE_T_ONE)) != 0) || - ((psize & (psize - SIZE_T_ONE)) != 0)) - { - ABORT; - } - - mparams.granularity = gsize; - mparams.page_size = psize; - mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; - mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; -#if MORECORE_CONTIGUOUS - mparams.default_mflags = USE_LOCK_BIT | USE_MMAP_BIT; -#else /* MORECORE_CONTIGUOUS */ - mparams.default_mflags = USE_LOCK_BIT | USE_MMAP_BIT | USE_NONCONTIGUOUS_BIT; -#endif /* MORECORE_CONTIGUOUS */ - -#if !ONLY_MSPACES - /* Set up lock for main malloc area */ - gm->mflags = mparams.default_mflags; - INITIAL_LOCK(&gm->mutex); -#endif - - { -#if USE_DEV_RANDOM - int fd; - unsigned char buf[sizeof(size_t)]; - /* Try to use /dev/urandom, else fall back on using time */ - if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && - read(fd, buf, sizeof(buf)) == sizeof(buf)) - { - magic = *((size_t*) buf); - close(fd); - } - else -#endif /* USE_DEV_RANDOM */ -#if TRAIT_USE_QUERYPERFORMANCECOUNTER - { - // GetTickCount not available on Metro style apps - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - magic = (size_t)(li.QuadPart ^ (size_t)0x55555555U); - } -#elif defined(WIN32) - magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U); -#else - magic = (size_t)(time(0) ^ (size_t)0x55555555U); -#endif - magic |= (size_t)8U; /* ensure nonzero */ - magic &= ~(size_t)7U; /* improve chances of fault for bad values */ - mparams.magic = magic; - } - } - - RELEASE_MALLOC_GLOBAL_LOCK(); - return 1; -} - -/* support for mallopt */ -static int change_mparam(int param_number, int value) -{ - size_t val; - ensure_initialization(); - val = (value == -1) ? MAX_SIZE_T : (size_t)value; - switch (param_number) - { - case M_TRIM_THRESHOLD: - mparams.trim_threshold = val; - return 1; - case M_GRANULARITY: - if (val >= mparams.page_size && ((val & (val - 1)) == 0)) - { - mparams.granularity = val; - return 1; - } - else - { - return 0; - } - case M_MMAP_THRESHOLD: - mparams.mmap_threshold = val; - return 1; - default: - return 0; - } -} - -#if DEBUG -/* ------------------------- Debugging Support --------------------------- */ - -/* Check properties of any chunk, whether free, inuse, mmapped etc */ -static void do_check_any_chunk(mstate m, mchunkptr p) -{ - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); -} - -/* Check properties of top chunk */ -static void do_check_top_chunk(mstate m, mchunkptr p) -{ - msegmentptr sp = segment_holding(m, (char*)p); - size_t sz = p->head & ~INUSE_BITS;/* third-lowest bit can be set! */ - assert(sp != 0); - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); - assert(sz == m->topsize); - assert(sz > 0); - assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); - assert(pinuse(p)); - assert(!pinuse(chunk_plus_offset(p, sz))); -} - -/* Check properties of (inuse) mmapped chunks */ -static void do_check_mmapped_chunk(mstate m, mchunkptr p) -{ - size_t sz = chunksize(p); - size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD); - assert(is_mmapped(p)); - assert(use_mmap(m)); - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); - assert(!is_small(sz)); - assert((len & (mparams.page_size - SIZE_T_ONE)) == 0); - assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); - assert(chunk_plus_offset(p, sz + SIZE_T_SIZE)->head == 0); -} - -/* Check properties of inuse chunks */ -static void do_check_inuse_chunk(mstate m, mchunkptr p) -{ - do_check_any_chunk(m, p); - assert(is_inuse(p)); - assert(next_pinuse(p)); - /* If not pinuse and not mmapped, previous chunk has OK offset */ - assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); - if (is_mmapped(p)) - { - do_check_mmapped_chunk(m, p); - } -} - -/* Check properties of free chunks */ -static void do_check_free_chunk(mstate m, mchunkptr p) -{ - size_t sz = chunksize(p); - mchunkptr next = chunk_plus_offset(p, sz); - do_check_any_chunk(m, p); - assert(!is_inuse(p)); - assert(!next_pinuse(p)); - assert (!is_mmapped(p)); - if (p != m->dv && p != m->top) - { - if (sz >= MIN_CHUNK_SIZE) - { - assert((sz & CHUNK_ALIGN_MASK) == 0); - assert(is_aligned(chunk2mem(p))); - assert(next->prev_foot == sz); - assert(pinuse(p)); - assert (next == m->top || is_inuse(next)); - assert(p->fd->bk == p); - assert(p->bk->fd == p); - } - else /* markers are always of size SIZE_T_SIZE */ - { - assert(sz == SIZE_T_SIZE); - } - } -} - -/* Check properties of malloced chunks at the point they are malloced */ -static void do_check_malloced_chunk(mstate m, void* mem, size_t s) -{ - if (mem != 0) - { - mchunkptr p = mem2chunk(mem); - size_t sz = p->head & ~INUSE_BITS; - do_check_inuse_chunk(m, p); - assert((sz & CHUNK_ALIGN_MASK) == 0); - assert(sz >= MIN_CHUNK_SIZE); - assert(sz >= s); - /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ - assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); - } -} - -/* Check a tree and its subtrees. */ -static void do_check_tree(mstate m, tchunkptr t) -{ - tchunkptr head = 0; - tchunkptr u = t; - bindex_t tindex = t->index; - size_t tsize = chunksize(t); - bindex_t idx; - compute_tree_index(tsize, idx); - assert(tindex == idx); - assert(tsize >= MIN_LARGE_SIZE); - assert(tsize >= minsize_for_tree_index(idx)); - assert((idx == NTREEBINS - 1) || (tsize < minsize_for_tree_index((idx + 1)))); - - do /* traverse through chain of same-sized nodes */ - { - do_check_any_chunk(m, ((mchunkptr)u)); - assert(u->index == tindex); - assert(chunksize(u) == tsize); - assert(!is_inuse(u)); - assert(!next_pinuse(u)); - assert(u->fd->bk == u); - assert(u->bk->fd == u); - if (u->parent == 0) - { - assert(u->child[0] == 0); - assert(u->child[1] == 0); - } - else - { - assert(head == 0); /* only one node on chain has parent */ - head = u; - assert(u->parent != u); - assert (u->parent->child[0] == u || - u->parent->child[1] == u || - *((tbinptr*)(u->parent)) == u); - if (u->child[0] != 0) - { - assert(u->child[0]->parent == u); - assert(u->child[0] != u); - do_check_tree(m, u->child[0]); - } - if (u->child[1] != 0) - { - assert(u->child[1]->parent == u); - assert(u->child[1] != u); - do_check_tree(m, u->child[1]); - } - if (u->child[0] != 0 && u->child[1] != 0) - { - assert(chunksize(u->child[0]) < chunksize(u->child[1])); - } - } - u = u->fd; - } while (u != t); - assert(head != 0); -} - -/* Check all the chunks in a treebin. */ -static void do_check_treebin(mstate m, bindex_t i) -{ - tbinptr* tb = treebin_at(m, i); - tchunkptr t = *tb; - int empty = (m->treemap & (1U << i)) == 0; - if (t == 0) - { - assert(empty); - } - if (!empty) - { - do_check_tree(m, t); - } -} - -/* Check all the chunks in a smallbin. */ -static void do_check_smallbin(mstate m, bindex_t i) -{ - sbinptr b = smallbin_at(m, i); - mchunkptr p = b->bk; - unsigned int empty = (m->smallmap & (1U << i)) == 0; - if (p == b) - { - assert(empty); - } - if (!empty) - { - for (; p != b; p = p->bk) - { - size_t size = chunksize(p); - mchunkptr q; - /* each chunk claims to be free */ - do_check_free_chunk(m, p); - /* chunk belongs in bin */ - assert(small_index(size) == i); - assert(p->bk == b || chunksize(p->bk) == chunksize(p)); - /* chunk is followed by an inuse chunk */ - q = next_chunk(p); - if (q->head != FENCEPOST_HEAD) - { - do_check_inuse_chunk(m, q); - } - } - } -} - -/* Find x in a bin. Used in other check functions. */ -static int bin_find(mstate m, mchunkptr x) -{ - size_t size = chunksize(x); - if (is_small(size)) - { - bindex_t sidx = small_index(size); - sbinptr b = smallbin_at(m, sidx); - if (smallmap_is_marked(m, sidx)) - { - mchunkptr p = b; - do - { - if (p == x) - { - return 1; - } - } while ((p = p->fd) != b); - } - } - else - { - bindex_t tidx; - compute_tree_index(size, tidx); - if (treemap_is_marked(m, tidx)) - { - tchunkptr t = *treebin_at(m, tidx); - size_t sizebits = size << leftshift_for_tree_index(tidx); - while (t != 0 && chunksize(t) != size) - { - t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1]; - sizebits <<= 1; - } - if (t != 0) - { - tchunkptr u = t; - do - { - if (u == (tchunkptr)x) - { - return 1; - } - } while ((u = u->fd) != t); - } - } - } - return 0; -} - -/* Traverse each chunk and check it; return total */ -static size_t traverse_and_check(mstate m) -{ - size_t sum = 0; - if (is_initialized(m)) - { - msegmentptr s = &m->seg; - sum += m->topsize + TOP_FOOT_SIZE; - while (s != 0) - { - mchunkptr q = align_as_chunk(s->base); - mchunkptr lastq = 0; - assert(pinuse(q)); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) - { - sum += chunksize(q); - if (is_inuse(q)) - { - assert(!bin_find(m, q)); - do_check_inuse_chunk(m, q); - } - else - { - assert(q == m->dv || bin_find(m, q)); - assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */ - do_check_free_chunk(m, q); - } - lastq = q; - q = next_chunk(q); - } - s = s->next; - } - } - return sum; -} - -/* Check all properties of malloc_state. */ -static void do_check_malloc_state(mstate m) -{ - bindex_t i; - size_t total; - /* check bins */ - for (i = 0; i < NSMALLBINS; ++i) - { - do_check_smallbin(m, i); - } - for (i = 0; i < NTREEBINS; ++i) - { - do_check_treebin(m, i); - } - - if (m->dvsize != 0) /* check dv chunk */ - { - do_check_any_chunk(m, m->dv); - assert(m->dvsize == chunksize(m->dv)); - assert(m->dvsize >= MIN_CHUNK_SIZE); - assert(bin_find(m, m->dv) == 0); - } - - if (m->top != 0) /* check top chunk */ - { - do_check_top_chunk(m, m->top); - /*assert(m->topsize == chunksize(m->top)); redundant */ - assert(m->topsize > 0); - assert(bin_find(m, m->top) == 0); - } - - total = traverse_and_check(m); - assert(total <= m->footprint); - assert(m->footprint <= m->max_footprint); -} -#endif /* DEBUG */ - -/* ----------------------------- statistics ------------------------------ */ - -#if !NO_MALLINFO -static struct mallinfo internal_mallinfo(mstate m) -{ - struct mallinfo nm = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - ensure_initialization(); - if (!PREACTION(m)) - { - check_malloc_state(m); - if (is_initialized(m)) - { - size_t nfree = SIZE_T_ONE; /* top always free */ - size_t mfree = m->topsize + TOP_FOOT_SIZE; - size_t sum = mfree; - msegmentptr s = &m->seg; - while (s != 0) - { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) - { - size_t sz = chunksize(q); - sum += sz; - if (!is_inuse(q)) - { - mfree += sz; - ++nfree; - } - q = next_chunk(q); - } - s = s->next; - } - - nm.arena = sum; - nm.ordblks = nfree; - nm.hblkhd = m->footprint - sum; - nm.usmblks = m->max_footprint; - nm.uordblks = m->footprint - mfree; - nm.fordblks = mfree; - nm.keepcost = m->topsize; - } - - POSTACTION(m); - } - return nm; -} -#endif /* !NO_MALLINFO */ - -static void internal_malloc_stats(mstate m) -{ - ensure_initialization(); - if (!PREACTION(m)) - { - size_t maxfp = 0; - size_t fp = 0; - size_t used = 0; - check_malloc_state(m); - if (is_initialized(m)) - { - msegmentptr s = &m->seg; - maxfp = m->max_footprint; - fp = m->footprint; - used = fp - (m->topsize + TOP_FOOT_SIZE); - - while (s != 0) - { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) - { - if (!is_inuse(q)) - { - used -= chunksize(q); - } - q = next_chunk(q); - } - s = s->next; - } - } - - fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); - fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); - fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); - - POSTACTION(m); - } -} - -static void internal_malloc_stats_ret(mstate m, size_t* sysOut, size_t* maxSysOut, size_t* usedOut) -{ - ensure_initialization(); - if (!PREACTION(m)) - { - size_t maxfp = 0; - size_t fp = 0; - size_t used = 0; - check_malloc_state(m); - if (is_initialized(m)) - { - msegmentptr s = &m->seg; - maxfp = m->max_footprint; - fp = m->footprint; - used = fp - (m->topsize + TOP_FOOT_SIZE); - - while (s != 0) - { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) - { - if (!is_inuse(q)) - { - used -= chunksize(q); - } - q = next_chunk(q); - } - s = s->next; - } - } - - (*sysOut) = fp; - (*maxSysOut) = maxfp; - (*usedOut) = used; - - POSTACTION(m); - } -} - -/* ----------------------- Operations on smallbins ----------------------- */ - -/* - Various forms of linking and unlinking are defined as macros. Even - the ones for trees, which are very long but have very short typical - paths. This is ugly but reduces reliance on inlining support of - compilers. -*/ - -/* Link a free chunk into a smallbin */ -#define insert_small_chunk(M, P, S) { \ - bindex_t I = small_index(S); \ - mchunkptr B = smallbin_at(M, I); \ - mchunkptr F = B; \ - assert(S >= MIN_CHUNK_SIZE); \ - if (!smallmap_is_marked(M, I)) { \ - mark_smallmap(M, I); } \ - else if (RTCHECK(ok_address(M, B->fd))) { \ - F = B->fd; } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - } \ - B->fd = P; \ - F->bk = P; \ - P->fd = F; \ - P->bk = B; \ -} - -/* Unlink a chunk from a smallbin */ -#define unlink_small_chunk(M, P, S) { \ - mchunkptr F = P->fd; \ - mchunkptr B = P->bk; \ - bindex_t I = small_index(S); \ - assert(P != B); \ - assert(P != F); \ - assert(chunksize(P) == small_index2size(I)); \ - if (F == B) { \ - clear_smallmap(M, I); } \ - else if (RTCHECK((F == smallbin_at(M, I) || ok_address(M, F)) && \ - (B == smallbin_at(M, I) || ok_address(M, B)))) { \ - F->bk = B; \ - B->fd = F; \ - } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - } \ -} - -/* Unlink the first chunk from a smallbin */ -#define unlink_first_small_chunk(M, B, P, I) { \ - mchunkptr F = P->fd; \ - assert(P != B); \ - assert(P != F); \ - assert(chunksize(P) == small_index2size(I)); \ - if (B == F) { \ - clear_smallmap(M, I); } \ - else if (RTCHECK(ok_address(M, F))) { \ - B->fd = F; \ - F->bk = B; \ - } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - } \ -} - - - -/* Replace dv node, binning the old one */ -/* Used only when dvsize known to be small */ -#define replace_dv(M, P, S) { \ - size_t DVS = M->dvsize; \ - if (DVS != 0) { \ - mchunkptr DV = M->dv; \ - assert(is_small(DVS)); \ - insert_small_chunk(M, DV, DVS); \ - } \ - M->dvsize = S; \ - M->dv = P; \ -} - -/* ------------------------- Operations on trees ------------------------- */ - -/* Insert chunk into tree */ -#define insert_large_chunk(M, X, S) { \ - tbinptr* H; \ - bindex_t I; \ - compute_tree_index(S, I); \ - H = treebin_at(M, I); \ - X->index = I; \ - X->child[0] = X->child[1] = 0; \ - if (!treemap_is_marked(M, I)) { \ - mark_treemap(M, I); \ - * H = X; \ - X->parent = (tchunkptr)H; \ - X->fd = X->bk = X; \ - } \ - else { \ - tchunkptr T = * H; \ - size_t K = S << leftshift_for_tree_index(I); \ - for (;; ) { \ - if (chunksize(T) != S) { \ - tchunkptr* C = & (T->child[(K >> (SIZE_T_BITSIZE - SIZE_T_ONE))& 1]); \ - K <<= 1; \ - if (* C != 0) { \ - T = * C; } \ - else if (RTCHECK(ok_address(M, C))) { \ - * C = X; \ - X->parent = T; \ - X->fd = X->bk = X; \ - break; \ - } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - break; \ - } \ - } \ - else { \ - tchunkptr F = T->fd; \ - if (RTCHECK(ok_address(M, T) && ok_address(M, F))) { \ - T->fd = F->bk = X; \ - X->fd = F; \ - X->bk = T; \ - X->parent = 0; \ - break; \ - } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - break; \ - } \ - } \ - } \ - } \ -} - -/* - Unlink steps: - - 1. If x is a chained node, unlink it from its same-sized fd/bk links - and choose its bk node as its replacement. - 2. If x was the last node of its size, but not a leaf node, it must - be replaced with a leaf node (not merely one with an open left or - right), to make sure that lefts and rights of descendents - correspond properly to bit masks. We use the rightmost descendent - of x. We could use any other leaf, but this is easy to locate and - tends to counteract removal of leftmosts elsewhere, and so keeps - paths shorter than minimally guaranteed. This doesn't loop much - because on average a node in a tree is near the bottom. - 3. If x is the base of a chain (i.e., has parent links) relink - x's parent and children to x's replacement (or null if none). -*/ - -#define unlink_large_chunk(M, X) { \ - tchunkptr XP = X->parent; \ - tchunkptr R; \ - if (X->bk != X) { \ - tchunkptr F = X->fd; \ - R = X->bk; \ - if (RTCHECK(ok_address(M, F))) { \ - F->bk = R; \ - R->fd = F; \ - } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - } \ - } \ - else { \ - tchunkptr* RP; \ - if (((R = *(RP = & (X->child[1]))) != 0) || \ - ((R = *(RP = & (X->child[0]))) != 0)) { \ - tchunkptr* CP; \ - while ((*(CP = & (R->child[1])) != 0) || \ - (*(CP = & (R->child[0])) != 0)) { \ - R = *(RP = CP); \ - } \ - if (RTCHECK(ok_address(M, RP))) { \ - * RP = 0; } \ - else { \ - CORRUPTION_ERROR_ACTION(M); \ - } \ - } \ - } \ - if (XP != 0) { \ - tbinptr* H = treebin_at(M, X->index); \ - if (X == * H) { \ - if ((* H = R) == 0) { \ - clear_treemap(M, X->index); } \ - } \ - else if (RTCHECK(ok_address(M, XP))) { \ - if (XP->child[0] == X) { \ - XP->child[0] = R; } \ - else{ \ - XP->child[1] = R; } \ - } \ - else{ \ - CORRUPTION_ERROR_ACTION(M); } \ - if (R != 0) { \ - if (RTCHECK(ok_address(M, R))) { \ - tchunkptr C0, C1; \ - R->parent = XP; \ - if ((C0 = X->child[0]) != 0) { \ - if (RTCHECK(ok_address(M, C0))) { \ - R->child[0] = C0; \ - C0->parent = R; \ - } \ - else{ \ - CORRUPTION_ERROR_ACTION(M); } \ - } \ - if ((C1 = X->child[1]) != 0) { \ - if (RTCHECK(ok_address(M, C1))) { \ - R->child[1] = C1; \ - C1->parent = R; \ - } \ - else{ \ - CORRUPTION_ERROR_ACTION(M); } \ - } \ - } \ - else{ \ - CORRUPTION_ERROR_ACTION(M); } \ - } \ - } \ -} - -/* Relays to large vs small bin operations */ - -#define insert_chunk(M, P, S) \ - if (is_small(S)) { insert_small_chunk(M, P, S) } \ - else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } - -#define unlink_chunk(M, P, S) \ - if (is_small(S)) { unlink_small_chunk(M, P, S) } \ - else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } - - -/* Relays to internal calls to malloc/free from realloc, memalign etc */ - -#if ONLY_MSPACES -#define internal_malloc(m, b) mspace_malloc(m, b) -#define internal_free(m, mem) mspace_free(m, mem); -#else /* ONLY_MSPACES */ -#if MSPACES -#define internal_malloc(m, b) \ - (m == gm) ? dlmalloc(b) : mspace_malloc(m, b) -#define internal_free(m, mem) \ - if (m == gm) { dlfree(mem); } else{ mspace_free(m, mem); } -#else /* MSPACES */ -#define internal_malloc(m, b) dlmalloc(b) -#define internal_free(m, mem) dlfree(mem) -#endif /* MSPACES */ -#endif /* ONLY_MSPACES */ - -/* ----------------------- Direct-mmapping chunks ----------------------- */ - -/* - Directly mmapped chunks are set up with an offset to the start of - the mmapped region stored in the prev_foot field of the chunk. This - allows reconstruction of the required argument to MUNMAP when freed, - and also allows adjustment of the returned chunk to meet alignment - requirements (especially in memalign). -*/ - -/* Malloc using mmap */ -static void* mmap_alloc(mstate m, size_t nb) -{ - size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - if (mmsize > nb) /* Check for wrap around 0 */ - { - char* mm = (char*)((*m->mmap)(m->extp, mmsize)); - if (mm != CMFAIL) - { - size_t offset = align_offset(chunk2mem(mm)); - size_t psize = mmsize - offset - MMAP_FOOT_PAD; - mchunkptr p = (mchunkptr)(mm + offset); - p->prev_foot = offset; - p->head = psize; - mark_inuse_foot(m, p, psize); - chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; - chunk_plus_offset(p, psize + SIZE_T_SIZE)->head = 0; - - if (m->least_addr == 0 || mm < m->least_addr) - { - m->least_addr = mm; - } - if ((m->footprint += mmsize) > m->max_footprint) - { - m->max_footprint = m->footprint; - } - assert(is_aligned(chunk2mem(p))); - check_mmapped_chunk(m, p); - return chunk2mem(p); - } - } - return 0; -} - -/* Realloc using mmap */ -static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) -{ - size_t oldsize = chunksize(oldp); - if (is_small(nb)) /* Can't shrink mmap regions below small size */ - { - return 0; - } - /* Keep old chunk if big enough but not too big */ - if (oldsize >= nb + SIZE_T_SIZE && - (oldsize - nb) <= (mparams.granularity << 1)) - { - return oldp; - } - else - { - size_t offset = oldp->prev_foot; - size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; - size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - char* cp = (char*)CALL_MREMAP((char*)oldp - offset, - oldmmsize, newmmsize, 1); - if (cp != CMFAIL) - { - mchunkptr newp = (mchunkptr)(cp + offset); - size_t psize = newmmsize - offset - MMAP_FOOT_PAD; - newp->head = psize; - mark_inuse_foot(m, newp, psize); - chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; - chunk_plus_offset(newp, psize + SIZE_T_SIZE)->head = 0; - - if (cp < m->least_addr) - { - m->least_addr = cp; - } - if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) - { - m->max_footprint = m->footprint; - } - check_mmapped_chunk(m, newp); - return newp; - } - } - return 0; -} - -/* -------------------------- mspace management -------------------------- */ - -/* Initialize top chunk and its size */ -static void init_top(mstate m, mchunkptr p, size_t psize) -{ - /* Ensure alignment */ - size_t offset = align_offset(chunk2mem(p)); - p = (mchunkptr)((char*)p + offset); - psize -= offset; - - m->top = p; - m->topsize = psize; - p->head = psize | PINUSE_BIT; - /* set size of fake trailing chunk holding overhead space only once */ - chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; - m->trim_check = mparams.trim_threshold; /* reset on each update */ -} - -/* Initialize bins for a new mstate that is otherwise zeroed out */ -static void init_bins(mstate m) -{ - /* Establish circular links for smallbins */ - bindex_t i; - for (i = 0; i < NSMALLBINS; ++i) - { - sbinptr bin = smallbin_at(m, i); - bin->fd = bin->bk = bin; - } -} - -#if PROCEED_ON_ERROR - -/* default corruption action */ -static void reset_on_error(mstate m) -{ - int i; - ++malloc_corruption_error_count; - /* Reinitialize fields to forget about all memory */ - m->smallbins = m->treebins = 0; - m->dvsize = m->topsize = 0; - m->seg.base = 0; - m->seg.size = 0; - m->seg.next = 0; - m->top = m->dv = 0; - for (i = 0; i < NTREEBINS; ++i) - { - *treebin_at(m, i) = 0; - } - init_bins(m); -} -#endif /* PROCEED_ON_ERROR */ - -/* Allocate chunk and prepend remainder with chunk in successor base. */ -static void* prepend_alloc(mstate m, char* newbase, char* oldbase, - size_t nb) -{ - mchunkptr p = align_as_chunk(newbase); - mchunkptr oldfirst = align_as_chunk(oldbase); - size_t psize = (char*)oldfirst - (char*)p; - mchunkptr q = chunk_plus_offset(p, nb); - size_t qsize = psize - nb; - set_size_and_pinuse_of_inuse_chunk(m, p, nb); - - assert((char*)oldfirst > (char*)q); - assert(pinuse(oldfirst)); - assert(qsize >= MIN_CHUNK_SIZE); - - /* consolidate remainder with first chunk of old base */ - if (oldfirst == m->top) - { - size_t tsize = m->topsize += qsize; - m->top = q; - q->head = tsize | PINUSE_BIT; - check_top_chunk(m, q); - } - else if (oldfirst == m->dv) - { - size_t dsize = m->dvsize += qsize; - m->dv = q; - set_size_and_pinuse_of_free_chunk(q, dsize); - } - else - { - if (!is_inuse(oldfirst)) - { - size_t nsize = chunksize(oldfirst); - unlink_chunk(m, oldfirst, nsize); - oldfirst = chunk_plus_offset(oldfirst, nsize); - qsize += nsize; - } - set_free_with_pinuse(q, qsize, oldfirst); - insert_chunk(m, q, qsize); - check_free_chunk(m, q); - } - - check_malloced_chunk(m, chunk2mem(p), nb); - return chunk2mem(p); -} - -/* Add a segment to hold a new noncontiguous region */ -static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) -{ - /* Determine locations and sizes of segment, fenceposts, old top */ - char* old_top = (char*)m->top; - msegmentptr oldsp = segment_holding(m, old_top); - char* old_end = oldsp->base + oldsp->size; - size_t ssize = pad_request(sizeof(struct malloc_segment)); - char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - size_t offset = align_offset(chunk2mem(rawsp)); - char* asp = rawsp + offset; - char* csp = (asp < (old_top + MIN_CHUNK_SIZE)) ? old_top : asp; - mchunkptr sp = (mchunkptr)csp; - msegmentptr ss = (msegmentptr)(chunk2mem(sp)); - mchunkptr tnext = chunk_plus_offset(sp, ssize); - mchunkptr p = tnext; - int nfences = 0; - - /* reset top to new space */ - init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); - - /* Set up segment record */ - assert(is_aligned(ss)); - set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); - *ss = m->seg; /* Push current record */ - m->seg.base = tbase; - m->seg.size = tsize; - m->seg.sflags = mmapped; - m->seg.next = ss; - - /* Insert trailing fenceposts */ - for (;; ) - { - mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); - p->head = FENCEPOST_HEAD; - ++nfences; - if ((char*)(&(nextp->head)) < old_end) - { - p = nextp; - } - else - { - break; - } - } - assert(nfences >= 2); - - /* Insert the rest of old top into a bin as an ordinary free chunk */ - if (csp != old_top) - { - mchunkptr q = (mchunkptr)old_top; - size_t psize = csp - old_top; - mchunkptr tn = chunk_plus_offset(q, psize); - set_free_with_pinuse(q, psize, tn); - insert_chunk(m, q, psize); - } - - check_top_chunk(m, m->top); -} - -/* -------------------------- System allocation -------------------------- */ - -/* Get memory from system using MORECORE or MMAP */ -static void* sys_alloc(mstate m, size_t nb) -{ - char* tbase = CMFAIL; - size_t tsize = 0; - flag_t mmap_flag = 0; - - ensure_initialization(); - - /* Directly map large chunks, but only if already initialized */ - if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) - { - void* mem = mmap_alloc(m, nb); - if (mem != 0) - { - return mem; - } - } - - /* - Try getting memory in any of three ways (in most-preferred to - least-preferred order): - 1. A call to MORECORE that can normally contiguously extend memory. - (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or - or main space is mmapped or a previous contiguous call failed) - 2. A call to MMAP new space (disabled if not HAVE_MMAP). - Note that under the default settings, if MORECORE is unable to - fulfill a request, and HAVE_MMAP is true, then mmap is - used as a noncontiguous system allocator. This is a useful backup - strategy for systems with holes in address spaces -- in this case - sbrk cannot contiguously expand the heap, but mmap may be able to - find space. - 3. A call to MORECORE that cannot usually contiguously extend memory. - (disabled if not HAVE_MORECORE) - - In all cases, we need to request enough bytes from system to ensure - we can malloc nb bytes upon success, so pad with enough space for - top_foot, plus alignment-pad to make sure we don't lose bytes if - not on boundary, and round this up to a granularity unit. - */ - - if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) - { - char* br = CMFAIL; - msegmentptr ss = (m->top == 0) ? 0 : segment_holding(m, (char*)m->top); - size_t asize = 0; - ACQUIRE_MALLOC_GLOBAL_LOCK(); - - if (ss == 0) /* First time through or recovery */ - { - char* base = (char*)CALL_MORECORE(0); - if (base != CMFAIL) - { - asize = granularity_align(nb + SYS_ALLOC_PADDING); - /* Adjust to end on a page boundary */ - if (!is_page_aligned(base)) - { - asize += (page_align((size_t)base) - (size_t)base); - } - /* Can't call MORECORE if size is negative when treated as signed */ - if (asize < HALF_MAX_SIZE_T && - (br = (char*)(CALL_MORECORE(asize))) == base) - { - tbase = base; - tsize = asize; - } - } - } - else - { - /* Subtract out existing available top space from MORECORE request. */ - asize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING); - /* Use mem here only if it did continuously extend old space */ - if (asize < HALF_MAX_SIZE_T && - (br = (char*)(CALL_MORECORE(asize))) == ss->base + ss->size) - { - tbase = br; - tsize = asize; - } - } - - if (tbase == CMFAIL) /* Cope with partial failure */ - { - if (br != CMFAIL) /* Try to use/extend the space we did get */ - { - if (asize < HALF_MAX_SIZE_T && - asize < nb + SYS_ALLOC_PADDING) - { - size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - asize); - if (esize < HALF_MAX_SIZE_T) - { - char* end = (char*)CALL_MORECORE(esize); - if (end != CMFAIL) - { - asize += esize; - } - else /* Can't use; try to release */ - { - (void) CALL_MORECORE(-asize); - br = CMFAIL; - } - } - } - } - if (br != CMFAIL) /* Use the space we did get */ - { - tbase = br; - tsize = asize; - } - else - { - disable_contiguous(m); /* Don't try contiguous path in the future */ - } - } - - RELEASE_MALLOC_GLOBAL_LOCK(); - } - - if (HAVE_MMAP && tbase == CMFAIL) /* Try MMAP */ - { - size_t rsize = granularity_align(nb + SYS_ALLOC_PADDING); - if (rsize > nb) /* Fail if wraps around zero */ - { - char* mp = (char*)((*m->mmap)(m->extp, rsize)); - if (mp != CMFAIL) - { - tbase = mp; - tsize = rsize; - mmap_flag = USE_MMAP_BIT; - } - } - } - - if (HAVE_MORECORE && tbase == CMFAIL) /* Try noncontiguous MORECORE */ - { - size_t asize = granularity_align(nb + SYS_ALLOC_PADDING); - if (asize < HALF_MAX_SIZE_T) - { - char* br = CMFAIL; - char* end = CMFAIL; - ACQUIRE_MALLOC_GLOBAL_LOCK(); - br = (char*)(CALL_MORECORE(asize)); - end = (char*)(CALL_MORECORE(0)); - RELEASE_MALLOC_GLOBAL_LOCK(); - if (br != CMFAIL && end != CMFAIL && br < end) - { - size_t ssize = end - br; - if (ssize > nb + TOP_FOOT_SIZE) - { - tbase = br; - tsize = ssize; - } - } - } - } - - if (tbase != CMFAIL) - { - if ((m->footprint += tsize) > m->max_footprint) - { - m->max_footprint = m->footprint; - } - - if (!is_initialized(m)) /* first-time initialization */ - { - if (m->least_addr == 0 || tbase < m->least_addr) - { - m->least_addr = tbase; - } - m->seg.base = tbase; - m->seg.size = tsize; - m->seg.sflags = mmap_flag; - m->magic = mparams.magic; - m->release_checks = MAX_RELEASE_CHECK_RATE; - init_bins(m); -#if !ONLY_MSPACES - if (is_global(m)) - { - init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); - } - else -#endif - { - /* Offset top by embedded malloc_state */ - mchunkptr mn = next_chunk(mem2chunk(m)); - init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); - } - } - - else - { - /* Try to merge with an existing segment */ - msegmentptr sp = &m->seg; - /* Only consider most recent segment if traversal suppressed */ - while (sp != 0 && tbase != sp->base + sp->size) - { - sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; - } - if (sp != 0 && - !is_extern_segment(sp) && - (sp->sflags & USE_MMAP_BIT) == mmap_flag && - segment_holds(sp, m->top)) /* append */ - { - sp->size += tsize; - init_top(m, m->top, m->topsize + tsize); - } - else - { - if (tbase < m->least_addr) - { - m->least_addr = tbase; - } - sp = &m->seg; - while (sp != 0 && sp->base != tbase + tsize) - { - sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; - } - if (sp != 0 && - !is_extern_segment(sp) && - (sp->sflags & USE_MMAP_BIT) == mmap_flag) - { - char* oldbase = sp->base; - sp->base = tbase; - sp->size += tsize; - return prepend_alloc(m, tbase, oldbase, nb); - } - else - { - add_segment(m, tbase, tsize, mmap_flag); - } - } - } - - if (nb < m->topsize) /* Allocate from new or extended top space */ - { - size_t rsize = m->topsize -= nb; - mchunkptr p = m->top; - mchunkptr r = m->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(m, p, nb); - check_top_chunk(m, m->top); - check_malloced_chunk(m, chunk2mem(p), nb); - return chunk2mem(p); - } - } - - MALLOC_FAILURE_ACTION; - return 0; -} - -/* ----------------------- system deallocation -------------------------- */ - -/* Unmap and unlink any mmapped segments that don't contain used chunks */ -static size_t release_unused_segments(mstate m) -{ - size_t released = 0; - int nsegs = 0; - msegmentptr pred = &m->seg; - msegmentptr sp = pred->next; - while (sp != 0) - { - char* base = sp->base; - size_t size = sp->size; - msegmentptr next = sp->next; - ++nsegs; - if (is_mmapped_segment(sp) && !is_extern_segment(sp)) - { - mchunkptr p = align_as_chunk(base); - size_t psize = chunksize(p); - /* Can unmap if first chunk holds entire segment and not pinned */ - if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) - { - tchunkptr tp = (tchunkptr)p; - assert(segment_holds(sp, (char*)sp)); - if (p == m->dv) - { - m->dv = 0; - m->dvsize = 0; - } - else - { - unlink_large_chunk(m, tp); - } - if ((*m->munmap)(m->extp, base, size) == 0) - { - released += size; - m->footprint -= size; - /* unlink obsoleted record */ - sp = pred; - sp->next = next; - } - else /* back out if cannot unmap */ - { - insert_large_chunk(m, tp, psize); - } - } - } - if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */ - { - break; - } - pred = sp; - sp = next; - } - /* Reset check counter */ - m->release_checks = ((nsegs > MAX_RELEASE_CHECK_RATE) ? - nsegs : MAX_RELEASE_CHECK_RATE); - return released; -} - -static int sys_trim(mstate m, size_t pad) -{ - size_t released = 0; - ensure_initialization(); - if (pad < MAX_REQUEST && is_initialized(m)) - { - pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ - - if (m->topsize > pad) - { - /* Shrink top space in granularity-size units, keeping at least one */ - size_t unit = mparams.granularity; - size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - - SIZE_T_ONE) * unit; - msegmentptr sp = segment_holding(m, (char*)m->top); - - if (!is_extern_segment(sp)) - { - if (is_mmapped_segment(sp)) - { - if (HAVE_MMAP && - sp->size >= extra && - 1 /*!has_segment_link(m, sp)*/) /* can't shrink if pinned */ - { - size_t newsize = sp->size - extra; - /* Prefer mremap, fall back to munmap */ - if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || - ((*m->munmap)(m->extp, sp->base + newsize, extra) == 0)) - { - released = extra; - } - } - } - else if (HAVE_MORECORE) - { - if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ - { - extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; - } - ACQUIRE_MALLOC_GLOBAL_LOCK(); - { - /* Make sure end of memory is where we last set it. */ - char* old_br = (char*)(CALL_MORECORE(0)); - if (old_br == sp->base + sp->size) - { - char* rel_br = (char*)(CALL_MORECORE(-extra)); - char* new_br = (char*)(CALL_MORECORE(0)); - if (rel_br != CMFAIL && new_br < old_br) - { - released = old_br - new_br; - } - } - } - RELEASE_MALLOC_GLOBAL_LOCK(); - } - } - - if (released != 0) - { - sp->size -= released; - m->footprint -= released; - init_top(m, m->top, m->topsize - released); - check_top_chunk(m, m->top); - } - } - - /* Unmap any unused mmapped segments */ - if (HAVE_MMAP) - { - released += release_unused_segments(m); - } - - /* On failure, disable autotrim to avoid repeated failed future calls */ - if (released == 0 && m->topsize > m->trim_check) - { - m->trim_check = MAX_SIZE_T; - } - } - - return (released != 0) ? 1 : 0; -} - - -/* ---------------------------- malloc support --------------------------- */ - -/* allocate a large request from the best fitting chunk in a treebin */ -static void* tmalloc_large(mstate m, size_t nb) -{ - tchunkptr v = 0; - size_t rsize = -nb; /* Unsigned negation */ - tchunkptr t; - bindex_t idx; - compute_tree_index(nb, idx); - if ((t = *treebin_at(m, idx)) != 0) - { - /* Traverse tree for this bin looking for node with size == nb */ - size_t sizebits = nb << leftshift_for_tree_index(idx); - tchunkptr rst = 0; /* The deepest untaken right subtree */ - for (;; ) - { - tchunkptr rt; - size_t trem = chunksize(t) - nb; - if (trem < rsize) - { - v = t; - if ((rsize = trem) == 0) - { - break; - } - } - rt = t->child[1]; - t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1]; - if (rt != 0 && rt != t) - { - rst = rt; - } - if (t == 0) - { - t = rst; /* set t to least subtree holding sizes > nb */ - break; - } - sizebits <<= 1; - } - } - if (t == 0 && v == 0) /* set t to root of next non-empty treebin */ - { - binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; - if (leftbits != 0) - { - bindex_t i; - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - t = *treebin_at(m, i); - } - } - - while (t != 0) /* find smallest of tree or subtree */ - { - size_t trem = chunksize(t) - nb; - if (trem < rsize) - { - rsize = trem; - v = t; - } - t = leftmost_child(t); - } - - /* If dv is a better fit, return 0 so malloc will use it */ - if (v != 0 && rsize < (size_t)(m->dvsize - nb)) - { - if (RTCHECK(ok_address(m, v))) /* split */ - { - mchunkptr r = chunk_plus_offset(v, nb); - assert(chunksize(v) == rsize + nb); - if (RTCHECK(ok_next(v, r))) - { - unlink_large_chunk(m, v); - if (rsize < MIN_CHUNK_SIZE) - { - set_inuse_and_pinuse(m, v, (rsize + nb)); - } - else - { - set_size_and_pinuse_of_inuse_chunk(m, v, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - insert_chunk(m, r, rsize); - } - return chunk2mem(v); - } - } - CORRUPTION_ERROR_ACTION(m); - } - return 0; -} - -/* allocate a small request from the best fitting chunk in a treebin */ -static void* tmalloc_small(mstate m, size_t nb) -{ - tchunkptr t, v; - size_t rsize; - bindex_t i; - binmap_t leastbit = least_bit(m->treemap); - compute_bit2idx(leastbit, i); - v = t = *treebin_at(m, i); - rsize = chunksize(t) - nb; - - while ((t = leftmost_child(t)) != 0) - { - size_t trem = chunksize(t) - nb; - if (trem < rsize) - { - rsize = trem; - v = t; - } - } - - if (RTCHECK(ok_address(m, v))) - { - mchunkptr r = chunk_plus_offset(v, nb); - assert(chunksize(v) == rsize + nb); - if (RTCHECK(ok_next(v, r))) - { - unlink_large_chunk(m, v); - if (rsize < MIN_CHUNK_SIZE) - { - set_inuse_and_pinuse(m, v, (rsize + nb)); - } - else - { - set_size_and_pinuse_of_inuse_chunk(m, v, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(m, r, rsize); - } - return chunk2mem(v); - } - } - - CORRUPTION_ERROR_ACTION(m); -#if PROCEED_ON_ERROR - return 0; -#endif -} - -/* --------------------------- realloc support --------------------------- */ - -static void* internal_realloc(mstate m, void* oldmem, size_t bytes) -{ - if (bytes >= MAX_REQUEST) - { - MALLOC_FAILURE_ACTION; - return 0; - } - if (!PREACTION(m)) - { - mchunkptr oldp = mem2chunk(oldmem); - size_t oldsize = chunksize(oldp); - mchunkptr next = chunk_plus_offset(oldp, oldsize); - mchunkptr newp = 0; - void* extra = 0; - - /* Try to either shrink or extend into top. Else malloc-copy-free */ - - if (RTCHECK(ok_address(m, oldp) && ok_inuse(oldp) && - ok_next(oldp, next) && ok_pinuse(next))) - { - size_t nb = request2size(bytes); - if (is_mmapped(oldp)) - { - newp = mmap_resize(m, oldp, nb); - } - else if (oldsize >= nb) /* already big enough */ - { - size_t rsize = oldsize - nb; - newp = oldp; - if (rsize >= MIN_CHUNK_SIZE) - { - mchunkptr remainder = chunk_plus_offset(newp, nb); - set_inuse(m, newp, nb); - set_inuse_and_pinuse(m, remainder, rsize); - extra = chunk2mem(remainder); - } - } - else if (next == m->top && oldsize + m->topsize > nb) - { - /* Expand into top */ - size_t newsize = oldsize + m->topsize; - size_t newtopsize = newsize - nb; - mchunkptr newtop = chunk_plus_offset(oldp, nb); - set_inuse(m, oldp, nb); - newtop->head = newtopsize | PINUSE_BIT; - m->top = newtop; - m->topsize = newtopsize; - newp = oldp; - } - } - else - { - USAGE_ERROR_ACTION(m, oldmem); - POSTACTION(m); -#if PROCEED_ON_ERROR - return 0; -#endif - } -#if DEBUG - if (newp != 0) - { - check_inuse_chunk(m, newp); /* Check requires lock */ - } -#endif - - POSTACTION(m); - - if (newp != 0) - { - if (extra != 0) - { - internal_free(m, extra); - } - return chunk2mem(newp); - } - else - { - void* newmem = internal_malloc(m, bytes); - if (newmem != 0) - { - size_t oc = oldsize - overhead_for(oldp); - memcpy(newmem, oldmem, (oc < bytes) ? oc : bytes); - internal_free(m, oldmem); - } - return newmem; - } - } - return 0; -} - -/* --------------------------- memalign support -------------------------- */ - -static void* internal_memalign(mstate m, size_t alignment, size_t bytes) -{ - if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */ - { - return internal_malloc(m, bytes); - } - if (alignment < MIN_CHUNK_SIZE)/* must be at least a minimum chunk size */ - { - alignment = MIN_CHUNK_SIZE; - } - if ((alignment & (alignment - SIZE_T_ONE)) != 0)/* Ensure a power of 2 */ - { - size_t a = MALLOC_ALIGNMENT << 1; - while (a < alignment) - { - a <<= 1; - } - alignment = a; - } - - if (bytes >= MAX_REQUEST - alignment) - { - if (m != 0) /* Test isn't needed but avoids compiler warning */ - { - MALLOC_FAILURE_ACTION; - } - } - else - { - size_t nb = request2size(bytes); - size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; - char* mem = (char*)internal_malloc(m, req); - if (mem != 0) - { - void* leader = 0; - void* trailer = 0; - mchunkptr p = mem2chunk(mem); - - if (PREACTION(m)) - { - return 0; - } - if ((((size_t)(mem)) % alignment) != 0) /* misaligned */ - { - /* - Find an aligned spot inside chunk. Since we need to give - back leading space in a chunk of at least MIN_CHUNK_SIZE, if - the first calculation places us at a spot with less than - MIN_CHUNK_SIZE leader, we can move to the next aligned spot. - We've allocated enough total room so that this is always - possible. - */ - char* br = (char*)mem2chunk((size_t)(((size_t)(mem + - alignment - - SIZE_T_ONE)) & - - alignment)); - char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE) ? - br : br + alignment; - mchunkptr newp = (mchunkptr)pos; - size_t leadsize = pos - (char*)(p); - size_t newsize = chunksize(p) - leadsize; - - if (is_mmapped(p)) /* For mmapped chunks, just adjust offset */ - { - newp->prev_foot = p->prev_foot + leadsize; - newp->head = newsize; - } - else /* Otherwise, give back leader, use the rest */ - { - set_inuse(m, newp, newsize); - set_inuse(m, p, leadsize); - leader = chunk2mem(p); - } - p = newp; - } - - /* Give back spare room at the end */ - if (!is_mmapped(p)) - { - size_t size = chunksize(p); - if (size > nb + MIN_CHUNK_SIZE) - { - size_t remainder_size = size - nb; - mchunkptr remainder = chunk_plus_offset(p, nb); - set_inuse(m, p, nb); - set_inuse(m, remainder, remainder_size); - trailer = chunk2mem(remainder); - } - } - - assert (chunksize(p) >= nb); - assert((((size_t)(chunk2mem(p))) % alignment) == 0); - check_inuse_chunk(m, p); - POSTACTION(m); - if (leader != 0) - { - internal_free(m, leader); - } - if (trailer != 0) - { - internal_free(m, trailer); - } - return chunk2mem(p); - } - } - return 0; -} - -/* ------------------------ comalloc/coalloc support --------------------- */ - -static void** ialloc(mstate m, - size_t n_elements, - size_t* sizes, - int opts, - void* chunks[]) -{ - /* - This provides common support for independent_X routines, handling - all of the combinations that can result. - - The opts arg has: - bit 0 set if all elements are same size (using sizes[0]) - bit 1 set if elements should be zeroed - */ - - size_t element_size; /* chunksize of each element, if all same */ - size_t contents_size;/* total size of elements */ - size_t array_size; /* request size of pointer array */ - void* mem; /* malloced aggregate space */ - mchunkptr p; /* corresponding chunk */ - size_t remainder_size;/* remaining bytes while splitting */ - void** marray; /* either "chunks" or malloced ptr array */ - mchunkptr array_chunk; /* chunk for malloced ptr array */ - flag_t was_enabled; /* to disable mmap */ - size_t size; - size_t i; - - ensure_initialization(); - /* compute array length, if needed */ - if (chunks != 0) - { - if (n_elements == 0) - { - return chunks; /* nothing to do */ - } - marray = chunks; - array_size = 0; - } - else - { - /* if empty req, must still return chunk representing empty array */ - if (n_elements == 0) - { - return (void**)internal_malloc(m, 0); - } - marray = 0; - array_size = request2size(n_elements * (sizeof(void*))); - } - - /* compute total element size */ - if (opts & 0x1) /* all-same-size */ - { - element_size = request2size(*sizes); - contents_size = n_elements * element_size; - } - else /* add up all the sizes */ - { - element_size = 0; - contents_size = 0; - for (i = 0; i != n_elements; ++i) - { - contents_size += request2size(sizes[i]); - } - } - - size = contents_size + array_size; - - /* - Allocate the aggregate chunk. First disable direct-mmapping so - malloc won't use it, since we would not be able to later - free/realloc space internal to a segregated mmap region. - */ - was_enabled = use_mmap(m); - disable_mmap(m); - mem = internal_malloc(m, size - CHUNK_OVERHEAD); - if (was_enabled) - { - enable_mmap(m); - } - if (mem == 0) - { - return 0; - } - - if (PREACTION(m)) - { - return 0; - } - p = mem2chunk(mem); - remainder_size = chunksize(p); - - assert(!is_mmapped(p)); - - if (opts & 0x2) /* optionally clear the elements */ - { - memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); - } - - /* If not provided, allocate the pointer array as final part of chunk */ - if (marray == 0) - { - size_t array_chunk_size; - array_chunk = chunk_plus_offset(p, contents_size); - array_chunk_size = remainder_size - contents_size; - marray = (void**) (chunk2mem(array_chunk)); - set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); - remainder_size = contents_size; - } - - /* split out elements */ - for (i = 0;; ++i) - { - marray[i] = chunk2mem(p); - if (i != n_elements - 1) - { - if (element_size != 0) - { - size = element_size; - } - else - { - size = request2size(sizes[i]); - } - remainder_size -= size; - set_size_and_pinuse_of_inuse_chunk(m, p, size); - p = chunk_plus_offset(p, size); - } - else /* the final element absorbs any overallocation slop */ - { - set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); - break; - } - } - -#if DEBUG - if (marray != chunks) - { - /* final element must have exactly exhausted chunk */ - if (element_size != 0) - { - assert(remainder_size == element_size); - } - else - { - assert(remainder_size == request2size(sizes[i])); - } - check_inuse_chunk(m, mem2chunk(marray)); - } - for (i = 0; i != n_elements; ++i) - { - check_inuse_chunk(m, mem2chunk(marray[i])); - } - -#endif /* DEBUG */ - - POSTACTION(m); - return marray; -} - - -/* -------------------------- public routines ---------------------------- */ - -#if !ONLY_MSPACES - -void* dlmalloc(size_t bytes) -{ - /* - Basic algorithm: - If a small request (< 256 bytes minus per-chunk overhead): - 1. If one exists, use a remainderless chunk in associated smallbin. - (Remainderless means that there are too few excess bytes to - represent as a chunk.) - 2. If it is big enough, use the dv chunk, which is normally the - chunk adjacent to the one used for the most recent small request. - 3. If one exists, split the smallest available chunk in a bin, - saving remainder in dv. - 4. If it is big enough, use the top chunk. - 5. If available, get memory from system and use it - Otherwise, for a large request: - 1. Find the smallest available binned chunk that fits, and use it - if it is better fitting than dv chunk, splitting if necessary. - 2. If better fitting than any binned chunk, use the dv chunk. - 3. If it is big enough, use the top chunk. - 4. If request size >= mmap threshold, try to directly mmap this chunk. - 5. If available, get memory from system and use it - - The ugly goto's here ensure that postaction occurs along all paths. - */ - -#if USE_LOCKS - ensure_initialization(); /* initialize in sys_alloc if not using locks */ -#endif - - if (!PREACTION(gm)) - { - void* mem; - size_t nb; - if (bytes <= MAX_SMALL_REQUEST) - { - bindex_t idx; - binmap_t smallbits; - nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); - idx = small_index(nb); - smallbits = gm->smallmap >> idx; - - if ((smallbits & 0x3U) != 0) /* Remainderless fit to a smallbin. */ - { - mchunkptr b, p; - idx += ~smallbits & 1; /* Uses next bin if idx empty */ - b = smallbin_at(gm, idx); - p = b->fd; - assert(chunksize(p) == small_index2size(idx)); - unlink_first_small_chunk(gm, b, p, idx); - set_inuse_and_pinuse(gm, p, small_index2size(idx)); - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - else if (nb > gm->dvsize) - { - if (smallbits != 0) /* Use chunk in next nonempty smallbin */ - { - mchunkptr b, p, r; - size_t rsize; - bindex_t i; - binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - b = smallbin_at(gm, i); - p = b->fd; - assert(chunksize(p) == small_index2size(i)); - unlink_first_small_chunk(gm, b, p, i); - rsize = small_index2size(i) - nb; - /* Fit here cannot be remainderless if 4byte sizes */ - if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) - { - set_inuse_and_pinuse(gm, p, small_index2size(i)); - } - else - { - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - r = chunk_plus_offset(p, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(gm, r, rsize); - } - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) - { - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - } - } - else if (bytes >= MAX_REQUEST) - { - nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ - } - else - { - nb = pad_request(bytes); - if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) - { - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - } - - if (nb <= gm->dvsize) - { - size_t rsize = gm->dvsize - nb; - mchunkptr p = gm->dv; - if (rsize >= MIN_CHUNK_SIZE) /* split dv */ - { - mchunkptr r = gm->dv = chunk_plus_offset(p, nb); - gm->dvsize = rsize; - set_size_and_pinuse_of_free_chunk(r, rsize); - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - } - else /* exhaust dv */ - { - size_t dvs = gm->dvsize; - gm->dvsize = 0; - gm->dv = 0; - set_inuse_and_pinuse(gm, p, dvs); - } - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - else if (nb < gm->topsize) /* Split top */ - { - size_t rsize = gm->topsize -= nb; - mchunkptr p = gm->top; - mchunkptr r = gm->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - mem = chunk2mem(p); - check_top_chunk(gm, gm->top); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - mem = sys_alloc(gm, nb); - -postaction: - POSTACTION(gm); - return mem; - } - - return 0; -} - -void dlfree(void* mem) -{ - /* - Consolidate freed chunks with preceeding or succeeding bordering - free chunks, if they exist, and then place in a bin. Intermixed - with special cases for top, dv, mmapped chunks, and usage errors. - */ - - if (mem != 0) - { - mchunkptr p = mem2chunk(mem); -#if FOOTERS - mstate fm = get_mstate_for(p); - if (!ok_magic(fm)) - { - USAGE_ERROR_ACTION(fm, p); - return; - } -#else /* FOOTERS */ -#define fm gm -#endif /* FOOTERS */ - if (!PREACTION(fm)) - { - check_inuse_chunk(fm, p); - if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) - { - size_t psize = chunksize(p); - mchunkptr next = chunk_plus_offset(p, psize); - if (!pinuse(p)) - { - size_t prevsize = p->prev_foot; - if (is_mmapped(p)) - { - psize += prevsize + MMAP_FOOT_PAD; - if ((*fm->munmap)(fm->extp, (char*)p - prevsize, psize) == 0) - { - fm->footprint -= psize; - } - goto postaction; - } - else - { - mchunkptr prev = chunk_minus_offset(p, prevsize); - psize += prevsize; - p = prev; - if (RTCHECK(ok_address(fm, prev))) /* consolidate backward */ - { - if (p != fm->dv) - { - unlink_chunk(fm, p, prevsize); - } - else if ((next->head & INUSE_BITS) == INUSE_BITS) - { - fm->dvsize = psize; - set_free_with_pinuse(p, psize, next); - goto postaction; - } - } - else - { - goto erroraction; - } - } - } - - if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) - { - if (!cinuse(next)) /* consolidate forward */ - { - if (next == fm->top) - { - size_t tsize = fm->topsize += psize; - fm->top = p; - p->head = tsize | PINUSE_BIT; - if (p == fm->dv) - { - fm->dv = 0; - fm->dvsize = 0; - } - if (should_trim(fm, tsize)) - { - sys_trim(fm, 0); - } - goto postaction; - } - else if (next == fm->dv) - { - size_t dsize = fm->dvsize += psize; - fm->dv = p; - set_size_and_pinuse_of_free_chunk(p, dsize); - goto postaction; - } - else - { - size_t nsize = chunksize(next); - psize += nsize; - unlink_chunk(fm, next, nsize); - set_size_and_pinuse_of_free_chunk(p, psize); - if (p == fm->dv) - { - fm->dvsize = psize; - goto postaction; - } - } - } - else - { - set_free_with_pinuse(p, psize, next); - } - - if (is_small(psize)) - { - insert_small_chunk(fm, p, psize); - check_free_chunk(fm, p); - } - else - { - tchunkptr tp = (tchunkptr)p; - insert_large_chunk(fm, tp, psize); - check_free_chunk(fm, p); - if (--fm->release_checks == 0) - { - release_unused_segments(fm); - } - } - goto postaction; - } - } -erroraction: - USAGE_ERROR_ACTION(fm, p); -postaction: - POSTACTION(fm); - } - } -#if !FOOTERS -#undef fm -#endif /* FOOTERS */ -} - -void* dlcalloc(size_t n_elements, size_t elem_size) -{ - void* mem; - size_t req = 0; - if (n_elements != 0) - { - req = n_elements * elem_size; - if (((n_elements | elem_size) & ~(size_t)0xffff) && - (req / n_elements != elem_size)) - { - req = MAX_SIZE_T; /* force downstream failure on overflow */ - } - } - mem = dlmalloc(req); - if (mem != 0 && calloc_must_clear(mem2chunk(mem))) - { - memset(mem, 0, req); - } - return mem; -} - -void* dlrealloc(void* oldmem, size_t bytes) -{ - if (oldmem == 0) - { - return dlmalloc(bytes); - } -#ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) - { - dlfree(oldmem); - return 0; - } -#endif /* REALLOC_ZERO_BYTES_FREES */ - else - { -#if !FOOTERS - mstate m = gm; -#else /* FOOTERS */ - mstate m = get_mstate_for(mem2chunk(oldmem)); - if (!ok_magic(m)) - { - USAGE_ERROR_ACTION(m, oldmem); - return 0; - } -#endif /* FOOTERS */ - return internal_realloc(m, oldmem, bytes); - } -} - -void* dlmemalign(size_t alignment, size_t bytes) -{ - return internal_memalign(gm, alignment, bytes); -} - -void** dlindependent_calloc(size_t n_elements, size_t elem_size, - void* chunks[]) -{ - size_t sz = elem_size; /* serves as 1-element array */ - return ialloc(gm, n_elements, &sz, 3, chunks); -} - -void** dlindependent_comalloc(size_t n_elements, size_t sizes[], - void* chunks[]) -{ - return ialloc(gm, n_elements, sizes, 0, chunks); -} - -void* dlvalloc(size_t bytes) -{ - size_t pagesz; - ensure_initialization(); - pagesz = mparams.page_size; - return dlmemalign(pagesz, bytes); -} - -void* dlpvalloc(size_t bytes) -{ - size_t pagesz; - ensure_initialization(); - pagesz = mparams.page_size; - return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); -} - -int dlmalloc_trim(size_t pad) -{ - int result = 0; - ensure_initialization(); - if (!PREACTION(gm)) - { - result = sys_trim(gm, pad); - POSTACTION(gm); - } - return result; -} - -size_t dlmalloc_footprint(void) -{ - return gm->footprint; -} - -size_t dlmalloc_max_footprint(void) -{ - return gm->max_footprint; -} - -#if !NO_MALLINFO -struct mallinfo dlmallinfo(void) -{ - return internal_mallinfo(gm); -} -#endif /* NO_MALLINFO */ - -void dlmalloc_stats() -{ - internal_malloc_stats(gm); -} - -void dlmalloc_stats_ret(size_t* sys, size_t* maxSys, size_t* used) -{ - internal_malloc_stats_ret(gm, sys, maxSys, used); -} - -int dlmallopt(int param_number, int value) -{ - return change_mparam(param_number, value); -} - -void dlPrintStats(void) -{ - struct mallinfo info = dlmallinfo(); - fprintf(stdout, "Non-MMap:%d\nFreeChunks:%d\nMMap Space:%d\nTotal Space:%d\nAlloc Space:%d\nFree Space:%d\nReleasable:%d\n", - (int)info.arena, (int)info.ordblks, (int)info.hblkhd, (int)info.usmblks, (int)info.uordblks, (int)info.fordblks, (int)info.keepcost); - - ensure_initialization(); - if (!PREACTION(gm)) - { - check_malloc_state(gm); - if (is_initialized(gm)) - { - msegmentptr s = &gm->seg; - while (s != 0) - { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != gm->top && q->head != FENCEPOST_HEAD) - { - size_t sz = chunksize(q); - if (!is_inuse(q)) - { - fprintf(stdout, "Free: %p %d\n", q, (int)sz); - } - else - { - fprintf(stdout, "InUse: %p %d\n", q, (int)sz); - } - q = next_chunk(q); - } - s = s->next; - } - } - } -} -#endif /* !ONLY_MSPACES */ - -size_t dlmalloc_usable_size(void* mem) -{ - if (mem != 0) - { - mchunkptr p = mem2chunk(mem); - if (is_inuse(p)) - { - return chunksize(p) - overhead_for(p); - } - } - return 0; -} - -/* ----------------------------- user mspaces ---------------------------- */ - -#if MSPACES - -static mstate init_user_mstate(char* tbase, size_t tsize, void* user, dlmmap_handler mmap, dlmunmap_handler munmap) -{ - size_t msize = pad_request(sizeof(struct malloc_state)); - mchunkptr mn; - mchunkptr msp = align_as_chunk(tbase); - mstate m = (mstate)(chunk2mem(msp)); - memset(m, 0, msize); - INITIAL_LOCK(&m->mutex); - msp->head = (msize | INUSE_BITS); - m->seg.base = m->least_addr = tbase; - m->seg.size = m->footprint = m->max_footprint = tsize; - m->magic = mparams.magic; - m->release_checks = MAX_RELEASE_CHECK_RATE; - m->mflags = mparams.default_mflags; - m->extp = user; - m->exts = 0; - m->mmap = mmap; - m->munmap = munmap; - disable_contiguous(m); - init_bins(m); - mn = next_chunk(mem2chunk(m)); - init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); - check_top_chunk(m, m->top); - return m; -} - -static void* mmap_default(void* u, size_t sz) -{ - (void)u; - return CALL_MMAP(sz); -} - -static int munmap_default(void* u, void* p, size_t s) -{ - (void)u; - return CALL_MUNMAP(p, s); -} - -static void* mmap_missing(void* u, size_t sz) -{ - (void)u; - (void)sz; - return (void*) -1; -} - -static int munmap_missing(void* u, void* p, size_t s) -{ - (void)u; - (void)p; - (void)s; - return -1; -} - -int mspace_create_overhead(void) -{ - size_t msize = pad_request(sizeof(struct malloc_state)); - return msize + TOP_FOOT_SIZE; -} - -mspace create_mspace(size_t capacity, int locked, void* user, dlmmap_handler mmap, dlmunmap_handler munmap) -{ - mstate m = 0; - size_t msize; - ensure_initialization(); - msize = pad_request(sizeof(struct malloc_state)); - - if (!mmap) - { - mmap = mmap_default; - } - if (!munmap) - { - munmap = munmap_default; - } - - if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) - { - size_t rs = ((capacity == 0) ? mparams.granularity : - (capacity + TOP_FOOT_SIZE + msize)); - size_t tsize = granularity_align(rs); - char* tbase = (char*)((*mmap)(user, tsize)); - if (tbase != CMFAIL) - { - m = init_user_mstate(tbase, tsize, user, mmap, munmap); - m->seg.sflags = USE_MMAP_BIT; - set_lock(m, locked); - } - } - return (mspace)m; -} - -mspace create_mspace_with_base(void* base, size_t capacity, int locked) -{ - mstate m = 0; - size_t msize; - ensure_initialization(); - msize = pad_request(sizeof(struct malloc_state)); - if (capacity > msize + TOP_FOOT_SIZE && - capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) - { - m = init_user_mstate((char*)base, capacity, NULL, mmap_missing, munmap_missing); - m->seg.sflags = EXTERN_BIT; - set_lock(m, locked); - } - return (mspace)m; -} - -int mspace_track_large_chunks(mspace msp, int enable) -{ - int ret = 0; - mstate ms = (mstate)msp; - if (!PREACTION(ms)) - { - if (!use_mmap(ms)) - { - ret = 1; - } - if (!enable) - { - enable_mmap(ms); - } - else - { - disable_mmap(ms); - } - POSTACTION(ms); - } - return ret; -} - -size_t destroy_mspace(mspace msp) -{ - size_t freed = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) - { - msegmentptr sp = &ms->seg; - while (sp != 0) - { - char* base = sp->base; - size_t size = sp->size; - flag_t flag = sp->sflags; - sp = sp->next; - if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) && - (*ms->munmap)(ms->extp, base, size) == 0) - { - freed += size; - } - } - } - else - { - USAGE_ERROR_ACTION(ms, ms); - } - return freed; -} - -/* - mspace versions of routines are near-clones of the global - versions. This is not so nice but better than the alternatives. -*/ - - -void* mspace_malloc(mspace msp, size_t bytes) -{ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); -#if PROCEED_ON_ERROR - return 0; -#endif - } - if (!PREACTION(ms)) - { - void* mem; - size_t nb; - if (bytes <= MAX_SMALL_REQUEST) - { - bindex_t idx; - binmap_t smallbits; - nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); - idx = small_index(nb); - smallbits = ms->smallmap >> idx; - - if ((smallbits & 0x3U) != 0) /* Remainderless fit to a smallbin. */ - { - mchunkptr b, p; - idx += ~smallbits & 1; /* Uses next bin if idx empty */ - b = smallbin_at(ms, idx); - p = b->fd; - assert(chunksize(p) == small_index2size(idx)); - unlink_first_small_chunk(ms, b, p, idx); - set_inuse_and_pinuse(ms, p, small_index2size(idx)); - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (nb > ms->dvsize) - { - if (smallbits != 0) /* Use chunk in next nonempty smallbin */ - { - mchunkptr b, p, r; - size_t rsize; - bindex_t i; - binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - b = smallbin_at(ms, i); - p = b->fd; - assert(chunksize(p) == small_index2size(i)); - unlink_first_small_chunk(ms, b, p, i); - rsize = small_index2size(i) - nb; - /* Fit here cannot be remainderless if 4byte sizes */ - if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) - { - set_inuse_and_pinuse(ms, p, small_index2size(i)); - } - else - { - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - r = chunk_plus_offset(p, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(ms, r, rsize); - } - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) - { - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - } - } - else if (bytes >= MAX_REQUEST) - { - nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ - } - else - { - nb = pad_request(bytes); - if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) - { - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - } - - if (nb <= ms->dvsize) - { - size_t rsize = ms->dvsize - nb; - mchunkptr p = ms->dv; - if (rsize >= MIN_CHUNK_SIZE) /* split dv */ - { - mchunkptr r = ms->dv = chunk_plus_offset(p, nb); - ms->dvsize = rsize; - set_size_and_pinuse_of_free_chunk(r, rsize); - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - } - else /* exhaust dv */ - { - size_t dvs = ms->dvsize; - ms->dvsize = 0; - ms->dv = 0; - set_inuse_and_pinuse(ms, p, dvs); - } - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (nb < ms->topsize) /* Split top */ - { - size_t rsize = ms->topsize -= nb; - mchunkptr p = ms->top; - mchunkptr r = ms->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - mem = chunk2mem(p); - check_top_chunk(ms, ms->top); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - mem = sys_alloc(ms, nb); - -postaction: - POSTACTION(ms); - return mem; - } - - return 0; -} - -void mspace_free(mspace msp, void* mem) -{ - if (mem != 0) - { - mchunkptr p = mem2chunk(mem); -#if FOOTERS - mstate fm = get_mstate_for(p); - msp = msp; /* placate people compiling -Wunused */ -#else /* FOOTERS */ - mstate fm = (mstate)msp; -#endif /* FOOTERS */ - if (!ok_magic(fm)) - { - USAGE_ERROR_ACTION(fm, p); - return; - } - if (!PREACTION(fm)) - { - check_inuse_chunk(fm, p); - if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) - { - size_t psize = chunksize(p); - mchunkptr next = chunk_plus_offset(p, psize); - if (!pinuse(p)) - { - size_t prevsize = p->prev_foot; - if (is_mmapped(p)) - { - psize += prevsize + MMAP_FOOT_PAD; - if ((*fm->munmap)(fm->extp, (char*)p - prevsize, psize) == 0) - { - fm->footprint -= psize; - } - goto postaction; - } - else - { - mchunkptr prev = chunk_minus_offset(p, prevsize); - psize += prevsize; - p = prev; - if (RTCHECK(ok_address(fm, prev))) /* consolidate backward */ - { - if (p != fm->dv) - { - unlink_chunk(fm, p, prevsize); - } - else if ((next->head & INUSE_BITS) == INUSE_BITS) - { - fm->dvsize = psize; - set_free_with_pinuse(p, psize, next); - goto postaction; - } - } - else - { - goto erroraction; - } - } - } - - if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) - { - if (!cinuse(next)) /* consolidate forward */ - { - if (next == fm->top) - { - size_t tsize = fm->topsize += psize; - fm->top = p; - p->head = tsize | PINUSE_BIT; - if (p == fm->dv) - { - fm->dv = 0; - fm->dvsize = 0; - } - if (should_trim(fm, tsize)) - { - sys_trim(fm, 0); - } - goto postaction; - } - else if (next == fm->dv) - { - size_t dsize = fm->dvsize += psize; - fm->dv = p; - set_size_and_pinuse_of_free_chunk(p, dsize); - goto postaction; - } - else - { - size_t nsize = chunksize(next); - psize += nsize; - unlink_chunk(fm, next, nsize); - set_size_and_pinuse_of_free_chunk(p, psize); - if (p == fm->dv) - { - fm->dvsize = psize; - goto postaction; - } - } - } - else - { - set_free_with_pinuse(p, psize, next); - } - - if (is_small(psize)) - { - insert_small_chunk(fm, p, psize); - check_free_chunk(fm, p); - } - else - { - tchunkptr tp = (tchunkptr)p; - insert_large_chunk(fm, tp, psize); - check_free_chunk(fm, p); - if (--fm->release_checks == 0) - { - release_unused_segments(fm); - } - } - goto postaction; - } - } -erroraction: - USAGE_ERROR_ACTION(fm, p); -postaction: - POSTACTION(fm); - } - } -} - -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) -{ - void* mem; - size_t req = 0; - mstate ms = (mstate)msp; - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); -#if PROCEED_ON_ERROR - return 0; -#endif - } - if (n_elements != 0) - { - req = n_elements * elem_size; - if (((n_elements | elem_size) & ~(size_t)0xffff) && - (req / n_elements != elem_size)) - { - req = MAX_SIZE_T; /* force downstream failure on overflow */ - } - } - mem = internal_malloc(ms, req); - if (mem != 0 && calloc_must_clear(mem2chunk(mem))) - { - memset(mem, 0, req); - } - return mem; -} - -void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) -{ - if (oldmem == 0) - { - return mspace_malloc(msp, bytes); - } -#ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) - { - mspace_free(msp, oldmem); - return 0; - } -#endif /* REALLOC_ZERO_BYTES_FREES */ - else - { -#if FOOTERS - mchunkptr p = mem2chunk(oldmem); - mstate ms = get_mstate_for(p); -#else /* FOOTERS */ - mstate ms = (mstate)msp; -#endif /* FOOTERS */ - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); -#if PROCEED_ON_ERROR - return 0; -#endif - } - return internal_realloc(ms, oldmem, bytes); - } -} - -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) -{ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); -#if PROCEED_ON_ERROR - return 0; -#endif - } - return internal_memalign(ms, alignment, bytes); -} - -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]) -{ - size_t sz = elem_size; /* serves as 1-element array */ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); -#if PROCEED_ON_ERROR - return 0; -#endif - } - return ialloc(ms, n_elements, &sz, 3, chunks); -} - -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]) -{ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); -#if PROCEED_ON_ERROR - return 0; -#endif - } - return ialloc(ms, n_elements, sizes, 0, chunks); -} - -int mspace_trim(mspace msp, size_t pad) -{ - int result = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) - { - if (!PREACTION(ms)) - { - result = sys_trim(ms, pad); - POSTACTION(ms); - } - } - else - { - USAGE_ERROR_ACTION(ms, ms); - } - return result; -} - -void mspace_malloc_stats(mspace msp) -{ - mstate ms = (mstate)msp; - if (ok_magic(ms)) - { - internal_malloc_stats(ms); - } - else - { - USAGE_ERROR_ACTION(ms, ms); - } -} - -size_t mspace_footprint(mspace msp) -{ - size_t result = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) - { - result = ms->footprint; - } - else - { - USAGE_ERROR_ACTION(ms, ms); - } - return result; -} - - -size_t mspace_max_footprint(mspace msp) -{ - size_t result = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) - { - result = ms->max_footprint; - } - else - { - USAGE_ERROR_ACTION(ms, ms); - } - return result; -} - - -#if !NO_MALLINFO -struct mallinfo mspace_mallinfo(mspace msp) -{ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) - { - USAGE_ERROR_ACTION(ms, ms); - } - return internal_mallinfo(ms); -} - -size_t mspace_get_used_space(mspace msp) -{ - struct mallinfo info = mspace_mallinfo(msp); - return info.uordblks; -} -#endif /* NO_MALLINFO */ - -size_t mspace_usable_size(void* mem) -{ - if (mem != 0) - { - mchunkptr p = mem2chunk(mem); - if (is_inuse(p)) - { - return chunksize(p) - overhead_for(p); - } - } - return 0; -} - -int mspace_mallopt(int param_number, int value) -{ - return change_mparam(param_number, value); -} - -#endif /* MSPACES */ - - -/* -------------------- Alternative MORECORE functions ------------------- */ - -/* - Guidelines for creating a custom version of MORECORE: - - * For best performance, MORECORE should allocate in multiples of pagesize. - * MORECORE may allocate more memory than requested. (Or even less, - but this will usually result in a malloc failure.) - * MORECORE must not allocate memory when given argument zero, but - instead return one past the end address of memory from previous - nonzero call. - * For best performance, consecutive calls to MORECORE with positive - arguments should return increasing addresses, indicating that - space has been contiguously extended. - * Even though consecutive calls to MORECORE need not return contiguous - addresses, it must be OK for malloc'ed chunks to span multiple - regions in those cases where they do happen to be contiguous. - * MORECORE need not handle negative arguments -- it may instead - just return MFAIL when given negative arguments. - Negative arguments are always multiples of pagesize. MORECORE - must not misinterpret negative args as large positive unsigned - args. You can suppress all such calls from even occurring by defining - MORECORE_CANNOT_TRIM, - - As an example alternative MORECORE, here is a custom allocator - kindly contributed for pre-OSX macOS. It uses virtually but not - necessarily physically contiguous non-paged memory (locked in, - present and won't get swapped out). You can use it by uncommenting - this section, adding some #includes, and setting up the appropriate - defines above: - - #define MORECORE osMoreCore - - There is also a shutdown routine that should somehow be called for - cleanup upon program exit. - - #define MAX_POOL_ENTRIES 100 - #define MINIMUM_MORECORE_SIZE (64 * 1024U) - static int next_os_pool; - void *our_os_pools[MAX_POOL_ENTRIES]; - - void *osMoreCore(int size) - { - void *ptr = 0; - static void *sbrk_top = 0; - - if (size > 0) - { - if (size < MINIMUM_MORECORE_SIZE) - size = MINIMUM_MORECORE_SIZE; - if (CurrentExecutionLevel() == kTaskLevel) - ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); - if (ptr == 0) - { - return (void *) MFAIL; - } - // save ptrs so they can be freed during cleanup - our_os_pools[next_os_pool] = ptr; - next_os_pool++; - ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); - sbrk_top = (char *) ptr + size; - return ptr; - } - else if (size < 0) - { - // we don't currently support shrink behavior - return (void *) MFAIL; - } - else - { - return sbrk_top; - } - } - - // cleanup any allocated memory pools - // called as last thing before shutting down driver - - void osCleanupMem(void) - { - void **ptr; - - for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) - if (*ptr) - { - PoolDeallocate(*ptr); - *ptr = 0; - } - } - -*/ - - -/* ----------------------------------------------------------------------- -History: - V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) - * Use zeros instead of prev foot for is_mmapped - * Add mspace_track_large_chunks; thanks to Jean Brouwers - * Fix set_inuse in internal_realloc; thanks to Jean Brouwers - * Fix insufficient sys_alloc padding when using 16byte alignment - * Fix bad error check in mspace_footprint - * Adaptations for ptmalloc; thanks to Wolfram Gloger. - * Reentrant spin locks; thanks to Earl Chew and others - * Win32 improvements; thanks to Niall Douglas and Earl Chew - * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options - * Extension hook in malloc_state - * Various small adjustments to reduce warnings on some compilers - * Various configuration extensions/changes for more platforms. Thanks - to all who contributed these. - - V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee) - * Add max_footprint functions - * Ensure all appropriate literals are size_t - * Fix conditional compilation problem for some #define settings - * Avoid concatenating segments with the one provided - in create_mspace_with_base - * Rename some variables to avoid compiler shadowing warnings - * Use explicit lock initialization. - * Better handling of sbrk interference. - * Simplify and fix segment insertion, trimming and mspace_destroy - * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x - * Thanks especially to Dennis Flanagan for help on these. - - V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee) - * Fix memalign brace error. - - V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee) - * Fix improper #endif nesting in C++ - * Add explicit casts needed for C++ - - V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee) - * Use trees for large bins - * Support mspaces - * Use segments to unify sbrk-based and mmap-based system allocation, - removing need for emulation on most platforms without sbrk. - * Default safety checks - * Optional footer checks. Thanks to William Robertson for the idea. - * Internal code refactoring - * Incorporate suggestions and platform-specific changes. - Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas, - Aaron Bachmann, Emery Berger, and others. - * Speed up non-fastbin processing enough to remove fastbins. - * Remove useless cfree() to avoid conflicts with other apps. - * Remove internal memcpy, memset. Compilers handle builtins better. - * Remove some options that no one ever used and rename others. - - V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee) - * Fix malloc_state bitmap array misdeclaration - - V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee) - * Allow tuning of FIRST_SORTED_BIN_SIZE - * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte. - * Better detection and support for non-contiguousness of MORECORE. - Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger - * Bypass most of malloc if no frees. Thanks To Emery Berger. - * Fix freeing of old top non-contiguous chunk im sysmalloc. - * Raised default trim and map thresholds to 256K. - * Fix mmap-related #defines. Thanks to Lubos Lunak. - * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield. - * Branch-free bin calculation - * Default trim and mmap thresholds now 256K. - - V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) - * Introduce independent_comalloc and independent_calloc. - Thanks to Michael Pachos for motivation and help. - * Make optional .h file available - * Allow > 2GB requests on 32bit systems. - * new WIN32 sbrk, mmap, munmap, lock code from . - Thanks also to Andreas Mueller , - and Anonymous. - * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for - helping test this.) - * memalign: check alignment arg - * realloc: don't try to shift chunks backwards, since this - leads to more fragmentation in some programs and doesn't - seem to help in any others. - * Collect all cases in malloc requiring system memory into sysmalloc - * Use mmap as backup to sbrk - * Place all internal state in malloc_state - * Introduce fastbins (although similar to 2.5.1) - * Many minor tunings and cosmetic improvements - * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK - * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS - Thanks to Tony E. Bennett and others. - * Include errno.h to support default failure action. - - V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) - * return null for negative arguments - * Added Several WIN32 cleanups from Martin C. Fong - * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' - (e.g. WIN32 platforms) - * Cleanup header file inclusion for WIN32 platforms - * Cleanup code to avoid Microsoft Visual C++ compiler complaints - * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing - memory allocation routines - * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) - * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to - usage of 'assert' in non-WIN32 code - * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to - avoid infinite loop - * Always call 'fREe()' rather than 'free()' - - V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) - * Fixed ordering problem with boundary-stamping - - V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) - * Added pvalloc, as recommended by H.J. Liu - * Added 64bit pointer support mainly from Wolfram Gloger - * Added anonymously donated WIN32 sbrk emulation - * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen - * malloc_extend_top: fix mask error that caused wastage after - foreign sbrks - * Add linux mremap support code from HJ Liu - - V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) - * Integrated most documentation with the code. - * Add support for mmap, with help from - Wolfram Gloger (Gloger@lrz.uni-muenchen.de). - * Use last_remainder in more cases. - * Pack bins using idea from colin@nyx10.cs.du.edu - * Use ordered bins instead of best-fit threshhold - * Eliminate block-local decls to simplify tracing and debugging. - * Support another case of realloc via move into top - * Fix error occuring when initial sbrk_base not word-aligned. - * Rely on page size for units instead of SBRK_UNIT to - avoid surprises about sbrk alignment conventions. - * Add mallinfo, mallopt. Thanks to Raymond Nijssen - (raymond@es.ele.tue.nl) for the suggestion. - * Add `pad' argument to malloc_trim and top_pad mallopt parameter. - * More precautions for cases where other routines call sbrk, - courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). - * Added macros etc., allowing use in linux libc from - H.J. Lu (hjl@gnu.ai.mit.edu) - * Inverted this history list - - V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) - * Re-tuned and fixed to behave more nicely with V2.6.0 changes. - * Removed all preallocation code since under current scheme - the work required to undo bad preallocations exceeds - the work saved in good cases for most test programs. - * No longer use return list or unconsolidated bins since - no scheme using them consistently outperforms those that don't - given above changes. - * Use best fit for very large chunks to prevent some worst-cases. - * Added some support for debugging - - V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) - * Removed footers when chunks are in use. Thanks to - Paul Wilson (wilson@cs.texas.edu) for the suggestion. - - V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) - * Added malloc_trim, with help from Wolfram Gloger - (wmglo@Dent.MED.Uni-Muenchen.DE). - - V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) - - V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) - * realloc: try to expand in both directions - * malloc: swap order of clean-bin strategy; - * realloc: only conditionally expand backwards - * Try not to scavenge used bins - * Use bin counts as a guide to preallocation - * Occasionally bin return list chunks in first scan - * Add a few optimizations from colin@nyx10.cs.du.edu - - V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) - * faster bin computation & slightly different binning - * merged all consolidations to one part of malloc proper - (eliminating old malloc_find_space & malloc_clean_bin) - * Scan 2 returns chunks (not just 1) - * Propagate failure in realloc if malloc returns 0 - * Add stuff to allow compilation on non-ANSI compilers - from kpv@research.att.com - - V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) - * removed potential for odd address access in prev_chunk - * removed dependency on getpagesize.h - * misc cosmetics and a bit more internal documentation - * anticosmetics: mangled names in macros to evade debugger strangeness - * tested on sparc, hp-700, dec-mips, rs6000 - with gcc & native cc (hp, dec only) allowing - Detlefs & Zorn comparison study (in SIGPLAN Notices.) - - Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) - * Based loosely on libg++-1.2X malloc. (It retains some of the overall - structure of old version, but most details differ.) - -*/ - -#endif diff --git a/Code/CryEngine/CrySystem/CrySystem.rc b/Code/CryEngine/CrySystem/CrySystem.rc deleted file mode 100644 index f3412468f5..0000000000 --- a/Code/CryEngine/CrySystem/CrySystem.rc +++ /dev/null @@ -1,91 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "000904b0" - BEGIN - VALUE "CompanyName", "Amazon.com, Inc." - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "LegalCopyright", "Portions of this file Copyright (c) Amazon.com, Inc. or its affiliates. All Rights Reserved. Original file Copyright (c) Crytek GMBH. Used under license by Amazon.com, Inc. and its affiliates." - VALUE "ProductName", "Lumberyard" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x9, 1200 - END -END - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED -#endif // English (United States) resources diff --git a/Code/CryEngine/CrySystem/CryWaterMark.h b/Code/CryEngine/CrySystem/CryWaterMark.h deleted file mode 100644 index 4272b63aab..0000000000 --- a/Code/CryEngine/CrySystem/CryWaterMark.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Header for adding a watermark to an exe, which can then be set -// by the external CryWaterMark program. To use, simply write: -// -// WATERMARKDATA(__blah); -// -// anywhere in the global scope in the program - - -#ifndef CRYINCLUDE_CRYSYSTEM_CRYWATERMARK_H -#define CRYINCLUDE_CRYSYSTEM_CRYWATERMARK_H -#pragma once - - -#define NUMMARKWORDS 10 -#define WATERMARKDATA(name) unsigned int name[] = { 0xDEBEFECA, 0xFABECEDA, 0xADABAFBE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - -// (the name is such that you can have multiple watermarks in one exe, don't use -// names like "watermark" just incase you accidentally give out an exe with -// debug information). - -#endif // CRYINCLUDE_CRYSYSTEM_CRYWATERMARK_H diff --git a/Code/CryEngine/CrySystem/HandlerBase.cpp b/Code/CryEngine/CrySystem/HandlerBase.cpp deleted file mode 100644 index 6e1b7fdc77..0000000000 --- a/Code/CryEngine/CrySystem/HandlerBase.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "HandlerBase.h" - -const char* SERVER_LOCK_NAME = "SynchronizeGameServer"; -const char* CLIENT_LOCK_NAME = "SynchronizeGameClient"; - -HandlerBase::HandlerBase(const char* bucket, int affinity) -{ - m_serverLockName.Format("%s_%s", SERVER_LOCK_NAME, bucket); - m_clientLockName.Format("%s_%s", CLIENT_LOCK_NAME, bucket); - if (affinity != 0) - { - m_affinity = uint32(1) << (affinity - 1); - } - else - { - m_affinity = -1; - } - m_prevAffinity = 0; -} - -HandlerBase::~HandlerBase() -{ - if (m_prevAffinity) - { - if (SyncSetAffinity(m_prevAffinity)) - { - CryLogAlways("Restored affinity to %d", m_prevAffinity); - } - else - { - CryLogAlways("Failed to restore affinity to %d", m_prevAffinity); - } - } -} - -void HandlerBase::SetAffinity() -{ - if (m_prevAffinity) //already set - { - return; - } - if (uint32 p = SyncSetAffinity(m_affinity)) - { - CryLogAlways("Changed affinity to %d", m_affinity); - m_prevAffinity = p; - } - else - { - CryLogAlways("Failed to change affinity to %d", m_affinity); - } -} - -#if defined(LINUX) - -uint32 HandlerBase::SyncSetAffinity(uint32 cpuMask)//put -1 -{ - if (cpuMask != 0) - { - cpu_set_t cpuSet; - uint32 affinity = 0; - if (!sched_getaffinity(getpid(), sizeof cpuSet, &cpuSet)) - { - for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu) - { - if (CPU_ISSET(cpu, &cpuSet)) - { - affinity |= 1 << cpu; - } - } - } - if (affinity) - { - CPU_ZERO(&cpuSet); - for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu) - { - if (cpuMask & (1 << cpu)) - { - CPU_SET(cpu, &cpuSet); - } - } - - if (!sched_setaffinity(getpid(), sizeof(cpuSet), &cpuSet)) - { - return affinity; - } - } - } - return 0; -} - -#elif AZ_LEGACY_CRYSYSTEM_TRAIT_USE_HANDLER_SYNC_AFFINITY - -uint32 HandlerBase::SyncSetAffinity(uint32 cpuMask)//put -1 -{ - uint32 p = (uint32)SetThreadAffinityMask(GetCurrentThread(), cpuMask); - if (p == 0) - { - CryLogAlways("Error updating affinity mask to %d", cpuMask); - } - return p; -} - -#else - -uint32 HandlerBase::SyncSetAffinity(uint32 cpuMask)//put -1 -{ - CryLogAlways("Updating thread affinity not supported on this platform"); - return 0; -} - -#endif - -#endif // defined(MAP_LOADING_SLICING) diff --git a/Code/CryEngine/CrySystem/HandlerBase.h b/Code/CryEngine/CrySystem/HandlerBase.h deleted file mode 100644 index 67e7a828a6..0000000000 --- a/Code/CryEngine/CrySystem/HandlerBase.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_HANDLERBASE_H -#define CRYINCLUDE_CRYSYSTEM_HANDLERBASE_H - -#pragma once - -const int MAX_CLIENTS_NUM = 100; - -struct HandlerBase -{ - HandlerBase(const char* bucket, int affinity); - ~HandlerBase(); - - void SetAffinity(); - uint32 SyncSetAffinity(uint32 cpuMask); - - string m_serverLockName; - string m_clientLockName; - uint32 m_affinity; - uint32 m_prevAffinity; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_HANDLERBASE_H diff --git a/Code/CryEngine/CrySystem/IOSConsole.h b/Code/CryEngine/CrySystem/IOSConsole.h deleted file mode 100644 index 8bd2a8779e..0000000000 --- a/Code/CryEngine/CrySystem/IOSConsole.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Console implementation for iOS, reports back to the main interface - -#pragma once - -#include -#include - -class CIOSConsole - : public ISystemUserCallback - , public IOutputPrintSink - , public ITextModeConsole -{ - CIOSConsole(const CIOSConsole&); - CIOSConsole& operator = (const CIOSConsole&); - - bool m_isInitialized; -public: - static CryCriticalSectionNonRecursive s_lock; -public: - CIOSConsole(); - ~CIOSConsole(); - - // Interface IOutputPrintSink ///////////////////////////////////////////// - DLL_EXPORT virtual void Print(const char* line); - - // Interface ISystemUserCallback ////////////////////////////////////////// - virtual bool OnError(const char* errorString); - virtual bool OnSaveDocument() { return false; } - virtual void OnProcessSwitch() { } - virtual void OnInitProgress(const char* sProgressMsg); - virtual void OnInit(ISystem*); - virtual void OnShutdown(); - virtual void OnUpdate(); - virtual void GetMemoryUsage(ICrySizer* pSizer); - void SetRequireDedicatedServer(bool) {} - void SetHeader(const char*) {} - // Interface ITextModeConsole ///////////////////////////////////////////// - virtual Vec2_tpl BeginDraw(); - virtual void PutText(int x, int y, const char* msg); - virtual void EndDraw(); -}; diff --git a/Code/CryEngine/CrySystem/IOSConsole.mm b/Code/CryEngine/CrySystem/IOSConsole.mm deleted file mode 100644 index 6058ea8a44..0000000000 --- a/Code/CryEngine/CrySystem/IOSConsole.mm +++ /dev/null @@ -1,94 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#if defined(IOS) -#include "IOSConsole.h" - - - -CIOSConsole::CIOSConsole(): -m_isInitialized(false) -{ - -} - -CIOSConsole::~CIOSConsole() -{ - -} - -// Interface IOutputPrintSink ///////////////////////////////////////////// -void CIOSConsole::Print(const char *line) -{ - printf("MSG: %s\n", line); -} -// Interface ISystemUserCallback ////////////////////////////////////////// -bool CIOSConsole::OnError(const char *errorString) -{ - printf("ERR: %s\n", errorString); - return true; -} - -void CIOSConsole::OnInitProgress(const char *sProgressMsg) -{ - (void) sProgressMsg; - // Do Nothing -} -void CIOSConsole::OnInit(ISystem *pSystem) -{ - if (!m_isInitialized) - { - IConsole* pConsole = pSystem->GetIConsole(); - if (pConsole != 0) - { - pConsole->AddOutputPrintSink(this); - } - m_isInitialized = true; - } -} -void CIOSConsole::OnShutdown() -{ - if (m_isInitialized) - { - // remove outputprintsink - m_isInitialized = false; - } -} -void CIOSConsole::OnUpdate() -{ - // Do Nothing -} -void CIOSConsole::GetMemoryUsage(ICrySizer *pSizer) -{ - size_t size = sizeof(*this); - - - - pSizer->AddObject(this, size); -} - -// Interface ITextModeConsole ///////////////////////////////////////////// -Vec2_tpl CIOSConsole::BeginDraw() -{ - return Vec2_tpl(0,0); -} -void CIOSConsole::PutText( int x, int y, const char * msg ) -{ - printf("PUT: %s\n", msg); -} -void CIOSConsole::EndDraw() { - // Do Nothing -} -#endif // IOS diff --git a/Code/CryEngine/CrySystem/LZ4Decompressor.cpp b/Code/CryEngine/CrySystem/LZ4Decompressor.cpp deleted file mode 100644 index a4b8a2b8e6..0000000000 --- a/Code/CryEngine/CrySystem/LZ4Decompressor.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : lz4 hc decompress wrapper - - -#include "CrySystem_precompiled.h" -#include -#include "LZ4Decompressor.h" - -bool CLZ4Decompressor::DecompressData(const char* pIn, char* pOut, const uint outputSize) const -{ - return LZ4_decompress_fast(pIn, pOut, outputSize) >= 0; -} - -void CLZ4Decompressor::Release() -{ - delete this; -} diff --git a/Code/CryEngine/CrySystem/LZ4Decompressor.h b/Code/CryEngine/CrySystem/LZ4Decompressor.h deleted file mode 100644 index 20652a8e78..0000000000 --- a/Code/CryEngine/CrySystem/LZ4Decompressor.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : lz4 hc decompress wrapper - - -#ifndef CRYINCLUDE_CRYSYSTEM_LZ4DECOMPRESSOR_H -#define CRYINCLUDE_CRYSYSTEM_LZ4DECOMPRESSOR_H -#pragma once - - -#include "ILZ4Decompressor.h" - -class CLZ4Decompressor - : public ILZ4Decompressor -{ -public: - virtual bool DecompressData(const char* pIn, char* pOut, const uint outputSize) const; - virtual void Release(); - -private: - virtual ~CLZ4Decompressor() {} -}; - -#endif // CRYINCLUDE_CRYSYSTEM_LZ4DECOMPRESSOR_H diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index 8d9c0dd8e8..68fc4b558a 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -260,16 +260,6 @@ void CLevelSystem::Rescan(const char* levelsFolder) { if (levelsFolder) { - if (const ICmdLineArg* pModArg = m_pSystem->GetICmdLine()->FindArg(eCLAT_Pre, "MOD")) - { - if (m_pSystem->IsMODValid(pModArg->GetValue())) - { - m_levelsFolder.format("Mods/%s/%s", pModArg->GetValue(), levelsFolder); - m_levelInfos.clear(); - ScanFolder(0, true); - } - } - m_levelsFolder = levelsFolder; } diff --git a/Code/CryEngine/CrySystem/Log.cpp b/Code/CryEngine/CrySystem/Log.cpp index 63aee4422f..c37e12cebd 100644 --- a/Code/CryEngine/CrySystem/Log.cpp +++ b/Code/CryEngine/CrySystem/Log.cpp @@ -417,7 +417,7 @@ void CLog::LogV(const ELogType type, const char* szFormat, va_list args) LogV(type, 0, szFormat, args); } -void CLog::LogV(const ELogType type, int flags, const char* szFormat, va_list args) +void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFormat, va_list args) { // this is here in case someone called LogV directly, with an invalid formatter. if (!CheckLogFormatter(szFormat)) @@ -595,28 +595,6 @@ void CLog::LogV(const ELogType type, int flags, const char* szFormat, va_list ar GetISystem()->GetIRemoteConsole()->AddLogError(szString); break; } - - ////////////////////////////////////////////////////////////////////////// - if (type == eWarningAlways || type == eWarning || type == eError || type == eErrorAlways) - { - IValidator* pValidator = m_pSystem->GetIValidator(); - if (pValidator && (flags & VALIDATOR_FLAG_SKIP_VALIDATOR) == 0) - { - CryAutoCriticalSection scope_lock(m_logCriticalSection); - - SValidatorRecord record; - record.text = szBuffer; - record.module = VALIDATOR_MODULE_SYSTEM; - record.severity = VALIDATOR_WARNING; - record.assetScope = GetAssetScopeString(); - record.flags = flags; - if (type == eError || type == eErrorAlways) - { - record.severity = VALIDATOR_ERROR; - } - pValidator->Report(record); - } - } } //will log the text both to the end of file and console diff --git a/Code/CryEngine/CrySystem/MobileDetectSpec.cpp b/Code/CryEngine/CrySystem/MobileDetectSpec.cpp deleted file mode 100644 index 342537daeb..0000000000 --- a/Code/CryEngine/CrySystem/MobileDetectSpec.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include -#include - -#include "MobileDetectSpec.h" - -namespace MobileSysInspect -{ - struct GpuApiPair - { - AZStd::string gpuDescription; - AZStd::string apiDescription; - }; - - AZStd::vector> deviceSpecMapping; - AZStd::vector> gpuSpecMapping; - const float LOW_SPEC_RAM = 1.0f; - const float MEDIUM_SPEC_RAM = 2.0f; - const float HIGH_SPEC_RAM = 3.0f; - - bool GetSpecForGPUAndAPI(const AZStd::string& gpuName, const AZStd::string& apiDescription, AZStd::string& specName) - { - for (const auto& descriptionSpecPair : gpuSpecMapping) - { - const GpuApiPair& currentPair = descriptionSpecPair.first; - AZStd::regex currentRegex(currentPair.gpuDescription.c_str()); - if (!AZStd::regex_search(gpuName, currentRegex)) - { - continue; - } - - currentRegex.assign(currentPair.apiDescription.c_str()); - if (!currentRegex.Empty() && !AZStd::regex_search(apiDescription, currentRegex)) - { - continue; - } - - specName = descriptionSpecPair.second; - return true; - } - - return false; - } - - namespace Internal - { - void LoadDeviceSpecMapping_impl(const char* filename) - { - XmlNodeRef xmlNode = GetISystem()->LoadXmlFromFile(filename); - - if (!xmlNode) - { - return; - } - - const int fileCount = xmlNode->getChildCount(); - - for (int i = 0; i < fileCount; ++i) - { - XmlNodeRef fileNode = xmlNode->getChild(i); - AZStd::string file = fileNode->getAttr("file"); - - if (!file.empty()) - { - const int mappingCount = fileNode->getChildCount(); - - deviceSpecMapping.reserve(mappingCount); - - for (int j = 0; j < mappingCount; ++j) - { - XmlNodeRef modelNode = fileNode->getChild(j); - AZStd::string model = modelNode->getAttr("model"); - - if (!model.empty()) - { - deviceSpecMapping.push_back(AZStd::make_pair(model, file)); - } - } - } - } - } - - void LoadGpuSpecMapping_impl(const char* filename) - { - XmlNodeRef xmlNode = GetISystem()->LoadXmlFromFile(filename); - - if (!xmlNode) - { - return; - } - - const int fileCount = xmlNode->getChildCount(); - - for (int i = 0; i < fileCount; ++i) - { - XmlNodeRef fileNode = xmlNode->getChild(i); - AZStd::string file = fileNode->getAttr("file"); - - if (!file.empty()) - { - const int mappingCount = fileNode->getChildCount(); - - gpuSpecMapping.reserve(mappingCount); - - for (int j = 0; j < mappingCount; ++j) - { - XmlNodeRef modelNode = fileNode->getChild(j); - GpuApiPair gpuApiPair; - gpuApiPair.gpuDescription = modelNode->getAttr("gpuName"); - gpuApiPair.apiDescription = modelNode->getAttr("apiVersion"); - - if (!gpuApiPair.gpuDescription.empty() || !gpuApiPair.apiDescription.empty()) - { - gpuSpecMapping.push_back(AZStd::make_pair(gpuApiPair, file)); - } - } - } - } - } - - bool GetSpecForModelName(const AZStd::string& modelName, AZStd::string& specName) - { - for (const auto& descriptionSpecPair : deviceSpecMapping) - { - AZStd::regex currentRegex(descriptionSpecPair.first.c_str()); - if (AZStd::regex_search(modelName, currentRegex)) - { - specName = descriptionSpecPair.second; - return true; - } - } - - return false; - } - - } // namespace Internal -} // namespace MobileSysInspect diff --git a/Code/CryEngine/CrySystem/MobileDetectSpec.h b/Code/CryEngine/CrySystem/MobileDetectSpec.h deleted file mode 100644 index bbb15d301a..0000000000 --- a/Code/CryEngine/CrySystem/MobileDetectSpec.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "AzCore/std/containers/unordered_map.h" - -namespace MobileSysInspect -{ - extern const float LOW_SPEC_RAM; - extern const float MEDIUM_SPEC_RAM; - extern const float HIGH_SPEC_RAM; - - void LoadDeviceSpecMapping(); - bool GetAutoDetectedSpecName(AZStd::string &buffer); - bool GetSpecForGPUAndAPI(const AZStd::string& gpuName, const AZStd::string& apiDescription, AZStd::string& specName); - const float GetDeviceRamInGB(); - - namespace Internal - { - void LoadDeviceSpecMapping_impl(const char* fileName); - void LoadGpuSpecMapping_impl(const char* filename); - bool GetSpecForModelName(const AZStd::string& modelName, AZStd::string& specName); - } -} diff --git a/Code/CryEngine/CrySystem/MobileDetectSpec_Android.cpp b/Code/CryEngine/CrySystem/MobileDetectSpec_Android.cpp deleted file mode 100644 index 181200d383..0000000000 --- a/Code/CryEngine/CrySystem/MobileDetectSpec_Android.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include -#include - -#include "MobileDetectSpec.h" - -namespace MobileSysInspect -{ - void LoadDeviceSpecMapping() - { - Internal::LoadDeviceSpecMapping_impl("@assets@/config/gpu/android_models.xml"); - Internal::LoadGpuSpecMapping_impl("@assets@/config/gpu/android_gpus.xml"); - } - - // Returns true if device is found in the device spec mapping - bool GetAutoDetectedSpecName(AZStd::string &buffer) - { - static constexpr const char* s_javaFieldName = "MODEL"; - AZ::Android::JNI::Object obj("android/os/Build"); - obj.RegisterStaticField(s_javaFieldName, "Ljava/lang/String;"); - AZStd::string name = obj.GetStaticStringField(s_javaFieldName); - - return Internal::GetSpecForModelName(name, buffer); - } - - const float GetDeviceRamInGB() - { - static constexpr const char* s_javaFuntionNameGetDeviceRamInGB = "GetDeviceRamInGB"; - AZ::Android::JNI::Object obj("com/amazon/lumberyard/AndroidDeviceManager"); - obj.RegisterStaticMethod(s_javaFuntionNameGetDeviceRamInGB, "()F"); - return obj.InvokeStaticFloatMethod(s_javaFuntionNameGetDeviceRamInGB); - } -} diff --git a/Code/CryEngine/CrySystem/MobileDetectSpec_Ios.cpp b/Code/CryEngine/CrySystem/MobileDetectSpec_Ios.cpp deleted file mode 100644 index dc0a28490d..0000000000 --- a/Code/CryEngine/CrySystem/MobileDetectSpec_Ios.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include - -#include "MobileDetectSpec.h" -#include - -namespace MobileSysInspect -{ - void LoadDeviceSpecMapping() - { - Internal::LoadDeviceSpecMapping_impl("@assets@/config/gpu/ios_models.xml"); - } - - // Returns true if device is found in the device spec mapping - bool GetAutoDetectedSpecName(AZStd::string &buffer) - { - AZStd::string name = SystemUtilsApple::GetMachineName(); - - return Internal::GetSpecForModelName(name, buffer); - } - - const float GetDeviceRamInGB() - { - // not supported on this platform - return 0.0f; - } -} diff --git a/Code/CryEngine/CrySystem/PhysRenderer.cpp b/Code/CryEngine/CrySystem/PhysRenderer.cpp deleted file mode 100644 index a17fcb7063..0000000000 --- a/Code/CryEngine/CrySystem/PhysRenderer.cpp +++ /dev/null @@ -1,18 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : impelemnation of a simple dedicated renderer for the physics subsystem - - -#include "CrySystem_precompiled.h" - diff --git a/Code/CryEngine/CrySystem/PhysRenderer.h b/Code/CryEngine/CrySystem/PhysRenderer.h deleted file mode 100644 index bbcca4626e..0000000000 --- a/Code/CryEngine/CrySystem/PhysRenderer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : declaration of a simple dedicated renderer for the physics subsystem - - -#ifndef CRYINCLUDE_CRYSYSTEM_PHYSRENDERER_H -#define CRYINCLUDE_CRYSYSTEM_PHYSRENDERER_H -#pragma once - - -#endif // CRYINCLUDE_CRYSYSTEM_PHYSRENDERER_H diff --git a/Code/CryEngine/CrySystem/Platform/Android/platform_android.cmake b/Code/CryEngine/CrySystem/Platform/Android/platform_android.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Android/platform_android.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Code/CryEngine/CrySystem/Platform/Android/platform_android_files.cmake b/Code/CryEngine/CrySystem/Platform/Android/platform_android_files.cmake deleted file mode 100644 index ce1124fe07..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Android/platform_android_files.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../MobileDetectSpec_Android.cpp - ../../MobileDetectSpec.cpp - ../../MobileDetectSpec.h - ../../ThermalInfoAndroid.h - ../../ThermalInfoAndroid.cpp -) diff --git a/Code/CryEngine/CrySystem/Platform/Linux/platform_linux.cmake b/Code/CryEngine/CrySystem/Platform/Linux/platform_linux.cmake deleted file mode 100644 index 971c8ad67f..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Linux/platform_linux.cmake +++ /dev/null @@ -1,21 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files - -set(LY_BUILD_DEPENDENCIES - PRIVATE - m -) diff --git a/Code/CryEngine/CrySystem/Platform/Linux/platform_linux_files.cmake b/Code/CryEngine/CrySystem/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Linux/platform_linux_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CrySystem/Platform/Mac/platform_mac.cmake b/Code/CryEngine/CrySystem/Platform/Mac/platform_mac.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Mac/platform_mac.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Code/CryEngine/CrySystem/Platform/Mac/platform_mac_files.cmake b/Code/CryEngine/CrySystem/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index 4d5680a30d..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Mac/platform_mac_files.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# diff --git a/Code/CryEngine/CrySystem/Platform/Windows/platform_windows.cmake b/Code/CryEngine/CrySystem/Platform/Windows/platform_windows.cmake deleted file mode 100644 index bafe20e506..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Windows/platform_windows.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -# Platform specific cmake file for configuring target compiler/link properties -# based on the active platform -# NOTE: functions in cmake are global, therefore adding functions to this file -# is being avoided to prevent overriding functions declared in other targets platfrom -# specific cmake files diff --git a/Code/CryEngine/CrySystem/Platform/Windows/platform_windows_files.cmake b/Code/CryEngine/CrySystem/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CrySystem/Platform/Windows/platform_windows_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CrySystem/Platform/iOS/platform_ios.cmake b/Code/CryEngine/CrySystem/Platform/iOS/platform_ios.cmake deleted file mode 100644 index f607478131..0000000000 --- a/Code/CryEngine/CrySystem/Platform/iOS/platform_ios.cmake +++ /dev/null @@ -1,22 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(LY_COMPILE_OPTIONS - PRIVATE - -xobjective-c++ -) - -find_library(UI_KIT_FRAMEWORK UIKit) - -set(LY_BUILD_DEPENDENCIES - PRIVATE - ${UI_KIT_FRAMEWORK} -) diff --git a/Code/CryEngine/CrySystem/Platform/iOS/platform_ios_files.cmake b/Code/CryEngine/CrySystem/Platform/iOS/platform_ios_files.cmake deleted file mode 100644 index bbe61fb488..0000000000 --- a/Code/CryEngine/CrySystem/Platform/iOS/platform_ios_files.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../MobileDetectSpec_Ios.cpp - ../../MobileDetectSpec.cpp - ../../MobileDetectSpec.h -) - - diff --git a/Code/CryEngine/CrySystem/SSAPI.DLL b/Code/CryEngine/CrySystem/SSAPI.DLL deleted file mode 100644 index b1f3d6cfce..0000000000 --- a/Code/CryEngine/CrySystem/SSAPI.DLL +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:45dfbb9836e8a8ac4ed5b427528dadf9134618e6977a1eb67af067e0eaadc185 -size 561936 diff --git a/Code/CryEngine/CrySystem/Sampler.cpp b/Code/CryEngine/CrySystem/Sampler.cpp deleted file mode 100644 index b6866ba6cd..0000000000 --- a/Code/CryEngine/CrySystem/Sampler.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "Sampler.h" - -#if defined(WIN32) - -#include -#include -#include - -#define MAX_SYMBOL_LENGTH 512 - -////////////////////////////////////////////////////////////////////////// -// Makes thread. -////////////////////////////////////////////////////////////////////////// -class CSamplingThread -{ -public: - CSamplingThread(CSampler* pSampler) - { - m_hThread = NULL; - m_pSampler = pSampler; - m_bStop = false; - m_samplePeriodMs = pSampler->GetSamplePeriod(); - - m_hProcess = GetCurrentProcess(); - m_hSampledThread = GetCurrentThread(); - DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &m_hSampledThread, 0, FALSE, DUPLICATE_SAME_ACCESS); - } - - // Start thread. - void Start(); - void Stop(); - -protected: - virtual ~CSamplingThread() {}; - static DWORD WINAPI ThreadFunc(void* pThreadParam); - void Run(); // Derived classes must override this. - - HANDLE m_hProcess; - HANDLE m_hThread; - HANDLE m_hSampledThread; - DWORD m_ThreadId; - - CSampler* m_pSampler; - bool m_bStop; - int m_samplePeriodMs; -}; - -////////////////////////////////////////////////////////////////////////// -void CSamplingThread::Start() -{ - m_hThread = CreateThread(NULL, 0, ThreadFunc, this, 0, &m_ThreadId); -} - -////////////////////////////////////////////////////////////////////////// -void CSamplingThread::Stop() -{ - m_bStop = true; -} - -////////////////////////////////////////////////////////////////////////// -DWORD CSamplingThread::ThreadFunc(void* pThreadParam) -{ - CSamplingThread* thread = (CSamplingThread*)pThreadParam; - thread->Run(); - // Auto destruct thread class. - delete thread; - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CSamplingThread::Run() -{ - //SetThreadPriority( m_hThread,THREAD_PRIORITY_HIGHEST ); - SetThreadPriority(m_hThread, THREAD_PRIORITY_TIME_CRITICAL); - while (!m_bStop) - { - SuspendThread(m_hSampledThread); - - CONTEXT context; - context.ContextFlags = CONTEXT_CONTROL; - - uint64 ip = 0; - if (GetThreadContext(m_hSampledThread, &context)) - { -#ifdef CONTEXT_i386 - ip = context.Eip; -#else - ip = context.Rip; -#endif - } - ResumeThread(m_hSampledThread); - - if (!m_pSampler->AddSample(ip)) - { - break; - } - - Sleep(m_samplePeriodMs); - } -} - -////////////////////////////////////////////////////////////////////////// -CSampler::CSampler() -{ - m_pSamplingThread = NULL; - SetMaxSamples(2000); - m_bSamplingFinished = false; - m_bSampling = false; - m_samplePeriodMs = 1; //1ms -} - -////////////////////////////////////////////////////////////////////////// -CSampler::~CSampler() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CSampler::SetMaxSamples(int nMaxSamples) -{ - m_rawSamples.reserve(nMaxSamples); - m_nMaxSamples = nMaxSamples; -} - -////////////////////////////////////////////////////////////////////////// -void CSampler::Start() -{ - if (m_bSampling) - { - return; - } - - CryLogAlways("Staring Sampling with interval %dms, max samples: %d ...", m_samplePeriodMs, m_nMaxSamples); - - m_bSampling = true; - m_bSamplingFinished = false; - m_pSamplingThread = new CSamplingThread(this); - m_rawSamples.clear(); - m_functionSamples.clear(); - - m_pSamplingThread->Start(); -} - -////////////////////////////////////////////////////////////////////////// -void CSampler::Stop() -{ - if (m_bSamplingFinished) - { - } - if (m_bSampling) - { - m_pSamplingThread->Stop(); - } - m_bSampling = false; - m_pSamplingThread = 0; -} - -////////////////////////////////////////////////////////////////////////// -void CSampler::Update() -{ - if (m_bSamplingFinished) - { - ProcessSampledData(); - m_bSamplingFinished = false; - } -} - -////////////////////////////////////////////////////////////////////////// -bool CSampler::AddSample(uint64 ip) -{ - if ((int)m_rawSamples.size() >= m_nMaxSamples) - { - m_bSamplingFinished = true; - m_bSampling = false; - m_pSamplingThread = 0; - return false; - } - m_rawSamples.push_back(ip); - return true; -} - -inline bool CompareFunctionSamples(const CSampler::SFunctionSample& s1, const CSampler::SFunctionSample& s2) -{ - return s1.nSamples < s2.nSamples; -} - -////////////////////////////////////////////////////////////////////////// -void CSampler::ProcessSampledData() -{ - CryLogAlways("Processing collected samples..."); - - uint32 i; - // Count duplicates. - std::map counts; - std::map::iterator cit; - for (i = 0; i < m_rawSamples.size(); i++) - { - uint32 ip = (uint32)m_rawSamples[i]; - cit = counts.find(ip); - if (cit != counts.end()) - { - cit->second++; - } - else - { - counts[ip] = 0; - } - } - - std::map funcCounts; - - AZ::Debug::SymbolStorage::StackLine func, file, module; - int line; - void* baseAddr; - string funcName; - for (i = 0; i < m_rawSamples.size(); i++) - { - // lookup module name here, and aggregate the results - AZ::Debug::SymbolStorage::FindFunctionFromIP((void*)m_rawSamples[i], &func, &file, &module, line, baseAddr); - - // Developer note: this file was using the module name instead of the function name. There was stub code - // to use the function name instead that. This function was updated to use FindFunctionFromIP(), but - // continues to use the module instead of the function. - funcName = module; - funcCounts[funcName] += 1; - } - - { - // Combine function samples. - std::map::iterator it; - for (it = funcCounts.begin(); it != funcCounts.end(); ++it) - { - SFunctionSample fs; - fs.function = it->first; - fs.nSamples = it->second; - m_functionSamples.push_back(fs); - } - } - - // Sort vector by number of samples. - std::sort(m_functionSamples.begin(), m_functionSamples.end(), CompareFunctionSamples); - - LogSampledData(); -} - -////////////////////////////////////////////////////////////////////////// -void CSampler::LogSampledData() -{ - int nTotalSamples = m_rawSamples.size(); - - // Log sample info. - CryLogAlways("========================================================================="); - CryLogAlways("= Profiler Output"); - CryLogAlways("========================================================================="); - - float fOnePercent = (float)nTotalSamples / 100; - - float fPercentTotal = 0; - int nSampleSum = 0; - for (uint32 i = 0; i < m_functionSamples.size(); i++) - { - // Calculate percentage. - float fPercent = m_functionSamples[i].nSamples / fOnePercent; - const char* func = m_functionSamples[i].function; - CryLogAlways("%6.2f%% (%4d samples) : %s", fPercent, m_functionSamples[i].nSamples, func); - fPercentTotal += fPercent; - nSampleSum += m_functionSamples[i].nSamples; - } - CryLogAlways("Samples: %d / %d (%.2f%%)", nSampleSum, nTotalSamples, fPercentTotal); - CryLogAlways("========================================================================="); -} - - -#endif // defined(WIN32) diff --git a/Code/CryEngine/CrySystem/Sampler.h b/Code/CryEngine/CrySystem/Sampler.h deleted file mode 100644 index b2c61013a2..0000000000 --- a/Code/CryEngine/CrySystem/Sampler.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SAMPLER_H -#define CRYINCLUDE_CRYSYSTEM_SAMPLER_H -#pragma once - -#ifdef WIN32 - -class CSamplingThread; - -////////////////////////////////////////////////////////////////////////// -// Sampler class is running a second thread which is at regular intervals -// eg 1ms samples main thread and stores current IP in the samples buffers. -// After sampling finishes it can resolve collected IP buffer info to -// the function names and calculated where most of the execution time spent. -////////////////////////////////////////////////////////////////////////// -class CSampler -{ -public: - struct SFunctionSample - { - string function; - uint32 nSamples; // Number of samples per function. - }; - - CSampler(); - ~CSampler(); - - void Start(); - void Stop(); - void Update(); - - // Adds a new sample to the ip buffer, return false if no more samples can be added. - bool AddSample(uint64 ip); - void SetMaxSamples(int nMaxSamples); - - int GetSamplePeriod() const { return m_samplePeriodMs; } - void SetSamplePeriod(int millis) { m_samplePeriodMs = millis; } - -private: - void ProcessSampledData(); - void LogSampledData(); - - // Buffer for IP samples. - std::vector m_rawSamples; - std::vector m_functionSamples; - int m_nMaxSamples; - bool m_bSampling; - bool m_bSamplingFinished; - - int m_samplePeriodMs; - - CSamplingThread* m_pSamplingThread; -}; - -#else //WIN32 - -// Dummy sampler. -class CSampler -{ -public: - void Start() {} - void Stop() {} - void Update() {} - void SetMaxSamples(int) {} - void SetSamplePeriod(int) {} -}; - -#endif // WIN32 - -#endif // CRYINCLUDE_CRYSYSTEM_SAMPLER_H diff --git a/Code/CryEngine/CrySystem/ServerHandler.cpp b/Code/CryEngine/CrySystem/ServerHandler.cpp deleted file mode 100644 index 85b3192650..0000000000 --- a/Code/CryEngine/CrySystem/ServerHandler.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "ServerHandler.h" - -ServerHandler::ServerHandler(const char* bucket, int affinity, int serverTimeout) - : HandlerBase(bucket, affinity) -{ - m_serverTimeout = serverTimeout; - DoScan(); -} - -void ServerHandler::DoScan() -{ - std::set gotIndices; - for (int i = 0; i < m_srvLocks.size(); ++i) - { - gotIndices.insert(m_srvLocks[i]->number); - } - for (int i = 0; i < MAX_CLIENTS_NUM; ++i) - { - if (gotIndices.find(i) == gotIndices.end()) - { - std::unique_ptr lock(new SSyncLock(m_clientLockName, i, false)); - if (lock->IsValid()) - { - std::unique_ptr srv(new SSyncLock(m_serverLockName, i, true)); - if (srv->IsValid()) - { - m_srvLocks.push_back(std::move(srv)); - m_clientLocks.push_back(std::move(lock)); - CryLogAlways("Client %d bound", i); - } - else - { - CryLogAlways("Failed to bind client %d", i); - } - } - } - } - if (!m_clientLocks.empty()) - { - SetAffinity(); - } - m_lastScan = gEnv->pTimer->GetAsyncTime(); -} - -bool ServerHandler::Sync() -{ - if ((gEnv->pTimer->GetAsyncTime() - m_lastScan).GetSeconds() > 1.0f) - { - DoScan(); - } - for (int i = 0; i < m_srvLocks.size(); ) - { - m_srvLocks[i]->Signal(); - if (!m_clientLocks[i]->Wait(m_serverTimeout))//actually if not waited, let's kill it! - { - CryLogAlways("Dropped client %d", m_clientLocks[i]->number); - m_clientLocks[i]->Own(m_clientLockName); - m_clientLocks.erase(m_clientLocks.begin() + i); - m_srvLocks.erase(m_srvLocks.begin() + i); - continue; - } - ++i; - } - return false;//!m_clientLocks.empty(); -} - -#endif // defined(MAP_LOADING_SLICING) diff --git a/Code/CryEngine/CrySystem/ServerHandler.h b/Code/CryEngine/CrySystem/ServerHandler.h deleted file mode 100644 index 37a870efee..0000000000 --- a/Code/CryEngine/CrySystem/ServerHandler.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SERVERHANDLER_H -#define CRYINCLUDE_CRYSYSTEM_SERVERHANDLER_H -#pragma once - -#include "HandlerBase.h" -#include "SyncLock.h" - -struct ServerHandler - : public HandlerBase -{ - ServerHandler(const char* bucket, int affinity, int serverTimeout); - - void DoScan(); - bool Sync(); - -private: - int m_serverTimeout; - std::vector > m_clientLocks; - std::vector > m_srvLocks; - CTimeValue m_lastScan; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_SERVERHANDLER_H diff --git a/Code/CryEngine/CrySystem/ServerThrottle.cpp b/Code/CryEngine/CrySystem/ServerThrottle.cpp deleted file mode 100644 index c183f1a4fc..0000000000 --- a/Code/CryEngine/CrySystem/ServerThrottle.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ServerThrottle.h" -#include "TimeValue.h" -#include "ISystem.h" -#include "ITimer.h" -#include "IConsole.h" - -#if defined(WIN32) -static float ftdiff(const FILETIME& b, const FILETIME& a) -{ - uint64 aa = *reinterpret_cast(&a); - uint64 bb = *reinterpret_cast(&b); - return (bb - aa) * 1e-7f; -} - -class CCPUMonitor -{ -public: - CCPUMonitor(ISystem* pSystem, int nCPUs) - : m_lastUpdate(0.0f) - , m_pTimer(pSystem->GetITimer()) - , m_nCPUs(nCPUs) - { - FILETIME notNeeded; - GetProcessTimes(GetCurrentProcess(), ¬Needed, ¬Needed, &m_lastKernel, &m_lastUser); - } - - float* Update() - { - CTimeValue frameTime = gEnv->pTimer->GetFrameStartTime(); - if (frameTime - m_lastUpdate > 5.0f) - { - m_lastUpdate = frameTime; - - static float result = 0.0f; - - FILETIME kernel, user, cur; - FILETIME notNeeded; - GetSystemTimeAsFileTime(&cur); - GetProcessTimes(GetCurrentProcess(), ¬Needed, ¬Needed, &kernel, &user); - - float sKernel = ftdiff(kernel, m_lastKernel); - float sUser = ftdiff(user, m_lastUser); - float sCur = ftdiff(cur, m_lastTime); - - result = 100 * (sKernel + sUser) / sCur / m_nCPUs; - - m_lastTime = cur; - m_lastKernel = kernel; - m_lastUser = user; - - return &result; - } - return 0; - } - -private: - ITimer* m_pTimer; - CTimeValue m_lastUpdate; - FILETIME m_lastKernel, m_lastUser, m_lastTime; - int m_nCPUs; -}; -#else -class CCPUMonitor -{ -public: - CCPUMonitor(ISystem*, int) {} - - float* Update() { return 0; } -}; -#endif - -CServerThrottle::CServerThrottle(ISystem* pSys, int nCPUs) -{ - m_pCPUMonitor.reset(new CCPUMonitor(pSys, nCPUs)); - m_pDedicatedMaxRate = pSys->GetIConsole()->GetCVar("sv_DedicatedMaxRate"); - m_pDedicatedCPU = pSys->GetIConsole()->GetCVar("sv_DedicatedCPUPercent"); - m_pDedicatedCPUVariance = pSys->GetIConsole()->GetCVar("sv_DedicatedCPUVariance"); - - m_minFPS = 20; - m_maxFPS = 60; - m_nSteps = 8; - m_nCurStep = 0; - - if (m_pDedicatedCPU->GetFVal() >= 1.0f) - { - SetStep(m_nSteps / 2, 0); - } -} - -CServerThrottle::~CServerThrottle() -{ -} - -void CServerThrottle::Update() -{ - float tgtCPU = m_pDedicatedCPU->GetFVal(); - if (tgtCPU < 1) - { - return; - } - if (float* pCPU = m_pCPUMonitor->Update()) - { - float varCPU = m_pDedicatedCPUVariance->GetFVal(); - if (tgtCPU < 5) - { - tgtCPU = 5; - } - else if (tgtCPU > 95) - { - tgtCPU = 95; - } - float minCPU = std::max(tgtCPU - varCPU, tgtCPU / 2.0f); - float maxCPU = std::min(tgtCPU + varCPU, (100.0f + tgtCPU) / 2.0f); - - if (*pCPU > maxCPU) - { - SetStep(m_nCurStep - 1, pCPU); - } - else if (*pCPU < minCPU) - { - SetStep(m_nCurStep + 1, pCPU); - } - } -} - -void CServerThrottle::SetStep(int step, float* pDueToCPU) -{ - if (step < 0) - { - step = 0; - } - else if (step > m_nSteps) - { - step = m_nSteps; - } - if (step != m_nCurStep) - { - float fps = step * (m_maxFPS - m_minFPS) / m_nSteps + m_minFPS; - m_pDedicatedMaxRate->Set(fps); - if (pDueToCPU) - { - CryLog("ServerThrottle: Set framerate to %.1f fps [due to cpu being %d%%]", fps, int(*pDueToCPU + 0.5f)); - } - else - { - CryLog("ServerThrottle: Set framerate to %.1f fps", fps); - } - m_nCurStep = step; - } -} diff --git a/Code/CryEngine/CrySystem/ServerThrottle.h b/Code/CryEngine/CrySystem/ServerThrottle.h deleted file mode 100644 index ce658f4d2e..0000000000 --- a/Code/CryEngine/CrySystem/ServerThrottle.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Handle raising/lowering the frame rate on server -// based upon CPU usage - - -#ifndef CRYINCLUDE_CRYSYSTEM_SERVERTHROTTLE_H -#define CRYINCLUDE_CRYSYSTEM_SERVERTHROTTLE_H -#pragma once - - -struct ISystem; - -class CCPUMonitor; - -class CServerThrottle -{ -public: - CServerThrottle(ISystem* pSys, int nCPUs); - ~CServerThrottle(); - void Update(); - -private: - std::unique_ptr m_pCPUMonitor; - - void SetStep(int step, float* dueToCPU); - - float m_minFPS; - float m_maxFPS; - int m_nSteps; - int m_nCurStep; - ICVar* m_pDedicatedMaxRate; - ICVar* m_pDedicatedCPU; - ICVar* m_pDedicatedCPUVariance; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_SERVERTHROTTLE_H diff --git a/Code/CryEngine/CrySystem/SyncLock.cpp b/Code/CryEngine/CrySystem/SyncLock.cpp deleted file mode 100644 index 4fb30e2ee2..0000000000 --- a/Code/CryEngine/CrySystem/SyncLock.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "SyncLock.h" - -SSyncLock::SSyncLock(const char* name, int id, bool own) -{ - stack_string ss; - ss.Format("%s_%d", name, id); - - Open(ss); - if (own) - { - if (!IsValid()) - { - Create(ss); - number = id; - } - else - { - Close(); - } - } - else - { - number = id; - } -} - -SSyncLock::SSyncLock(const char* name, int minId, int maxId) -{ - ev = 0; - stack_string ss; - for (int i = minId; i < maxId; ++i) - { - ss.Format("%s_%d", name, i); - if (Open(ss)) - { - Close(); - continue; - } - if (Create(ss)) - { - number = i; - } - break; - } -} - -SSyncLock::~SSyncLock() -{ - Close(); -} - -void SSyncLock::Own(const char* name) -{ - o_name.Format("%s_%d", name, number); -} - -#if defined(LINUX) || defined(APPLE) - -bool SSyncLock::Open(const char* name) -{ - ev = sem_open(name, 0); - if (ev != SEM_FAILED) - { - CryLogAlways("Opened semaphore %p %s", ev, name); - } - return IsValid(); -} - -bool SSyncLock::Create(const char* name) -{ - ev = sem_open(name, O_CREAT | O_EXCL, 0777, 0); - if (ev != SEM_FAILED) - { - CryLogAlways("Created semaphore %p %s", ev, name); - } - else - { - CryLogAlways("Failed to create semaphore %s %d", name, errno); - } - return IsValid(); -} - -void SSyncLock::Signal() -{ - if (ev) - { - sem_post(ev); - } -} - -bool SSyncLock::Wait(int ms) -{ - if (!ev) - { - return false; - } - - timespec t = { 0 }; -#if defined(LINUX) - clock_gettime(CLOCK_REALTIME, &t); -#elif defined(APPLE) - // On OSX/iOS there is no sem_timedwait() - // We use repeated sem_trywait() instead - if (sem_trywait(ev) == 0) - { - return true; - } -#endif - - static const long NANOSECS_IN_MSEC = 1000000L; - static const long NANOSECS_IN_SEC = 1000000000L; - - t.tv_sec += ms / 1000; - t.tv_nsec += (ms % 1000) * NANOSECS_IN_MSEC; - if (t.tv_nsec > NANOSECS_IN_SEC) - { - t.tv_nsec -= NANOSECS_IN_SEC; - ++t.tv_sec; - } -#if defined(LINUX) - return sem_timedwait(ev, &t) == 0; //ETIMEDOUT for timeout -#elif defined (APPLE) - // t = time left, interval = max time between tries, elapsed = actual time elapsed during a try - const int num_ms_interval = 50; // poll time, in ms - const timespec interval = { 0, NANOSECS_IN_MSEC * num_ms_interval }; - while (t.tv_sec >= 0 || t.tv_nsec > interval.tv_nsec) - { - timespec remaining; - timespec elapsed = interval; - if (nanosleep(&interval, &remaining) == -1) - { - elapsed.tv_nsec -= remaining.tv_nsec; - } - t.tv_nsec -= elapsed.tv_nsec; - if (t.tv_nsec < 0L) - { - t.tv_nsec += NANOSECS_IN_SEC; - t.tv_sec -= 1; - } - if (sem_trywait(ev) == 0) - { - return true; - } - } - nanosleep(&t, NULL); - return sem_trywait(ev) == 0; -#else -#error Not implemented -#endif -} - -void SSyncLock::Close() -{ - if (ev) - { - sem_close(ev); - ev = nullptr; - if (!o_name.empty()) - { - sem_unlink(o_name); - } - } -} - -#else // defined(LINUX) || defined(APPLE) - -bool SSyncLock::Open(const char* name) -{ - ev = OpenEvent(SYNCHRONIZE, FALSE, name); - if (ev) - { - CryLogAlways("Opened event %p %s", ev, name); - } - return IsValid(); -} - -bool SSyncLock::Create(const char* name) -{ - ev = CreateEvent(NULL, FALSE, FALSE, name); - if (ev) - { - CryLogAlways("Created event %p %s", ev, name); - } - else - { - CryLogAlways("Failed to create event %s", name); - } - return IsValid(); -} - -bool SSyncLock::Wait(int ms) -{ - // CryLogAlways("Waiting %p", ev); - DWORD res = WaitForSingleObject(ev, ms); - if (res != WAIT_OBJECT_0) - { - CryLogAlways("WFS result %d", res); - } - return res == WAIT_OBJECT_0; -} - -void SSyncLock::Signal() -{ - //CryLogAlways("Signaled %p", ev); - if (!SetEvent(ev)) - { - CryLogAlways("Error signalling!"); - } -} - -void SSyncLock::Close() -{ - if (ev) - { - CryLogAlways("Closed event %p", ev); - CloseHandle(ev); - ev = 0; - } -} - -#endif // defined(LINUX) || defined(APPLE) - -bool SSyncLock::IsValid() const -{ - return ev != 0; -} - -#endif // defined(MAP_LOADING_SLICING) diff --git a/Code/CryEngine/CrySystem/SyncLock.h b/Code/CryEngine/CrySystem/SyncLock.h deleted file mode 100644 index 5e22797a6b..0000000000 --- a/Code/CryEngine/CrySystem/SyncLock.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SYNCLOCK_H -#define CRYINCLUDE_CRYSYSTEM_SYNCLOCK_H - -#pragma once - -#if defined(LINUX) || defined(APPLE) -#include -#endif - -struct SSyncLock -{ -#if defined(LINUX) || defined(APPLE) - typedef sem_t* HandleType; -#else - typedef HANDLE HandleType; -#endif - - SSyncLock(const char* name, int id, bool own); - SSyncLock(const char* name, int minId, int maxId); - ~SSyncLock(); - - void Own(const char* name); - bool Open(const char* name); - bool Create(const char* name); - void Signal(); - bool Wait(int ms); - void Close(); - bool IsValid() const; - - HandleType ev; - int number; - string o_name; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_SYNCLOCK_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index b105ec2f27..6fcbc32b72 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -135,25 +135,16 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "XML/xml.h" #include "XML/ReadWriteXMLSink.h" -#include "PhysRenderer.h" - #include "LocalizedStringManager.h" #include "XML/XmlUtils.h" #include "SystemEventDispatcher.h" -#include "ServerThrottle.h" #include "HMDBus.h" -#include "IZLibCompressor.h" -#include "IZlibDecompressor.h" -#include "ILZ4Decompressor.h" -#include "IZStdDecompressor.h" #include "zlib.h" #include "RemoteConsole/RemoteConsole.h" #include #include -#include "CryWaterMark.h" -WATERMARKDATA(_m); #include #include @@ -170,10 +161,6 @@ WATERMARKDATA(_m); #include #endif -#if USE_STEAM -#include "Steamworks/public/steam/steam_api.h" -#endif - #include #include @@ -185,11 +172,6 @@ VTuneFunction VTPause = NULL; // Define global cvars. SSystemCVars g_cvars; -#include "ITextModeConsole.h" - -////////////////////////////////////////////////////////////////////////// -#include "Validator.h" - #include #include @@ -308,16 +290,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_rFullscreen = NULL; m_sysNoUpdate = NULL; m_pProcess = NULL; - - m_pValidator = NULL; m_pCmdLine = NULL; - m_pDefaultValidator = NULL; m_pLevelSystem = NULL; m_pViewSystem = NULL; - m_pIZLibCompressor = NULL; - m_pIZLibDecompressor = NULL; - m_pILZ4Decompressor = NULL; - m_pIZStdDecompressor = nullptr; m_pLocalizationManager = NULL; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_2 @@ -332,14 +307,12 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_sys_memory_debug = NULL; m_sysWarnings = NULL; m_sysKeyboard = NULL; - m_sys_GraphicsQuality = NULL; m_sys_firstlaunch = NULL; m_sys_enable_budgetmonitoring = NULL; m_sys_preload = NULL; // m_sys_filecache = NULL; m_gpu_particle_physics = NULL; - m_pCpu = NULL; m_bInitializedSuccessfully = false; m_bRelaunch = false; @@ -371,7 +344,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); - m_pTextModeConsole = NULL; if (!AZ::AllocatorInstance::IsReady()) { @@ -390,7 +362,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_eRuntimeState = ESYSTEM_EVENT_LEVEL_UNLOAD; m_bHasRenderedErrorMessage = false; - m_bIsSteamInitialized = false; m_pDataProbe = nullptr; #if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER @@ -509,14 +480,6 @@ void CSystem::ShutDown() GetIRemoteConsole()->Stop(); } - // clean up properly the console - if (m_pTextModeConsole) - { - m_pTextModeConsole->OnShutdown(); - } - - SAFE_DELETE(m_pTextModeConsole); - if (m_sys_firstlaunch) { m_sys_firstlaunch->Set("0"); @@ -566,10 +529,6 @@ void CSystem::ShutDown() { ((CXConsole*)m_env.pConsole)->FreeRenderResources(); } - SAFE_RELEASE(m_pIZLibCompressor); - SAFE_RELEASE(m_pIZLibDecompressor); - SAFE_RELEASE(m_pILZ4Decompressor); - SAFE_RELEASE(m_pIZStdDecompressor); SAFE_RELEASE(m_pViewSystem); SAFE_RELEASE(m_pLevelSystem); @@ -596,7 +555,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sysWarnings); SAFE_RELEASE(m_sysKeyboard); - SAFE_RELEASE(m_sys_GraphicsQuality); SAFE_RELEASE(m_sys_firstlaunch); SAFE_RELEASE(m_sys_enable_budgetmonitoring); @@ -608,13 +566,8 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_min_step); SAFE_RELEASE(m_sys_max_step); - SAFE_DELETE(m_pDefaultValidator); - m_pValidator = nullptr; - SAFE_DELETE(m_pLocalizationManager); - SAFE_DELETE(m_pCpu); - delete m_pCmdLine; m_pCmdLine = 0; @@ -941,13 +894,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) //update time subsystem m_Time.UpdateOnFrameStart(); - ////////////////////////////////////////////////////////////////////// - // update rate limiter for dedicated server - if (m_pServerThrottle.get()) - { - m_pServerThrottle->Update(); - } - ////////////////////////////////////////////////////////////////////// //update console system if (m_env.pConsole) @@ -1277,21 +1223,6 @@ void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int m_env.pLog->LogWithType(ltype, flags | VALIDATOR_FLAG_SKIP_VALIDATOR, "%s", szBuffer); } - //if(file) - //m_env.pLog->LogWithType( ltype, " ... caused by file '%s'",file); - - if (m_pValidator && (flags & VALIDATOR_FLAG_SKIP_VALIDATOR) == 0) - { - SValidatorRecord record; - record.file = file; - record.text = szBuffer; - record.module = module; - record.severity = severity; - record.flags = flags; - record.assetScope = m_env.pLog->GetAssetScopeString(); - m_pValidator->Report(record); - } - if (bDbgBreak && g_cvars.sys_error_debugbreak) { AZ::Debug::Trace::Break(); @@ -1412,12 +1343,6 @@ void CSystem::ExecuteCommandLine(bool deferred) m_executedCommandLine = true; - // auto detect system spec (overrides profile settings) - if (m_pCmdLine->FindArg(eCLAT_Pre, "autodetect")) - { - AutoDetectSpec(false); - } - // execute command line arguments e.g. +g_gametype ASSAULT +map "testy" ICmdLine* pCmdLine = GetICmdLine(); @@ -1446,50 +1371,6 @@ void CSystem::ExecuteCommandLine(bool deferred) //gEnv->pConsole->ExecuteString("sys_RestoreSpec test*"); // to get useful debugging information about current spec settings to the log file } -ITextModeConsole* CSystem::GetITextModeConsole() -{ - if (m_bDedicatedServer) - { - return m_pTextModeConsole; - } - - return 0; -} - -////////////////////////////////////////////////////////////////////////// -ESystemConfigSpec CSystem::GetConfigSpec(bool bClient) -{ - if (bClient) - { - if (m_sys_GraphicsQuality) - { - return (ESystemConfigSpec)m_sys_GraphicsQuality->GetIVal(); - } - return CONFIG_VERYHIGH_SPEC; // highest spec. - } - else - { - return m_nServerConfigSpec; - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SetConfigSpec(ESystemConfigSpec spec, ESystemConfigPlatform platform, bool bClient) -{ - if (bClient) - { - if (m_sys_GraphicsQuality) - { - SetConfigPlatform(platform); - m_sys_GraphicsQuality->Set(static_cast(spec)); - } - } - else - { - m_nServerConfigSpec = spec; - } -} - ////////////////////////////////////////////////////////////////////////// ESystemConfigSpec CSystem::GetMaxConfigSpec() const { @@ -1539,49 +1420,6 @@ void CProfilingSystem::VTunePause() #endif } -bool CSystem::SteamInit() -{ -#if USE_STEAM - if (m_bIsSteamInitialized) - { - return true; - } - - AZStd::string_view exePath; - AZ::ComponentApplicationBus::BroadcastResult(exePath, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - //////////////////////////////////////////////////////////////////////////// - // ** DEVELOPMENT ONLY ** - creates the appropriate steam_appid.txt file needed to call SteamAPI_Init() -#if !defined(RELEASE) - AZStd::string appidPath = AZStd::string::format("%.*s/steam_appid.txt", aznumeric_cast(exePath.size()), exePath.data()); - azfopen(&pSteamAppID, appidPath.c_str(), "wt"); - fprintf(pSteamAppID, "%d", g_cvars.sys_steamAppId); - fclose(pSteamAppID); -#endif // !defined(RELEASE) - // ** END DEVELOPMENT ONLY ** - //////////////////////////////////////////////////////////////////////////// - - if (!SteamAPI_Init()) - { - CryLog("[STEAM] SteamApi_Init failed"); - return false; - } - - //////////////////////////////////////////////////////////////////////////// - // ** DEVELOPMENT ONLY ** - deletes the appropriate steam_appid.txt file as it's no longer needed -#if !defined(RELEASE) - remove(appidPath.c_str()); -#endif // !defined(RELEASE) - // ** END DEVELOPMENT ONLY ** - //////////////////////////////////////////////////////////////////////////// - - m_bIsSteamInitialized = true; - return true; -#else - return false; -#endif -} - ////////////////////////////////////////////////////////////////////// void CSystem::OnLanguageCVarChanged(ICVar* language) { diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index 2e272c2f9e..631d84d934 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -23,12 +23,10 @@ #include "CmdLine.h" #include "CryName.h" -#include "CPUDetect.h" #include #include "RenderBus.h" #include -#include #include @@ -38,8 +36,6 @@ namespace AzFramework } struct IConsoleCmdArgs; -class CServerThrottle; -struct IZLibCompressor; class CWatchdogThread; #if defined(AZ_RESTRICTED_PLATFORM) @@ -50,18 +46,6 @@ class CWatchdogThread; #define SYSTEM_H_SECTION_4 4 #endif -#if defined(ANDROID) -#define USE_ANDROIDCONSOLE -#elif defined(MAC) // || defined(LINUX) -#define USE_UNIXCONSOLE -#elif defined(IOS) -#define USE_IOSCONSOLE -#elif defined(WIN32) || defined(WIN64) -#define USE_WINDOWSCONSOLE -#else -#define USE_NULLCONSOLE -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_1 #include AZ_RESTRICTED_FILE(System_h) @@ -185,20 +169,12 @@ typedef void* WIN_HMODULE; typedef void* WIN_HMODULE; #endif -#if !defined(CRY_ASYNC_MEMCPY_DELEGATE_TO_CRYSYSTEM) -CRY_ASYNC_MEMCPY_API void cryAsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync); -#else -CRY_ASYNC_MEMCPY_API void cryAsyncMemcpyDelegate(void* dst, const void* src, size_t size, int nFlags, volatile int* sync); -#endif - - //forward declarations namespace Audio { struct IAudioSystem; struct IMusicSystem; } // namespace Audio -struct SDefaultValidator; struct IDataProbe; #define PHSYICS_OBJECT_ENTITY 0 @@ -232,7 +208,6 @@ struct SSystemCVars int sys_no_crash_dialog; int sys_no_error_report_window; int sys_dump_aux_threads; - int sys_WER; int sys_dump_type; int sys_ai; int sys_entitysystem; @@ -255,12 +230,6 @@ struct SSystemCVars int sys_FilesystemCaseSensitivity; int sys_deferAudioUpdateOptim; -#if USE_STEAM -#ifndef RELEASE - int sys_steamAppId; -#endif // RELEASE - int sys_useSteamCloudForPlatformSaving; -#endif // USE_STEAM AZ::IO::ArchiveVars archiveVars; @@ -343,16 +312,11 @@ public: virtual void DoWorkDuringOcclusionChecks(); virtual bool NeedDoWorkDuringOcclusionChecks() { return m_bNeedDoWorkDuringOcclusionChecks; } - //Called when the renderer finishes rendering the scene - void OnScene3DEnd() override; - //////////////////////////////////////////////////////////////////////// // CrySystemRequestBus interface implementation ISystem* GetCrySystem() override; //////////////////////////////////////////////////////////////////////// - virtual bool SteamInit(); - void Relaunch(bool bRelaunch); bool IsRelaunch() const { return m_bRelaunch; }; @@ -374,17 +338,11 @@ public: ICryFont* GetICryFont(){ return m_env.pCryFont; } ILog* GetILog(){ return m_env.pLog; } ICmdLine* GetICmdLine(){ return m_pCmdLine; } - IValidator* GetIValidator() { return m_pValidator; }; INameTable* GetINameTable() { return m_env.pNameTable; }; IViewSystem* GetIViewSystem(); ILevelSystem* GetILevelSystem(); ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; } - ITextModeConsole* GetITextModeConsole(); IProfilingSystem* GetIProfilingSystem() { return &m_ProfilingSystem; } - IZLibCompressor* GetIZLibCompressor() { return m_pIZLibCompressor; } - IZLibDecompressor* GetIZLibDecompressor() { return m_pIZLibDecompressor; } - ILZ4Decompressor* GetLZ4Decompressor() { return m_pILZ4Decompressor; } - IZStdDecompressor* GetZStdDecompressor() { return m_pIZStdDecompressor; } ////////////////////////////////////////////////////////////////////////// // retrieves the perlin noise singleton instance CPNoise3* GetNoiseGen(); @@ -406,45 +364,6 @@ public: void SetViewCamera(CCamera& Camera){ m_ViewCamera = Camera; } CCamera& GetViewCamera() { return m_ViewCamera; } - virtual int GetCPUFlags() - { - int Flags = 0; - if (!m_pCpu) - { - return Flags; - } - if (m_pCpu->hasMMX()) - { - Flags |= CPUF_MMX; - } - if (m_pCpu->hasSSE()) - { - Flags |= CPUF_SSE; - } - if (m_pCpu->hasSSE2()) - { - Flags |= CPUF_SSE2; - } - if (m_pCpu->has3DNow()) - { - Flags |= CPUF_3DNOW; - } - if (m_pCpu->hasF16C()) - { - Flags |= CPUF_F16C; - } - - return Flags; - } - virtual int GetLogicalCPUCount() - { - if (m_pCpu) - { - return m_pCpu->GetLogicalCPUCount(); - } - return 0; - } - void IgnoreUpdates(bool bIgnore) { m_bIgnoreUpdates = bIgnore; }; void SetIProcess(IProcess* process); @@ -455,8 +374,6 @@ public: void SleepIfNeeded(); - virtual void DisplayErrorMessage(const char* acMessage, float fTime, const float* pfColor = 0, bool bHardError = true); - virtual void FatalError(const char* format, ...) PRINTF_PARAMS(2, 3); virtual void ReportBug(const char* format, ...) PRINTF_PARAMS(2, 3); // Validator Warning. @@ -471,8 +388,6 @@ public: ////////////////////////////////////////////////////////////////////////// virtual void SaveConfiguration(); virtual void LoadConfiguration(const char* sFilename, ILoadConfigurationEntrySink* pSink = 0, bool warnIfMissing = true); - virtual ESystemConfigSpec GetConfigSpec(bool bClient = true); - virtual void SetConfigSpec(ESystemConfigSpec spec, ESystemConfigPlatform platform, bool bClient); virtual ESystemConfigSpec GetMaxConfigSpec() const; virtual ESystemConfigPlatform GetConfigPlatform() const; virtual void SetConfigPlatform(ESystemConfigPlatform platform); @@ -567,24 +482,7 @@ public: virtual bool GetForceNonDevMode() const; virtual bool WasInDevMode() const { return m_bWasInDevMode; }; virtual bool IsDevMode() const { return m_bInDevMode && !GetForceNonDevMode(); } - virtual bool IsMODValid(const char* szMODName) const - { - if (!szMODName || strstr(szMODName, ".") || strstr(szMODName, "\\")) - { - return (false); - } - return (true); - } - virtual void AutoDetectSpec(bool detectResolution); - virtual void AsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync) - { -#if !defined(CRY_ASYNC_MEMCPY_DELEGATE_TO_CRYSYSTEM) - cryAsyncMemcpy(dst, src, size, nFlags, sync); -#else - cryAsyncMemcpyDelegate(dst, src, size, nFlags, sync); -#endif - } virtual void SetConsoleDrawEnabled(bool enabled) { m_bDrawConsole = enabled; } virtual void SetUIDrawEnabled(bool enabled) { m_bDrawUI = enabled; } @@ -594,18 +492,11 @@ public: //! recreates the variable if necessary ICVar* attachVariable (const char* szVarName, int* pContainer, const char* szComment, int dwFlags = 0); - CCpuFeatures* GetCPUFeatures() { return m_pCpu; }; - const CTimeValue& GetLastTickTime(void) const { return m_lastTickTime; } const ICVar* GetDedicatedMaxRate(void) const { return m_svDedicatedMaxRate; } std::shared_ptr CreateLocalFileIO(); - // Gets the dimensions (in pixels) of the primary physical display. - // Returns true if this info is available, returns false otherwise. - bool GetPrimaryPhysicalDisplayDimensions(int& o_widthPixels, int& o_heightPixels); - bool IsTablet(); - private: // ------------------------------------------------------ // System environment. @@ -623,13 +514,10 @@ private: // ------------------------------------------------------ bool m_bPreviewMode; //!< If running in Preview mode. bool m_bDedicatedServer; //!< If running as Dedicated server. bool m_bIgnoreUpdates; //!< When set to true will ignore Update and Render calls, - IValidator* m_pValidator; //!< Pointer to validator interface. bool m_bForceNonDevMode; //!< true when running on a cheat protected server or a client that is connected to it (not used in singlplayer) bool m_bWasInDevMode; //!< Set to true if was in dev mode. bool m_bInDevMode; //!< Set to true if was in dev mode. bool m_bGameFolderWritable;//!< True when verified that current game folder have write access. - SDefaultValidator* m_pDefaultValidator; //!< - CCpuFeatures* m_pCpu; //!< CPU features int m_ttMemStatSS; //!< Time to memstat screenshot bool m_bDrawConsole; //!< Set to true if OK to draw the console. bool m_bDrawUI; //!< Set to true if OK to draw UI. @@ -661,18 +549,6 @@ private: // ------------------------------------------------------ //! System to manage views. IViewSystem* m_pViewSystem; - //! System to access zlib compressor - IZLibCompressor* m_pIZLibCompressor; - - //! System to access zlib decompressor - IZLibDecompressor* m_pIZLibDecompressor; - - //! System to access lz4 hc decompressor - ILZ4Decompressor* m_pILZ4Decompressor; - - //! System access to zstd decompressor - IZStdDecompressor* m_pIZStdDecompressor; - // XML Utils interface. class CXmlUtils* m_pXMLUtils; @@ -736,7 +612,6 @@ private: // ------------------------------------------------------ ICVar* m_sysWarnings; //!< might be 0, "sys_warnings" - Treat warning as errors. ICVar* m_cvSSInfo; //!< might be 0, "sys_SSInfo" 0/1 - get file sourcesafe info ICVar* m_svDedicatedMaxRate; - ICVar* m_sys_GraphicsQuality; ICVar* m_sys_firstlaunch; ICVar* m_sys_asset_processor; ICVar* m_sys_load_files_to_memory; @@ -777,8 +652,6 @@ private: // ------------------------------------------------------ ESystemConfigSpec m_nMaxConfigSpec; ESystemConfigPlatform m_ConfigPlatform; - std::unique_ptr m_pServerThrottle; - CProfilingSystem m_ProfilingSystem; // Pause mode. @@ -803,9 +676,6 @@ public: virtual const SFileVersion& GetProductVersion(); virtual const SFileVersion& GetBuildVersion(); - bool CompressDataBlock(const void* input, size_t inputSize, void* output, size_t& outputSize, int level); - bool DecompressDataBlock(const void* input, size_t inputSize, void* output, size_t& outputSize); - bool InitVTuneProfiler(); void OpenBasicPaks(); @@ -856,7 +726,6 @@ public: protected: // ------------------------------------------------------------- CCmdLine* m_pCmdLine; - ITextModeConsole* m_pTextModeConsole; string m_currentLanguageAudio; string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_es3.cfg or system_android_opengl.cfg or system_windows_pc.cfg @@ -878,15 +747,7 @@ protected: // ------------------------------------------------------------- ESystemEvent m_eRuntimeState; bool m_bIsAsserting; - friend struct SDefaultValidator; - friend struct SCryEngineFoldersLoader; - // friend void ScreenshotCmd( IConsoleCmdArgs *pParams ); - - bool m_bIsSteamInitialized; - std::vector m_windowMessageHandlers; bool m_initedOSAllocator = false; bool m_initedSysAllocator = false; - - AZStd::unique_ptr m_thermalInfoHandler; }; diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 239f670453..afc5bd9144 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -12,7 +12,7 @@ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "CrySystem_precompiled.h" -#include "SystemInit.h" +#include "System.h" #if defined(AZ_RESTRICTED_PLATFORM) || defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) #undef AZ_RESTRICTED_SECTION @@ -95,17 +95,8 @@ #include "XConsole.h" #include "Log.h" #include "XML/xml.h" -#include "PhysRenderer.h" #include "LocalizedStringManager.h" #include "SystemEventDispatcher.h" -#include "Validator.h" -#include "ServerThrottle.h" -#include "SystemCFG.h" -#include "AutoDetectSpec.h" -#include "ZLibCompressor.h" -#include "ZLibDecompressor.h" -#include "ZStdDecompressor.h" -#include "LZ4Decompressor.h" #include "LevelSystem/LevelSystem.h" #include "LevelSystem/SpawnableLevelSystem.h" #include "ViewSystem/ViewSystem.h" @@ -114,29 +105,10 @@ #include #include -#if USE_STEAM -#include "Steamworks/public/steam/steam_api.h" -#include "Steamworks/public/steam/isteamremotestorage.h" -#endif - -#if defined(IOS) -#include "IOSConsole.h" -#endif - #if defined(ANDROID) #include - #include "AndroidConsole.h" -#if !defined(AZ_RELEASE_BUILD) - #include "ThermalInfoAndroid.h" -#endif // !defined(AZ_RELEASE_BUILD) #endif -#if defined(AZ_PLATFORM_ANDROID) || defined(AZ_PLATFORM_IOS) -#include "MobileDetectSpec.h" -#endif - -#include "WindowsConsole.h" - #if defined(EXTERNAL_CRASH_REPORTING) #include #endif @@ -150,10 +122,6 @@ # include #endif -#ifdef WIN32 -extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_14 #include AZ_RESTRICTED_FILE(SystemInit_cpp) @@ -196,12 +164,6 @@ void CryEngineSignalHandler(int signal) #endif // AZ_TRAIT_USE_CRY_SIGNAL_HANDLER -#if defined(USE_UNIXCONSOLE) -#if defined(LINUX) && !defined(ANDROID) -CUNIXConsole* pUnixConsole; -#endif -#endif // USE_UNIXCONSOLE - ////////////////////////////////////////////////////////////////////////// #define DEFAULT_LOG_FILENAME "@log@/Log.txt" @@ -333,26 +295,6 @@ static void CmdCrashTest(IConsoleCmdArgs* pArgs) } AZ_POP_DISABLE_WARNING -#if USE_STEAM -////////////////////////////////////////////////////////////////////////// -static void CmdWipeSteamCloud(IConsoleCmdArgs* pArgs) -{ - if (!gEnv->pSystem->SteamInit()) - { - return; - } - - int32 fileCount = SteamRemoteStorage()->GetFileCount(); - for (int i = 0; i < fileCount; i++) - { - int32 size = 0; - const char* name = SteamRemoteStorage()->GetFileNameAndSize(i, &size); - bool success = SteamRemoteStorage()->FileDelete(name); - CryLog("Deleting file: %s - success: %d", name, success); - } -} -#endif - ////////////////////////////////////////////////////////////////////////// struct SysSpecOverrideSink : public ILoadConfigurationEntrySink @@ -466,275 +408,6 @@ static ESystemConfigPlatform GetDevicePlatform() #endif } -static void GetSpecConfigFileToLoad(ICVar* pVar, AZStd::string& cfgFile, ESystemConfigPlatform platform) -{ - switch (platform) - { - case CONFIG_PC: - cfgFile = "pc"; - break; - case CONFIG_ANDROID: - cfgFile = "android"; - break; - case CONFIG_IOS: - cfgFile = "ios"; - break; -#if defined(AZ_PLATFORM_JASPER) || defined(TOOLS_SUPPORT_JASPER) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE_EXPLICIT(SystemInit_cpp, jasper) -#endif -#if defined(AZ_PLATFORM_PROVO) || defined(TOOLS_SUPPORT_PROVO) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE_EXPLICIT(SystemInit_cpp, provo) -#endif -#if defined(AZ_PLATFORM_SALEM) || defined(TOOLS_SUPPORT_SALEM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE_EXPLICIT(SystemInit_cpp, salem) -#endif - case CONFIG_OSX_METAL: - cfgFile = "osx_metal"; - break; - case CONFIG_OSX_GL: - // Spec level is hardcoded for these platforms - cfgFile = ""; - return; - default: - AZ_Assert(false, "Platform not supported"); - return; - } - - switch (pVar->GetIVal()) - { - case CONFIG_AUTO_SPEC: - // Spec level is set for autodetection - cfgFile = ""; - break; - case CONFIG_LOW_SPEC: - cfgFile += "_low.cfg"; - break; - case CONFIG_MEDIUM_SPEC: - cfgFile += "_medium.cfg"; - break; - case CONFIG_HIGH_SPEC: - cfgFile += "_high.cfg"; - break; - case CONFIG_VERYHIGH_SPEC: -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_4 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif - cfgFile += "_veryhigh.cfg"; - break; - default: - AZ_Assert(false, "Invalid value for r_GraphicsQuality"); - break; - } -} - -static void LoadDetectedSpec(ICVar* pVar) -{ - CDebugAllowFileAccess ignoreInvalidFileAccess; - SysSpecOverrideSink sysSpecOverrideSink; - ILoadConfigurationEntrySink* pSysSpecOverrideSinkConsole = nullptr; - -#if !defined(CONSOLE) - SysSpecOverrideSinkConsole sysSpecOverrideSinkConsole; - pSysSpecOverrideSinkConsole = &sysSpecOverrideSinkConsole; -#endif - - // g_sysSpecChanged = true; - static int no_recursive = false; - if (no_recursive) - { - return; - } - no_recursive = true; - - int spec = pVar->GetIVal(); - ESystemConfigPlatform platform = GetDevicePlatform(); - if (gEnv->IsEditor()) - { - ESystemConfigPlatform configPlatform = GetISystem()->GetConfigPlatform(); - // Check if the config platform is set first. - if (configPlatform != CONFIG_INVALID_PLATFORM) - { - platform = configPlatform; - } - } - - AZStd::string configFile; - GetSpecConfigFileToLoad(pVar, configFile, platform); - if (configFile.length()) - { - GetISystem()->LoadConfiguration(configFile.c_str(), platform == CONFIG_PC ? &sysSpecOverrideSink : pSysSpecOverrideSinkConsole); - } - else - { - // Automatically sets graphics quality - spec level autodetected for ios/android, hardcoded for all other platforms - - switch (platform) - { - case CONFIG_PC: - { - // TODO: add support for autodetection - pVar->Set(CONFIG_VERYHIGH_SPEC); - GetISystem()->LoadConfiguration("pc_veryhigh.cfg", &sysSpecOverrideSink); - break; - } - case CONFIG_ANDROID: - { -#if defined(AZ_PLATFORM_ANDROID) - AZStd::string file; - if (MobileSysInspect::GetAutoDetectedSpecName(file)) - { - if (file == "android_low.cfg") - { - pVar->Set(CONFIG_LOW_SPEC); - } - if (file == "android_medium.cfg") - { - pVar->Set(CONFIG_MEDIUM_SPEC); - } - if (file == "android_high.cfg") - { - pVar->Set(CONFIG_HIGH_SPEC); - } - if (file == "android_veryhigh.cfg") - { - pVar->Set(CONFIG_VERYHIGH_SPEC); - } - GetISystem()->LoadConfiguration(file.c_str(), pSysSpecOverrideSinkConsole); - } - else - { - float totalRAM = MobileSysInspect::GetDeviceRamInGB(); - if (totalRAM < MobileSysInspect::LOW_SPEC_RAM) - { - pVar->Set(CONFIG_LOW_SPEC); - GetISystem()->LoadConfiguration("android_low.cfg", pSysSpecOverrideSinkConsole); - } - else if (totalRAM < MobileSysInspect::MEDIUM_SPEC_RAM) - { - pVar->Set(CONFIG_MEDIUM_SPEC); - GetISystem()->LoadConfiguration("android_medium.cfg", pSysSpecOverrideSinkConsole); - } - else if (totalRAM < MobileSysInspect::HIGH_SPEC_RAM) - { - pVar->Set(CONFIG_HIGH_SPEC); - GetISystem()->LoadConfiguration("android_high.cfg", pSysSpecOverrideSinkConsole); - } - else - { - pVar->Set(CONFIG_VERYHIGH_SPEC); - GetISystem()->LoadConfiguration("android_veryhigh.cfg", pSysSpecOverrideSinkConsole); - } - } -#endif - break; - } - case CONFIG_IOS: - { -#if defined(AZ_PLATFORM_IOS) - AZStd::string file; - if (MobileSysInspect::GetAutoDetectedSpecName(file)) - { - if (file == "ios_low.cfg") - { - pVar->Set(CONFIG_LOW_SPEC); - } - if (file == "ios_medium.cfg") - { - pVar->Set(CONFIG_MEDIUM_SPEC); - } - if (file == "ios_high.cfg") - { - pVar->Set(CONFIG_HIGH_SPEC); - } - if (file == "ios_veryhigh.cfg") - { - pVar->Set(CONFIG_VERYHIGH_SPEC); - } - GetISystem()->LoadConfiguration(file.c_str(), pSysSpecOverrideSinkConsole); - } - else - { - pVar->Set(CONFIG_MEDIUM_SPEC); - GetISystem()->LoadConfiguration("ios_medium.cfg", pSysSpecOverrideSinkConsole); - } -#endif - break; - } -#if defined(AZ_PLATFORM_JASPER) || defined(TOOLS_SUPPORT_JASPER) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_5 -#include AZ_RESTRICTED_FILE_EXPLICIT(SystemInit_cpp, jasper) -#endif -#if defined(AZ_PLATFORM_PROVO) || defined(TOOLS_SUPPORT_PROVO) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_5 -#include AZ_RESTRICTED_FILE_EXPLICIT(SystemInit_cpp, provo) -#endif -#if defined(AZ_PLATFORM_SALEM) || defined(TOOLS_SUPPORT_SALEM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_5 -#include AZ_RESTRICTED_FILE_EXPLICIT(SystemInit_cpp, salem) -#endif - - case CONFIG_OSX_GL: - { - pVar->Set(CONFIG_HIGH_SPEC); - GetISystem()->LoadConfiguration("osx_gl.cfg", pSysSpecOverrideSinkConsole); - break; - } - case CONFIG_OSX_METAL: - { - pVar->Set(CONFIG_HIGH_SPEC); - GetISystem()->LoadConfiguration("osx_metal_high.cfg", pSysSpecOverrideSinkConsole); - break; - } - default: - AZ_Assert(false, "Platform not supported"); - break; - } - } - - // make sure editor specific settings are not changed - if (gEnv->IsEditor()) - { - GetISystem()->LoadConfiguration("editor.cfg"); - } - - // override cvars just loaded based on current API version/GPU - - GetISystem()->SetConfigSpec(static_cast(spec), platform, false); - - no_recursive = false; -} - -////////////////////////////////////////////////////////////////////////// -struct SCryEngineLanguageConfigLoader - : public ILoadConfigurationEntrySink -{ - CSystem* m_pSystem; - string m_language; - string m_pakFile; - - SCryEngineLanguageConfigLoader(CSystem* pSystem) { m_pSystem = pSystem; } - void Load(const char* sCfgFilename) - { - CSystemConfiguration cfg(sCfgFilename, m_pSystem, this); // Parse folders config file. - } - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, [[maybe_unused]] const char* szGroup) - { - if (azstricmp(szKey, "Language") == 0) - { - m_language = szValue; - } - else if (azstricmp(szKey, "PAK") == 0) - { - m_pakFile = szValue; - } - } - virtual void OnLoadConfigurationEntry_End() {} -}; - ////////////////////////////////////////////////////////////////////////// #if !defined(AZ_MONOLITHIC_BUILD) @@ -1392,96 +1065,6 @@ string GetUniqueLogFileName(string logFileName) return logFileName; } - -#if defined(WIN32) || defined(WIN64) -static wstring GetErrorStringUnsupportedCPU() -{ - static const wchar_t s_EN[] = L"Unsupported CPU detected. CPU needs to support SSE, SSE2, SSE3 and SSE4.1."; - static const wchar_t s_FR[] = { 0 }; - static const wchar_t s_RU[] = { 0 }; - static const wchar_t s_ES[] = { 0 }; - static const wchar_t s_DE[] = { 0 }; - static const wchar_t s_IT[] = { 0 }; - - const size_t fullLangID = (size_t) GetKeyboardLayout(0); - const size_t primLangID = fullLangID & 0x3FF; - const wchar_t* pFmt = s_EN; - - /*switch (primLangID) - { - case 0x07: // German - pFmt = s_DE; - break; - case 0x0a: // Spanish - pFmt = s_ES; - break; - case 0x0c: // French - pFmt = s_FR; - break; - case 0x10: // Italian - pFmt = s_IT; - break; - case 0x19: // Russian - pFmt = s_RU; - break; - case 0x09: // English - default: - break; - }*/ - wchar_t msg[1024]; - msg[0] = L'\0'; - msg[sizeof(msg) / sizeof(msg[0]) - 1] = L'\0'; - azsnwprintf(msg, sizeof(msg) / sizeof(msg[0]) - 1, pFmt); - return msg; -} -#endif - -static bool CheckCPURequirements([[maybe_unused]] CCpuFeatures* pCpu, [[maybe_unused]] CSystem* pSystem) -{ -#if defined(WIN32) || defined(WIN64) - if (!gEnv->IsDedicated()) - { - if (!(pCpu->hasSSE() && pCpu->hasSSE2() && pCpu->hasSSE3() && pCpu->hasSSE41())) - { - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Unsupported CPU! Need SSE, SSE2, SSE3 and SSE4.1 instructions to be available."); - -#if !defined(_RELEASE) - const bool allowPrompts = pSystem->GetICmdLine()->FindArg(eCLAT_Pre, "noprompt") == 0; -#else - const bool allowPrompts = true; -#endif // !defined(_RELEASE) - if (allowPrompts) - { - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Asking user if they wish to continue..."); - const int mbRes = MessageBoxW(0, GetErrorStringUnsupportedCPU().c_str(), L"Open 3D Engine", MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON2 | MB_DEFAULT_DESKTOP_ONLY); - if (mbRes == IDCANCEL) - { - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "User chose to cancel startup."); - return false; - } - } - else - { -#if !defined(_RELEASE) - const bool obeyCPUCheck = pSystem->GetICmdLine()->FindArg(eCLAT_Pre, "anycpu") == 0; -#else - const bool obeyCPUCheck = true; -#endif // !defined(_RELEASE) - if (obeyCPUCheck) - { - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "No prompts allowed and unsupported CPU check active. Treating unsupported CPU as error and exiting."); - return false; - } - } - - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "User chose to continue despite unsupported CPU!"); - } - } -#endif - return true; -} - - class AzConsoleToCryConsoleBinder final { public: @@ -1692,16 +1275,6 @@ AZ_POP_DISABLE_WARNING } } - if (!startupParams.pValidator) - { - m_pDefaultValidator = new SDefaultValidator(this); - m_pValidator = m_pDefaultValidator; - } - else - { - m_pValidator = startupParams.pValidator; - } - #if !defined(_RELEASE) if (!m_bDedicatedServer) { @@ -1717,79 +1290,6 @@ AZ_POP_DISABLE_WARNING gEnv->SetIsDedicated(m_bDedicatedServer); #endif -#if !defined(CONSOLE) -#if !defined(_RELEASE) - bool isDaemonMode = (m_pCmdLine->FindArg(eCLAT_Pre, "daemon") != 0); -#endif // !defined(_RELEASE) - -#if defined(USE_DEDICATED_SERVER_CONSOLE) - -#if !defined(_RELEASE) - bool isSimpleConsole = (m_pCmdLine->FindArg(eCLAT_Pre, "simple_console") != 0); - - if (!(isDaemonMode || isSimpleConsole)) -#endif // !defined(_RELEASE) - { -#if defined(USE_UNIXCONSOLE) - CUNIXConsole* pConsole = new CUNIXConsole(); -#if defined(LINUX) - pUnixConsole = pConsole; -#endif -#elif defined(USE_IOSCONSOLE) - CIOSConsole* pConsole = new CIOSConsole(); -#elif defined(USE_WINDOWSCONSOLE) - CWindowsConsole* pConsole = new CWindowsConsole(); -#elif defined(USE_ANDROIDCONSOLE) - CAndroidConsole* pConsole = new CAndroidConsole(); -#else - CNULLConsole* pConsole = new CNULLConsole(false); -#endif - m_pTextModeConsole = static_cast(pConsole); - - if (m_pUserCallback == nullptr && m_bDedicatedServer) - { - char headerString[128]; - m_pUserCallback = pConsole; - pConsole->SetRequireDedicatedServer(true); - - azstrcpy( - headerString, - AZ_ARRAY_SIZE(headerString), - "Open 3D Engine - " -#if defined(LINUX) - "Linux " -#elif defined(MAC) - "MAC " -#elif defined(IOS) - "iOS " -#endif - "Dedicated Server" - " - Version "); - - char* str = headerString + strlen(headerString); - GetProductVersion().ToString(str, sizeof(headerString) - (str - headerString)); - pConsole->SetHeader(headerString); - } - } -#if !defined(_RELEASE) - else -#endif -#endif - -#if !(defined(USE_DEDICATED_SERVER_CONSOLE) && defined(_RELEASE)) - { - CNULLConsole* pConsole = new CNULLConsole(isDaemonMode); - m_pTextModeConsole = pConsole; - - if (m_pUserCallback == nullptr && m_bDedicatedServer) - { - m_pUserCallback = pConsole; - } - } -#endif - -#endif // !defined(CONSOLE) - { EBUS_EVENT(CrySystemEventBus, OnCrySystemPreInitialize, *this, startupParams); @@ -1909,9 +1409,6 @@ AZ_POP_DISABLE_WARNING // Need to load the engine.pak that includes the config files needed during initialization m_env.pCryPak->OpenPack("@assets@", "Engine.pak"); -#if defined(AZ_PLATFORM_ANDROID) || defined(AZ_PLATFORM_IOS) - MobileSysInspect::LoadDeviceSpecMapping(); -#endif InitFileSystem_LoadEngineFolders(startupParams); @@ -1920,16 +1417,6 @@ AZ_POP_DISABLE_WARNING GetIRemoteConsole()->Update(); #endif - // CPU features detection. - m_pCpu = new CCpuFeatures; - m_pCpu->Detect(); - - // Check hard minimum CPU requirements - if (!CheckCPURequirements(m_pCpu, this)) - { - return false; - } - InlineInitializationProcessing("CSystem::Init Load Engine Folders"); ////////////////////////////////////////////////////////////////////////// @@ -1998,14 +1485,6 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init LoadConfigurations"); -#ifdef WIN32 - if ((g_cvars.sys_WER)) - { - SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); - } -#endif - - ////////////////////////////////////////////////////////////////////////// // Localization ////////////////////////////////////////////////////////////////////////// @@ -2014,10 +1493,6 @@ AZ_POP_DISABLE_WARNING } InlineInitializationProcessing("CSystem::Init InitLocalizations"); -#if !defined(AZ_RELEASE_BUILD) && defined(AZ_PLATFORM_ANDROID) - m_thermalInfoHandler = AZStd::make_unique(); -#endif - ////////////////////////////////////////////////////////////////////////// // Open basic pak files after intro movie playback started ////////////////////////////////////////////////////////////////////////// @@ -2129,30 +1604,6 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init View System"); - ////////////////////////////////////////////////////////////////////////// - // Zlib compressor - m_pIZLibCompressor = new CZLibCompressor(); - - InlineInitializationProcessing("CSystem::Init ZLibCompressor"); - - ////////////////////////////////////////////////////////////////////////// - // Zlib decompressor - m_pIZLibDecompressor = new CZLibDecompressor(); - - InlineInitializationProcessing("CSystem::Init ZLibDecompressor"); - - ////////////////////////////////////////////////////////////////////////// - // LZ4 decompressor - m_pILZ4Decompressor = new CLZ4Decompressor(); - - InlineInitializationProcessing("CSystem::Init LZ4Decompressor"); - - ////////////////////////////////////////////////////////////////////////// - // ZStd decompressor - m_pIZStdDecompressor = new CZStdDecompressor(); - - InlineInitializationProcessing("CSystem::Init ZStdDecompressor"); - if (m_env.pLyShine) { m_env.pLyShine->PostInit(); @@ -2192,9 +1643,6 @@ AZ_POP_DISABLE_WARNING LoadConfiguration("client.cfg", &CVarsClientConfigSink); } - // All CVars should be registered by this point, we must now flush the cvar groups - LoadDetectedSpec(m_sys_GraphicsQuality); - //Connect to the render bus AZ::RenderNotificationsBus::Handler::BusConnect(); @@ -2268,153 +1716,6 @@ void CmdSetAwsLogLevel(IConsoleCmdArgs* pArgs) } } -static void SysRestoreSpecCmd(IConsoleCmdArgs* pParams) -{ - assert(pParams); - - if (pParams->GetArgCount() == 2) - { - const char* szArg = pParams->GetArg(1); - - ICVar* pCVar = gEnv->pConsole->GetCVar("sys_spec_Full"); - - if (!pCVar) - { - gEnv->pLog->LogWithType(ILog::eInputResponse, "sys_RestoreSpec: no action"); // e.g. running Editor in shder compile mode - return; - } - - ICVar::EConsoleLogMode mode = ICVar::eCLM_Off; - - if (azstricmp(szArg, "test") == 0) - { - mode = ICVar::eCLM_ConsoleAndFile; - } - else if (azstricmp(szArg, "test*") == 0) - { - mode = ICVar::eCLM_FileOnly; - } - else if (azstricmp(szArg, "info") == 0) - { - mode = ICVar::eCLM_FullInfo; - } - - if (mode != ICVar::eCLM_Off) - { - bool bFileOrConsole = (mode == ICVar::eCLM_FileOnly || mode == ICVar::eCLM_FullInfo); - - if (bFileOrConsole) - { - gEnv->pLog->LogToFile(" "); - } - else - { - CryLog(" "); - } - - int iSysSpec = pCVar->GetRealIVal(); - - if (iSysSpec == -1) - { - iSysSpec = ((CSystem*)gEnv->pSystem)->GetMaxConfigSpec(); - - if (bFileOrConsole) - { - gEnv->pLog->LogToFile(" sys_spec = Custom (assuming %d)", iSysSpec); - } - else - { - gEnv->pLog->LogWithType(ILog::eInputResponse, " $3sys_spec = $6Custom (assuming %d)", iSysSpec); - } - } - else - { - if (bFileOrConsole) - { - gEnv->pLog->LogToFile(" sys_spec = %d", iSysSpec); - } - else - { - gEnv->pLog->LogWithType(ILog::eInputResponse, " $3sys_spec = $6%d", iSysSpec); - } - } - - pCVar->DebugLog(iSysSpec, mode); - - if (bFileOrConsole) - { - gEnv->pLog->LogToFile(" "); - } - else - { - gEnv->pLog->LogWithType(ILog::eInputResponse, " "); - } - - return; - } - else if (strcmp(szArg, "apply") == 0) - { - const char* szPrefix = "sys_spec_"; - - ESystemConfigSpec originalSpec = CONFIG_AUTO_SPEC; - ESystemConfigPlatform originalPlatform = GetDevicePlatform(); - - if (gEnv->IsEditor()) - { - originalSpec = gEnv->pSystem->GetConfigSpec(true); - } - - std::vector cmds; - - cmds.resize(gEnv->pConsole->GetSortedVars(0, 0, szPrefix)); - gEnv->pConsole->GetSortedVars(&cmds[0], cmds.size(), szPrefix); - - gEnv->pLog->LogWithType(IMiniLog::eInputResponse, " "); - - std::vector::const_iterator it, end = cmds.end(); - - for (it = cmds.begin(); it != end; ++it) - { - const char* szName = *it; - - if (azstricmp(szName, "sys_spec_Full") == 0) - { - continue; - } - - pCVar = gEnv->pConsole->GetCVar(szName); - assert(pCVar); - - if (!pCVar) - { - continue; - } - - bool bNeeded = pCVar->GetIVal() != pCVar->GetRealIVal(); - - gEnv->pLog->LogWithType(IMiniLog::eInputResponse, " $3%s = $6%d ... %s", - szName, pCVar->GetIVal(), - bNeeded ? "$4restored" : "valid"); - - if (bNeeded) - { - pCVar->Set(pCVar->GetIVal()); - } - } - - gEnv->pLog->LogWithType(IMiniLog::eInputResponse, " "); - - if (gEnv->IsEditor()) - { - gEnv->pSystem->SetConfigSpec(originalSpec, originalPlatform, true); - } - return; - } - } - - gEnv->pLog->LogWithType(ILog::eInputResponse, "ERROR: sys_RestoreSpec invalid arguments"); -} - void CmdDrillToFile(IConsoleCmdArgs* pArgs) { if (azstricmp(pArgs->GetArg(0), "DrillerStop") == 0) @@ -2551,14 +1852,6 @@ void CSystem::CreateSystemVars() "1 - enable optimisation\n" "Default is 1"); -#if USE_STEAM -#ifndef RELEASE - REGISTER_CVAR2("sys_steamAppId", &g_cvars.sys_steamAppId, 0, VF_NULL, "steam appId used for development testing"); - REGISTER_COMMAND("sys_wipeSteamCloud", CmdWipeSteamCloud, VF_CHEAT, "Delete all files from steam cloud for this user"); -#endif // RELEASE - REGISTER_CVAR2("sys_useSteamCloudForPlatformSaving", &g_cvars.sys_useSteamCloudForPlatformSaving, 0, VF_NULL, "Use steam cloud for save games and profile on PC (instead of the user folder)"); -#endif - m_sysNoUpdate = REGISTER_INT("sys_noupdate", 0, VF_CHEAT, "Toggles updating of system with sys_script_debugger.\n" "Usage: sys_noupdate [0/1]\n" @@ -2622,9 +1915,6 @@ void CSystem::CreateSystemVars() #else const uint32 nJobSystemDefaultCoreNumber = 4; #endif - m_sys_GraphicsQuality = REGISTER_INT_CB("r_GraphicsQuality", 0, VF_ALWAYSONCHANGE, - "Specifies the system cfg spec. 1=low, 2=med, 3=high, 4=very high)", - LoadDetectedSpec); m_sys_firstlaunch = REGISTER_INT("sys_firstlaunch", 0, 0, "Indicates that the game was run for the first time."); @@ -2731,14 +2021,6 @@ void CSystem::CreateSystemVars() REGISTER_CVAR2("sys_update_profile_time", &g_cvars.sys_update_profile_time, 1.0f, 0, "Time to keep updates timings history for."); REGISTER_CVAR2("sys_no_crash_dialog", &g_cvars.sys_no_crash_dialog, m_bNoCrashDialog, VF_NULL, "Whether to disable the crash dialog window"); REGISTER_CVAR2("sys_no_error_report_window", &g_cvars.sys_no_error_report_window, m_bNoErrorReportWindow, VF_NULL, "Whether to disable the error report list"); -#if defined(_RELEASE) - if (!gEnv->IsDedicated()) - { - REGISTER_CVAR2("sys_WER", &g_cvars.sys_WER, 1, 0, "Enables Windows Error Reporting"); - } -#else - REGISTER_CVAR2("sys_WER", &g_cvars.sys_WER, 0, 0, "Enables Windows Error Reporting"); -#endif #ifdef USE_HTTP_WEBSOCKETS REGISTER_CVAR2("sys_simple_http_base_port", &g_cvars.sys_simple_http_base_port, 1880, VF_REQUIRE_APP_RESTART, @@ -2820,11 +2102,6 @@ void CSystem::CreateSystemVars() REGISTER_STRING_CB("g_language", "", VF_NULL, "Defines which language pak is loaded", CSystem::OnLanguageCVarChanged); REGISTER_STRING_CB("g_languageAudio", "", VF_NULL, "Will automatically match g_language setting unless specified otherwise", CSystem::OnLanguageAudioCVarChanged); - REGISTER_COMMAND("sys_RestoreSpec", &SysRestoreSpecCmd, 0, - "Restore or test the cvar settings of game specific spec settings,\n" - "'test*' and 'info' log to the log file only\n" - "Usage: sys_RestoreSpec [test|test*|apply|info]"); - #if defined(WIN32) REGISTER_CVAR2("sys_display_threads", &g_cvars.sys_display_threads, 0, 0, "Displays Thread info"); #elif defined(AZ_RESTRICTED_PLATFORM) diff --git a/Code/CryEngine/CrySystem/SystemInit.h b/Code/CryEngine/CrySystem/SystemInit.h deleted file mode 100644 index 55eecb97db..0000000000 --- a/Code/CryEngine/CrySystem/SystemInit.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SYSTEMINIT_H -#define CRYINCLUDE_CRYSYSTEM_SYSTEMINIT_H -#pragma once - - -#include "System.h" - -#if defined(AZ_PLATFORM_ANDROID) - #include "AndroidConsole.h" - -// let the java code know the native renderer is taking over now -extern "C" DLL_EXPORT void OnEngineRendererTakeover(bool engineSplashActive); -#endif - -#include "UnixConsole.h" - -#if defined(USE_UNIXCONSOLE) -#if defined(LINUX) && !defined(ANDROID) -extern __attribute__((visibility("default"))) CUNIXConsole* pUnixConsole; -#endif -#endif // USE_UNIXCONSOLE - -#endif // CRYINCLUDE_CRYSYSTEM_SYSTEMINIT_H diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp deleted file mode 100644 index 2314f593b7..0000000000 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : CryENGINE system core - - -#include "CrySystem_precompiled.h" -#include "System.h" - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include "windows.h" -#endif - -#if defined(AZ_PLATFORM_IOS) -#import -#endif - -#include -#include -#include -#include "Log.h" -#include "XConsole.h" -#include -#include "PhysRenderer.h" -#include - -#include "ITextModeConsole.h" -#include -#include - -#include - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEMRENDERER_CPP_SECTION_1 1 -#define SYSTEMRENDERER_CPP_SECTION_2 2 -#endif - -#if defined(AZ_PLATFORM_ANDROID) -#include -#endif - -///////////////////////////////////////////////////////////////////////////////// -bool CSystem::GetPrimaryPhysicalDisplayDimensions([[maybe_unused]] int& o_widthPixels, [[maybe_unused]] int& o_heightPixels) -{ -#if defined(AZ_PLATFORM_WINDOWS) - o_widthPixels = GetSystemMetrics(SM_CXSCREEN); - o_heightPixels = GetSystemMetrics(SM_CYSCREEN); - return true; -#elif defined(AZ_PLATFORM_ANDROID) - return AZ::Android::Utils::GetWindowSize(o_widthPixels, o_heightPixels); -#else - return false; -#endif -} - - -bool CSystem::IsTablet() -{ -//TODO: Add support for Android tablets -#if defined(AZ_PLATFORM_IOS) - return [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad; -#else - return false; -#endif -} - -void CSystem::OnScene3DEnd() -{ - //Render Console - if (m_bDrawConsole && gEnv->pConsole) - { - gEnv->pConsole->Draw(); - } -} - -////////////////////////////////////////////////////////////////////////// - -void CSystem::DisplayErrorMessage(const char* acMessage, - [[maybe_unused]] float fTime, - const float* pfColor, - bool bHardError) -{ - SErrorMessage message; - message.m_Message = acMessage; - if (pfColor) - { - memcpy(message.m_Color, pfColor, 4 * sizeof(float)); - } - else - { - message.m_Color[0] = 1.0f; - message.m_Color[1] = 0.0f; - message.m_Color[2] = 0.0f; - message.m_Color[3] = 1.0f; - } - message.m_HardFailure = bHardError; -#ifdef _RELEASE - message.m_fTimeToShow = fTime; -#else - message.m_fTimeToShow = 1.0f; -#endif - m_ErrorMessages.push_back(message); -} diff --git a/Code/CryEngine/CrySystem/SystemWin32.cpp b/Code/CryEngine/CrySystem/SystemWin32.cpp index c40b0f7c7b..c974365bfc 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -53,7 +53,6 @@ #include "XConsole.h" #include "LocalizedStringManager.h" #include "XML/XmlUtils.h" -#include "AutoDetectSpec.h" #if defined(WIN32) __pragma(comment(lib, "wininet.lib")) diff --git a/Code/CryEngine/CrySystem/Tests/Test_CLog.cpp b/Code/CryEngine/CrySystem/Tests/Test_CLog.cpp deleted file mode 100644 index e792ba095f..0000000000 --- a/Code/CryEngine/CrySystem/Tests/Test_CLog.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" - -#include -#include - -#include -#include - -#include // for max path decl -#include -#include -#include -#include - -namespace CLogUnitTests -{ - using ::testing::NiceMock; - using ::testing::_; - using ::testing::Return; - - // for fuzzing test, how much work to do? Not much, as this must be fast. - const int NumTrialsToPerform = 16000; - - class CLogUnitTests - : public ::testing::Test - { - public: - - using CryPrimitivesAllocatorScope = AZ::AllocatorScope; - - void SetUp() override - { - m_primitiveAllocators.ActivateAllocators(); - - m_priorEnv = gEnv; - m_priorFileIO = AZ::IO::FileIOBase::GetInstance(); - m_priorDirectFileIO = AZ::IO::FileIOBase::GetDirectInstance(); - - m_data = AZStd::make_unique(); - m_data->m_stubEnv.pSystem = &m_data->m_system; - - gEnv = &m_data->m_stubEnv; - - // for FileIO, you must set the instance to null before changing it. - // this is a way to tell the singleton system that you mean to replace a singleton and its - // not a mistake. - AZ::IO::FileIOBase::SetInstance(nullptr); - AZ::IO::FileIOBase::SetInstance(&m_data->m_fileIOMock); - AZ::IO::FileIOBase::SetDirectInstance(nullptr); - AZ::IO::FileIOBase::SetDirectInstance(&m_data->m_fileIOMock); - - ON_CALL(m_data->m_system, GetIRemoteConsole()) - .WillByDefault( - Return(&m_data->m_remoteConsoleMock)); - - AZ::IO::MockFileIOBase::InstallDefaultReturns(m_data->m_fileIOMock); - } - - void TearDown() override - { - AZ::IO::FileIOBase::SetInstance(nullptr); - AZ::IO::FileIOBase::SetInstance(m_priorFileIO); - AZ::IO::FileIOBase::SetDirectInstance(nullptr); - AZ::IO::FileIOBase::SetDirectInstance(m_priorDirectFileIO); - - m_data.reset(); - - // restore state. - gEnv = m_priorEnv; - m_primitiveAllocators.DeactivateAllocators(); - } - - struct DataMembers - { - SSystemGlobalEnvironment m_stubEnv; - NiceMock m_system; - NiceMock m_fileIOMock; - NiceMock m_remoteConsoleMock; - }; - - AZStd::unique_ptr m_data; - SSystemGlobalEnvironment* m_priorEnv = nullptr; - ISystem* m_priorSystem = nullptr; - AZ::IO::FileIOBase* m_priorFileIO = nullptr; - AZ::IO::FileIOBase* m_priorDirectFileIO = nullptr; - CryPrimitivesAllocatorScope m_primitiveAllocators; - }; - - TEST_F(CLogUnitTests, LogAlways_InvalidString_Asserts) - { - AZ_TEST_START_TRACE_SUPPRESSION; - CLog testLog(&m_data->m_system); - testLog.LogAlways(nullptr); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); - } - - TEST_F(CLogUnitTests, LogAlways_EmptyString_IgnoresWithoutCrashing) - { - CLog testLog(&m_data->m_system); - testLog.LogAlways(""); - } - - TEST_F(CLogUnitTests, LogAlways_NormalString_NoFileName_DoesNotCrash) - { - CLog testLog(&m_data->m_system); - testLog.LogAlways("test"); - } - - TEST_F(CLogUnitTests, LogAlways_SetFileName_Empty_DoesNotCrash) - { - CLog testLog(&m_data->m_system); - testLog.SetFileName("", false); - testLog.LogAlways("test"); - } - -#if AZ_TRAIT_DISABLE_LOG_ALWAYS_FUZZ_TEST - TEST_F(CLogUnitTests, DISABLED_LogAlways_FuzzTest) -#else - TEST_F(CLogUnitTests, LogAlways_FuzzTest) -#endif // AZ_TRAIT_DISABLE_LOG_ALWAYS_FUZZ_TEST - { - CLog testLog(&m_data->m_system); - AZStd::string randomJunkName; - - randomJunkName.resize(128, '\0'); - - // expect the mock to repeatedly get called. If we fail this expectation - // it means the code is early-outing somewhere and we are not getting coverage. - EXPECT_CALL(m_data->m_fileIOMock, Write(_, _, _, _)) - .WillRepeatedly( - Return(AZ::IO::Result(AZ::IO::ResultCode::Success))); - - // don't rely on randomness in unit tests, they need to be repeatable. - // the following random generator is not seeded by the time, but by a constant (default 1234). - AZ::SimpleLcgRandom randGen; - - for (int trialNumber = 0; trialNumber < NumTrialsToPerform; ++trialNumber) - { - for (int randomChar = 0; randomChar < randomJunkName.size(); ++randomChar) - { - // note that this is intentionally allowing null characters to generate. - // note that this also puts characters AFTER the null, if a null appears in the mddle. - // so that if there are off by one errors they could include cruft afterwards. - - if (randomChar > trialNumber % randomJunkName.size()) - { - // choose this point for the nulls to begin. It makes sure we test every size of string. - randomJunkName[randomChar] = 0; - } - else - { - randomJunkName[randomChar] = (char)(randGen.GetRandom() % 256); // this will trigger invalid UTF8 decoding too - } - } - testLog.LogAlways("%s", randomJunkName.c_str()); - } - } - - TEST_F(CLogUnitTests, LogAlways_SetFileName_Correct_DoesNotCrash_WritesToFile) - { - CLog testLog(&m_data->m_system); - testLog.SetFileName("logfile.log", false); - - // EXPECT a call to the file system - if we dont get a call here, it means something went wrong. - // it also expects exactly one call to write. One call to log should be one call to write, - // or else performance will suffer. - - EXPECT_CALL(m_data->m_fileIOMock, Write(_, _, _, _)) - .WillOnce( - Return(AZ::IO::Result(AZ::IO::ResultCode::Success))); - - testLog.LogAlways("test"); - } -} // end namespace CLogUnitTests - - diff --git a/Code/CryEngine/CrySystem/Tests/Test_CommandRegistration.cpp b/Code/CryEngine/CrySystem/Tests/Test_CommandRegistration.cpp deleted file mode 100644 index d54ba87446..0000000000 --- a/Code/CryEngine/CrySystem/Tests/Test_CommandRegistration.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" - -#include - -#include - -#include -#include -#include -#include - -#include - -namespace UnitTests -{ - class RemoteConsoleMock - : public IRemoteConsole - { - public: - MOCK_METHOD0(RegisterConsoleVariables, void()); - MOCK_METHOD0(UnregisterConsoleVariables, void()); - MOCK_METHOD0(Start, void()); - MOCK_METHOD0(Stop, void()); - MOCK_CONST_METHOD0(IsStarted, bool()); - MOCK_METHOD1(AddLogMessage, void(const char*)); - MOCK_METHOD1(AddLogWarning, void(const char*)); - MOCK_METHOD1(AddLogError, void(const char*)); - MOCK_METHOD0(Update, void()); - MOCK_METHOD2(RegisterListener, void(IRemoteConsoleListener*, const char*)); - MOCK_METHOD1(UnregisterListener, void(IRemoteConsoleListener*)); - }; - - struct TestTraceMessageCapture - : public AZ::Debug::TraceMessageBus::Handler - { - using Callback = AZStd::function; - Callback m_callback; - - TestTraceMessageCapture() - { - AZ::Debug::TraceMessageBus::Handler::BusConnect(); - } - - ~TestTraceMessageCapture() - { - AZ::Debug::TraceMessageBus::Handler::BusDisconnect(); - } - - bool OnError(const char* window, const char* message) override - { - if (m_callback) - { - m_callback(window, message); - } - return false; - } - - bool OnWarning(const char* window, const char* message) override - { - if (m_callback) - { - m_callback(window, message); - } - return false; - } - }; - - using SystemAllocatorScope = AZ::AllocatorScope; - - struct CommandRegistrationUnitTests - : public ::testing::Test - , public SystemAllocatorScope - { - CommandRegistrationUnitTests() - { - EXPECT_CALL(m_system, GetIRemoteConsole()) - .WillRepeatedly(::testing::Return(&m_remoteConsole)); - } - - void SetUp() override - { - SystemAllocatorScope::ActivateAllocators(); - - memset(&m_stubEnv, 0, sizeof(SSystemGlobalEnvironment)); - m_stubEnv.pSystem = &m_system; - m_priorEnv = gEnv; - gEnv = &m_stubEnv; - - // now it safe to set up the console - m_console = AZStd::make_unique(); - m_stubEnv.pConsole = m_console.get(); - - EXPECT_CALL(m_system, GetIConsole()) - .WillRepeatedly(::testing::Return(m_stubEnv.pConsole)); - } - - void TearDown() override - { - m_console.reset(); - gEnv = m_priorEnv; - SystemAllocatorScope::DeactivateAllocators(); - } - - ::testing::NiceMock m_system; - ::testing::NiceMock m_remoteConsole; - AZStd::unique_ptr m_console; - SSystemGlobalEnvironment m_stubEnv; - SSystemGlobalEnvironment* m_priorEnv = nullptr; - }; - - TEST_F(CommandRegistrationUnitTests, RegisterUnregisterTest) - { - using namespace AzFramework; - - { - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "foo", "", 0, [](const AZStd::vector&) -> CommandResult - { - return CommandResult::Success; - }); - EXPECT_TRUE(result); - } - - { - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::UnregisterCommand, "foo"); - EXPECT_TRUE(result); - } - } - - TEST_F(CommandRegistrationUnitTests, RegisterUnregisterNegativeTest) - { - using namespace AzFramework; - - // register too many times - { - auto fnFoo = [](const AZStd::vector&) -> CommandResult - { - return CommandResult::Success; - }; - - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "foo", "", 0, fnFoo); - EXPECT_TRUE(result); - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "foo", "", 0, fnFoo); - EXPECT_FALSE(result); - } - - // unregister too many times - { - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::UnregisterCommand, "foo"); - EXPECT_TRUE(result); - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::UnregisterCommand, "foo"); - EXPECT_FALSE(result); - } - - // a null callback should fail - { - AZ_TEST_START_TRACE_SUPPRESSION; - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "shouldfail", "", 0, nullptr); - EXPECT_FALSE(result); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); - } - - // a null identifier should fail - { - AZ_TEST_START_TRACE_SUPPRESSION; - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "", "", 0, nullptr); - EXPECT_FALSE(result); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); - } - } - - TEST_F(CommandRegistrationUnitTests, DoCallback) - { - using namespace AzFramework; - - int count = 0; - - { - auto fnCommand = [&count](const AZStd::vector&) -> CommandResult - { - ++count; - return CommandResult::Success; - }; - - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "bar", "bar docs", CommandFlags::Development, fnCommand); - EXPECT_TRUE(result); - } - - const bool bSilentMode = true; - const bool bDeferExecution = false; - m_console->ExecuteString("bar", bSilentMode, bDeferExecution); - EXPECT_EQ(1, count); - - { - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::UnregisterCommand, "bar"); - EXPECT_TRUE(result); - } - } - - TEST_F(CommandRegistrationUnitTests, DoCallbackNegativeTests) - { - using namespace AzFramework; - - bool result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::RegisterCommand, "bar", "", 0, [](const AZStd::vector& args) - { - if (args.size() > 1) - { - return CommandResult::ErrorWrongNumberOfArguments; - } - return CommandResult::Error; - }); - EXPECT_TRUE(result); - - const bool bSilentMode = true; - const bool bDeferExecution = false; - - // general error - { - int found = 0; - TestTraceMessageCapture capture; - capture.m_callback = [&found](const char* window, const char* message) - { - if (azstrnicmp(window, "console", AZ_ARRAY_SIZE("console") - 1) == 0) - { - if (azstrnicmp(message, "Command returned a generic error\n", AZ_ARRAY_SIZE("Command returned a generic error\n") - 1) == 0) - { - ++found; - } - } - }; - m_console->ExecuteString("bar", bSilentMode, bDeferExecution); - EXPECT_EQ(1, found); - } - - // too many args - { - int found = 0; - TestTraceMessageCapture capture; - capture.m_callback = [&found](const char* window, const char* message) - { - if (azstrnicmp(window, "console", AZ_ARRAY_SIZE("console") - 1) == 0) - { - if (azstrnicmp(message, "Command does not have the right number of arguments (send = 4)\n", AZ_ARRAY_SIZE("Command does not have the right number of arguments (send = 4)\n") - 1) == 0) - { - ++found; - } - } - }; - m_console->ExecuteString("bar 1 2 3", bSilentMode, bDeferExecution); - EXPECT_EQ(1, found); - } - - // clean up - { - result = false; - CommandRegistrationBus::BroadcastResult(result, &CommandRegistrationBus::Events::UnregisterCommand, "bar"); - EXPECT_TRUE(result); - } - } - -} // namespace UnitTests - - diff --git a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp deleted file mode 100644 index 26d12ffd8c..0000000000 --- a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" -#include -#include - -TEST(StringTests, CUT_Strings) -{ - bool bOk; - char bf[4]; - - // cry_strcpy() - - bOk = cry_strcpy(0, 0, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcpy(0, 0, 0, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcpy(0, 1, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcpy(0, 1, 0, 1); - EXPECT_TRUE(!bOk); - - bOk = cry_strcpy(0, 1, ""); - EXPECT_TRUE(!bOk); - - bOk = cry_strcpy(0, 1, "", 1); - EXPECT_TRUE(!bOk); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 0, ""); - EXPECT_TRUE(!bOk && !memcmp(bf, "abcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 0, "", 1); - EXPECT_TRUE(!bOk && !memcmp(bf, "abcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 1, 0); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 1, 0, 0); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 0); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 3, "qwerty"); - EXPECT_TRUE(!bOk && !memcmp(bf, "qw\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 3, "qwerty", 4); - EXPECT_TRUE(!bOk && !memcmp(bf, "qw\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 3, "qwerty", 3); - EXPECT_TRUE(!bOk && !memcmp(bf, "qw\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 3, "qwerty", 2); - EXPECT_TRUE(bOk && !memcmp(bf, "qw\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 3, "qwerty", 1); - EXPECT_TRUE(bOk && !memcmp(bf, "q\000cd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, 3, "qwerty", 0); - EXPECT_TRUE(bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qwerty"); - EXPECT_TRUE(!bOk && !memcmp(bf, "qwe\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qwerty", 4); - EXPECT_TRUE(!bOk && !memcmp(bf, "qwe\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qwerty", 3); - EXPECT_TRUE(bOk && !memcmp(bf, "qwe\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qwerty", 2); - EXPECT_TRUE(bOk && !memcmp(bf, "qw\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qwe"); - EXPECT_TRUE(bOk && !memcmp(bf, "qwe\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qwe", 4); - EXPECT_TRUE(bOk && !memcmp(bf, "qwe\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, "qw", 3); - EXPECT_TRUE(bOk && !memcmp(bf, "qw\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, sizeof(bf), "q"); - EXPECT_TRUE(bOk && !memcmp(bf, "q\000cd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcpy(bf, sizeof(bf), "q", 2); - EXPECT_TRUE(bOk && !memcmp(bf, "q\000cd", 4)); - - // cry_strcat() - - bOk = cry_strcat(0, 0, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcat(0, 0, 0, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcat(0, 1, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcat(0, 1, 0, 0); - EXPECT_TRUE(!bOk); - - bOk = cry_strcat(0, 1, ""); - EXPECT_TRUE(!bOk); - - bOk = cry_strcat(0, 1, "", 1); - EXPECT_TRUE(!bOk); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 0, "xy"); - EXPECT_TRUE(!bOk && !memcmp(bf, "abcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 0, "xy", 3); - EXPECT_TRUE(!bOk && !memcmp(bf, "abcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 0, "xy", 0); - EXPECT_TRUE(!bOk && !memcmp(bf, "abcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 1, "xyz"); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 1, "xyz", 4); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 1, "xyz", 1); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 1, "xyz", 0); - EXPECT_TRUE(bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, 1, 0, 0); - EXPECT_TRUE(!bOk && !memcmp(bf, "\000bcd", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, 3, "xyz"); - EXPECT_TRUE(!bOk && !memcmp(bf, "ax\000d", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, 3, "xyz", 4); - EXPECT_TRUE(!bOk && !memcmp(bf, "ax\000d", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, 3, "xyz", 2); - EXPECT_TRUE(!bOk && !memcmp(bf, "ax\000d", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, 3, "xyz", 1); - EXPECT_TRUE(bOk && !memcmp(bf, "ax\000d", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, "xyz"); - EXPECT_TRUE(!bOk && !memcmp(bf, "abc\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, "xyz", 4); - EXPECT_TRUE(!bOk && !memcmp(bf, "abc\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, "xyz", 1); - EXPECT_TRUE(!bOk && !memcmp(bf, "abc\000", 4)); - - memcpy(bf, "abcd", 4); - bOk = cry_strcat(bf, "xyz", 0); - EXPECT_TRUE(bOk && !memcmp(bf, "abc\000", 4)); - - memcpy(bf, "ab\000d", 4); - bOk = cry_strcat(bf, "xyz"); - EXPECT_TRUE(!bOk && !memcmp(bf, "abx\000", 4)); - - memcpy(bf, "ab\000d", 4); - bOk = cry_strcat(bf, "xyz", 4); - EXPECT_TRUE(!bOk && !memcmp(bf, "abx\000", 4)); - - memcpy(bf, "ab\000d", 4); - bOk = cry_strcat(bf, "xyz", 1); - EXPECT_TRUE(bOk && !memcmp(bf, "abx\000", 4)); - - memcpy(bf, "ab\000d", 4); - bOk = cry_strcat(bf, "xyz", 0); - EXPECT_TRUE(bOk && !memcmp(bf, "ab\000d", 4)); - - memcpy(bf, "ab\000d", 4); - bOk = cry_strcat(bf, 0, 0); - EXPECT_TRUE(!bOk && !memcmp(bf, "ab\000d", 4)); - - memcpy(bf, "ab\000d", 4); - bOk = cry_strcat(bf, 0, 1); - EXPECT_TRUE(!bOk && !memcmp(bf, "ab\000d", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, sizeof(bf), "xy"); - EXPECT_TRUE(bOk && !memcmp(bf, "axy\000", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, sizeof(bf), "xy", 3); - EXPECT_TRUE(bOk && !memcmp(bf, "axy\000", 4)); - - memcpy(bf, "a\000cd", 4); - bOk = cry_strcat(bf, sizeof(bf), "xy", 1); - EXPECT_TRUE(bOk && !memcmp(bf, "ax\000d", 4)); -} - -using CryPrimitivesAllocatorScope = AZ::AllocatorScope; - -class CryPrimitives - : public ::testing::Test -{ -public: - void SetUp() override - { - m_memory.ActivateAllocators(); - } - - void TearDown() override - { - m_memory.DeactivateAllocators(); - } - - CryPrimitivesAllocatorScope m_memory; -}; - -TEST_F(CryPrimitives, CUT_CryString) -{ - ////////////////////////////////////////////////////////////////////////// - // Based on MS documentation of find_last_of - string strTestFindLastOfOverload1("abcd-1234-abcd-1234"); - string strTestFindLastOfOverload2("ABCD-1234-ABCD-1234"); - string strTestFindLastOfOverload3("456-EFG-456-EFG"); - string strTestFindLastOfOverload4("12-ab-12-ab"); - - const char* cstr2 = "B1"; - const char* cstr2b = "D2"; - const char* cstr3a = "5E"; - string str4a("ba3"); - string str4b("a2"); - - size_t nPosition(string::npos); - - nPosition = strTestFindLastOfOverload1.find_last_of('d', 14); - EXPECT_TRUE(nPosition == 13); - - - nPosition = strTestFindLastOfOverload2.find_last_of(cstr2, 12); - EXPECT_TRUE(nPosition == 11); - - - nPosition = strTestFindLastOfOverload2.find_last_of(cstr2b); - EXPECT_TRUE(nPosition == 16); - - - nPosition = strTestFindLastOfOverload3.find_last_of(cstr3a, 8, 2); - EXPECT_TRUE(nPosition == 4); - - - nPosition = strTestFindLastOfOverload4.find_last_of(str4a, 8); - EXPECT_TRUE(nPosition == 4); - - - nPosition = strTestFindLastOfOverload4.find_last_of(str4b); - EXPECT_TRUE(nPosition == 9); - - ////////////////////////////////////////////////////////////////////////// - // Based on MS documentation of find_last_not_of - string strTestFindLastNotOfOverload1("dddd-1dd4-abdd"); - string strTestFindLastNotOfOverload2("BBB-1111"); - string strTestFindLastNotOfOverload3("444-555-GGG"); - string strTestFindLastNotOfOverload4("12-ab-12-ab"); - - const char* cstr2NF = "B1"; - const char* cstr3aNF = "45G"; - const char* cstr3bNF = "45G"; - - string str4aNF("b-a"); - string str4bNF("12"); - - nPosition = strTestFindLastNotOfOverload1.find_last_not_of('d', 7); - EXPECT_TRUE(nPosition == 5); - - nPosition = strTestFindLastNotOfOverload1.find_last_not_of("d"); - EXPECT_TRUE(nPosition == 11); - - nPosition = strTestFindLastNotOfOverload2.find_last_not_of(cstr2NF, 6); - EXPECT_TRUE(nPosition == 3); - - nPosition = strTestFindLastNotOfOverload3.find_last_not_of(cstr3aNF); - EXPECT_TRUE(nPosition == 7); - - nPosition = strTestFindLastNotOfOverload3.find_last_not_of(cstr3bNF, 6, 3);//nPosition - 1 ); - EXPECT_TRUE(nPosition == 3); - - nPosition = strTestFindLastNotOfOverload4.find_last_not_of(str4aNF, 5); - EXPECT_TRUE(nPosition == 1); - - nPosition = strTestFindLastNotOfOverload4.find_last_not_of(str4bNF); - EXPECT_TRUE(nPosition == 10); -} - - -TEST_F(CryPrimitives, CUT_FixedString) -{ - CryStackStringT str1; - CryStackStringT str2; - CryStackStringT str3; - CryStackStringT str4; - CryStackStringT str5; - CryStackStringT wstr1; - CryStackStringT wstr2; - CryFixedStringT<100> fixedString100; - CryFixedStringT<200> fixedString200; - - typedef CryStackStringT T; - T* pStr = new T; - *pStr = "adads"; - delete pStr; - - str1 = "abcd"; - EXPECT_EQ(str1, "abcd"); - - str2 = "efg"; - EXPECT_EQ(str2, "efg"); - - str2 = str1; - EXPECT_EQ(str2, "abcd"); - - str1 += "XY"; - EXPECT_EQ(str1, "abcdXY"); - - str2 += "efghijk"; - EXPECT_EQ(str2, "abcdefghijk"); - - str1.replace("bc", ""); - EXPECT_EQ(str1, "adXY"); - - str1.replace("XY", "1234"); - EXPECT_EQ(str1, "ad1234"); - - str1.replace("1234", "1234567890"); - EXPECT_EQ(str1, "ad1234567890"); - - str1.reserve(200); - EXPECT_EQ(str1, "ad1234567890"); - EXPECT_TRUE(str1.capacity() == 200); - - str1.reserve(0); - EXPECT_EQ(str1, "ad1234567890"); - EXPECT_TRUE(str1.capacity() == str1.length()); - - str1.erase(7); // doesn't change capacity - EXPECT_EQ(str1, "ad12345"); - - str4.assign("abc"); - EXPECT_EQ(str4, "abc"); - str4.reserve(9); - EXPECT_TRUE(str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - str4.reserve(0); - EXPECT_TRUE(str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - - size_t idx = str1.find("123"); - EXPECT_TRUE(idx == 2); - - idx = str1.find("123", 3); - EXPECT_TRUE(idx == str1.npos); - - wstr1 = L"abc"; - EXPECT_EQ(wstr1, L"abc"); - EXPECT_TRUE(wstr1.compare(L"aBc") > 0); - EXPECT_TRUE(wstr1.compare(L"babc") < 0); - EXPECT_TRUE(wstr1.compareNoCase(L"aBc") == 0); - - str1.Format("This is a %s %ls with %d params", "mixed", L"string", 3); - str2.Format("This is a %ls %s with %d params", L"mixed", "string", 3); - EXPECT_EQ(str1, "This is a mixed string with 3 params"); - EXPECT_EQ(str1, str2); - - wstr1.Format(L"This is a %ls %hs with %d params", L"mixed", "string", 3); - wstr2.Format(L"This is a %hs %ls with %d params", "mixed", L"string", 3); - EXPECT_EQ(wstr1, L"This is a mixed string with 3 params"); - - str5.FormatFast("%s", "12345"); - EXPECT_EQ("1234", str5); - - // we expect here that the string gets cut since it doesn't fit into the string buffer - str5.FormatFast("%s", "012345"); - EXPECT_EQ("0123", str5); -} - -TEST_F(CryPrimitives, CUT_DynArray) -{ - LegacyDynArray a; - a.push_back(3); - a.insert(&a[0], 1, 1); - a.insert(&a[1], 1, 2); - a.insert(&a[0], 1, 0); - - for (int i = 0; i < 4; i++) - { - EXPECT_TRUE(a[i] == i); - } - - const int nStrs = 11; - string Strs[nStrs] = { "nought", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" }; - LegacyDynArray s; - for (int i = 0; i < nStrs; i += 2) - { - s.push_back(Strs[i]); - } - for (int i = 1; i < nStrs; i += 2) - { - s.insert(i, Strs[i]); - } - for (int i = 0; i < nStrs; i++) - { - EXPECT_TRUE(s[i] == Strs[i]); - } - - LegacyDynArray s2 = s; - s.erase(5, 2); - EXPECT_TRUE(s.size() == nStrs - 2); - - s.insert(&s[3], &Strs[5], &Strs[8]); - - s2 = s2(3, 4); - EXPECT_TRUE(s2.size() == 4); -} diff --git a/Code/CryEngine/CrySystem/Tests/Test_Localization.cpp b/Code/CryEngine/CrySystem/Tests/Test_Localization.cpp deleted file mode 100644 index ad3972fffe..0000000000 --- a/Code/CryEngine/CrySystem/Tests/Test_Localization.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" -#include -#include -#include "LocalizedStringManager.h" -#include -#include -#include -#include - -#include - -class SystemEventDispatcherMock - : public ISystemEventDispatcher -{ -public: - virtual ~SystemEventDispatcherMock() {} - MOCK_METHOD1(RegisterListener, bool(ISystemEventListener* pListener)); - MOCK_METHOD1(RemoveListener, bool(ISystemEventListener* pListener)); - MOCK_METHOD3(OnSystemEvent, void(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam)); - MOCK_METHOD0(Update, void()); -}; - -using namespace testing; -using ::testing::NiceMock; - -using SystemAllocatorScope = AZ::AllocatorScope; - -class SystemFixture - : public ::testing::Test - , public SystemAllocatorScope -{ -public: - SystemFixture() - { - EXPECT_CALL(m_system, GetISystemEventDispatcher()) - .WillRepeatedly(Return(&m_dispatcher)); - - EXPECT_CALL(m_console, GetCVar(_)) - .WillRepeatedly(Return(&m_cvarMock)); - - EXPECT_CALL(m_cryPak, FindFirst(_, _, _)) - .WillRepeatedly(Return(AZ::IO::ArchiveFileIterator{})); - - EXPECT_CALL(m_cryPak, GetLocalizationFolder()) - .WillRepeatedly(Return("french")); - - EXPECT_CALL(m_cvarMock, GetFlags()) - .WillRepeatedly(Return(VF_WASINCONFIG)); - } - - void SetUp() override - { - SystemAllocatorScope::ActivateAllocators(); - - memset(&m_stubEnv, 0, sizeof(SSystemGlobalEnvironment)); - m_stubEnv.pConsole = &m_console; - m_stubEnv.pSystem = &m_system; - m_stubEnv.pCryPak = &m_cryPak; - m_stubEnv.pLog = nullptr; - m_priorEnv = gEnv; - gEnv = &m_stubEnv; - } - - void TearDown() override - { - gEnv = m_priorEnv; - - SystemAllocatorScope::DeactivateAllocators(); - } - - NiceMock m_system; - NiceMock m_dispatcher; - NiceMock m_console; - NiceMock m_cryPak; - NiceMock m_cvarMock; - SSystemGlobalEnvironment m_stubEnv; - SSystemGlobalEnvironment* m_priorEnv = nullptr; -}; - -class UnitTestCLocalizedStringsManager : public CLocalizedStringsManager -{ -public: - UnitTestCLocalizedStringsManager(ISystem* pSystem) : CLocalizedStringsManager(pSystem) - { - } - - bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) override - { - m_capturedLabels.push_back(sLabel); - return CLocalizedStringsManager::LocalizeLabel(sLabel, outLocalizedString, bEnglish); - } - - std::vector m_capturedLabels; - - friend class GTEST_TEST_CLASS_NAME_(SystemFixture, LocalizeStringInternal_WhitespaceCharacters_CorrectlyTokenizes); -}; - -// this test makes sure that whitespace characters such as tab work (not just space) and are considered to be separators. -TEST_F(SystemFixture, LocalizeStringInternal_SpecificWhitespaceCharacters_CorrectlyTokenizes) -{ - UnitTestCLocalizedStringsManager manager(&m_system); - manager.SetLanguage("french"); - - string outString; - manager.LocalizeString_s("@hello\t@world", outString, false); - ASSERT_EQ(manager.m_capturedLabels.size(), 2); - EXPECT_STREQ(manager.m_capturedLabels[0].c_str(), "@hello"); - EXPECT_STREQ(manager.m_capturedLabels[1].c_str(), "@world"); - manager.m_capturedLabels.clear(); - - manager.LocalizeString_s("@hello\n@world", outString, false); - ASSERT_EQ(manager.m_capturedLabels.size(), 2); - EXPECT_STREQ(manager.m_capturedLabels[0].c_str(), "@hello"); - EXPECT_STREQ(manager.m_capturedLabels[1].c_str(), "@world"); - manager.m_capturedLabels.clear(); - - manager.LocalizeString_s("@hello\r@world", outString, false); - ASSERT_EQ(manager.m_capturedLabels.size(), 2); - EXPECT_STREQ(manager.m_capturedLabels[0].c_str(), "@hello"); - EXPECT_STREQ(manager.m_capturedLabels[1].c_str(), "@world"); - manager.m_capturedLabels.clear(); - - manager.LocalizeString_s("@hello @world", outString, false); - ASSERT_EQ(manager.m_capturedLabels.size(), 2); - EXPECT_STREQ(manager.m_capturedLabels[0].c_str(), "@hello"); - EXPECT_STREQ(manager.m_capturedLabels[1].c_str(), "@world"); - manager.m_capturedLabels.clear(); -} - - -// this test makes sure that multiple whitespace characters in a row don't themselves count as tokens or change the output in undesirable ways. -TEST_F(SystemFixture, LocalizeStringInternal_ManyWhitespaceCharacters_CorrectlyTokenizes) -{ - UnitTestCLocalizedStringsManager manager(&m_system); - manager.SetLanguage("french"); - - string outString; - const char* testString = "@hello\n\r\t \t\r\n@world\n\r\t "; - manager.LocalizeString_ch(testString, outString, false); - ASSERT_EQ(manager.m_capturedLabels.size(), 2); - EXPECT_STREQ(manager.m_capturedLabels[0].c_str(), "@hello"); - EXPECT_STREQ(manager.m_capturedLabels[1].c_str(), "@world"); - - // since there are no localizations available it should not have gobbled up whitespace or altered it. - EXPECT_STREQ(outString, testString); -} diff --git a/Code/CryEngine/CrySystem/Tests/test_CrySystem.cpp b/Code/CryEngine/CrySystem/Tests/test_CrySystem.cpp deleted file mode 100644 index e384893e10..0000000000 --- a/Code/CryEngine/CrySystem/Tests/test_CrySystem.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" -#include -#include -#include -#include -#include - -namespace UnitTests -{ - class CSystemUnitTests - : public ::testing::Test - { - public: - void SetUp() override - { - SSystemInitParams startupParams; - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - m_system = new CSystem(startupParams.pSharedEnvironment); - } - - void TearDown() override - { - delete m_system; - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - } - - - CSystem* m_system = nullptr; - }; - - TEST_F(CSystemUnitTests, ApplicationLogInstanceUnitTests) - { - const char dummyString[] = "dummy"; - const char testString[] = "test"; - EXPECT_EQ(m_system->GetApplicationLogInstance(dummyString), 0); - EXPECT_EQ(m_system->GetApplicationLogInstance(testString), 0); -#if AZ_TRAIT_OS_USE_WINDOWS_MUTEX - EXPECT_EQ(m_system->GetApplicationLogInstance(dummyString), 1); -#endif - } -} diff --git a/Code/CryEngine/CrySystem/Tests/test_Main.cpp b/Code/CryEngine/CrySystem/Tests/test_Main.cpp deleted file mode 100644 index 5ae78cabbf..0000000000 --- a/Code/CryEngine/CrySystem/Tests/test_Main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" -#include -#include -#include -#include - -class CrySystemTestEnvironment - : public AZ::Test::ITestEnvironment - , public ::UnitTest::TraceBusRedirector -{ -public: - virtual ~CrySystemTestEnvironment() - {} - -protected: - void SetupEnvironment() override - { - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - ::UnitTest::TraceBusRedirector::BusConnect(); - } - - void TeardownEnvironment() override - { - ::UnitTest::TraceBusRedirector::BusDisconnect(); - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - } -}; - -AZ_UNIT_TEST_HOOK(new CrySystemTestEnvironment) diff --git a/Code/CryEngine/CrySystem/Tests/test_MaterialUtils.cpp b/Code/CryEngine/CrySystem/Tests/test_MaterialUtils.cpp deleted file mode 100644 index 99077e41e8..0000000000 --- a/Code/CryEngine/CrySystem/Tests/test_MaterialUtils.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" -#include - -#include -#include -#include "MaterialUtils.h" - -#include - - -TEST(CrySystemMaterialUtilsTests, MaterialUtilsTestBasics) -{ - char tempBuffer[AZ_MAX_PATH_LEN] = { 0 }; - // call to ensure that it handles nullptr without crashing - MaterialUtils::UnifyMaterialName(nullptr); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(tempBuffer[0] == 0); -} - -TEST(CrySystemMaterialUtilsTests, MaterialUtilsTestExtensions) -{ - char tempBuffer[AZ_MAX_PATH_LEN]; - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, "blahblah.mtl"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "blahblah") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, "blahblah.mat.mat.abc.test.mtl"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "blahblah.mat.mat.abc.test") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, "test/.mat.mat/blahblah.mat.mat.abc.test.mtl"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "test/.mat.mat/blahblah.mat.mat.abc.test") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, ".mat.mat.blahblah.mat.mat.abc.test.mtl"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, ".mat.mat.blahblah.mat.mat.abc.test") == 0); -} - -TEST(CrySystemMaterialUtilsTests, MaterialUtilsTestPrefixes) -{ - char tempBuffer[AZ_MAX_PATH_LEN]; - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, ".\\blahblah.mat"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "blahblah") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, "./materials/blahblah.mat.mat.abc.test"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "materials/blahblah.mat.mat.abc") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, ".\\engine\\materials\\blahblah.mat.mat.abc.test"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "materials/blahblah.mat.mat.abc") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, "engine/materials/blahblah.mat.mat.abc.test"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "materials/blahblah.mat.mat.abc") == 0); - - azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, "materials/blahblah.mat"); - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "materials/blahblah") == 0); -} - -TEST(CrySystemMaterialUtilsTests, MaterialUtilsTestGameName) -{ - char tempBuffer[AZ_MAX_PATH_LEN]; - - auto projectName = AZ::Utils::GetProjectName(); - azsnprintf(tempBuffer, AZ_MAX_PATH_LEN, ".\\%s\\materials\\blahblah.mat.mat.abc.test", projectName.c_str()); - - MaterialUtils::UnifyMaterialName(tempBuffer); - EXPECT_TRUE(strcmp(tempBuffer, "materials/blahblah.mat.mat.abc") == 0); -} diff --git a/Code/CryEngine/CrySystem/Timer.h b/Code/CryEngine/CrySystem/Timer.h index 8778405067..33cfbd6087 100644 --- a/Code/CryEngine/CrySystem/Timer.h +++ b/Code/CryEngine/CrySystem/Timer.h @@ -31,7 +31,7 @@ public: // interface ITimer ---------------------------------------------------------- - // TODO: Review m_time usage in System.cpp / SystemRender.cpp + // TODO: Review m_time usage in System.cpp // if it wants Game Time / UI Time or a new Render Time? virtual void ResetTimer(); diff --git a/Code/CryEngine/CrySystem/UnixConsole.cpp b/Code/CryEngine/CrySystem/UnixConsole.cpp deleted file mode 100644 index 5ec186b8b8..0000000000 --- a/Code/CryEngine/CrySystem/UnixConsole.cpp +++ /dev/null @@ -1,2518 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Console implementation for UNIX systems based on curses ncurses - - -#include "CrySystem_precompiled.h" -#include "System.h" -#include "UnixConsole.h" - -#if defined(USE_DEDICATED_SERVER_CONSOLE) - -#if defined(USE_UNIXCONSOLE) - -#if !defined(WIN32) -#include -#include -#include -#include -#if defined(MAC) -#include -#include -#else -#include -#endif // defined(MAC) -#if defined(LINUX) || defined(MAC) - #include -#endif -#endif -#include - -#define UNIXConsole_MORE_LEFT "<<" -#define UNIXConsole_MORE_RIGHT ">>" -#define UNIXConsole_MORE_COLOR (3) // Colorpair index -#define UNIXConsole_PROMPT "] " -#define UNIXConsole_PROMPT_COLOR (2) // Colorpair index -#define UNIXConsole_WRAP_CHAR '\\' -#define UNIXConsole_WRAP_COLOR (4) -#define UNIXConsole_MIN_WIDTH (10) -#define UNIXConsole_MAX_LINES (1000) -#define UNIXConsole_MAX_HISTORY (100) - -#if defined(LINUX) || defined(MAC) -// Should find a better test for ncurses... -#define NCURSES 1 -#endif - -#if defined(WIN32) -#define snprintf _snprintf -#endif - -// macro which check if we should process console function -// used for disable console on Linux -#define IS_SHOW_CONSOLE if (!m_bShowConsole) {return; } -#define IS_SHOW_CONSOLE_RET(ret) if (!m_bShowConsole) {return ret; } - - -CryCriticalSectionNonRecursive CUNIXConsole::m_cleanupLock; - -class CUNIXConsoleInputThread - : public CrySimpleThread<> -{ - CUNIXConsole& m_UNIXConsole; -#if !defined(WIN32) - int m_IntrPipe[2]; -#else - HANDLE m_IntrEvent; -#endif - bool m_Cancelled; - -public: - CUNIXConsoleInputThread(CUNIXConsole& UNIXConsole) - : m_UNIXConsole(UNIXConsole) - , m_Cancelled(false) - { -#if !defined(WIN32) - pipe(m_IntrPipe); -#else - m_IntrEvent = CreateEvent(NULL, true, false, NULL); -#endif - } - - ~CUNIXConsoleInputThread() - { -#if !defined(WIN32) - close(m_IntrPipe[0]); - close(m_IntrPipe[1]); -#else - CloseHandle(m_IntrEvent); -#endif - } - - virtual void Run(); - virtual void Cancel() { m_Cancelled = true; Interrupt(); } - void Interrupt() - { -#if !defined(WIN32) - write(m_IntrPipe[1], "", 1); -#else - SetEvent(m_IntrEvent); -#endif - } -}; - -class CUNIXConsoleSignalHandler -{ - friend class CUNIXConsole; - - static CUNIXConsole* m_pUNIXConsole; - static void Handler(int signum); -}; - -CUNIXConsole::CUNIXConsole() - : m_HistoryIndex(-1) - , m_PromptResponse(0) - , m_pSystem(NULL) - , m_pConsole(NULL) - , m_pTimer(NULL) - , m_OnUpdateCalled(false) - , m_LastUpdateTime(0.0f) - , m_svMap(NULL) - , m_svGameRules(NULL) - , m_Width(~0) - , m_Height(~0) - , m_HeaderHeight(1) - , m_StatusHeight(1) - , m_CmdHeight(2) - , m_Color(DEFAULT_COLOR) - , m_DefaultColorPair(-1) - , m_EnableColor(true) - , m_WindowResized(false) - , m_OnShutdownCalled(false) - , m_Initialized(false) - , m_RequireDedicatedServer(false) - , m_ScrollUp(0) - , m_InputThread(NULL) - , m_CursorPosition(0) - , m_ScrollPosition(0) - , m_fsMode(false) - , m_bShowConsole(true) -{ -} - -CUNIXConsole::~CUNIXConsole() -{ - Cleanup(); - m_Lock.Lock(); -} - -void CUNIXConsole::SetRequireDedicatedServer(bool value) -{ - assert(!m_Initialized); - m_RequireDedicatedServer = value; -} - -#if defined(WIN32) || defined(WIN64) -void ResizeConBufAndWindow(HANDLE hConsole, SHORT xSize, SHORT ySize) -{ - CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */ - BOOL bSuccess; - SMALL_RECT srWindowRect; /* hold the new console size */ - COORD coordScreen; - - bSuccess = GetConsoleScreenBufferInfo(hConsole, &csbi); - /* get the largest size we can size the console window to */ - coordScreen = GetLargestConsoleWindowSize(hConsole); - /* define the new console window size and scroll position */ - srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1); - srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1); - srWindowRect.Left = srWindowRect.Top = (SHORT) 0; - /* define the new console buffer size */ - coordScreen.X = xSize; - coordScreen.Y = ySize; - /* if the current buffer is larger than what we want, resize the */ - /* console window first, then the buffer */ - if ((DWORD) csbi.dwSize.X * csbi.dwSize.Y > (DWORD) xSize * ySize) - { - bSuccess = SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect); - bSuccess = SetConsoleScreenBufferSize(hConsole, coordScreen); - bSuccess = SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect); - bSuccess = SetConsoleScreenBufferSize(hConsole, coordScreen); - } - /* if the current buffer is smaller than what we want, resize the */ - /* buffer first, then the console window */ - if ((DWORD) csbi.dwSize.X * csbi.dwSize.Y < (DWORD) xSize * ySize) - { - bSuccess = SetConsoleScreenBufferSize(hConsole, coordScreen); - bSuccess = SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect); - } - /* if the current buffer *is* the size we want, don't do anything! */ - return; -} - -BOOL WINAPI CtrlHandler(DWORD evt) -{ - switch (evt) - { - case CTRL_C_EVENT: - case CTRL_BREAK_EVENT: - return TRUE; - case CTRL_CLOSE_EVENT: - gEnv->pSystem->Quit(); - return TRUE; - } - return FALSE; -} -#endif - -void CUNIXConsole::Init(const char* headerString) -{ - assert(!m_Initialized); - - if (headerString != NULL) - { - m_HeaderString = headerString; - } - -#if defined(WIN32) || defined(WIN64) - // Allocate a console for the process. We don't care if this is successful - // or not, because failure indicates that the process already has a - // console, which is fine. - AllocConsole(); - HANDLE hConsOut = GetStdHandle(STD_OUTPUT_HANDLE); - ResizeConBufAndWindow(hConsOut, 120, 60); - SetConsoleCtrlHandler(CtrlHandler, TRUE); -#endif - - // Initialize curses. - initscr(); - cbreak(); - noecho(); - nonl(); - intrflush(stdscr, FALSE); - keypad(stdscr, TRUE); - scrollok(stdscr, TRUE); - idcok(stdscr, TRUE); - idlok(stdscr, TRUE); - nodelay(stdscr, TRUE); - - // Enable color output. - if (m_EnableColor) - { - if (start_color() != OK) - { - m_EnableColor = false; - } - } - - if (m_EnableColor) - { -#if defined(NCURSES) - // Setup the color table. - short colorPair = 0; - attr_t attr; - attr_get(&attr, &colorPair, NULL); - m_DefaultColorPair = colorPair; - m_ColorPair[0] = m_DefaultColorPair; - m_ColorPair[1] = m_DefaultColorPair; - short color_fg = 0, color_bg = 0; - pair_content(m_DefaultColorPair, &color_fg, &color_bg); - short pair = 0; - init_pair(++pair, COLOR_BLUE, color_bg); - m_ColorPair[2] = pair; - init_pair(++pair, COLOR_GREEN, color_bg); - m_ColorPair[3] = pair; - init_pair(++pair, COLOR_RED, color_bg); - m_ColorPair[4] = pair; - init_pair(++pair, COLOR_CYAN, color_bg); - m_ColorPair[5] = pair; - init_pair(++pair, COLOR_YELLOW, COLOR_BLACK); - m_ColorPair[6] = pair; - init_pair(++pair, COLOR_MAGENTA, color_bg); - m_ColorPair[7] = pair; - init_pair(++pair, COLOR_RED, color_bg); - m_ColorPair[8] = pair; - init_pair(++pair, COLOR_BLACK, COLOR_WHITE); - m_ColorPair[9] = pair; -#else - // Color output supported only for ncurses. - m_EnableColor = false; - m_DefaultColorPair = 0; -#endif - } - else - { - m_DefaultColorPair = 0; - } - - // Set the screen size and draw the initial screen. - SetSize(COLS, LINES); - - m_syslogStats.Init(); - - m_Initialized = true; -} - -void CUNIXConsole::Cleanup() -{ - m_cleanupLock.Lock(); - if (m_Initialized) - { - // Kill the input thread. - if (m_InputThread != NULL) - { - m_InputThread->Cancel(); - m_InputThread->WaitForThread(); - delete m_InputThread; - m_InputThread = NULL; - } - - // Curses cleanup. - clear(); - endwin(); - - m_Initialized = false; - } - m_cleanupLock.Unlock(); -} - -void CUNIXConsole::SetSize(unsigned width, unsigned height) -{ - bool repaint = false; - - assert(IsLocked()); - if (width != m_Width) - { - m_Width = width; - FixCursorPosition(); - repaint = true; - } - if (height != m_Height) - { - m_Height = height; - repaint = true; - } - if (repaint) - { - Repaint(); - } -} - -bool CUNIXConsole::IsTooSmall() -{ - assert(IsLocked()); - if (m_Height < m_HeaderHeight + m_StatusHeight + m_CmdHeight + 1) - { - return true; - } - if (m_Width < UNIXConsole_MIN_WIDTH) - { - return true; - } - return false; -} - -void CUNIXConsole::CheckResize() -{ - assert(IsLocked()); -#if defined(NCURSES) - int lines, cols; - - IS_SHOW_CONSOLE - - if (m_WindowResized) - { - m_WindowResized = false; - // Get the new window size from the terminal driver. - winsize ws; - memset(&ws, 0, sizeof ws); - ioctl(1, TIOCGWINSZ, &ws); - lines = ws.ws_row; - cols = ws.ws_col; - if (m_Width != lines || m_Height != cols) - { - resizeterm(lines, cols); - SetSize(cols, lines); - Repaint(); - } - } -#endif -} - -void CUNIXConsole::NewLine() -{ - char lineBuf[3] = "\1X"; - bool doScroll = !m_LineBuffer.empty(); - - assert(IsLocked()); - lineBuf[1] = m_Color + '0'; - - if (m_LineBuffer.size() == UNIXConsole_MAX_LINES) - { - m_LineBuffer.pop_front(); - } - m_LineBuffer.push_back(lineBuf); - - if (doScroll) - { - ScrollLog(); - } - else - { - unsigned row = m_Height - m_CmdHeight - m_StatusHeight - 1; - move(row, 0); - } - if (m_ScrollUp > 0) - { - const string& lastDisplayLine - = m_LineBuffer[m_LineBuffer.size() - m_ScrollUp - 1]; - DrawLogLine(lastDisplayLine); - } -} - -void CUNIXConsole::ContinueLine() -{ - IS_SHOW_CONSOLE - - if (m_LineBuffer.empty()) - { - NewLine(); - return; - } - const string& lastLine = *m_LineBuffer.rbegin(); - unsigned column = DrawLogLine(lastLine, true /* noOutput */); - SetColorRaw(m_Color); - const unsigned row = m_Height - m_CmdHeight - m_StatusHeight - 1; - move(row, column); -} - -void CUNIXConsole::SetColor(int color) -{ - assert(IsLocked()); - m_Color = color; - SetColorRaw(color); - if (m_LineBuffer.empty()) - { - m_LineBuffer.push_back(""); - } - const TLineBuffer::const_reverse_iterator it = m_LineBuffer.rbegin(); - string& lastLine = const_cast(*it); - lastLine.push_back(1); - lastLine.push_back('0' + color); -} - -void CUNIXConsole::SetColorRaw(int color) -{ - attr_t colorAttr = 0; - - assert(IsLocked()); - if (color == DEFAULT_COLOR) - { - color = 0; - } - if (m_EnableColor) - { - colorAttr = COLOR_PAIR(m_ColorPair[color]); - } - switch (color) - { - case 0: - attrset(A_NORMAL | colorAttr); - break; - case 1: - attrset(A_REVERSE | colorAttr); - break; - case 2: - case 3: - attrset(A_NORMAL | colorAttr); - break; - case 4: - attrset(A_BOLD | colorAttr); - break; - case 5: - attrset(A_NORMAL | colorAttr); - break; - case 6: - attrset(A_BOLD | colorAttr); - break; - case 7: - case 8: - case 9: - attrset(A_NORMAL | colorAttr); - break; - default: - abort(); - } -} - -void CUNIXConsole::Put(int c) -{ - assert(IsLocked()); - - // Get the last buffer line. - if (m_LineBuffer.empty()) - { - NewLine(); - } - const TLineBuffer::const_reverse_iterator it = m_LineBuffer.rbegin(); - string& lastLine = const_cast(*it); - assert(c >= 0x20); - - // Wrap the line if required. - unsigned row = m_Height - m_CmdHeight - m_StatusHeight - 1; - unsigned column = 0; - GetLineHeight(lastLine, &column); - assert(column <= m_Width); - lastLine.push_back(char(c)); - - if (m_ScrollUp == 0) - { - // Output the line wrap character. - if (column == m_Width - 1) - { - move(row, m_Width - 1); - attr_t colorAttr = 0; - if (m_EnableColor) - { - colorAttr = COLOR_PAIR(UNIXConsole_WRAP_COLOR); - } - attrset(A_NORMAL | colorAttr); - addch(UNIXConsole_WRAP_CHAR); - ScrollLog(); - move(row, 0); - } - - // Output the character. - SetColorRaw(m_Color); - addch(c); - } -} - -void CUNIXConsole::Put(const char* s) -{ - assert(IsLocked()); - while (*s) - { - if (*s == '\n') - { - NewLine(); - } - else - { - Put(*s); - } - ++s; - } -} - -unsigned CUNIXConsole::GetLineLength(const string& line) -{ - unsigned length = 0; - - for (string::const_iterator it = line.begin(), itEnd = line.end(); - it != itEnd; - ++it) - { - char c = *it; - if (c == 1) - { - ++it; - assert(it != itEnd); - continue; - } - ++length; - } - return length; -} - -char CUNIXConsole::GetLastCharacter(const string& line, int* color) -{ - char c0 = 0, c1 = 0; - char lastChar = 0; - - if (!line.empty()) - { - for (int i = line.size() - 1; i >= 0; i--) - { - c1 = c0; - c0 = line[i]; - if (c0 == 1) - { - assert(lastChar); - if (color) - { - *color = c1 - '0'; - } - return lastChar; - } - else if (c0 && c1 != 1 && !lastChar) - { - lastChar = c0; - } - } - } - - *color = DEFAULT_COLOR; - if (lastChar) - { - return lastChar; - } - assert(c0 && c0 != 1); - return c0; -} - -unsigned CUNIXConsole::GetLineHeight(const string& line, unsigned* column) -{ - unsigned lineLength = GetLineLength(line); - unsigned height = 1; - - assert(IsLocked()); - while (lineLength > m_Width) - { - lineLength -= m_Width - 1; - ++height; - } - if (column != NULL) - { - *column = lineLength; - } - return height; -} - -void CUNIXConsole::ScrollLog() -{ - if (m_fsMode) - { - return; - } - - // Scroll the log window. We'll do that by defining a software scrolling - // region. The constructor has set scrollok() and idlok(), so the output - // routing will use the hardware scrolling region (if available). - unsigned top = m_HeaderHeight; - unsigned bottom = m_Height - m_CmdHeight - m_StatusHeight; - - assert(IsLocked()); - // Some curses implementations (pdcurses) require the current position to - // be within the defined scrolling region. - move(top, 0); - if (setscrreg(top, bottom) == OK) - { - move(bottom, 0); - addch('\n'); - setscrreg(0, m_Height - 1); - DrawStatus(1); - } - else - { - // Scrolling regions not supported. We'll scroll the entire window and - // the repaint everything except for the log window. - scroll(stdscr); - move(bottom - 1, 0); - attrset(A_NORMAL); - clrtobot(); - DrawHeader(); - DrawStatus(); - DrawCmd(); - } - move(bottom - 1, 0); -} - -bool CUNIXConsole::FixCursorPosition() -{ - IS_SHOW_CONSOLE_RET(false) - - bool repaint = false; - - assert(IsLocked()); - - // Clip the cursor position. - if (m_CursorPosition > (int)m_InputLine.size()) - { - m_CursorPosition = m_InputLine.size(); - } - - // Trivial scroll position fixes. - if (m_CursorPosition < (int)m_Width / 2 && m_ScrollPosition > 0) - { - m_ScrollPosition = 0; - repaint = true; - } - else if (m_CursorPosition < m_ScrollPosition) - { - m_ScrollPosition = m_CursorPosition - m_Width / 4; - repaint = true; - } - - assert(m_ScrollPosition <= m_CursorPosition); - // The method may be called after the cursor has been moved to the - // right, so we may have to scroll the input line. - int displayLenth = m_Width * m_CmdHeight; - displayLenth -= strlen(UNIXConsole_PROMPT); - // If the cursor is at the end of the input line, then we only must leave - // one space for the cursor itself, otherwise we must leave space for the - // right scroll indicator. - if (m_CursorPosition == m_InputLine.size()) - { - displayLenth -= 1; - } - else - { - displayLenth -= strlen(UNIXConsole_MORE_RIGHT); - } - if (m_ScrollPosition < m_CursorPosition - displayLenth) - { - m_ScrollPosition = m_CursorPosition - displayLenth; - repaint = true; - } - - return repaint; -} - -void CUNIXConsole::OnEdit() -{ - assert(IsLocked()); - m_SavedInputLine.clear(); - m_HistoryIndex = -1; - if (m_pConsole != NULL) - { - m_pConsole->ResetAutoCompletion(); - } -} - -void CUNIXConsole::KeyEnter() -{ - bool redrawAll = false; - bool pushCommand = false; - - assert(IsLocked()); - - // Scroll the log window to the bottom. - if (m_ScrollUp > 0) - { - m_ScrollUp = 0; - redrawAll = true; - } - - // Process the input line. - while (!m_InputLine.empty() && m_InputLine[0] == '\\') - { - m_InputLine.erase(0, 1); - } - if (!m_InputLine.empty()) - { - pushCommand = true; - -#if defined(UC_ENABLE_MAGIC_COMMANDS) - // Enable some magic commands intercepted by the console. All magic - // commands start with an '@' character. - { - const char* const command = m_InputLine.c_str(); - if (!azstricmp(command, "@quit")) - { - // We're called from the input thread, hence we can't join it. We - // have to prevent Cleanup() (called via atexit()) from trying to - // join. - CUNIXConsoleInputThread* inputThread = m_InputThread; - m_InputThread = NULL; - Unlock(); - if (m_pSystem != NULL) - { - m_pSystem->Quit(); - inputThread->Exit(); - } - exit(0); - // Not reached. - abort(); - } - // Add other magic commands here. - } -#endif - } - - if (pushCommand) - { - { - m_CommandQueue.push_back(m_InputLine); - } - } - - if (!m_InputLine.empty()) - { - m_CommandHistory.push_back(m_InputLine); - while (m_CommandHistory.size() > UNIXConsole_MAX_HISTORY) - { - m_CommandHistory.pop_front(); - } - m_HistoryIndex = -1; - m_InputLine.clear(); - m_SavedInputLine.clear(); - m_CursorPosition = 0; - m_ScrollPosition = 0; - if (!redrawAll) - { - DrawCmd(); - refresh(); - } - } - - if (redrawAll) - { - Repaint(); - } -} -void CUNIXConsole::KeyUp() -{ - const int historySize = m_CommandHistory.size(); - - assert(IsLocked()); - if (m_HistoryIndex < historySize - 1) - { - if (m_HistoryIndex == -1) - { - m_SavedInputLine = m_InputLine; - } - m_HistoryIndex += 1; - m_InputLine = m_CommandHistory[historySize - m_HistoryIndex - 1]; - m_CursorPosition = m_InputLine.size(); - FixCursorPosition(); - DrawCmd(); - refresh(); - } -} - -void CUNIXConsole::KeyDown() -{ - const int historySize = m_CommandHistory.size(); - - assert(IsLocked()); - if (m_HistoryIndex > -1) - { - m_HistoryIndex -= 1; - if (m_HistoryIndex == -1) - { - m_InputLine = m_SavedInputLine; - m_SavedInputLine.clear(); - } - else - { - m_InputLine = m_CommandHistory[historySize - m_HistoryIndex - 1]; - } - m_CursorPosition = m_InputLine.size(); - FixCursorPosition(); - DrawCmd(); - refresh(); - } -} - -void CUNIXConsole::KeyLeft() -{ - assert(IsLocked()); - if (m_CursorPosition > 0) - { - m_CursorPosition -= 1; - DrawCmd(!FixCursorPosition()); - } -} - -void CUNIXConsole::KeyRight() -{ - assert(IsLocked()); - if (m_CursorPosition < (int)m_InputLine.size()) - { - m_CursorPosition += 1; - DrawCmd(!FixCursorPosition()); - } -} - -void CUNIXConsole::KeyHome(bool ctrl) -{ - assert(IsLocked()); - if (ctrl) - { - const int logHeight = GetLogHeight(); - int maxUp = m_LineBuffer.size() - logHeight; - if (m_ScrollUp != maxUp) - { - m_ScrollUp = maxUp; - Repaint(); - } - } - else if (m_CursorPosition != 0) - { - m_CursorPosition = 0; - DrawCmd(!FixCursorPosition()); - } -} - -void CUNIXConsole::KeyEnd(bool ctrl) -{ - assert(IsLocked()); - if (ctrl) - { - const int logHeight = GetLogHeight(); - int maxUp = m_LineBuffer.size() - logHeight; - if (m_ScrollUp != 0) - { - m_ScrollUp = 0; - Repaint(); - } - } - else if (m_CursorPosition < (int)m_InputLine.size()) - { - m_CursorPosition = m_InputLine.size(); - DrawCmd(!FixCursorPosition()); - } -} - -void CUNIXConsole::KeyBackspace() -{ - assert(IsLocked()); - if (m_CursorPosition > 0) - { - m_InputLine.erase(m_CursorPosition - 1, 1); - m_CursorPosition -= 1; - FixCursorPosition(); - OnEdit(); - DrawCmd(); - } -} - -void CUNIXConsole::KeyDelete() -{ - assert(IsLocked()); - if (m_CursorPosition < (int)m_InputLine.size()) - { - m_InputLine.erase(m_CursorPosition, 1); - FixCursorPosition(); - OnEdit(); - DrawCmd(); - } -} - -void CUNIXConsole::KeyDeleteWord() -{ - assert(IsLocked()); - if (m_CursorPosition > 0) - { - const char* const inputLine = m_InputLine.c_str(); - const char* p = inputLine + m_CursorPosition - 1; - - while (p > inputLine && *p == ' ') - { - --p; - } - while (p > inputLine && *p != ' ') - { - --p; - } - m_InputLine.erase(p - inputLine, m_CursorPosition); - m_CursorPosition = (uint32)(p - inputLine); - FixCursorPosition(); - OnEdit(); - DrawCmd(); - - /* Old std::string based code, kept for reference. - size_t wordIndex; - wordIndex = m_InputLine.find_last_of(" ", m_CursorPosition - 1); - if (wordIndex != string::npos) - { - wordIndex = m_InputLine.find_last_not_of(" ", wordIndex); - if (wordIndex != string::npos) - wordIndex += 1; - } - if (wordIndex == string::npos) - { - m_InputLine.erase(0, m_CursorPosition); - m_CursorPosition = 0; - } - else - { - m_InputLine.erase(wordIndex, m_CursorPosition - wordIndex); - m_CursorPosition = wordIndex; - } - FixCursorPosition(); - OnEdit(); - DrawCmd(); - */ - } -} - -void CUNIXConsole::KeyKill() -{ - assert(IsLocked()); - if (m_CursorPosition < (int)m_InputLine.size()) - { - m_InputLine.resize(m_CursorPosition); - FixCursorPosition(); - OnEdit(); - DrawCmd(); - } -} - -void CUNIXConsole::KeyRepaint() -{ - assert(IsLocked()); - Repaint(); -} - -void CUNIXConsole::KeyTab() -{ - const char* result; - - assert(IsLocked()); - if (m_OnShutdownCalled) - { - return; - } - string Tmp(m_InputLine); - Unlock(); - result = m_pConsole->ProcessCompletion(Tmp.c_str()); - Lock(); - if (result != NULL) - { - if (result[0] == '\\') - { - ++result; - } - m_InputLine = result; - m_CursorPosition = m_InputLine.size(); - FixCursorPosition(); - m_SavedInputLine.clear(); - m_HistoryIndex = -1; - DrawCmd(); - refresh(); - } -} - -void CUNIXConsole::KeyPgUp(bool ctrl) -{ - const int logHeight = GetLogHeight(); - // int logStep = logHeight - 2; - int logStep = ctrl ? 10 : 1; - int maxUp = m_LineBuffer.size() - logHeight; - int prevScrollUp = m_ScrollUp; - - assert(IsLocked()); - if (logStep < 1) - { - logStep = 1; - } - if (maxUp < 0) - { - maxUp = 0; - } - m_ScrollUp += logStep; - if (m_ScrollUp > maxUp) - { - m_ScrollUp = maxUp; - } - if (m_ScrollUp != prevScrollUp) - { - Repaint(); - } -} - -void CUNIXConsole::KeyPgDown(bool ctrl) -{ - const int logHeight = GetLogHeight(); - // int logStep = logHeight - 2; - int logStep = ctrl ? 10 : 1; - int prevScrollUp = m_ScrollUp; - - assert(IsLocked()); - if (logStep < 1) - { - logStep = 1; - } - if (m_ScrollUp > 0) - { - m_ScrollUp -= logStep; - } - if (m_ScrollUp < 0) - { - m_ScrollUp = 0; - } - if (m_ScrollUp != prevScrollUp) - { - Repaint(); - } -} - -void CUNIXConsole::Key(int c) -{ - assert(IsLocked()); - assert(c >= 0x20 && c <= 0xff); - assert(m_CursorPosition <= (int)m_InputLine.size()); - m_InputLine.insert(m_CursorPosition, 1, (char)c); - m_CursorPosition += 1; - FixCursorPosition(); - OnEdit(); - DrawCmd(); - refresh(); -} - -void CUNIXConsole::Repaint() -{ - IS_SHOW_CONSOLE - - assert(IsLocked()); - clear(); - DrawHeader(); - if (m_fsMode) - { - DrawFullscreen(); - } - else - { - DrawLog(); - } - DrawStatus(); - DrawCmd(); - refresh(); -} - -void CUNIXConsole::Flush() -{ - IS_SHOW_CONSOLE - - assert(IsLocked()); - refresh(); -} - -void CUNIXConsole::InputIdle() -{ - IS_SHOW_CONSOLE - - if (m_pTimer == NULL) - { - return; - } - - Lock(); - - CTimeValue now = m_pTimer->GetAsyncTime(); - float timePassed = (now - m_LastUpdateTime).GetSeconds(); - - // If more than 0.2 sec have passed since the last OnUpdate() call, then - // we'll start painting dots to the status line. - if (timePassed > 0.2f) - { - int nDots = (int)(timePassed + 0.5) / 3; - if (nDots > (int) m_Width - 2) - { - nDots = (int)m_Width - 2; - } - if (m_ProgressStatus.length() != nDots) - { - m_ProgressStatus.clear(); - m_ProgressStatus.append(nDots, '.'); - DrawStatus(); - DrawCmd(true); - refresh(); - } - } - - Unlock(); -} - -// get at least n spaces -static char* GetSpaces(int n) -{ - static char* spaceBuffer = 0; - static int spaceBufferSz = 0; - - if (n > spaceBufferSz) - { - spaceBufferSz = MAX(spaceBufferSz * 2, n); - delete[] spaceBuffer; - spaceBuffer = new char[spaceBufferSz]; - memset(spaceBuffer, ' ', spaceBufferSz); - } - - return spaceBuffer; -} - -void CUNIXConsole::DrawHeader() -{ - IS_SHOW_CONSOLE - - const char* const headerString = m_HeaderString.c_str(); - int headerLength = m_HeaderString.size(); - int padLeft = 0, padRight = 0; - const char* term = termname(); - - assert(IsLocked()); - - if (m_HeaderHeight == 0) - { - return; - } - - if (headerLength >= (int)m_Width) - { - padLeft = 0; - padRight = 0; - headerLength = m_Width; - } - else - { - padLeft = (m_Width - headerLength) / 2; - padRight = m_Width - headerLength - padLeft; - } - move(m_HeaderHeight - 1, 0); -#if defined(LINUX) - // For the Linux console ncurses reports the A_UNDERLINE is supported, even - // thought it is not. We'll do an explicit test for the terminal type - // "linux" (i.e. Linux console). - if ((termattrs() & A_UNDERLINE) && strcasecmp(term, "linux")) - { - attrset(A_UNDERLINE); - } - else -#endif - { - if (m_EnableColor) - { - attrset(A_BOLD | COLOR_PAIR(m_ColorPair[2] /* blue */)); - } - else - { - attrset(A_REVERSE); - } - } - scrollok(stdscr, FALSE); - addnstr(GetSpaces(padLeft), padLeft); - addnstr(headerString, headerLength); - addnstr(GetSpaces(padRight), padRight); - scrollok(stdscr, TRUE); - attrset(A_NORMAL); -} - -// Output a single log line. -// If the noOutput flag is set to 'true', then no output is written to the -// screen and no cursor movements are performed. -// The method returns the current output column (i.e. the output column for -// the next charater to be written to the log window). -// Note: Even it the noOutput flag is set, the method will update the m_Color -// field of the UNIX console. -unsigned CUNIXConsole::DrawLogLine(const string& line, bool noOutput) -{ - IS_SHOW_CONSOLE_RET(0) - - const unsigned row = m_Height - m_CmdHeight - m_StatusHeight - 1; - unsigned column = 0; - - if (!noOutput) - { - assert(IsLocked()); - move(row, column); - attrset(A_NORMAL); - } - for (string::const_iterator it = line.begin(), itEnd = line.end(); it != itEnd; ) - { - char c = *it++; - if (column == m_Width - 1) - { - if (!noOutput) - { - attr_t colorAttr = 0; - if (m_EnableColor) - { - colorAttr = COLOR_PAIR(UNIXConsole_WRAP_COLOR); - } - attrset(A_NORMAL | colorAttr); - addch(UNIXConsole_WRAP_CHAR); - ScrollLog(); - move(row, 0); - SetColorRaw(m_Color); - } - column = 0; - } - if (c == 1) - { - assert(it != itEnd); - int color = *it - '0'; - m_Color = color; - ++it; - if (!noOutput) - { - SetColorRaw(color); - } - continue; - } - if (!noOutput) - { - addch(c); - } - ++column; - } - return column; -} - -// The scrollUp parameter indicates how many log lines to scroll up from the -// bottom. -void CUNIXConsole::DrawLog() -{ - IS_SHOW_CONSOLE - - unsigned scrollUp = m_ScrollUp; - - assert(IsLocked()); - - if (IsTooSmall()) - { - return; - } - if (m_LineBuffer.empty()) - { - return; - } - - // DrawLog is called only on refresh and on window resize, so performance is - // not an issue. We'll simply repaint by re-sending the log lines from the - // scroll buffer. - int nLines = m_LineBuffer.size(); - int lastLine = nLines - 1 - (int)scrollUp; - int firstLine = lastLine - GetLogHeight(); - - if (firstLine < 0) - { - firstLine = 0; - } - for (int i = firstLine; i <= lastLine; ++i) - { - const string& line = m_LineBuffer[i]; - if (i > firstLine) - { - ScrollLog(); - } - DrawLogLine(line); - } -} - -void CUNIXConsole::DrawStatus(int maxLines) -{ - IS_SHOW_CONSOLE - - unsigned row = m_Height - m_CmdHeight - m_StatusHeight; - const char* statusLeft = NULL; - const char* statusRight = NULL; - char bufferLeft[256]; - char bufferRight[256]; - - assert(IsLocked()); - - if (IsTooSmall() || maxLines == 0 || m_StatusHeight == 0) - { - return; - } - else if (maxLines == -1) - { - maxLines = m_StatusHeight; - } - - // If we're scrolled, then the right size shows a scroll indicator. - if (m_ScrollUp > 0) - { - const int logHeight = GetLogHeight(); - int logBottomLine = (int)m_LineBuffer.size() - m_ScrollUp; - assert(logBottomLine >= 0); - float percent = 100.f * (float)logBottomLine / m_LineBuffer.size(); - if (m_ScrollUp == m_LineBuffer.size() - logHeight) - { - cry_strcpy(bufferRight, "| SCROLL:TOP "); - } - else - { - snprintf( - bufferRight, - sizeof bufferRight, - "| SCROLL:%.1f%% ", - percent); - bufferRight[sizeof(bufferRight) - 1] = 0; - } - statusRight = bufferRight; - } - - if (!m_Prompt.empty()) - { - // No status display when a user prompt is active. - } - else if (!m_ProgressStatus.empty()) - { - snprintf(bufferLeft, sizeof bufferLeft, " %s", m_ProgressStatus.c_str()); - bufferLeft[sizeof bufferLeft - 1] = 0; - statusLeft = bufferLeft; - } - else if (m_OnUpdateCalled) - { - // Standard status display. - // Map name and game rules on the left. - // Current update rate and player count on the right. - const char* mapName = m_svMap->GetString(); - const char* gameRules = m_svGameRules->GetString(); - snprintf(bufferLeft, sizeof bufferLeft, - " map:%s rules:%s", - mapName, - gameRules); - bufferLeft[sizeof bufferLeft - 1] = 0; - statusLeft = bufferLeft; - float updateRate = 0.f; - static float displayUpdateRate = 0.f; - if (m_pTimer != NULL) - { - updateRate = m_pTimer->GetFrameRate(); -#if 0 - // Avoid jumping numbers in the update rate display. Per update the - // displayed update rate changes by at most maxDeltaRate. - const static float maxDeltaRate = 10.0f; - if (updateRate - displayUpdateRate > maxDeltaRate) - { - displayUpdateRate += maxDeltaRate; - } - else if (updateRate - displayUpdateRate < -maxDeltaRate) - { - displayUpdateRate -= maxDeltaRate; - } - else - { - displayUpdateRate = updateRate; - } -#else - // Display the update rate as reported by the timer. - displayUpdateRate = updateRate; -#endif - } - else - { - displayUpdateRate = 0.f; - } - if (statusRight == NULL) - { - char* pBufferRight = bufferRight; - char* const pBufferRightEnd = bufferRight + sizeof bufferRight; - azstrcpy(pBufferRight, AZ_ARRAY_SIZE(bufferRight), "| "); - pBufferRight += strlen(pBufferRight); - int numPlayers = 0; - - if (pBufferRight < pBufferRightEnd) - { - if (m_pConsole != NULL) - { - pBufferRight += snprintf( - pBufferRight, - pBufferRightEnd - pBufferRight, - "upd:%.1fms(%.2f..%.2f) " \ - "rate:%.1f/s", - m_updStats.avgUpdateTime, m_updStats.minUpdateTime, m_updStats.maxUpdateTime, - displayUpdateRate); - } - else - { - cry_strcpy(pBufferRight, pBufferRightEnd - pBufferRight, "BUSY "); - } - } - bufferRight[sizeof bufferRight - 1] = 0; - statusRight = bufferRight; - } - } - else - { - // No status display (blank). This branch is taken on the very first draw - // operation of the UNIX console. - } - if (statusLeft == NULL) - { - statusLeft = ""; - } - if (statusRight == NULL) - { - statusRight = ""; - } - - int leftWidth = strlen(statusLeft); - int rightWidth = strlen(statusRight); - int pad = 0; - - if (leftWidth + rightWidth > (int)m_Width) - { - pad = 0; - if (rightWidth > (int)m_Width) - { - leftWidth = 0; - rightWidth = m_Width; - } - else - { - leftWidth = m_Width - rightWidth; - } - } - else - { - pad = m_Width - leftWidth - rightWidth; - } - - move(row, 0); - attrset(A_REVERSE | A_BOLD); - scrollok(stdscr, FALSE); - for (int i = 0; i < leftWidth; ++i) - { - addch(statusLeft[i]); - } - for (int i = 0; i < pad; ++i) - { - addch(' '); - } - for (int i = 0; i < rightWidth; ++i) - { - addch(statusRight[i]); - } - scrollok(stdscr, TRUE); - attrset(A_NORMAL); -} - -void CUNIXConsole::DrawFullscreen() -{ - IS_SHOW_CONSOLE - - scrollok(stdscr, FALSE); - - int maxy = 1; - for (DynArray::iterator iter = m_drawCmds.begin(); iter != m_drawCmds.end(); ++iter) - { - maxy = max(maxy, iter->y); - } - - int scrolly = min(maxy - 1, m_ScrollUp); - - for (DynArray::iterator iter = m_drawCmds.begin(); iter != m_drawCmds.end(); ++iter) - { - switch (iter->op) - { - case eCDO_PutText: - { - int y = iter->y - scrolly; - if (y < 0 || y > (int)m_Height - 4) - { - break; - } - if (iter->x < 0 || iter->x > (int)m_Width) - { - break; - } - int len = strlen(iter->text); - if (iter->x + len > (int)m_Width) - { - len = m_Width - iter->x; - } - move(y + 1, iter->x); - for (int i = 0; i < len; i++) - { - addch(iter->text[i]); - } - } - } - } - scrollok(stdscr, TRUE); -} - -void CUNIXConsole::DrawCmd(bool cursorOnly) -{ - IS_SHOW_CONSOLE - - unsigned row = m_Height - m_CmdHeight; - unsigned column = 0; - attr_t colorAttr = 0; - const unsigned promptWidth = strlen(UNIXConsole_PROMPT); - const unsigned moreLeftWidth = strlen(UNIXConsole_MORE_LEFT); - const unsigned moreRightWidth = strlen(UNIXConsole_MORE_RIGHT); - - assert(IsLocked()); - - // If the window is too small, then don't draw anything. - if (IsTooSmall() - || m_CmdHeight == 0 - || m_Width < promptWidth + moreLeftWidth + moreRightWidth) - { - return; - } - - if (!m_Prompt.empty()) - { - DrawCmdPrompt(); - return; - } - - if (!cursorOnly) - { - scrollok(stdscr, FALSE); - - // Draw the command prompt. - if (m_EnableColor) - { - colorAttr = COLOR_PAIR(UNIXConsole_PROMPT_COLOR); - } - attrset(A_BOLD | colorAttr); - move(row, 0); - for (const char* p = UNIXConsole_PROMPT; *p; ++p) - { - addch(*p); - ++column; - } - - // Draw the left scroll indicator (if scrolled). - if (m_ScrollPosition > 0) - { - if (m_EnableColor) - { - colorAttr = COLOR_PAIR(UNIXConsole_MORE_COLOR); - } - attrset(A_NORMAL | colorAttr); - for (const char* p = UNIXConsole_MORE_LEFT; *p; ++p) - { - addch(*p); - ++column; - } - } - - // Draw the input line. We'll draw to the end of the command window - // (leaving the last cell blank) and the overdraw the more indicator (if - // required). - string::const_iterator it = m_InputLine.begin(); - string::const_iterator itEnd = m_InputLine.end(); - if (m_ScrollPosition > 0) - { - for (int i = m_ScrollPosition + strlen(UNIXConsole_MORE_LEFT); - i > 0; - --i, ++it) - { - ; - } - } - attrset(A_NORMAL); - bool lineTruncated = false; - for (; it != itEnd; ++it) - { - char c = *it; - if (row == m_Height - 1 && column == m_Width - 1) - { - lineTruncated = true; - break; - } - if (column == m_Width) - { - row += 1; - column = 0; - assert(row < m_Height); - move(row, column); - } - addch(c); - ++column; - } - - // Draw the right scroll indicator (if required). - if (lineTruncated) - { - move(m_Height - 1, m_Width - moreRightWidth); - if (m_EnableColor) - { - colorAttr = COLOR_PAIR(UNIXConsole_MORE_COLOR); - } - attrset(A_NORMAL | colorAttr); - for (const char* p = UNIXConsole_MORE_RIGHT; *p; ++p) - { - addch(*p); - ++column; - } - } - else - { - attrset(A_NORMAL); - clrtobot(); - move(m_Height - 1, m_Width - 1); - addch(' '); - } - - scrollok(stdscr, TRUE); - } - - // Update the cursor position. - column = m_CursorPosition - m_ScrollPosition + promptWidth; - row = m_Height - m_CmdHeight; - if (column >= m_Width) - { - row += column / m_Width; - column %= m_Width; - } - move(row, column); - refresh(); -} - -void CUNIXConsole::DrawCmdPrompt() -{ - IS_SHOW_CONSOLE - - unsigned row = m_Height - m_CmdHeight; - unsigned column = 0; - - string::const_iterator it = m_Prompt.begin(); - string::const_iterator itEnd = m_Prompt.end(); - attrset(A_BOLD); - clrtobot(); - scrollok(stdscr, FALSE); - move(row, column); - for (; it != itEnd; ++it) - { - char c = *it; - if (row == m_Height - 1 && column == m_Width - 1) - { - break; - } - if (column == m_Width) - { - row += 1; - column = 0; - move(row, column); - } - addch(c); - ++column; - } - scrollok(stdscr, TRUE); - move(row, column); - refresh(); -} - -char CUNIXConsole::Prompt(const char* promptString, const char* responseChars) -{ - char response = 0; - - Lock(); - - while (m_PromptResponse != 0) - { - m_PromptCond.Wait(m_Lock); - } -#ifndef _NDEBUG - // This method is called from __assert_fail, so we better don't put any - // asserts in here... - if (!m_Prompt.empty() || !*promptString || !*responseChars) - { - abort(); - } - if (strlen(responseChars) + 1 > sizeof m_PromptResponseChars) - { - abort(); - } -#endif - m_Prompt = promptString; - cry_strcpy(m_PromptResponseChars, responseChars); - DrawCmd(); - while (m_PromptResponse == 0) - { - m_PromptCond.Wait(m_Lock); - } - response = m_PromptResponse; - m_PromptResponse = 0; - m_Prompt.clear(); - m_PromptResponseChars[0] = 0; - m_PromptCond.Notify(); - DrawCmd(); - - Unlock(); - - return response; -} - -bool CUNIXConsole::IsInputThread() -{ - CrySimpleThread<>* callerThread = CrySimpleThread<>::Self(); - - return callerThread == m_InputThread; -} - -void CUNIXConsole::PrintF(const char* format, ...) -{ - char lineBuffer[1024]; - va_list ap; - - va_start(ap, format); - vsnprintf(lineBuffer, sizeof lineBuffer, format, ap); - lineBuffer[sizeof lineBuffer - 1] = 0; - Print(lineBuffer); - va_end(ap); -} - -void CUNIXConsole::Print(const char* line) -{ - IS_SHOW_CONSOLE - - static string lastLine; - static bool firstCall = true; - const size_t lineLength = strlen(line); - size_t lineOffset = 0; - - Lock(); - - // Check if the last line is a true prefix of the specified text argument. - // It it is a prefix, then the output is added to the last line sent to the - // sink. - if (!firstCall - && lineLength > lastLine.size() - && !strncmp(line, lastLine.c_str(), lastLine.size())) - { - // Line continued. - lineOffset = lastLine.size(); - ContinueLine(); // Will set the correct color. - } - else - { - NewLine(); - SetColor(); - } - lastLine = line; - firstCall = false; - - for (size_t i = lineOffset; i < lineLength; ++i) - { - char c = line[i]; - switch (c) - { - case '\\': - if (i < lineLength - 1 && line[i + 1] == 'n') - { - // Sequence "\\n", treat as "\n". - NewLine(); - ++i; - continue; - } - break; - case '\n': - NewLine(); - continue; - case '\r': - ClearLine(); - continue; - case '\t': - // We'll do it like the graphical console, just add 4 spaces and don't - // care about TAB stops. - for (unsigned j = 0; j < 4; ++j) - { - Put(' '); - } - continue; - case '$': - if (i < lineLength - 1) - { - ++i; - char colorChar = line[i]; - if (isdigit(colorChar)) - { - SetColor(colorChar - '0'); - continue; - } - if (colorChar == 'o' || colorChar == 'O') - { - // Ignore. - continue; - } - } - break; - default: - break; - } - if (c < 0x20) - { - // Unrecognized control character. Ignore. - continue; - } - Put((unsigned char)c); - } - DrawCmd(true); - // Flush(); - - Unlock(); -} - -bool CUNIXConsole::OnError(const char* errorString) -{ - if (!m_Initialized) - { - return true; - } - - return true; -} - -void CUNIXConsole::OnInitProgress(const char* sProgressMsg) -{ - if (!m_Initialized) - { - return; - } - - Lock(); - m_ProgressStatus = sProgressMsg; - DrawStatus(); - DrawCmd(true); - Flush(); - Unlock(); -} - -void CUNIXConsole::OnInit(ISystem* pSystem) -{ - if (m_RequireDedicatedServer && !gEnv->IsDedicated()) - { - return; - } - - Lock(); - - if (!m_Initialized) - { - Init(); - } - - assert(m_pSystem == NULL); - m_pSystem = pSystem; - assert(m_pConsole == NULL); - m_pConsole = pSystem->GetIConsole(); - - // Add the output print sink to the system console. - if (m_pConsole != 0) - { - m_pConsole->AddOutputPrintSink(this); - } - - // Start the input thread. - m_InputThread = new CUNIXConsoleInputThread(*this); - m_InputThread->Start(); - - Unlock(); - -#if defined(NCURSES) - // Setup the signal handler. - struct sigaction action; - memset(&action, 0, sizeof action); - action.sa_handler = CUNIXConsoleSignalHandler::Handler; - sigfillset(&action.sa_mask); - CUNIXConsoleSignalHandler::m_pUNIXConsole = this; - sigaction(SIGWINCH, &action, NULL); - sigset_t mask; - memset(&mask, 0, sizeof mask); - sigemptyset(&mask); - sigaddset(&mask, SIGWINCH); - sigprocmask(SIG_UNBLOCK, &mask, NULL); -#endif -} - -void CUNIXConsole::OnShutdown() -{ - if (!m_Initialized) - { - return; - } - - Lock(); - assert(!m_OnShutdownCalled); - m_pConsole->RemoveOutputPrintSink(this); - m_OnShutdownCalled = true; - Unlock(); - - Cleanup(); -} - -void CUNIXConsole::OnUpdate() -{ - FUNCTION_PROFILER(gEnv->pSystem, PROFILE_SYSTEM); - - IS_SHOW_CONSOLE - - if (!m_Initialized) - { - return; - } - - bool updateStatus = false; - static CTimeValue lastStatusUpdate = 0.f; - - if (m_OnShutdownCalled) - { - return; - } - - Lock(); - - if (!m_OnUpdateCalled) - { - m_OnUpdateCalled = true; - assert(m_svMap == NULL); - assert(m_svGameRules == NULL); - m_svMap = m_pConsole->GetCVar("sv_map"); - m_svGameRules = m_pConsole->GetCVar("sv_gamerules"); - assert(m_pTimer == NULL); - m_pTimer = m_pSystem->GetITimer(); - } - - if (!m_ProgressStatus.empty()) - { - m_ProgressStatus.clear(); - updateStatus = true; - } - CTimeValue now = m_pTimer->GetAsyncTime(); - if ((now - lastStatusUpdate).GetSeconds() > 0.1f) - { - updateStatus = true; - } - m_LastUpdateTime = now; - - if (updateStatus) - { - DrawStatus(); - DrawCmd(true); - Flush(); - lastStatusUpdate = now; - } - - while (!m_CommandQueue.empty()) - { - const string& command = m_CommandQueue[0]; - Unlock(); - if (m_pConsole) - { - m_pConsole->ExecuteString(command.c_str()); - - // doing the check again in case m_pConsole was nulled while executing the command - if (m_pConsole) - { - m_pConsole->AddCommandToHistory(command.c_str()); - } - } - Lock(); - m_CommandQueue.pop_front(); - } - - m_pSystem->GetUpdateStats(m_updStats); - - bool fsMode = !m_drawCmds.empty(); - if (fsMode || fsMode != m_fsMode) - { - m_fsMode = fsMode; - Repaint(); - } - - Unlock(); -} - -void CUNIXConsole::GetMemoryUsage(ICrySizer* pSizer) -{ - size_t size = sizeof *this; - - Lock(); - - // We're using string (for various reasons), so our best guess of the - // size is the .size(). - size += m_HeaderString.size(); - size += m_LineBuffer.size() * sizeof(string); - for (TLineBuffer::const_iterator it = m_LineBuffer.begin(), - itEnd = m_LineBuffer.end(); - it != itEnd; - ++it) - { - size += it->size(); - } - size += m_CommandQueue.size() * sizeof(string); - for (TCommandQueue::const_iterator it = m_CommandQueue.begin(), - itEnd = m_CommandQueue.end(); - it != itEnd; - ++it) - { - size += it->size(); - } - size += m_CommandHistory.size() * sizeof(string); - for (TCommandHistory::const_iterator it = m_CommandHistory.begin(), - itEnd = m_CommandHistory.end(); - it != itEnd; - ++it) - { - size += it->size(); - } - if (m_InputThread != NULL) - { - size += sizeof *m_InputThread; - } - size += m_InputLine.size(); - size += m_SavedInputLine.size(); - size += m_ProgressStatus.size(); - - Unlock(); - - pSizer->AddObject(this, size); -} - -Vec2_tpl CUNIXConsole::BeginDraw() -{ - m_newCmds.resize(0); - return Vec2_tpl(80, 25 - 3); -} - -void CUNIXConsole::PutText(int x, int y, const char* msg) -{ - IS_SHOW_CONSOLE - - SConDrawCmd cmd; - cmd.op = eCDO_PutText; - cmd.x = x; - cmd.y = y; - cry_strcpy(cmd.text, msg); - m_newCmds.push_back(cmd); -} - -void CUNIXConsole::EndDraw() -{ - IS_SHOW_CONSOLE - - Lock(); - m_drawCmds.swap(m_newCmds); - Unlock(); -} - -void CUNIXConsoleInputThread::Run() -{ -#if !defined(WIN32) - fd_set rdfds; -#endif - bool interrupted = false; - - // The input thread selects stdin (0) and the interrupt pipe. The select() - // call has a timeout (typically 0.5 sec) and will call the InputIdle() - // method whenever the timer expires. - while (true) - { - interrupted = false; -#if !defined(WIN32) - FD_ZERO(&rdfds); - FD_SET(m_IntrPipe[0], &rdfds); - FD_SET(0, &rdfds); - timeval tv; - memset(&tv, 0, sizeof tv); - tv.tv_sec = 0; - tv.tv_usec = 100000; // 0.1 sec. - if (select(m_IntrPipe[0] + 1, &rdfds, NULL, NULL, &tv) != -1) - { - if (FD_ISSET(m_IntrPipe[0], &rdfds)) - { - char buf; - read(m_IntrPipe[0], &buf, 1); - interrupted = true; - } - else if (!FD_ISSET(0, &rdfds)) - { - // Both m_IntrPipe[0] and 0 are not ready, so this must be a timeout. - m_UNIXConsole.InputIdle(); - continue; - } - } - else - { - // Got interrupted by a signal. - assert(errno == EINTR); - interrupted = true; - } -#else - HANDLE handles[2]; - handles[0] = m_IntrEvent; - handles[1] = GetStdHandle(STD_INPUT_HANDLE); - DWORD result = WaitForMultipleObjects(2, handles, false, 10 /* 0.1 sec */); - switch (result) - { - case WAIT_OBJECT_0: - interrupted = true; - ResetEvent(m_IntrEvent); - break; - case WAIT_OBJECT_0 + 1: - break; - case WAIT_TIMEOUT: - m_UNIXConsole.InputIdle(); - continue; - case WAIT_FAILED: - assert(!"WaitForMultipleObjects() failed"); - } -#endif - if (interrupted) - { - if (m_Cancelled) - { - break; - } - m_UNIXConsole.Lock(); - m_UNIXConsole.CheckResize(); - m_UNIXConsole.Unlock(); - continue; - } - int c = getch(); - m_UNIXConsole.Lock(); - - // Handle prompt responses. - if (!m_UNIXConsole.m_Prompt.empty()) - { - bool acceptAll = false; - char response = 0; - if (strchr(m_UNIXConsole.m_PromptResponseChars, '@')) - { - acceptAll = true; - } - if (c == KEY_ENTER || c == '\r') - { - c = '\n'; - } - if (c == KEY_BACKSPACE || c == 0x7f) - { - c = '\010'; - } - if (c <= 0xff && strchr(m_UNIXConsole.m_PromptResponseChars, (char)c)) - { - response = (char)c; - } - else if (acceptAll && (isprint(c) || c == '\n')) - { - response = (char)c; - } - else - { - beep(); - m_UNIXConsole.Unlock(); - continue; - } - m_UNIXConsole.m_PromptResponse = response; - m_UNIXConsole.m_PromptCond.Notify(); - m_UNIXConsole.Unlock(); - continue; - } - - // if console is hided then pass only F10 key - if (!m_UNIXConsole.m_bShowConsole) - { - if (KEY_F(10) == c) - { - m_UNIXConsole.KeyF(10); - } - m_UNIXConsole.Unlock(); - continue; - } - - switch (c) - { - case ERR: - break; - case KEY_RESIZE: - // Window size changed. This key is received only if the ncurses - // library is configured to handle SIGWINCH and if no other SIGWINCH - // handler has been installed. - m_UNIXConsole.SetSize(COLS, LINES); - m_UNIXConsole.Repaint(); - break; - case KEY_ENTER: - case PADENTER: - case '\r': - case '\n': - m_UNIXConsole.KeyEnter(); - break; - case KEY_UP: - case '\020': // CTRL-P - m_UNIXConsole.KeyUp(); - break; - case KEY_DOWN: - case '\016': // CTRL-N - m_UNIXConsole.KeyDown(); - break; - case KEY_LEFT: - m_UNIXConsole.KeyLeft(); - break; - case KEY_RIGHT: - m_UNIXConsole.KeyRight(); - break; - case KEY_HOME: - case '\001': // CTRL-A - m_UNIXConsole.KeyHome(false); - break; - case CTL_HOME: - m_UNIXConsole.KeyHome(true); - break; - case KEY_END: - case '\005': // CTRL-E - m_UNIXConsole.KeyEnd(false); - break; - case CTL_END: - m_UNIXConsole.KeyEnd(true); - break; - case KEY_BACKSPACE: -#if defined(MAC) - // Mac OS X returns delete key instead of backspace - case 0x7f: -#else - case '\010': // CTRL-H -#endif - m_UNIXConsole.KeyBackspace(); - break; - case KEY_DC: - case KEY_SDC: - case '\004': // CTRL-D - m_UNIXConsole.KeyDelete(); - break; - case '\027': // CTRL-W - m_UNIXConsole.KeyDeleteWord(); - break; - case '\013': // CTRL-K - m_UNIXConsole.KeyKill(); - break; - case '\014': // CTRL-L - m_UNIXConsole.KeyRepaint(); - break; - case '\t': // TAB - m_UNIXConsole.KeyTab(); - break; - case KEY_NPAGE: - case '\006': // CTRL-F - m_UNIXConsole.KeyPgDown(false); - break; - case CTL_PGDN: - m_UNIXConsole.KeyPgDown(true); - break; - case KEY_PPAGE: - case '\002': // CTRL-B - m_UNIXConsole.KeyPgUp(false); - break; - case CTL_PGUP: - m_UNIXConsole.KeyPgUp(true); - break; - case KEY_F(10): - m_UNIXConsole.KeyF(10); - break; - case KEY_F(11): - m_UNIXConsole.KeyF(11); - break; - default: - if (c >= 0x20 && c <= 0xff) - { - m_UNIXConsole.Key(c); - } - break; - } - m_UNIXConsole.Unlock(); - } -} - -void CUNIXConsole::KeyF(int id) -{ -#ifdef LINUX - if (11 == id) - { - def_prog_mode(); - endwin(); - m_bShowConsole = false; - system("/bin/bash"); - reset_prog_mode(); - refresh(); - m_bShowConsole = true; - } - else if (10 == id) - { - if (m_bShowConsole) - { - def_prog_mode(); - endwin(); - m_bShowConsole = false; - } - else - { - reset_prog_mode(); - refresh(); - m_bShowConsole = true; - } - } -#endif -} - -CUNIXConsole* CUNIXConsoleSignalHandler::m_pUNIXConsole = NULL; - -void CUNIXConsoleSignalHandler::Handler(int signum) -{ -#if defined(NCURSES) - switch (signum) - { - case SIGWINCH: - m_pUNIXConsole->m_WindowResized = true; - m_pUNIXConsole->m_InputThread->Interrupt(); - break; - default: - break; - } -#endif -} - -#endif // USE_UNIXCONSOLE - -/////////////////////////////////////////////////////////////////////////////////////// -// -// simple light-weight console implementation -// -/////////////////////////////////////////////////////////////////////////////////////// -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(UnixConsole_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -CNULLConsole::CNULLConsole(bool isDaemonMode) - : m_isDaemon(isDaemonMode) -{ -} - -void CNULLConsole::Print(const char* inszText) -{ - if (m_isDaemon) - { - return; - } - -#if defined(WIN32) || defined(WIN64) - DWORD written; - char buf[1024]; - sprintf_s(buf, "%s\n", inszText); - WriteConsole(m_hOut, buf, strlen(buf), &written, NULL); -#elif defined(LINUX) || defined(MAC) - printf("%s\n", inszText); -#endif -} - -void CNULLConsole::OnInit(ISystem* pSystem) -{ - m_syslogStats.Init(); - - if (m_isDaemon) - { - return; - } - - IConsole* pConsole = pSystem->GetIConsole(); - pConsole->AddOutputPrintSink(this); - -#if defined(WIN32) || defined(WIN64) - AllocConsole(); - m_hOut = GetStdHandle(STD_OUTPUT_HANDLE); -#endif -} - -void CNULLConsole::OnUpdate() -{ -} - -void CNULLConsole::PutText([[maybe_unused]] int x, [[maybe_unused]] int y, [[maybe_unused]] const char* msg) -{ -} -#endif - -/////////////////////////////////////////////////////////////////////////////////////// -// -// Logging server internal statistics into syslog service -// -/////////////////////////////////////////////////////////////////////////////////////// -CSyslogStats::CSyslogStats() - : m_syslog_stats(0) - , m_syslog_period(SYSLOG_DEFAULT_PERIOD) -{ -} - -CSyslogStats::~CSyslogStats() -{ -#if (defined(LINUX) && !defined(ANDROID)) || defined(MAC) -#if defined(NCURSES) - closelog(); -#endif - if (gEnv->pConsole) - { - gEnv->pConsole->UnregisterVariable("syslog_stats"); - gEnv->pConsole->UnregisterVariable("syslog_period"); - } -#endif -} - -void CSyslogStats::Init() -{ -#if (defined(LINUX) && !defined(ANDROID)) || defined(MAC) -#if defined(NCURSES) -# if defined(LINUX) - openlog("LinuxLauncher", LOG_PID, LOG_USER); -# elif defined(MAC) - openlog("MacLauncher", LOG_PID, LOG_USER); -# endif -#endif // NCURSES - - if (gEnv->pConsole) - { - REGISTER_CVAR2("syslog_stats", &m_syslog_stats, 0, 0, "Start/Stop logging server info into syslog"); - REGISTER_CVAR2("syslog_period", &m_syslog_period, SYSLOG_DEFAULT_PERIOD, 0, "Syslog logging timeout period"); - } -#endif -} - -void CSyslogStats::Update([[maybe_unused]] float srvRate, [[maybe_unused]] int numPlayers) -{ -} - -#endif // defined(USE_DEDICATED_SERVER_CONSOLE) - -// vim:ts=2 - diff --git a/Code/CryEngine/CrySystem/UnixConsole.h b/Code/CryEngine/CrySystem/UnixConsole.h deleted file mode 100644 index 12b2852e69..0000000000 --- a/Code/CryEngine/CrySystem/UnixConsole.h +++ /dev/null @@ -1,573 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Console implementation for UNIX systems, based on curses ncurses. - - -#pragma once - - -#include -#include - -#if defined(USE_DEDICATED_SERVER_CONSOLE) - -class CSyslogStats -{ -public: - CSyslogStats(); - ~CSyslogStats(); - - void Init(); - void Update(float srvRate, int numPlayers); - -private: - int m_syslog_stats; - int m_syslog_period; - CTimeValue m_syslogStartTime; - CTimeValue m_syslogCurrTime; - static const int SYSLOG_DEFAULT_PERIOD = 3000; // default timeout (sec) -}; - -#if defined(USE_UNIXCONSOLE) - -#if defined(WIN32) -// Avoid naming conflict with wincon.h. -#undef MOUSE_MOVED -#endif - -#include -#include - -// Avoid naming conflicts with pdcurses. -// Use werase(stdscr) instead of erase(). -#undef erase -// Use wclear(stdscr) instead of clear(). -#undef clear -// (MATT) Could not compile CONTAINER_VALUE etc templates for Vector{Map,Set} in ISerialise apparently because of the -// clear and erase macros. Changed order to undefine them straight after pdcurses. {2009/04/09} - -#include - - -// Define if you wish to enable the player count feature. -// Note: The player count feature can not be used when building -// Windows-style DLLs! -#if defined(LINUX) || defined(MAC) -#define UC_ENABLE_PLAYER_COUNT 1 -#else -#undef UC_ENABLE_PLAYER_COUNT -#endif - -// Define if you wish to enable magic console commands. -// These are commands starting with an '@' character, which are intercepted by -// the CUNIXConsole class and not passed to the system. -//#undef UC_ENABLE_MAGIC_COMMANDS -#define UC_ENABLE_MAGIC_COMMANDS 1 - -class CUNIXConsoleInputThread; -class CUNIXConsoleSignalHandler; - - -class CUNIXConsole - : public ISystemUserCallback - , public IOutputPrintSink - , public ITextModeConsole -{ - friend class CUNIXConsoleInputThread; - friend class CUNIXConsoleSignalHandler; - - static const int DEFAULT_COLOR = -1; - - typedef CryMutex ConsoleLock; - ConsoleLock m_Lock; - static CryCriticalSectionNonRecursive m_cleanupLock; - - enum EConDrawOp - { - eCDO_PutText, - }; - struct SConDrawCmd - { - EConDrawOp op; - int x, y; - char text[256]; - }; - DynArray m_drawCmds; - DynArray m_newCmds; - bool m_fsMode; - - CSyslogStats m_syslogStats; - bool m_bShowConsole; // hide or show console - - SSystemUpdateStats m_updStats; - - bool IsLocked() { return m_Lock.IsLocked(); } - - // The header string. - // - // Should be set by the launcher through SetHeader(). - string m_HeaderString; - - // The line buffer. - // - // We'll use the escape sequence "\1" followed by a digit to encode color - // changes. - typedef std::deque TLineBuffer; - TLineBuffer m_LineBuffer; - - // The command queue. - // - // Commands typed on the console are added to this command queue. It is - // processed by the OnUpdate() callback. - typedef std::deque TCommandQueue; - TCommandQueue m_CommandQueue; - - // The command history. - // - // The UNIX console is decoupled from the system console object through a - // command queue, so we can't use the history buffer from the system - // console. This is our own command history. - // - // The history index indicates the reverse index (counting from the end) - // into our command history. The special value -1 indicates that we're not - // currently showing a command from the history. - typedef std::deque TCommandHistory; - TCommandHistory m_CommandHistory; - int m_HistoryIndex; - - // Interactive prompt. - // - // If this is not empty, then this prompt is shown in the command area. The - // input thread will wait for one if the response characters. The response is - // stored to m_PromptResponse and m_PromptCond is notified. - string m_Prompt; - char m_PromptResponseChars[16]; // Null-terminated. - char m_PromptResponse; - CryConditionVariable m_PromptCond; - - ISystem* m_pSystem; - IConsole* m_pConsole; - ITimer* m_pTimer; // Initialized on the first call to OnUpdate(). - - // Flag indicating if OnUpdate() has been called. - // - // The initialization of the console variable pointers for 'sv_map' and - // 'sv_gamerules' is deferred until the first iteration of the update loop, - // because OnInit() is called too early for that. - bool m_OnUpdateCalled; - CTimeValue m_LastUpdateTime; - - ICVar* m_svMap; - ICVar* m_svGameRules; - - // Terminal window layout. - // - // The terminal window is split into 4 logical windows. Top to bottom, - // these windows are: - // - Header window. May be empty (height 0). - // - Log window. This is the area in the middle of the terminal showing the - // log messages. - // - Status window. This is a window below the log window showing things - // like current FPS or other status information. - // - Command window. This is a few lines (typically 1 or 2) at the - // bottom of the terminal window. The command prompt and command line - // editor is shown in the command window. - // - // The layout is implementated as a single curses window - the standard - // screen (stdscr). - - // The width and height of the terminal window. - unsigned m_Width, m_Height; - - // The height of the header window. - // The header window is displayed at the top of the terminal window. - // Typically 0 (no header) or 1 (single header line). - unsigned m_HeaderHeight; - - // The height of the status window. - // This is typically a single line between the log window and the command - // window, displayed in inverse video. - unsigned m_StatusHeight; - - // The height of the command window. - // This is typically a single line at the bottom of the screen. - unsigned m_CmdHeight; - - // The current text color. - int m_Color; - - // The default text color pair (read from curses when the app starts). - int m_DefaultColorPair; - - // Flag indicating if color output is enabled. - bool m_EnableColor; - - // Flag indicating that the window has been resized. - // Set by the SIGWINCH signal handler. - bool m_WindowResized; - - // Flag indicating that OnShutdown() has been called. - bool m_OnShutdownCalled; - - // Flag indicating if the console has been initialized (i.e. Init() has been - // called). - bool m_Initialized; - - // Flag indicating if the implied console initialization (performed by the - // OnInit() callback) requires a dedicated server. - // This flag is set through the public SetRequireDedicatedServer() method. - bool m_RequireDedicatedServer; - - // The number of (logical) lines scrolled up. - // 0 indicates that we're at the bottom of the log. - int m_ScrollUp; - - // Array of color pair handles. - // 0: default terminal color - // 1: default terminal color, reverse video - // 2: blue - // 3: green - // 4: red, bold font - // 5: cyan - // 6: yellow on black, bold font - // 7: magenta - // 8: red, normal text - // 9: black on white - short m_ColorPair[10]; - - // The keyboard input thread. - CUNIXConsoleInputThread* m_InputThread; - - // The current input line, cursor position, and horizontal scroll position. - string m_InputLine; - string m_SavedInputLine; - int m_CursorPosition; - int m_ScrollPosition; - - // The current progress status string. - // - // Set by the OnInitProgress() method and cleared by OnUpdate(). If this is - // not empty, then this is shown in the status line. - string m_ProgressStatus; - - // Set the size of the terminal window. - // - // This method is called when the UNIX console is created and whenever the - // size of the terminal window changes (i.e. SIGWINCH received). - // - // We're relying on the ncurses handler for SIGWINCH, so we'll call this - // method when getch() returns KEY_RESIZE. - void SetSize(unsigned width, unsigned height); - - // Check if the terminal window is too small for drawing. - bool IsTooSmall(); - - // Check if the window size has changed. - void CheckResize(); - - // Get the height of the log window. - unsigned GetLogHeight() - { - return m_Height - m_HeaderHeight - m_StatusHeight - m_CmdHeight; - } - - // Scroll the log window and start a new log line. - // - // Move the cursor position to the beginning of the new log line. - void NewLine(); - - // Continue the last log line. - // - // Move the cursor position to the first character following the last - // character logged and update the current color. - void ContinueLine(); - - // Clear the current output line. - // - // Move the cursor to the beginning of the current output line. - // - // Note: This is a bit fuzzy to implement because long wrapped lines are not - // easy to deal with. Instead I'll simply call NewLine() and maybe - // implement this later. - void ClearLine() { NewLine(); } - - // Set the output color. - // - // The color is one of the 10 color codes (0-9) used by the graphical - // console. If color output is enabled, then the corresponding terminal - // color is set. If color output is not enabled, then only the text - // attributes are changed. - // - // In addition to setting the color (if enabled), the method will set the - // following terminal attributes: - // 0, 1: Normal text (black, white) - // 4, 6: Bold text (red, yellow, typically indicates an error or warning) - // other: Underlined text - void SetColor(int color = DEFAULT_COLOR); - void SetColorRaw(int color); - - // Write a single character or a sequence of characters to the console, - // using the currently specified color. The specified character must be a - // printable character. - // - // Note: - // - The Put(const char *) method will interpret '\n' as a line separator an - // call NewLine() when encountered. All other characters must be - // printable characters. - // - Both Put() methods will _not_ update the cursor position before writing - // the character to the screen. It is up to the caller to update the - // cursor position (either by calling NewLine() or ContinueLine()). - void Put(int c); - void Put(const char* s); - - // Get the length of the line (number of displayed characters), not counting - // color change escapes. - static unsigned GetLineLength(const string& line); - - // Get the last printable character from the specified line. It is an error - // if the specified line contains no printable characters. If color is not - // NULL, then the selected color for the last character is stored to *color. - static char GetLastCharacter(const string& line, int* color); - - // Get the height of a line of text. - // - // The method returns the number of terminal lines to display the specified - // line (wrapped). If column is not NULL, then *column is set to the column - // indicating the end of the last wrapped terminal line. - unsigned GetLineHeight(const string& line, unsigned* column = NULL); - - // Scroll the log window one line. - void ScrollLog(); - - // Flush/repaint the screen. - void Flush(); - - // Called by the input thread when idle. - void InputIdle(); - - // Lock/unlock the UNIX console. - void Lock() { m_Lock.Lock(); } - void Unlock() { m_Lock.Unlock(); } - - // Fix the cursor position and scroll position after updating the command - // input line. Returns true if the command window must be repainted. - bool FixCursorPosition(); - - // Called when the command line has been edited. - void OnEdit(); - - // Keyboard input. - void KeyEnter(); - void KeyUp(); - void KeyDown(); - void KeyLeft(); - void KeyRight(); - void KeyHome(bool ctrl); - void KeyEnd(bool ctrl); - void KeyBackspace(); - void KeyDelete(); - void KeyDeleteWord(); - void KeyKill(); - void KeyRepaint(); - void KeyTab(); - void KeyPgUp(bool ctrl); - void KeyPgDown(bool ctrl); - void KeyF(int id); - void Key(int c); - - // Drawing. - void Repaint(); - void DrawHeader(); - unsigned DrawLogLine(const string&, bool noOutput = false); - void DrawLog(); - void DrawFullscreen(); - void DrawStatus(int maxLines = -1); - void DrawCmd(bool cursorOnly = false); - void DrawCmdPrompt(); - - CUNIXConsole(const CUNIXConsole&); - void operator = (const CUNIXConsole&); - -public: - CUNIXConsole(); - ~CUNIXConsole(); - - // Set or clear the RequireDedicatedServer flag. - // The implied initialization call performed by the - // ISystemUserCallback::OnInit() depends on this flag. - // Note: This method _must_ be called before Init() or OnInit() is called. - void SetRequireDedicatedServer(bool); - - // Initialize the console for use. - // - // This method must be called before any other method of the console is - // called. - // It is perfectly valid to instanciate a console and not use it (i.e. skip - // the Init() call). - // - // Note: If the ISystemUserCallback interface is used, then the call to - // Init() is optional. OnInit() will call Init() if it has not been called - // already. - void Init(const char* headerString = NULL); - - // Check if the console is initialized. - bool IsInitialized() { return m_Initialized; } - - // Cleanup function. - // This method is called by the destructor. - // If the instance has not been initialized (via Init() and/or OnInit()), - // then this method has no effect. - void Cleanup(); - - // Set the header string. - // Note: - // - Setting the header string does _not_ trigger a redraw. - // - This method may be called before Init() has been called. - void SetHeader(const char* headerString) - { - Lock(); - m_HeaderString = headerString; - Unlock(); - } - - // Issue a query-response prompt. - // - // promptString is the string to be shown as the query prompt. - // responseChars is a null-terminated string of valid response characters. - // Add '@' to the response characters if the user may type any character. - // - // The method blocks the caller until the user has typed a response. The - // return value is the response character typed by the user. - DLL_EXPORT char Prompt(const char* promptString, const char* responseChars); - - // Check if the calling thread is the input thread. - // - // This may be used to make sure that you're not calling Prompt() from the - // input thread - which will deadlock. - DLL_EXPORT bool IsInputThread(); - - // Print formatted. Calls Print(). - DLL_EXPORT void PrintF(const char* format, ...) PRINTF_PARAMS(2, 3); - - // Interface IOutputPrintSink ///////////////////////////////////////////// - DLL_EXPORT virtual void Print(const char* line); - - // Interface ISystemUserCallback ////////////////////////////////////////// - virtual bool OnError(const char* errorString); - virtual bool OnSaveDocument() { return false; } - virtual bool OnBackupDocument() { return false; } - virtual void OnProcessSwitch() { } - virtual void OnInitProgress(const char* sProgressMsg); - virtual void OnInit(ISystem*); - virtual void OnShutdown(); - virtual void OnUpdate(); - virtual void GetMemoryUsage(ICrySizer* pSizer); - - // Interface ITextModeConsole ///////////////////////////////////////////// - virtual Vec2_tpl BeginDraw(); - virtual void PutText(int x, int y, const char* msg); - virtual void EndDraw(); -}; - -#endif // USE_UNIXCONSOLE - -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(UnixConsole_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// simple light-weight console -class CNULLConsole - : public IOutputPrintSink - , public ISystemUserCallback - , public ITextModeConsole -{ -public: - CNULLConsole(bool isDaemonMode); - - /////////////////////////////////////////////////////////////////////////////////////// - // IOutputPrintSink - /////////////////////////////////////////////////////////////////////////////////////// - virtual void Print(const char* inszText); - - /////////////////////////////////////////////////////////////////////////////////////// - // ISystemUserCallback - /////////////////////////////////////////////////////////////////////////////////////// - /** this method is called at the earliest point the ISystem pointer can be used - the log might not be yet there - */ - virtual void OnSystemConnect([[maybe_unused]] ISystem* pSystem) {}; - /** Signals to User that engine error occured. - @return true to Halt execution or false to ignore this error. - */ - virtual bool OnError([[maybe_unused]] const char* szErrorString) { return false; }; - /** If working in Editor environment notify user that engine want to Save current document. - This happens if critical error have occured and engine gives a user way to save data and not lose it - due to crash. - */ - virtual bool OnSaveDocument() { return false; } - - /** If working in Editor environment and a critical error occurs notify the user to backup - the current document to prevent data loss due to crash. - */ - virtual bool OnBackupDocument() { return false; } - - /** Notify user that system wants to switch out of current process. - (For ex. Called when pressing ESC in game mode to go to Menu). - */ - virtual void OnProcessSwitch() {}; - - // Notify user, usually editor about initialization progress in system. - virtual void OnInitProgress([[maybe_unused]] const char* sProgressMsg) {}; - - // Initialization callback. This is called early in CSystem::Init(), before - // any of the other callback methods is called. - virtual void OnInit(ISystem*); - - // Shutdown callback. - virtual void OnShutdown() {}; - - // Notify user of an update iteration. Called in the update loop. - virtual void OnUpdate(); - - // to collect the memory information in the user program/application - virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) {}; - - /////////////////////////////////////////////////////////////////////////////////////// - // ITextModeConsole - /////////////////////////////////////////////////////////////////////////////////////// - virtual Vec2_tpl BeginDraw() { return Vec2_tpl(0, 0); }; - virtual void PutText(int x, int y, const char* msg); - virtual void EndDraw() {}; - - void SetRequireDedicatedServer(bool) - { - // Does nothing - } - void SetHeader(const char*) - { - //Does nothing - } -private: -#if defined(WIN32) || defined(WIN64) - HANDLE m_hOut; -#endif - bool m_isDaemon; - CSyslogStats m_syslogStats; -}; - -#endif - -#endif // defined(USE_DEDICATED_SERVER_CONSOLE) diff --git a/Code/CryEngine/CrySystem/Validator.h b/Code/CryEngine/CrySystem/Validator.h deleted file mode 100644 index 83dc0533f6..0000000000 --- a/Code/CryEngine/CrySystem/Validator.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_VALIDATOR_H -#define CRYINCLUDE_CRYSYSTEM_VALIDATOR_H - -#pragma once - -////////////////////////////////////////////////////////////////////////// -// Default validator implementation. -////////////////////////////////////////////////////////////////////////// -struct SDefaultValidator - : public IValidator -{ - CSystem* m_pSystem; - SDefaultValidator(CSystem* system) - : m_pSystem(system) {}; - virtual void Report(SValidatorRecord& record) - { - if (record.text) - { - static bool bNoMsgBoxOnWarnings = false; - if ((record.text[0] == '!') || (m_pSystem->m_sysWarnings && m_pSystem->m_sysWarnings->GetIVal() != 0)) - { - if (g_cvars.sys_no_crash_dialog) - { - return; - } - - if (bNoMsgBoxOnWarnings) - { - return; - } - -#ifdef WIN32 - string strMessage = record.text; - strMessage += "\n---------------------------------------------\nAbort - terminate application\nRetry - continue running the application\nIgnore - don't show this message box any more"; - switch (::MessageBox(NULL, strMessage.c_str(), "CryEngine Warning", MB_ABORTRETRYIGNORE | MB_DEFBUTTON2 | MB_ICONWARNING | MB_SYSTEMMODAL)) - { - case IDABORT: - m_pSystem->GetIConsole()->Exit ("User abort requested during showing the warning box with the following message: %s", record.text); - break; - case IDRETRY: - break; - case IDIGNORE: - bNoMsgBoxOnWarnings = true; - m_pSystem->m_sysWarnings->Set(0); - break; - } -#endif - } - } - } -}; - -#endif // CRYINCLUDE_CRYSYSTEM_VALIDATOR_H diff --git a/Code/CryEngine/CrySystem/WindowsConsole.cpp b/Code/CryEngine/CrySystem/WindowsConsole.cpp deleted file mode 100644 index c83606890e..0000000000 --- a/Code/CryEngine/CrySystem/WindowsConsole.cpp +++ /dev/null @@ -1,1153 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : CWindowsConsole member definitions - - -#include "CrySystem_precompiled.h" -#include "System.h" -#include "WindowsConsole.h" - -#ifdef USE_WINDOWSCONSOLE - -#define WINDOWS_CONSOLE_WIDTH 128 -#define WINDOWS_CONSOLE_HEIGHT 50 -#define WINDOWS_CONSOLE_LOG_BUFFER_LINES 1024 -#define WINDOWS_CONSOLE_LOG_SCROLL_LINES 10 -#define WINDOWS_CONSOLE_TAB_SIZE 4 -#define WINDOWS_CONSOLE_CRYENGINE_BLACK 0x0 -#define WINDOWS_CONSOLE_CRYENGINE_WHITE 0x1 -#define WINDOWS_CONSOLE_CRYENGINE_BLUE 0x2 -#define WINDOWS_CONSOLE_CRYENGINE_GREEN 0x3 -#define WINDOWS_CONSOLE_CRYENGINE_RED 0x4 -#define WINDOWS_CONSOLE_CRYENGINE_CYAN 0x5 -#define WINDOWS_CONSOLE_CRYENGINE_YELLOW 0x6 -#define WINDOWS_CONSOLE_CRYENGINE_MAGENTA 0x7 -#define WINDOWS_CONSOLE_CRYENGINE_ORANGE 0x8 -#define WINDOWS_CONSOLE_CRYENGINE_GREY 0x9 -#define WINDOWS_CONSOLE_NATIVE_BLACK 0x0 -#define WINDOWS_CONSOLE_NATIVE_BROWN 0x6 -#define WINDOWS_CONSOLE_NATIVE_LIGHTGREY 0x7 -#define WINDOWS_CONSOLE_NATIVE_LIGHTBLUE 0x9 -#define WINDOWS_CONSOLE_NATIVE_LIGHTGREEN 0xA -#define WINDOWS_CONSOLE_NATIVE_LIGHTCYAN 0xB -#define WINDOWS_CONSOLE_NATIVE_LIGHTRED 0xC -#define WINDOWS_CONSOLE_NATIVE_LIGHTMAGENTA 0xD -#define WINDOWS_CONSOLE_NATIVE_YELLOW 0xE -#define WINDOWS_CONSOLE_NATIVE_WHITE 0xF -#define WINDOWS_CONSOLE_COLOR_MASK 0xF -#define WINDOWS_CONSOLE_BGCOLOR_SHIFT 4 - -const uint8 CWindowsConsole::s_colorTable[ WINDOWS_CONSOLE_NUM_CRYENGINE_COLORS ] = -{ - WINDOWS_CONSOLE_NATIVE_BLACK, - WINDOWS_CONSOLE_NATIVE_WHITE, - WINDOWS_CONSOLE_NATIVE_LIGHTBLUE, - WINDOWS_CONSOLE_NATIVE_LIGHTGREEN, - WINDOWS_CONSOLE_NATIVE_LIGHTRED, - WINDOWS_CONSOLE_NATIVE_LIGHTCYAN, - WINDOWS_CONSOLE_NATIVE_YELLOW, - WINDOWS_CONSOLE_NATIVE_LIGHTMAGENTA, - WINDOWS_CONSOLE_NATIVE_BROWN, - WINDOWS_CONSOLE_NATIVE_LIGHTGREY -}; - -CWindowsConsole::CWindowsConsole() - : m_lock() - , m_consoleScreenBufferSize() - , m_consoleWindow() - , m_inputBufferHandle(INVALID_HANDLE_VALUE) - , m_screenBufferHandle(INVALID_HANDLE_VALUE) - , m_logBuffer(0, 0, WINDOWS_CONSOLE_WIDTH, WINDOWS_CONSOLE_HEIGHT - 2, WINDOWS_CONSOLE_LOG_BUFFER_LINES, L' ', WINDOWS_CONSOLE_CRYENGINE_GREY, WINDOWS_CONSOLE_CRYENGINE_BLACK) - , m_fullScreenBuffer(0, 0, WINDOWS_CONSOLE_WIDTH, WINDOWS_CONSOLE_HEIGHT - 2, WINDOWS_CONSOLE_HEIGHT - 2, L' ', WINDOWS_CONSOLE_CRYENGINE_GREY, WINDOWS_CONSOLE_CRYENGINE_BLACK) - , m_statusBuffer(0, WINDOWS_CONSOLE_HEIGHT - 2, WINDOWS_CONSOLE_WIDTH, 1, 1, L' ', WINDOWS_CONSOLE_CRYENGINE_BLACK, WINDOWS_CONSOLE_CRYENGINE_GREY) - , m_commandBuffer(0, WINDOWS_CONSOLE_HEIGHT - 1, WINDOWS_CONSOLE_WIDTH, 1, 1, L' ', WINDOWS_CONSOLE_CRYENGINE_WHITE, WINDOWS_CONSOLE_CRYENGINE_BLACK) - , m_dirtyCellBuffers(0) - , m_commandQueue() - , m_commandPrompt("] ") - , m_commandPromptLength(m_commandPrompt.length()) - , m_command() - , m_commandCursor(0) - , m_logLine() - , m_progressString() - , m_header() - , m_updStats() - , m_pInputThread(NULL) - , m_pSystem(NULL) - , m_pConsole(NULL) - , m_pTimer(NULL) - , m_pCVarSvMap(NULL) - , m_pCVarSvMission(NULL) - , m_pCVarSvGameRules(NULL) - , m_lastStatusUpdate() - , m_lastUpdateTime() - , m_initialized(false) - , m_OnUpdateCalled(false) - , m_requireDedicatedServer(false) -{ -} - -CWindowsConsole::~CWindowsConsole() -{ - CleanUp(); -} - -Vec2_tpl< int > CWindowsConsole::BeginDraw() -{ - m_newCmds.resize(0); - return Vec2_tpl< int >(WINDOWS_CONSOLE_WIDTH, WINDOWS_CONSOLE_HEIGHT - 2); -} - -void CWindowsConsole::PutText(int x, int y, const char* pMsg) -{ - SConDrawCmd cmd; - - cmd.x = x; - cmd.y = y; - cry_strcpy(cmd.text, pMsg); - m_newCmds.push_back(cmd); -} - -void CWindowsConsole::EndDraw() -{ - Lock(); - m_drawCmds.swap(m_newCmds); - Unlock(); -} - -void CWindowsConsole::SetTitle(const char* title) -{ - m_title = title; - - if (m_title.empty()) - { - SetConsoleTitle(m_header.c_str()); - } - else - { - stack_string fullHeader = m_title + " - " + m_header; - SetConsoleTitle(fullHeader); - } -} - -void CWindowsConsole::Print(const char* pInszText) -{ - Lock(); - - bool isContinue = true; - const char* pInszTextPtr = pInszText; - const char* pLogLinePtr = m_logLine.c_str(); - - while (*pLogLinePtr && isContinue) - { - if (*pInszTextPtr != *pLogLinePtr) - { - isContinue = false; - } - - ++pInszTextPtr; - ++pLogLinePtr; - } - - // Do not treat lines as equal if the new line starts the same as the previous line - isContinue = isContinue && (*pInszTextPtr == 0 || m_logLine.empty()); - - if (!isContinue) - { - pInszTextPtr = pInszText; - m_logBuffer.NewLine(); - m_logLine.clear(); - } - - m_logLine.append(pInszTextPtr); - m_logBuffer.Print(pInszTextPtr); - m_dirtyCellBuffers |= eCBB_Log; - - Unlock(); -} - -bool CWindowsConsole::OnError([[maybe_unused]] const char* szErrorString) -{ - return true; -} - -bool CWindowsConsole::OnSaveDocument() -{ - return false; -} - -bool CWindowsConsole::OnBackupDocument() -{ - return false; -} - -void CWindowsConsole::OnProcessSwitch() -{ -} - -void CWindowsConsole::OnInitProgress(const char* sProgressMsg) -{ - if (m_initialized) - { - Lock(); - m_progressString = sProgressMsg; - DrawStatus(); - Unlock(); - } -} - -// the CtrlHandler will be called from a separate thread that only handles -// Ctrl messages. When the CLOSE event is sent, this function can just wait -// forever, as FreeConsole() will kill the thread. If this function returns -// immediately, windows will call TerminateProcess() and nothing will be cleaned up. -static BOOL WINAPI CtrlHandler(DWORD ctrlEvent) -{ - switch (ctrlEvent) - { - case CTRL_C_EVENT: - case CTRL_BREAK_EVENT: - case CTRL_LOGOFF_EVENT: - case CTRL_SHUTDOWN_EVENT: - return TRUE; - case CTRL_CLOSE_EVENT: - if ( (gEnv != nullptr) && (gEnv->pSystem != nullptr) && (gEnv->pSystem->GetIConsole() != nullptr) ) - { - gEnv->pSystem->GetIConsole()->ExecuteString("quit", true, true); - Sleep(INFINITE); - return TRUE; - } - default: - break; - } - return FALSE; -} - -void CWindowsConsole::OnInit(ISystem* pSystem) -{ - if (m_requireDedicatedServer && !gEnv->IsDedicated()) - { - return; - } - - Lock(); - - if (!m_initialized) - { - assert(m_pSystem == NULL); - assert(m_pConsole == NULL); - - m_pSystem = pSystem; - m_pConsole = pSystem->GetIConsole(); - - AllocConsole(); - m_inputBufferHandle = GetStdHandle(STD_INPUT_HANDLE); - m_screenBufferHandle = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleMode(m_inputBufferHandle, ENABLE_WINDOW_INPUT); - m_consoleScreenBufferSize.X = WINDOWS_CONSOLE_WIDTH; - m_consoleScreenBufferSize.Y = WINDOWS_CONSOLE_HEIGHT; - m_consoleWindow.Left = 0; - m_consoleWindow.Top = 0; - m_consoleWindow.Right = WINDOWS_CONSOLE_WIDTH - 1; - m_consoleWindow.Bottom = WINDOWS_CONSOLE_HEIGHT - 1; - SetConsoleScreenBufferSize(m_screenBufferHandle, m_consoleScreenBufferSize); - SetConsoleWindowInfo(m_screenBufferHandle, TRUE, &m_consoleWindow); - SetConsoleTitle(m_header.c_str()); - - if (m_pConsole) - { - m_pConsole->AddOutputPrintSink(this); - } - - DrawCommand(); - - m_pInputThread = new CWindowsConsoleInputThread(*this); - m_pInputThread->Start(); - -#if !defined(NDEBUG) - BOOL handlerInstalled = -#endif - SetConsoleCtrlHandler(CtrlHandler, TRUE); - CRY_ASSERT(handlerInstalled); - - m_initialized = true; - } - - Unlock(); -} - -void CWindowsConsole::OnShutdown() -{ - CleanUp(); -} - -void CWindowsConsole::OnUpdate() -{ - if (m_initialized) - { - Lock(); - - bool updateStatus = false; - - if (!m_OnUpdateCalled) - { - assert(m_pCVarSvMap == NULL); - assert(m_pCVarSvGameRules == NULL); - assert(m_pTimer == NULL); - - m_pCVarSvMap = m_pConsole->GetCVar("sv_map"); - m_pCVarSvGameRules = m_pConsole->GetCVar("sv_gamerules"); - m_pTimer = m_pSystem->GetITimer(); - m_OnUpdateCalled = true; - - assert(m_pCVarSvMission == NULL); - m_pCVarSvMission = m_pConsole->GetCVar("sv_mission"); - } - - if (!m_progressString.empty()) - { - m_progressString.clear(); - updateStatus = true; - } - - CTimeValue now = m_pTimer->GetAsyncTime(); - - if ((now - m_lastStatusUpdate).GetSeconds() > 0.1F) - { - updateStatus = true; - } - - m_lastUpdateTime = now; - - m_pSystem->GetUpdateStats(m_updStats); - - if (updateStatus) - { - DrawStatus(); - m_lastStatusUpdate = now; - } - - while (m_commandQueue.size()) - { - const string& command = m_commandQueue[0]; - Unlock(); - // 'm_pConsole' will be set to NULL when executing 'quit' command - // Cache pointer in local variable to prevent crash when adding the last command to the history - IConsole* pConsole = m_pConsole; - pConsole->ExecuteString(command.c_str()); - pConsole->AddCommandToHistory(command.c_str()); - Lock(); - m_commandQueue.pop_front(); - } - - if (!m_drawCmds.empty()) - { - DrawFull(); - } - - Repaint(); - - Unlock(); - } -} - -void CWindowsConsole::OnConsoleInputEvent(INPUT_RECORD inputRecord) -{ - switch (inputRecord.EventType) - { - case KEY_EVENT: - OnKey(inputRecord.Event.KeyEvent); - break; - case WINDOW_BUFFER_SIZE_EVENT: - OnResize(inputRecord.Event.WindowBufferSizeEvent.dwSize); - break; - } -} - -void CWindowsConsole::OnKey(const KEY_EVENT_RECORD& event) -{ - if (event.bKeyDown) - { - for (uint32 i = 0; i < event.wRepeatCount; ++i) - { - switch (event.wVirtualKeyCode) - { - case VK_BACK: - OnBackspace(); - break; - case VK_TAB: - OnTab(); - break; - case VK_RETURN: - OnReturn(); - break; - case VK_PRIOR: - OnPgUp(); - break; - case VK_NEXT: - OnPgDn(); - break; - case VK_LEFT: - OnLeft(); - break; - case VK_UP: - OnUp(); - break; - case VK_RIGHT: - OnRight(); - break; - case VK_DOWN: - OnDown(); - break; - case VK_DELETE: - OnDelete(); - break; - default: - OnChar(event.uChar.AsciiChar); - break; - } - } - } -} - -void CWindowsConsole::OnResize(const COORD& size) -{ - if ((size.X != m_consoleScreenBufferSize.X) || (size.Y != m_consoleScreenBufferSize.Y)) - { - SetConsoleScreenBufferSize(m_screenBufferHandle, m_consoleScreenBufferSize); - SetConsoleWindowInfo(m_screenBufferHandle, TRUE, &m_consoleWindow); - } -} - -void CWindowsConsole::OnBackspace() -{ - if (m_commandCursor > 0) - { - m_command.erase(--m_commandCursor, 1); - m_pConsole->ResetAutoCompletion(); - DrawCommand(); - } -} - -void CWindowsConsole::OnTab() -{ - const char* pCompletion; - - pCompletion = m_pConsole->ProcessCompletion(m_command.c_str()); - - if (pCompletion) - { - m_command = pCompletion; - m_commandCursor = m_command.length(); - DrawCommand(); - } -} - -void CWindowsConsole::OnReturn() -{ - m_commandQueue.push_back(m_command); - m_command.clear(); - m_pConsole->ResetAutoCompletion(); - m_commandCursor = 0; - DrawCommand(); -} - -void CWindowsConsole::OnPgUp() -{ - if (m_logBuffer.Scroll(-WINDOWS_CONSOLE_LOG_SCROLL_LINES)) - { - m_dirtyCellBuffers |= eCBB_Log; - } -} - -void CWindowsConsole::OnPgDn() -{ - if (m_logBuffer.Scroll(WINDOWS_CONSOLE_LOG_SCROLL_LINES)) - { - m_dirtyCellBuffers |= eCBB_Log; - } -} - -void CWindowsConsole::OnLeft() -{ - if (m_commandCursor > 0) - { - --m_commandCursor; - m_commandBuffer.SetCursor(m_screenBufferHandle, m_commandCursor + m_commandPromptLength); - } -} - -void CWindowsConsole::OnUp() -{ - OnHistory(m_pConsole->GetHistoryElement(true)); -} - -void CWindowsConsole::OnRight() -{ - if (m_commandCursor < m_command.length()) - { - ++m_commandCursor; - m_commandBuffer.SetCursor(m_screenBufferHandle, m_commandCursor + m_commandPromptLength); - } -} - -void CWindowsConsole::OnDown() -{ - OnHistory(m_pConsole->GetHistoryElement(false)); -} - -void CWindowsConsole::OnDelete() -{ - if (m_commandCursor < m_command.length()) - { - m_command.erase(m_commandCursor, 1); - m_pConsole->ResetAutoCompletion(); - DrawCommand(); - } -} - -void CWindowsConsole::OnChar(CHAR ch) -{ - if ((ch >= ' ') && (ch <= '~')) - { - m_command.insert(m_commandCursor++, ch); - m_pConsole->ResetAutoCompletion(); - DrawCommand(); - } -} - -void CWindowsConsole::OnHistory(const char* pHistoryElement) -{ - if (pHistoryElement) - { - m_command = pHistoryElement; - } - else - { - m_command.clear(); - } - - m_commandCursor = m_command.length(); - DrawCommand(); -} - -void CWindowsConsole::DrawCommand() -{ - m_commandBuffer.Clear(); - m_commandBuffer.PutText(0, 0, m_commandPrompt.c_str()); - m_commandBuffer.PutText(m_commandPromptLength, 0, m_command); - m_commandBuffer.SetCursor(m_screenBufferHandle, m_commandCursor + m_commandPromptLength); - m_dirtyCellBuffers |= eCBB_Command; -} - -void CWindowsConsole::GetMemoryUsage(ICrySizer* pSizer) -{ - pSizer->Add(this); - pSizer->Add(m_command); - pSizer->Add(m_logLine); - pSizer->Add(m_pInputThread); - m_logBuffer.GetMemoryUsage(pSizer); - m_fullScreenBuffer.GetMemoryUsage(pSizer); - m_statusBuffer.GetMemoryUsage(pSizer); - m_commandBuffer.GetMemoryUsage(pSizer); -} - -void CWindowsConsole::SetRequireDedicatedServer(bool value) -{ - m_requireDedicatedServer = value; -} - -void CWindowsConsole::SetHeader(const char* pHeader) -{ - m_header = pHeader; - SetConsoleTitle(pHeader); -} - -void CWindowsConsole::InputIdle() -{ - if (m_pTimer) - { - CTimeValue now = m_pTimer->GetAsyncTime(); - float timePassed = (now - m_lastUpdateTime).GetSeconds(); - - if (timePassed > 0.2F) - { - int nDots = ( int )(timePassed + 0.5) / 3; - int nDotsMax = m_statusBuffer.Width() - 2; - - if (nDots > nDotsMax) - { - nDots = nDotsMax; - } - - if (m_progressString.length() != nDots) - { - m_progressString.clear(); - m_progressString.append(nDots, '.'); - DrawStatus(); - } - } - } - - Repaint(); -} - -void CWindowsConsole::Lock() -{ - m_lock.Lock(); -} - -void CWindowsConsole::Unlock() -{ - m_lock.Unlock(); -} - -bool CWindowsConsole::TryLock() -{ - return m_lock.TryLock(); -} - -void CWindowsConsole::Repaint() -{ - if (m_dirtyCellBuffers) - { - if (m_dirtyCellBuffers & eCBB_Full) - { - m_fullScreenBuffer.Blit(m_screenBufferHandle); - m_dirtyCellBuffers &= ~eCBB_Full; - } - else if (m_dirtyCellBuffers & eCBB_Log) - { - m_logBuffer.Blit(m_screenBufferHandle); - m_dirtyCellBuffers &= ~eCBB_Log; - } - - if (m_dirtyCellBuffers & eCBB_Status) - { - m_statusBuffer.Blit(m_screenBufferHandle); - m_dirtyCellBuffers &= ~eCBB_Status; - } - - if (m_dirtyCellBuffers & eCBB_Command) - { - m_commandBuffer.Blit(m_screenBufferHandle); - m_dirtyCellBuffers &= ~eCBB_Command; - } - } -} - -void CWindowsConsole::DrawStatus() -{ - const char* pStatusLeft = NULL; - const char* pStatusRight = NULL; - char bufferLeft[ 256 ]; - char bufferRight[ 256 ]; - - // If we're scrolled, then the right size shows a scroll indicator. - if (m_logBuffer.IsScrolledUp()) - { - m_logBuffer.FmtScrollStatus(sizeof bufferRight, bufferRight); - bufferRight[ sizeof bufferRight - 1 ] = 0; - pStatusRight = bufferRight; - } - - if (!m_progressString.empty()) - { - azsnprintf(bufferLeft, sizeof bufferLeft, " %s", m_progressString.c_str()); - bufferLeft [sizeof bufferLeft - 1 ] = 0; - pStatusLeft = bufferLeft; - } - else if (m_OnUpdateCalled) - { - // Standard status display. - // Map name and game rules on the left. - // Current update rate and player count on the right. - - const char* pMapName = m_pCVarSvMap->GetString(); - - const char* pMissionName = m_pCVarSvMission ? m_pCVarSvMission->GetString() : ""; - azsnprintf(bufferLeft, sizeof bufferLeft, " mission: %s map:%s", pMissionName, pMapName); - - bufferLeft[ sizeof bufferLeft - 1 ] = 0; - pStatusLeft = bufferLeft; - - if (!pStatusRight) - { - float updateRate = 0.f; - - if (m_pTimer != NULL) - { - updateRate = m_pTimer->GetFrameRate(); - } - else - { - updateRate = 0.f; - } - - char* pBufferRight = bufferRight; - char* const pBufferRightEnd = bufferRight + sizeof bufferRight; - - azstrcpy(pBufferRight, AZ_ARRAY_SIZE(bufferRight), "| "); - pBufferRight += strlen(pBufferRight); - - if (pBufferRight < pBufferRightEnd) - { - if (m_pConsole != NULL) - { - pBufferRight += azsnprintf( - pBufferRight, - pBufferRightEnd - pBufferRight, - "upd:%.1fms(%.2f..%.2f) " \ - "rate:%.1f/s", - m_updStats.avgUpdateTime, m_updStats.minUpdateTime, m_updStats.maxUpdateTime, - updateRate); - } - else - { - cry_strcpy(pBufferRight, pBufferRightEnd - pBufferRight, "BUSY "); - } - } - - bufferRight[ sizeof bufferRight - 1 ] = 0; - pStatusRight = bufferRight; - } - } - - if (pStatusLeft == NULL) - { - pStatusLeft = ""; - } - - if (pStatusRight == NULL) - { - pStatusRight = ""; - } - - int rightWidth = strlen(pStatusRight); - - m_statusBuffer.Clear(); - m_statusBuffer.PutText(0, 0, pStatusLeft); - m_statusBuffer.PutText(-rightWidth, 0, pStatusRight); - m_dirtyCellBuffers |= eCBB_Status; -} - -void CWindowsConsole::CleanUp() -{ - Lock(); - - if (m_initialized) - { - if (m_pInputThread) - { - m_pInputThread->Cancel(); - - // The input thread may continue to lock before it gets our cancel event, so - // we need to release the lock until we confirm that it has canceled its operations. - Unlock(); - m_pInputThread->WaitForThread(); - Lock(); - - delete m_pInputThread; - m_pInputThread = NULL; - } - - if (m_pConsole) - { - m_pConsole->RemoveOutputPrintSink(this); - } - - m_pSystem = NULL; - m_pConsole = NULL; - m_pTimer = NULL; - m_pCVarSvMap = NULL; - m_pCVarSvGameRules = NULL; - m_inputBufferHandle = INVALID_HANDLE_VALUE; - m_screenBufferHandle = INVALID_HANDLE_VALUE; - m_initialized = false; - } - - Unlock(); -} - -void CWindowsConsole::DrawFull() -{ - for (DynArray< SConDrawCmd >::iterator iter = m_drawCmds.begin(); iter != m_drawCmds.end(); ++iter) - { - m_fullScreenBuffer.PutText(iter->x, iter->y, iter->text); - } - - m_dirtyCellBuffers |= eCBB_Full; -} - -CWindowsConsole::CCellBuffer::CCellBuffer(SHORT x, short y, SHORT w, SHORT h, SHORT lines, WCHAR emptyChar, uint8 defaultFgColor, uint8 defaultBgColor) -{ - m_emptyCell.Char.UnicodeChar = emptyChar; - m_emptyCell.Attributes = s_colorTable[ defaultFgColor ] | (s_colorTable[ defaultBgColor ] << WINDOWS_CONSOLE_BGCOLOR_SHIFT); - m_attr = m_emptyCell.Attributes; - m_size.X = w; - m_size.Y = lines; - m_screenArea.Left = x; - m_screenArea.Top = y; - m_screenArea.Right = x + w - 1; - m_screenArea.Bottom = y + h - 1; - m_position.head = 0; - m_position.lines = 1; - m_position.wrap = 0; - m_position.offset = 0; - m_position.scroll = 0; - m_escape = false; - m_color = false; - m_buffer.resize(w * lines, m_emptyCell); -} - -CWindowsConsole::CCellBuffer::~CCellBuffer() -{ -} - -void CWindowsConsole::CCellBuffer::PutText(int x, int y, const char* pMsg) -{ - SPosition position; - - position.head = m_position.head; - position.offset = x; - position.lines = y; - position.scroll = 0; - position.wrap = 0; - - if (position.offset < 0) - { - position.offset += m_screenArea.Right - 1; - } - - if (position.lines < 0) - { - position.lines += m_screenArea.Bottom - 1; - } - - Print(pMsg, position); -} - -void CWindowsConsole::CCellBuffer::Print(const char* pInszText) -{ - Print(pInszText, m_position); -} - -void CWindowsConsole::CCellBuffer::ClearCells(TBuffer::iterator pDst, TBuffer::iterator pDstEnd) -{ - std::fill(pDst, pDstEnd, m_emptyCell); -} - -bool CWindowsConsole::CCellBuffer::Scroll(SHORT numLines) -{ - bool result = false; - SHORT newScroll = m_position.scroll + numLines; - SHORT maxScroll = m_position.lines - 1 - (m_screenArea.Bottom - m_screenArea.Top); - - if (newScroll > maxScroll) - { - newScroll = maxScroll; - } - - if (newScroll < 0) - { - newScroll = 0; - } - - if (newScroll != m_position.scroll) - { - m_position.scroll = newScroll; - result = true; - } - - return result; -} - -void CWindowsConsole::CCellBuffer::SetCursor(HANDLE hScreenBuffer, SHORT offset) -{ - COORD position; - - position.X = m_screenArea.Left + offset; - position.Y = m_screenArea.Top; - SetConsoleCursorPosition(hScreenBuffer, position); -} - -void CWindowsConsole::CCellBuffer::AddCharacter(WCHAR ch, SPosition& position) -{ - if (position.offset == m_size.X) - { - WrapLine(position); - } - - int32 index = (((position.head + position.lines + m_size.Y - 1) % m_size.Y) * m_size.X) + position.offset; - - CHAR_INFO& info = m_buffer[ index ]; - - info.Attributes = m_attr; - info.Char.UnicodeChar = ch; - ++position.offset; -} - -void CWindowsConsole::CCellBuffer::WrapLine(SPosition& position) -{ - ++position.wrap; - AdvanceLine(position); -} - -void CWindowsConsole::CCellBuffer::NewLine() -{ - NewLine(m_position); -} - -void CWindowsConsole::CCellBuffer::NewLine(SPosition& position) -{ - m_attr = m_emptyCell.Attributes; - position.wrap = 0; - AdvanceLine(position); -} - -void CWindowsConsole::CCellBuffer::ClearLine(SPosition& position) -{ - ClearCells(m_buffer.begin() + ((position.head + position.lines - position.wrap) % m_size.Y) * m_size.X, m_buffer.begin() + ((position.head + position.lines + 1) % m_size.Y) * m_size.X); - position.lines -= position.wrap; - position.wrap = 0; - position.offset = 0; -} - -void CWindowsConsole::CCellBuffer::Tab(SPosition& position) -{ - do - { - AddCharacter(' ', position); - } while (position.offset % WINDOWS_CONSOLE_TAB_SIZE); -} - -void CWindowsConsole::CCellBuffer::Blit(HANDLE hScreenBuffer) -{ - COORD src; - SMALL_RECT dst; - - src.X = 0; - src.Y = (m_position.head + m_position.scroll) % m_size.Y; - dst = m_screenArea; - WriteConsoleOutput(hScreenBuffer, &*m_buffer.begin(), m_size, src, &dst); - - if ((m_size.Y - src.Y) < (m_screenArea.Bottom - m_screenArea.Top + 1)) - { - src.Y = 0; - dst.Top = dst.Bottom + 1; - dst.Bottom = m_screenArea.Bottom; - WriteConsoleOutput(hScreenBuffer, &*m_buffer.begin(), m_size, src, &dst); - } -} - -void CWindowsConsole::CCellBuffer::AdvanceLine(SPosition& position) -{ - position.offset = 0; - - if (position.lines == m_size.Y) - { - position.head = (position.head + 1) % m_size.Y; - } - else - { - ++position.lines; - - if (position.lines > m_screenArea.Bottom - m_screenArea.Top + 1) - { - ++position.scroll; - } - } - - TBuffer::iterator start = m_buffer.begin() + ((position.head + position.lines + m_size.Y - 1) % m_size.Y) * m_size.X; - TBuffer::iterator end = start + m_size.X; - - ClearCells(start, end); -} - -void CWindowsConsole::CCellBuffer::SetFgColor(WORD color) -{ - m_attr = (m_attr & ~WINDOWS_CONSOLE_COLOR_MASK) | s_colorTable[ color ]; -} - -void CWindowsConsole::CCellBuffer::Print(const char* pInszText, SPosition& position) -{ - while (*pInszText) - { - switch (*pInszText) - { - case '$': - if (!m_escape) - { - m_color = true; - break; - } - case '\\': - m_escape = !m_escape; - if (m_escape) - { - break; - } - case 'n': - if (m_escape) - { - case '\n': - NewLine(position); - m_escape = false; - break; - } - case 'r': - if (m_escape) - { - case '\r': - ClearLine(position); - m_escape = false; - break; - } - case 't': - if (m_escape) - { - case '\t': - Tab(position); - m_escape = false; - break; - } - default: - if (m_color) - { - if (isdigit(*pInszText)) - { - SetFgColor(*pInszText - '0'); - } - - m_color = false; - } - else - { - if (m_escape && (*pInszText != '\\')) - { - AddCharacter('\\', position); - } - AddCharacter(*pInszText, position); - } - m_escape = false; - break; - } - - ++pInszText; - } -} - -void CWindowsConsole::CCellBuffer::GetMemoryUsage(ICrySizer* pSizer) -{ - pSizer->Add(m_buffer); -} - -bool CWindowsConsole::CCellBuffer::IsScrolledUp() -{ - return (m_position.lines - m_position.scroll) > (m_screenArea.Bottom - m_screenArea.Top + 1); -} - -void CWindowsConsole::CCellBuffer::FmtScrollStatus(uint32 size, char* pBuffer) -{ - if (m_position.scroll) - { - azsnprintf(pBuffer, size, "| SCROLL: %.1f%%", 100.0F * static_cast< float >(m_position.scroll) / static_cast< float >(m_position.lines - (m_screenArea.Bottom - m_screenArea.Top + 1))); - } - else - { - cry_strcpy(pBuffer, size, "| SCROLL:TOP "); - } -} - -void CWindowsConsole::CCellBuffer::Clear() -{ - ClearCells(m_buffer.begin(), m_buffer.end()); -} - -SHORT CWindowsConsole::CCellBuffer::Width() -{ - return m_screenArea.Right - m_screenArea.Left + 1; -} - - -CWindowsConsoleInputThread::CWindowsConsoleInputThread(CWindowsConsole& console) - : m_WindowsConsole(console) -{ - m_handles[ eWH_Event ] = CreateEvent(NULL, TRUE, FALSE, NULL); - m_handles[ eWH_Console ] = m_WindowsConsole.m_inputBufferHandle; -} - -CWindowsConsoleInputThread::~CWindowsConsoleInputThread() -{ - CloseHandle(m_handles[ eWH_Event ]); -} - -void CWindowsConsoleInputThread::Run() -{ - bool cancelled = false; - - do - { - DWORD inputRecordCount = 0; - DWORD waitResult; - - waitResult = WaitForMultipleObjects(eWH_NumWaitHandles, m_handles, FALSE, 100); - - switch (waitResult) - { - case WAIT_OBJECT_0 + eWH_Event: - - cancelled = true; - break; - - case WAIT_OBJECT_0 + eWH_Console: - - ReadConsoleInput(m_WindowsConsole.m_inputBufferHandle, m_inputRecords, WINDOWS_CONSOLE_MAX_INPUT_RECORDS, &inputRecordCount); - - // FALL THROUGH - - case WAIT_TIMEOUT: - - if (inputRecordCount || (m_WindowsConsole.m_dirtyCellBuffers && !m_WindowsConsole.m_OnUpdateCalled)) - { - m_WindowsConsole.Lock(); - - if (inputRecordCount) - { - PINPUT_RECORD pInputRecordEnd = m_inputRecords + inputRecordCount; - - for (PINPUT_RECORD pInputRecord = m_inputRecords; pInputRecord < pInputRecordEnd; ++pInputRecord) - { - m_WindowsConsole.OnConsoleInputEvent(*pInputRecord); - } - - m_WindowsConsole.DrawCommand(); - } - else - { - m_WindowsConsole.InputIdle(); - } - - m_WindowsConsole.Unlock(); - } - - break; - } - } while (!cancelled); -} - -void CWindowsConsoleInputThread::Cancel() -{ - SetEvent(m_handles[ eWH_Event ]); -} - -#endif // def USE_WINDOWSCONSOLE diff --git a/Code/CryEngine/CrySystem/WindowsConsole.h b/Code/CryEngine/CrySystem/WindowsConsole.h deleted file mode 100644 index cfecd06db2..0000000000 --- a/Code/CryEngine/CrySystem/WindowsConsole.h +++ /dev/null @@ -1,245 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : CWindowsConsole class definition - - -#ifndef CRYINCLUDE_CRYSYSTEM_WINDOWSCONSOLE_H -#define CRYINCLUDE_CRYSYSTEM_WINDOWSCONSOLE_H -#pragma once - - -#include -#include - -#if defined(USE_WINDOWSCONSOLE) - -class CWindowsConsole; -class CWindowsConsoleInputThread; - -#define WINDOWS_CONSOLE_MAX_INPUT_RECORDS 256 -#define WINDOWS_CONSOLE_NUM_CRYENGINE_COLORS 10 - -class CWindowsConsoleInputThread - : public CrySimpleThread<> -{ -public: - CWindowsConsoleInputThread(CWindowsConsole& console); - - ~CWindowsConsoleInputThread(); - - virtual void Run(); - virtual void Cancel(); - void Interrupt() - { - } - -private: - - enum EWaitHandle - { - eWH_Event, - eWH_Console, - eWH_NumWaitHandles - }; - - CWindowsConsole& m_WindowsConsole; - HANDLE m_handles[ eWH_NumWaitHandles ]; - INPUT_RECORD m_inputRecords[ WINDOWS_CONSOLE_MAX_INPUT_RECORDS ]; -}; - -class CWindowsConsole - : public ITextModeConsole - , public IOutputPrintSink - , public ISystemUserCallback -{ -public: - - CWindowsConsole(); - virtual ~CWindowsConsole(); - - // ITextModeConsole - virtual Vec2_tpl< int > BeginDraw(); - virtual void PutText(int x, int y, const char* pMsg); - virtual void EndDraw(); - virtual void SetTitle(const char* title); - - // ~ITextModeConsole - - // IOutputPrintSink - virtual void Print(const char* pInszText); - // ~IOutputPrintSink - - // ISystemUserCallback - virtual bool OnError(const char* szErrorString); - virtual bool OnSaveDocument(); - virtual bool OnBackupDocument(); - virtual void OnProcessSwitch(); - virtual void OnInitProgress(const char* sProgressMsg); - virtual void OnInit(ISystem* pSystem); - virtual void OnShutdown(); - virtual void OnUpdate(); - virtual void GetMemoryUsage(ICrySizer* pSizer); - // ~ISystemUserCallback - - void SetRequireDedicatedServer(bool value); - void SetHeader(const char* pHeader); - void InputIdle(); - -private: - - struct SConDrawCmd - { - int x; - int y; - char text[ 256 ]; - }; - - DynArray m_drawCmds; - DynArray m_newCmds; - - enum ECellBuffer - { - eCB_Log, - eCB_Full, - eCB_Status, - eCB_Command, - eCB_NumCellBuffers - }; - - enum ECellBufferBit - { - eCBB_Log = BIT(eCB_Log), - eCBB_Full = BIT(eCB_Full), - eCBB_Status = BIT(eCB_Status), - eCBB_Command = BIT(eCB_Command) - }; - - class CCellBuffer - { - public: - - CCellBuffer(SHORT x, short y, SHORT w, SHORT h, SHORT lines, WCHAR emptyChar, uint8 defaultFgColor, uint8 defaultBgColor); - ~CCellBuffer(); - - void PutText(int x, int y, const char* pMsg); - void Print(const char* pInszText); - void NewLine(); - void SetCursor(HANDLE hScreenBuffer, SHORT offset); - void SetFgColor(WORD color); - void Blit(HANDLE hScreenBuffer); - bool Scroll(SHORT numLines); - bool IsScrolledUp(); - void FmtScrollStatus(uint32 size, char* pBuffer); - void GetMemoryUsage(ICrySizer* pSizer); - void Clear(); - SHORT Width(); - - private: - - struct SPosition - { - SHORT head; - SHORT lines; - SHORT wrap; - SHORT offset; - SHORT scroll; - }; - - typedef std::vector< CHAR_INFO > TBuffer; - - void Print(const char* pInszText, SPosition& position); - void AddCharacter(WCHAR ch, SPosition& position); - void NewLine(SPosition& position); - void ClearLine(SPosition& position); - void Tab(SPosition& position); - void WrapLine(SPosition& position); - void AdvanceLine(SPosition& position); - void ClearCells(TBuffer::iterator pDst, TBuffer::iterator pDstEnd); - - TBuffer m_buffer; - CHAR_INFO m_emptyCell; - WORD m_attr; - COORD m_size; - SMALL_RECT m_screenArea; - SPosition m_position; - bool m_escape; - bool m_color; - }; - - void Lock(); - void Unlock(); - bool TryLock(); - void OnConsoleInputEvent(INPUT_RECORD inputRecord); - void OnKey(const KEY_EVENT_RECORD& event); - void OnResize(const COORD& size); - void OnBackspace(); - void OnTab(); - void OnReturn(); - void OnPgUp(); - void OnPgDn(); - void OnLeft(); - void OnUp(); - void OnRight(); - void OnDown(); - void OnDelete(); - void OnHistory(const char* pHistoryElement); - void OnChar(CHAR ch); - void DrawFull(); - void DrawStatus(); - void DrawCommand(); - void Repaint(); - void CleanUp(); - - CryCriticalSection m_lock; - COORD m_consoleScreenBufferSize; - SMALL_RECT m_consoleWindow; - HANDLE m_inputBufferHandle; - HANDLE m_screenBufferHandle; - CCellBuffer m_logBuffer; - CCellBuffer m_fullScreenBuffer; - CCellBuffer m_statusBuffer; - CCellBuffer m_commandBuffer; - uint32 m_dirtyCellBuffers; - std::deque< CryStringT< char > > m_commandQueue; - CryStringT< char > m_commandPrompt; - uint32 m_commandPromptLength; - CryStringT< char > m_command; - uint32 m_commandCursor; - CryStringT< char > m_logLine; - CryStringT< char > m_progressString; - CryStringT< char > m_header; - SSystemUpdateStats m_updStats; - CWindowsConsoleInputThread* m_pInputThread; - ISystem* m_pSystem; - IConsole* m_pConsole; - ITimer* m_pTimer; - ICVar* m_pCVarSvMap; - ICVar* m_pCVarSvMission; - CryStringT< char > m_title; - - ICVar* m_pCVarSvGameRules; - CTimeValue m_lastStatusUpdate; - CTimeValue m_lastUpdateTime; - bool m_initialized; - bool m_OnUpdateCalled; - bool m_requireDedicatedServer; - - static const uint8 s_colorTable[ WINDOWS_CONSOLE_NUM_CRYENGINE_COLORS ]; - - friend class CWindowsConsoleInputThread; -}; - -#endif // USE_WINDOWSCONSOLE - -#endif // CRYINCLUDE_CRYSYSTEM_WINDOWSCONSOLE_H diff --git a/Code/CryEngine/CrySystem/WindowsErrorReporting.cpp b/Code/CryEngine/CrySystem/WindowsErrorReporting.cpp deleted file mode 100644 index bd6f0c3ee2..0000000000 --- a/Code/CryEngine/CrySystem/WindowsErrorReporting.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Support for Windows Error Reporting (WER) - - -#include "CrySystem_precompiled.h" - -#ifdef WIN32 - -#include "System.h" -#include -#include -#include "errorrep.h" -#include "ISystem.h" - -#include - -static WCHAR szPath[MAX_PATH + 1]; -static WCHAR szFR[] = L"\\System32\\FaultRep.dll"; - -WCHAR* GetFullPathToFaultrepDll(void) -{ - UINT rc = GetSystemWindowsDirectoryW(szPath, ARRAYSIZE(szPath)); - if (rc == 0 || rc > ARRAYSIZE(szPath) - ARRAYSIZE(szFR) - 1) - { - return NULL; - } - - wcscat_s(szPath, szFR); - return szPath; -} - - -typedef BOOL (WINAPI * MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, - CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, - CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, - CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam - ); - -////////////////////////////////////////////////////////////////////////// -LONG WINAPI CryEngineExceptionFilterMiniDump(struct _EXCEPTION_POINTERS* pExceptionPointers, const char* szDumpPath, MINIDUMP_TYPE DumpType) -{ - // note: In debug mode, this dll is loaded on startup anyway, so this should not incur an additional load unless it crashes - // very early during startup. - - fflush(nullptr); // according to MSDN on fflush, calling fflush on null flushes all buffers. - HMODULE hndDBGHelpDLL = LoadLibraryA("DBGHELP.DLL"); - - if (!hndDBGHelpDLL) - { - CryLogAlways("Failed to record DMP file: Could not open DBGHELP.DLL"); - return EXCEPTION_CONTINUE_SEARCH; - } - - MINIDUMPWRITEDUMP dumpFnPtr = (MINIDUMPWRITEDUMP)::GetProcAddress(hndDBGHelpDLL, "MiniDumpWriteDump"); - if (!dumpFnPtr) - { - CryLogAlways("Failed to record DMP file: Unable to find MiniDumpWriteDump in DBGHELP.DLL"); - return EXCEPTION_CONTINUE_SEARCH; - } - - HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - CryLogAlways("Failed to record DMP file: could not open file '%s' for writing - error code: %d", szDumpPath, GetLastError()); - return EXCEPTION_CONTINUE_SEARCH; - } - - _MINIDUMP_EXCEPTION_INFORMATION ExInfo; - ExInfo.ThreadId = ::GetCurrentThreadId(); - ExInfo.ExceptionPointers = pExceptionPointers; - ExInfo.ClientPointers = NULL; - - BOOL bOK = dumpFnPtr(GetCurrentProcess(), GetCurrentProcessId(), hFile, DumpType, &ExInfo, NULL, NULL); - ::CloseHandle(hFile); - - if (bOK) - { - CryLogAlways("Successfully recorded DMP file: '%s'", szDumpPath); - return EXCEPTION_EXECUTE_HANDLER; // SUCCESS! you can execute your handlers now - } - else - { - CryLogAlways("Failed to record DMP file: '%s' - error code: %d", szDumpPath, GetLastError()); - } - - return EXCEPTION_CONTINUE_SEARCH; -} - -/* -struct AutoSetCryEngineExceptionFilter -{ - AutoSetCryEngineExceptionFilter() - { - WCHAR * psz = GetFullPathToFaultrepDll(); - SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); - } -}; -AutoSetCryEngineExceptionFilter g_AutoSetCryEngineExceptionFilter; -*/ - -////////////////////////////////////////////////////////////////////////// -LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers) -{ - if (g_cvars.sys_WER > 1) - { - char szScratch [_MAX_PATH]; - const char* szDumpPath = gEnv->pCryPak->AdjustFileName("@log@/CE2Dump.dmp", szScratch, AZ_ARRAY_SIZE(szScratch), 0); - - MINIDUMP_TYPE mdumpValue = (MINIDUMP_TYPE)(MiniDumpNormal); - if (g_cvars.sys_WER > 1) - { - mdumpValue = (MINIDUMP_TYPE)(g_cvars.sys_WER - 2); - } - - return CryEngineExceptionFilterMiniDump(pExceptionPointers, szDumpPath, mdumpValue); - } - - LONG lRet = EXCEPTION_CONTINUE_SEARCH; - WCHAR* psz = GetFullPathToFaultrepDll(); - if (psz) - { - HMODULE hFaultRepDll = LoadLibraryW(psz); - if (hFaultRepDll) - { - pfn_REPORTFAULT pfn = (pfn_REPORTFAULT)GetProcAddress(hFaultRepDll, "ReportFault"); - if (pfn) - { - pfn(pExceptionPointers, 0); - lRet = EXCEPTION_EXECUTE_HANDLER; - } - FreeLibrary(hFaultRepDll); - } - } - return lRet; -} - - -#endif // WIN32 - diff --git a/Code/CryEngine/CrySystem/ZLibCompressor.cpp b/Code/CryEngine/CrySystem/ZLibCompressor.cpp deleted file mode 100644 index 94d327940c..0000000000 --- a/Code/CryEngine/CrySystem/ZLibCompressor.cpp +++ /dev/null @@ -1,336 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "CryZlib.h" -#include "ZLibCompressor.h" -#include "TypeInfo_impl.h" -#include - -// keep these in sync with the enums in IZLibCompressor.h -static const int k_stratMap[] = {Z_DEFAULT_STRATEGY, Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE}; -static const int k_methodMap[] = {Z_DEFLATED}; -static const int k_flushMap[] = {Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH}; - -struct CZLibDeflateStream - : public IZLibDeflateStream -{ -protected: - virtual ~CZLibDeflateStream(); - -protected: - z_stream m_compressStream; - int m_zSize; - int m_zPeak; - int m_level; - int m_windowBits; - int m_memLevel; - int m_zlibFlush; - int m_bytesInput; - int m_bytesOutput; - EZLibStrategy m_strategy; - EZLibMethod m_method; - EZDeflateState m_curState; - bool m_streamOpened; - - - static voidpf ZAlloc( - voidpf pInOpaque, - uInt inItems, - uInt inSize); - static void ZFree( - voidpf pInOpaque, - voidpf pInAddress); - - EZDeflateState RunDeflate(); - -public: - CZLibDeflateStream( - int inLevel, - EZLibMethod inMethod, - int inWindowBits, - int inMemLevel, - EZLibStrategy inStrategy, - EZLibFlush inFlushMethod); - - virtual void SetOutputBuffer( - char* pInBuffer, - int inSize); - virtual int GetBytesOutput(); - - virtual void Input( - const char* pInSource, - int inSourceSize); - virtual void EndInput(); - - virtual EZDeflateState GetState(); - - virtual void GetStats( - SStats* pOutStats); - - virtual void Release(); -}; - -inline static int Lookup(int inIndex, const int* pInValues, [[maybe_unused]] int inMaxValues) -{ - CRY_ASSERT_MESSAGE(inIndex >= 0 && inIndex < inMaxValues, "CZLibDeflateStream mapping invalid"); - return pInValues[inIndex]; -} - -IZLibDeflateStream* CZLibCompressor::CreateDeflateStream(int inLevel, EZLibMethod inMethod, int inWindowBits, int inMemLevel, EZLibStrategy inStrategy, EZLibFlush inFlushMethod) -{ - return new CZLibDeflateStream(inLevel, inMethod, inWindowBits, inMemLevel, inStrategy, inFlushMethod); -} - -void CZLibCompressor::Release() -{ - delete this; -} - -void CZLibCompressor::MD5Init(SMD5Context* pIOCtx) -{ - COMPILE_TIME_ASSERT(sizeof(*pIOCtx) == sizeof(MD5Context)); - - ::MD5Init((MD5Context*)pIOCtx); -} - -void CZLibCompressor::MD5Update(SMD5Context* pIOCtx, const char* pInBuff, unsigned int len) -{ - ::MD5Update((MD5Context*)pIOCtx, (unsigned char*)pInBuff, len); -} - -void CZLibCompressor::MD5Final(SMD5Context* pIOCtx, char outDigest[16]) -{ - ::MD5Final((unsigned char*)outDigest, (MD5Context*)pIOCtx); -} - -CZLibCompressor::~CZLibCompressor() -{ -} - -CZLibDeflateStream::CZLibDeflateStream( - int inLevel, - EZLibMethod inMethod, - int inWindowBits, - int inMemLevel, - EZLibStrategy inStrategy, - EZLibFlush inFlushMethod) - : m_zSize(0) - , m_zPeak(0) - , m_level(inLevel) - , m_windowBits(inWindowBits) - , m_memLevel(inMemLevel) - , m_bytesInput(0) - , m_bytesOutput(0) - , m_strategy(inStrategy) - , m_method(inMethod) - , m_curState(eZDefState_AwaitingInput) - , m_streamOpened(false) -{ - memset(&m_compressStream, 0, sizeof(m_compressStream)); - m_zlibFlush = Lookup(inFlushMethod, k_flushMap, ARRAY_COUNT(k_flushMap)); -} - -CZLibDeflateStream::~CZLibDeflateStream() -{ -} - -void CZLibDeflateStream::Release() -{ - if (m_streamOpened) - { - int err = deflateEnd(&m_compressStream); - if (err != Z_OK) - { - CryLog("zlib deflateEnd() error %d returned when closing stream", err); - } - } - delete this; -} - -void CZLibDeflateStream::SetOutputBuffer( - char* pInBuffer, - int inSize) -{ - m_bytesOutput += m_compressStream.total_out; - - m_compressStream.next_out = (byte*)pInBuffer; - m_compressStream.avail_out = inSize; - m_compressStream.total_out = 0; -} - -void CZLibDeflateStream::GetStats( - IZLibDeflateStream::SStats* pOutStats) -{ - pOutStats->bytesInput = m_bytesInput; - pOutStats->bytesOutput = m_bytesOutput + m_compressStream.total_out; - pOutStats->curMemoryUsed = m_zSize; - pOutStats->peakMemoryUsed = m_zPeak; -} - -int CZLibDeflateStream::GetBytesOutput() -{ - return m_compressStream.total_out; -} - -void CZLibDeflateStream::Input( - const char* pInSource, - int inSourceSize) -{ - CRY_ASSERT_MESSAGE(m_curState == eZDefState_AwaitingInput, "CZLibDeflateStream::Input() called when stream is not awaiting input"); - - m_compressStream.next_in = (Bytef*)pInSource; - m_compressStream.avail_in = inSourceSize; - m_bytesInput += inSourceSize; -} - -void CZLibDeflateStream::EndInput() -{ - CRY_ASSERT_MESSAGE(m_curState == eZDefState_AwaitingInput, "CZLibDeflateStream::EndInput() called when stream is not awaiting input"); - - m_zlibFlush = Z_FINISH; -} - -voidpf CZLibDeflateStream::ZAlloc( - voidpf pInOpaque, - uInt inItems, - uInt inSize) -{ - CZLibDeflateStream* pStr = reinterpret_cast(pInOpaque); - - int size = inItems * inSize; - - int* ptr = (int*) CryModuleMalloc(sizeof(int) + size); - if (ptr) - { - *ptr = inItems * inSize; - ptr += 1; - - int newSize = pStr->m_zSize + size; - pStr->m_zSize = newSize; - if (newSize > pStr->m_zPeak) - { - pStr->m_zPeak = newSize; - } - } - return ptr; -} - -void CZLibDeflateStream::ZFree( - voidpf pInOpaque, - voidpf pInAddress) -{ - int* pPtr = reinterpret_cast(pInAddress); - if (pPtr) - { - CZLibDeflateStream* pStr = reinterpret_cast(pInOpaque); - pStr->m_zSize -= pPtr[-1]; - CryModuleFree(pPtr - 1); - } -} - -EZDeflateState CZLibDeflateStream::RunDeflate() -{ - bool runDeflate = false; - bool inputAvailable = (m_compressStream.avail_in > 0) || (m_zlibFlush == Z_FINISH); - bool outputAvailable = (m_compressStream.avail_out > 0); - - switch (m_curState) - { - case eZDefState_AwaitingInput: - case eZDefState_ConsumeOutput: - if (inputAvailable && outputAvailable) - { - runDeflate = true; - } - else if (inputAvailable || !outputAvailable) - { - m_curState = eZDefState_ConsumeOutput; - } - else - { - m_curState = eZDefState_AwaitingInput; - } - break; - - case eZDefState_Finished: - break; - - case eZDefState_Deflating: - CRY_ASSERT_MESSAGE(0, "Shouldn't be trying to run deflate whilst a deflate is in progress"); - break; - - case eZDefState_Error: - break; - - default: - CRY_ASSERT_MESSAGE(0, "unknown state"); - break; - } - - if (runDeflate) - { - if (!m_streamOpened) - { - m_streamOpened = true; - - // initialising with deflateInit2 requires that the next_in be initialised - m_compressStream.zalloc = &CZLibDeflateStream::ZAlloc; - m_compressStream.zfree = &CZLibDeflateStream::ZFree; - m_compressStream.opaque = this; - - int error = deflateInit2(&m_compressStream, m_level, Lookup(m_method, k_methodMap, ARRAY_COUNT(k_methodMap)), m_windowBits, m_memLevel, Lookup(m_strategy, k_stratMap, ARRAY_COUNT(k_stratMap))); - if (error != Z_OK) - { - m_curState = eZDefState_Error; - CryLog("zlib deflateInit2() error, err %d", error); - } - } - - if (m_curState != eZDefState_Error) - { - int error = deflate(&m_compressStream, m_zlibFlush); - - if (error == Z_STREAM_END) - { - // end of stream has been generated, only produced if we pass Z_FINISH into deflate - m_curState = eZDefState_Finished; - } - else if ((error == Z_OK && m_compressStream.avail_out == 0) || (error == Z_BUF_ERROR && m_compressStream.avail_out == 0)) - { - // output buffer has been filled - // data should be available for consumption by caller - m_curState = eZDefState_ConsumeOutput; - } - else if (m_compressStream.avail_in == 0) - { - // ran out of input data - // data may be available for consumption - but we need more input right now - m_curState = eZDefState_AwaitingInput; - } - else - { - // some sort of error has occurred - m_curState = eZDefState_Error; - CryLog("zlib deflate() error, err %d", error); - } - } - } - - return m_curState; -} - -EZDeflateState CZLibDeflateStream::GetState() -{ - return RunDeflate(); -} diff --git a/Code/CryEngine/CrySystem/ZLibCompressor.h b/Code/CryEngine/CrySystem/ZLibCompressor.h deleted file mode 100644 index 4c026d965f..0000000000 --- a/Code/CryEngine/CrySystem/ZLibCompressor.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_ZLIBCOMPRESSOR_H -#define CRYINCLUDE_CRYSYSTEM_ZLIBCOMPRESSOR_H -#pragma once - - -#include "IZLibCompressor.h" - -class CZLibCompressor - : public IZLibCompressor -{ -protected: - virtual ~CZLibCompressor(); - -public: - virtual IZLibDeflateStream* CreateDeflateStream(int inLevel, EZLibMethod inMethod, int inWindowBits, int inMemLevel, EZLibStrategy inStrategy, EZLibFlush inFlushMethod); - virtual void Release(); - - virtual void MD5Init(SMD5Context* pIOCtx); - virtual void MD5Update(SMD5Context* pIOCtx, const char* pInBuff, unsigned int len); - virtual void MD5Final(SMD5Context * pIOCtx, char outDigest[16]); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_ZLIBCOMPRESSOR_H diff --git a/Code/CryEngine/CrySystem/ZLibDecompressor.cpp b/Code/CryEngine/CrySystem/ZLibDecompressor.cpp deleted file mode 100644 index d75baf2c69..0000000000 --- a/Code/CryEngine/CrySystem/ZLibDecompressor.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : zlib inflate wrapper - - -#include "CrySystem_precompiled.h" - -#include "CryZlib.h" -#include "ZLibDecompressor.h" - -class CZLibInflateStream - : public IZLibInflateStream -{ -public: - CZLibInflateStream() - : m_bStreamOpened(false) - , m_zlibFlush(0) - , m_currentState(eZInfState_AwaitingInput) - , m_bytesInput(0) - , m_bytesOutput(0) - , m_zSize(0) - , m_zPeak(0) {} - - virtual void Release(); - - virtual void SetOutputBuffer(char* pInBuffer, unsigned int inSize); - virtual unsigned int GetBytesOutput(); - virtual void Input(const char* pInSource, unsigned int inSourceSize); - virtual void EndInput(); - virtual EZInflateState GetState(); - virtual void GetStats(IZLibInflateStream::SStats* pOutStats); - -private: - virtual ~CZLibInflateStream() {} - - EZInflateState RunInflate(); - - static voidpf ZAlloc(voidpf pInOpaque, uInt inItems, uInt inSize); - static void ZFree(voidpf pInOpaque, voidpf pInAddress); - - z_stream m_decompressStream; - bool m_bStreamOpened; - int m_zlibFlush; - EZInflateState m_currentState; - unsigned int m_bytesInput; - unsigned int m_bytesOutput; - unsigned int m_zSize; - unsigned int m_zPeak; -}; - -IZLibInflateStream* CZLibDecompressor::CreateInflateStream() -{ - return new CZLibInflateStream(); -} - -void CZLibDecompressor::Release() -{ - delete this; -} - -void CZLibInflateStream::Release() -{ - if (m_bStreamOpened) - { - int err = inflateEnd(&m_decompressStream); - if (err != Z_OK) - { - CryLog("zlib inflateEnd() error %d returned when closing stream", err); - } - } - - delete this; -} - -void CZLibInflateStream::SetOutputBuffer(char* pInBuffer, unsigned int inSize) -{ - m_bytesOutput += m_decompressStream.total_out; - - m_decompressStream.next_out = (byte*)pInBuffer; - m_decompressStream.avail_out = inSize; - m_decompressStream.total_out = 0; -} - -void CZLibInflateStream::GetStats(IZLibInflateStream::SStats* pOutStats) -{ - pOutStats->bytesInput = m_bytesInput; - pOutStats->bytesOutput = m_bytesOutput + m_decompressStream.total_out; - pOutStats->curMemoryUsed = m_zSize; - pOutStats->peakMemoryUsed = m_zPeak; -} - -unsigned int CZLibInflateStream::GetBytesOutput() -{ - return m_decompressStream.total_out; -} - -void CZLibInflateStream::Input(const char* pInSource, unsigned int inSourceSize) -{ - CRY_ASSERT_MESSAGE(m_currentState == eZInfState_AwaitingInput, "CZLibInflateStream::Input() called when stream is not awaiting input or has finished"); - - m_decompressStream.next_in = (Bytef*)pInSource; - m_decompressStream.avail_in = inSourceSize; - m_bytesInput += inSourceSize; -} - -void CZLibInflateStream::EndInput() -{ - CRY_ASSERT_MESSAGE(m_currentState == eZInfState_AwaitingInput, "CZLibInflateStream::EndInput() called when stream is not awaiting input"); - - m_zlibFlush = Z_FINISH; -} - -voidpf CZLibInflateStream::ZAlloc(voidpf pInOpaque, uInt inItems, uInt inSize) -{ - CZLibInflateStream* pStr = reinterpret_cast(pInOpaque); - - const unsigned int size = inItems * inSize; - - int* pPtr = (int*)CryModuleMalloc(sizeof(int) + size); - - if (pPtr) - { - *pPtr = inItems * inSize; - pPtr += 1; - - const unsigned int newSize = pStr->m_zSize + size; - pStr->m_zSize = newSize; - if (newSize > pStr->m_zPeak) - { - pStr->m_zPeak = newSize; - } - } - - return pPtr; -} - -void CZLibInflateStream::ZFree(voidpf pInOpaque, voidpf pInAddress) -{ - int* pPtr = reinterpret_cast(pInAddress); - - if (pPtr) - { - CZLibInflateStream* pStr = reinterpret_cast(pInOpaque); - pStr->m_zSize -= pPtr[-1]; - CryModuleFree(pPtr - 1); - } -} - -EZInflateState CZLibInflateStream::RunInflate() -{ - bool runInflate = false; - bool inputAvailable = (m_decompressStream.avail_in > 0) || (m_zlibFlush == Z_FINISH); - bool outputAvailable = (m_decompressStream.avail_out > 0); - - switch (m_currentState) - { - case eZInfState_AwaitingInput: - case eZInfState_ConsumeOutput: - if (inputAvailable && outputAvailable) - { - runInflate = true; - } - else if (inputAvailable || !outputAvailable) - { - m_currentState = eZInfState_ConsumeOutput; - } - else - { - m_currentState = eZInfState_AwaitingInput; - } - break; - - case eZInfState_Inflating: - CRY_ASSERT_MESSAGE(false, "Shouldn't be trying to run inflate whilst a inflate is in progress"); - break; - - case eZInfState_Error: - break; - - default: - CRY_ASSERT_MESSAGE(false, "unknown state"); - break; - } - - if (runInflate) - { - if (!m_bStreamOpened) - { - m_bStreamOpened = true; - - // initializing with inflateInit2 requires that the next_in be initialized - m_decompressStream.zalloc = &CZLibInflateStream::ZAlloc; - m_decompressStream.zfree = &CZLibInflateStream::ZFree; - m_decompressStream.opaque = this; - - const int error = inflateInit2(&m_decompressStream, -MAX_WBITS); - if (error != Z_OK) - { - m_currentState = eZInfState_Error; - CryLog("zlib inflateInit2() error, err %d", error); - } - } - - if (m_currentState != eZInfState_Error) - { - int error = inflate(&m_decompressStream, m_zlibFlush); - - if (error == Z_STREAM_END) - { - // end of stream has been generated, only produced if we pass Z_FINISH into inflate - m_currentState = eZInfState_Finished; - } - else if ((error == Z_OK && m_decompressStream.avail_out == 0) || (error == Z_BUF_ERROR && m_decompressStream.avail_out == 0)) - { - // output buffer has been filled - // data should be available for consumption by caller - m_currentState = eZInfState_ConsumeOutput; - } - else if (m_decompressStream.avail_in == 0) - { - // ran out of input data - // data may be available for consumption - but we need more input right now - m_currentState = eZInfState_AwaitingInput; - } - else - { - // some sort of error has occurred - m_currentState = eZInfState_Error; - CryLog("zlib inflate() error, err %d", error); - } - } - } - - return m_currentState; -} - -EZInflateState CZLibInflateStream::GetState() -{ - return RunInflate(); -} diff --git a/Code/CryEngine/CrySystem/ZLibDecompressor.h b/Code/CryEngine/CrySystem/ZLibDecompressor.h deleted file mode 100644 index 0a3ca0669f..0000000000 --- a/Code/CryEngine/CrySystem/ZLibDecompressor.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : zlib inflate wrapper - - -#ifndef CRYINCLUDE_CRYSYSTEM_ZLIBDECOMPRESSOR_H -#define CRYINCLUDE_CRYSYSTEM_ZLIBDECOMPRESSOR_H -#pragma once - - -#include "IZlibDecompressor.h" - -class CZLibDecompressor - : public IZLibDecompressor -{ -public: - virtual IZLibInflateStream* CreateInflateStream(); - virtual void Release(); - -private: - virtual ~CZLibDecompressor() {} -}; - -#endif // CRYINCLUDE_CRYSYSTEM_ZLIBDECOMPRESSOR_H diff --git a/Code/CryEngine/CrySystem/ZStdDecompressor.cpp b/Code/CryEngine/CrySystem/ZStdDecompressor.cpp deleted file mode 100644 index 0de76b82f8..0000000000 --- a/Code/CryEngine/CrySystem/ZStdDecompressor.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "CrySystem_precompiled.h" -#include -#include "ZStdDecompressor.h" - -bool CZStdDecompressor::DecompressData(const char* pIn, const uint inputSize, char* pOut, const uint outputSize) -{ - size_t result = ZSTD_decompress(pOut, outputSize, pIn, inputSize); - return !ZSTD_isError(result); -} - -void CZStdDecompressor::Release() -{ - delete this; -} diff --git a/Code/CryEngine/CrySystem/ZStdDecompressor.h b/Code/CryEngine/CrySystem/ZStdDecompressor.h deleted file mode 100644 index 200e5fe350..0000000000 --- a/Code/CryEngine/CrySystem/ZStdDecompressor.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - - -#include "IZStdDecompressor.h" - -class CZStdDecompressor - : public IZStdDecompressor -{ -public: - bool DecompressData(const char* pIn, const uint inputSize, char* pOut, const uint outputSize) override; - void Release() override; - -protected: - ~CZStdDecompressor() override = default; -}; - diff --git a/Code/CryEngine/CrySystem/ZipFile.h b/Code/CryEngine/CrySystem/ZipFile.h deleted file mode 100644 index e0c42088a3..0000000000 --- a/Code/CryEngine/CrySystem/ZipFile.h +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_ZIPFILE_H -#define CRYINCLUDE_CRYSYSTEM_ZIPFILE_H -#pragma once - - -#endif // CRYINCLUDE_CRYSYSTEM_ZIPFILE_H diff --git a/Code/CryEngine/CrySystem/ZipFileFormat_info.h b/Code/CryEngine/CrySystem/ZipFileFormat_info.h deleted file mode 100644 index d3fd4a3f54..0000000000 --- a/Code/CryEngine/CrySystem/ZipFileFormat_info.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_ZIPFILEFORMAT_INFO_H -#define CRYINCLUDE_CRYSYSTEM_ZIPFILEFORMAT_INFO_H -#pragma once - -#include "ZipFileFormat.h" - -#if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Waddress-of-packed-member" -#endif - -STRUCT_INFO_BEGIN(ZipFile::CDREnd) -VAR_INFO(lSignature) -VAR_INFO(nDisk) -VAR_INFO(nCDRStartDisk) -VAR_INFO(numEntriesOnDisk) -VAR_INFO(numEntriesTotal) -VAR_INFO(lCDRSize) -VAR_INFO(lCDROffset) -VAR_INFO(nCommentLength) -STRUCT_INFO_END(ZipFile::CDREnd) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor) -VAR_INFO(lCRC32) -VAR_INFO(lSizeCompressed) -VAR_INFO(lSizeUncompressed) -STRUCT_INFO_END(ZipFile::DataDescriptor) - -STRUCT_INFO_BEGIN(ZipFile::CDRFileHeader) -VAR_INFO(lSignature) -VAR_INFO(nVersionMadeBy) -VAR_INFO(nVersionNeeded) -VAR_INFO(nFlags) -VAR_INFO(nMethod) -VAR_INFO(nLastModTime) -VAR_INFO(nLastModDate) -VAR_INFO(desc) -VAR_INFO(nFileNameLength) -VAR_INFO(nExtraFieldLength) -VAR_INFO(nFileCommentLength) -VAR_INFO(nDiskNumberStart) -VAR_INFO(nAttrInternal) -VAR_INFO(lAttrExternal) -VAR_INFO(lLocalHeaderOffset) -STRUCT_INFO_END(ZipFile::CDRFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::LocalFileHeader) -VAR_INFO(lSignature) -VAR_INFO(nVersionNeeded) -VAR_INFO(nFlags) -VAR_INFO(nMethod) -VAR_INFO(nLastModTime) -VAR_INFO(nLastModDate) -VAR_INFO(desc) -VAR_INFO(nFileNameLength) -VAR_INFO(nExtraFieldLength) -STRUCT_INFO_END(ZipFile::LocalFileHeader) - -#if defined(__clang__) -# pragma clang diagnostic pop -#endif - -#endif // CRYINCLUDE_CRYSYSTEM_ZIPFILEFORMAT_INFO_H diff --git a/Code/CryEngine/CrySystem/crash_face.bmp b/Code/CryEngine/CrySystem/crash_face.bmp deleted file mode 100644 index 887e5111c9..0000000000 --- a/Code/CryEngine/CrySystem/crash_face.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ced9f21365ad5a4159f31f602be10a00becf389fa289694026425e7a6bc73077 -size 9272 diff --git a/Code/CryEngine/CrySystem/crysystem_android_files.cmake b/Code/CryEngine/CrySystem/crysystem_android_files.cmake deleted file mode 100644 index 9164dce432..0000000000 --- a/Code/CryEngine/CrySystem/crysystem_android_files.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - MobileDetectSpec_Android.cpp - MobileDetectSpec.cpp - MobileDetectSpec.h - ThermalInfoAndroid.h - ThermalInfoAndroid.cpp -) diff --git a/Code/CryEngine/CrySystem/crysystem_dlmalloc_files.cmake b/Code/CryEngine/CrySystem/crysystem_dlmalloc_files.cmake deleted file mode 100644 index 9f94bf6cff..0000000000 --- a/Code/CryEngine/CrySystem/crysystem_dlmalloc_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - CryDLMalloc.c -) diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 6eff1ee8e2..6a56339b85 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -10,41 +10,20 @@ # set(FILES - AutoDetectSpec.cpp AZCrySystemInitLogSink.cpp - ClientHandler.cpp CmdLine.cpp CmdLineArg.cpp - CompressedFile.cpp ConsoleBatchFile.cpp ConsoleHelpGen.cpp - CryAsyncMemcpy.cpp - HandlerBase.cpp Log.cpp - SystemRender.cpp - PhysRenderer.cpp - ServerHandler.cpp - ServerThrottle.cpp - SyncLock.cpp System.cpp SystemCFG.cpp SystemEventDispatcher.cpp SystemInit.cpp SystemWin32.cpp Timer.cpp - UnixConsole.cpp - WindowsConsole.cpp XConsole.cpp XConsoleVariable.cpp - AutoDetectSpec.h - ClientHandler.h - HandlerBase.h - PhysRenderer.h - ServerHandler.h - ServerThrottle.h - SyncLock.h - UnixConsole.h - SystemInit.h XML/ReadWriteXMLSink.h AZCrySystemInitLogSink.h AZCoreLogSink.h @@ -52,17 +31,13 @@ set(FILES CmdLineArg.h ConsoleBatchFile.h ConsoleHelpGen.h - CryWaterMark.h Log.h - resource.h SimpleStringPool.h CrySystem_precompiled.h System.h SystemCFG.h SystemEventDispatcher.h Timer.h - Validator.h - WindowsConsole.h XConsole.h XConsoleVariable.h XML/SerializeXMLReader.cpp @@ -78,24 +53,14 @@ set(FILES XML/XmlUtils.h XML/ReadXMLSink.cpp XML/WriteXMLSource.cpp - ZipFile.h - ZipFileFormat_info.h - Sampler.cpp - Sampler.h LocalizedStringManager.cpp LocalizedStringManager.h - ZLibCompressor.cpp - ZLibCompressor.h Huffman.cpp Huffman.h RemoteConsole/RemoteConsole.cpp RemoteConsole/RemoteConsole.h RemoteConsole/RemoteConsole_impl.inl RemoteConsole/RemoteConsole_none.inl - ZLibDecompressor.h - ZLibDecompressor.cpp - LZ4Decompressor.h - LZ4Decompressor.cpp LevelSystem/LevelSystem.cpp LevelSystem/LevelSystem.h LevelSystem/SpawnableLevelSystem.cpp @@ -106,10 +71,5 @@ set(FILES ViewSystem/View.h ViewSystem/ViewSystem.cpp ViewSystem/ViewSystem.h - ZStdDecompressor.h - ZStdDecompressor.cpp CrySystem_precompiled.cpp - CPUDetect.cpp - CPUDetect.h - WindowsErrorReporting.cpp ) diff --git a/Code/CryEngine/CrySystem/crysystem_ios_files.cmake b/Code/CryEngine/CrySystem/crysystem_ios_files.cmake deleted file mode 100644 index eca0f5142c..0000000000 --- a/Code/CryEngine/CrySystem/crysystem_ios_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - MobileDetectSpec_Ios.cpp - MobileDetectSpec.cpp - MobileDetectSpec.h -) diff --git a/Code/CryEngine/CrySystem/crysystem_mac_files.cmake b/Code/CryEngine/CrySystem/crysystem_mac_files.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CrySystem/crysystem_mac_files.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake deleted file mode 100644 index d8f6887da6..0000000000 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ /dev/null @@ -1,22 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - Components/MathConversionTests.cpp - Tests/Test_CLog.cpp - Tests/Test_CommandRegistration.cpp - Tests/Test_CryPrimitives.cpp - Tests/test_CrySystem.cpp - Tests/Test_Localization.cpp - Tests/test_Main.cpp - Tests/test_MaterialUtils.cpp - DllMain.cpp -) diff --git a/Code/CryEngine/CrySystem/resource.h b/Code/CryEngine/CrySystem/resource.h deleted file mode 100644 index a5970a6475..0000000000 --- a/Code/CryEngine/CrySystem/resource.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#define VS_VERSION_INFO 1 -#define IDD_CRITICAL_ERROR 101 -#define IDB_CONFIRM_SAVE 102 -#define IDB_DONT_SAVE 103 -#define IDD_CONFIRM_SAVE_LEVEL 127 -#define IDB_CRASH_FACE 128 -#define IDD_EXCEPTION 245 -#define IDC_CALLSTACK 1001 -#define IDC_EXCEPTION_CODE 1002 -#define IDC_EXCEPTION_ADDRESS 1003 -#define IDC_EXCEPTION_MODULE 1004 -#define IDC_EXCEPTION_DESC 1005 -#define IDB_EXIT 1008 -#define IDB_IGNORE 1010 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 129 -#define _APS_NEXT_COMMAND_VALUE 40072 -#define _APS_NEXT_CONTROL_VALUE 1003 -#define _APS_NEXT_SYMED_VALUE 104 -#endif -#endif diff --git a/Code/CryEngine/CryCommon/ThermalInfo.h b/Code/Framework/AzFramework/AzFramework/Thermal/ThermalInfo.h similarity index 100% rename from Code/CryEngine/CryCommon/ThermalInfo.h rename to Code/Framework/AzFramework/AzFramework/Thermal/ThermalInfo.h diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index f73e67b94e..8cff479ec8 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -296,6 +296,7 @@ set(FILES Spawnable/SpawnableSystemComponent.cpp Terrain/TerrainDataRequestBus.h Terrain/TerrainDataRequestBus.cpp + Thermal/ThermalInfo.h Platform/PlatformDefaults.h Windowing/WindowBus.h Windowing/NativeWindow.cpp diff --git a/Code/Framework/AzFramework/Platform/Android/AzFramework/Application/Application_Android.cpp b/Code/Framework/AzFramework/Platform/Android/AzFramework/Application/Application_Android.cpp index cc1b0b8035..cb003dd130 100644 --- a/Code/Framework/AzFramework/Platform/Android/AzFramework/Application/Application_Android.cpp +++ b/Code/Framework/AzFramework/Platform/Android/AzFramework/Application/Application_Android.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -95,6 +96,7 @@ namespace AzFramework private: AndroidEventDispatcher* m_eventDispatcher; ApplicationLifecycleEvents::Event m_lastEvent; + AZStd::unique_ptr m_thermalInfoHandler; AZStd::atomic m_requestResponseReceived; AZStd::unique_ptr m_lumberyardActivity; @@ -125,6 +127,10 @@ namespace AzFramework AndroidLifecycleEvents::Bus::Handler::BusConnect(); AndroidAppRequests::Bus::Handler::BusConnect(); PermissionRequestResultNotification::Bus::Handler::BusConnect(); + +#if !defined(AZ_RELEASE_BUILD) + m_thermalInfoHandler = AZStd::make_unique(); +#endif } //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/ThermalInfoAndroid.cpp b/Code/Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.cpp similarity index 99% rename from Code/CryEngine/CrySystem/ThermalInfoAndroid.cpp rename to Code/Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.cpp index 0c69a728fa..9a2100e1bd 100644 --- a/Code/CryEngine/CrySystem/ThermalInfoAndroid.cpp +++ b/Code/Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.cpp @@ -11,7 +11,7 @@ */ #if !defined(AZ_RELEASE_BUILD) -#include "ThermalInfoAndroid.h" +#include "ThermalInfo_Android.h" #include #include diff --git a/Code/CryEngine/CrySystem/ThermalInfoAndroid.h b/Code/Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.h similarity index 95% rename from Code/CryEngine/CrySystem/ThermalInfoAndroid.h rename to Code/Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.h index 07d1b86f68..2781d2cf52 100644 --- a/Code/CryEngine/CrySystem/ThermalInfoAndroid.h +++ b/Code/Framework/AzFramework/Platform/Android/AzFramework/Thermal/ThermalInfo_Android.h @@ -13,7 +13,7 @@ #pragma once #if !defined(AZ_RELEASE_BUILD) -#include +#include class ThermalInfoAndroidHandler : public ThermalInfoRequestsBus::Handler { diff --git a/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake b/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake index 38d07ec9f5..3721632fbb 100644 --- a/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake +++ b/Code/Framework/AzFramework/Platform/Android/platform_android_files.cmake @@ -36,4 +36,6 @@ set(FILES AzFramework/Process/ProcessCommon.h AzFramework/Process/ProcessWatcher_Android.cpp AzFramework/Process/ProcessCommunicator_Android.cpp + AzFramework/Thermal/ThermalInfo_Android.cpp + AzFramework/Thermal/ThermalInfo_Android.h ) diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index 2112d00d64..c338a2e28d 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -424,7 +424,6 @@ AZ::Outcome CGameEngine::Init( sip.pLogCallback = &m_logFile; sip.sLogFileName = "@log@/Editor.log"; sip.pUserCallback = m_pSystemUserCallback; - sip.pValidator = GetIEditor()->GetErrorReport(); // Assign validator from Editor. if (sInCmdLine) { diff --git a/Code/Sandbox/Editor/GraphicsSettingsDialog.cpp b/Code/Sandbox/Editor/GraphicsSettingsDialog.cpp index 516e723d6b..593abeeddc 100644 --- a/Code/Sandbox/Editor/GraphicsSettingsDialog.cpp +++ b/Code/Sandbox/Editor/GraphicsSettingsDialog.cpp @@ -779,36 +779,6 @@ bool GraphicsSettingsDialog::CVarChanged(AZStd::any val, const char* cvarName, i m_cVarTracker[cvarName].fileVals[specLevel].editedValue = val; } - // If changing cvar from the platform cfg file currently running, set cvar - if (GetISystem()->GetConfigPlatform() == m_currentPlatform && GetISystem()->GetConfigSpec() == specLevel + 1) - { - if (ICVar* cvar = gEnv->pConsole->GetCVar(cvarName)) - { - int type = cvar->GetType(); - if (type == CVAR_INT) - { - int newValue; - if (AZStd::any_numeric_cast(&val, newValue)) - { - cvar->Set(newValue); - } - } - else if (type == CVAR_FLOAT) - { - float newValue; - if (AZStd::any_numeric_cast(&val, newValue)) - { - cvar->Set(newValue); - } - } - else - { - AZStd::string* currValue = AZStd::any_cast(&val); - cvar->Set(currValue->c_str()); - } - } - } - // Checking if the newly edited value is equal to the overwritten value cvarInfo = AZStd::make_pair(azcvarName, m_cVarTracker[cvarName]); if (CheckCVarStatesForDiff(&cvarInfo, specLevel, EDITED_OVERWRITTEN_COMPARE)) diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 4b3c494413..0c8398050c 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -1584,16 +1584,9 @@ void CEditorImpl::AddUIEnums() m_pUIEnumsDatabase->SetEnumStrings("ShadowMinResPercent", types); } -void CEditorImpl::SetEditorConfigSpec(ESystemConfigSpec spec, ESystemConfigPlatform platform) +void CEditorImpl::SetEditorConfigSpec(ESystemConfigSpec spec, [[maybe_unused]]ESystemConfigPlatform platform) { gSettings.editorConfigSpec = spec; - if (m_pSystem->GetConfigSpec(true) != spec || m_pSystem->GetConfigPlatform() != platform) - { - m_pSystem->SetConfigSpec(spec, platform, true); - gSettings.editorConfigSpec = m_pSystem->GetConfigSpec(true); - GetObjectManager()->SendEvent(EVENT_CONFIG_SPEC_CHANGE); - AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::OnEditorSpecChange); - } } ESystemConfigSpec CEditorImpl::GetEditorConfigSpec() const diff --git a/Code/Sandbox/Editor/Util/PathUtil.cpp b/Code/Sandbox/Editor/Util/PathUtil.cpp index 9f713eb0f3..6efc06c79e 100644 --- a/Code/Sandbox/Editor/Util/PathUtil.cpp +++ b/Code/Sandbox/Editor/Util/PathUtil.cpp @@ -272,21 +272,6 @@ namespace Path return str; } - //! Set the current mod NAME for editing purposes. After doing this the above functions will take this into account - //! name only, please! - void SetModName(const char* input) - { - if ( - (!input) || - ((gEnv) && (gEnv->pSystem) && (!gEnv->pSystem->IsMODValid(input))) // we can only validate - ) - { - AZ_Warning("PathUtil", false, "Invalid mod name supplied to SetModName: %s - ignored.", input ? input : "(NULL)"); - return; - } - g_currentModName = input; - } - //! Get the root folder (in source control or other writable assets) where you should save root data. AZStd::string GetEditingRootFolder() { diff --git a/scripts/build/package/Platform/Windows/package_filelists/atom.json b/scripts/build/package/Platform/Windows/package_filelists/atom.json index ad2df7691e..e18e191882 100644 --- a/scripts/build/package/Platform/Windows/package_filelists/atom.json +++ b/scripts/build/package/Platform/Windows/package_filelists/atom.json @@ -138,7 +138,6 @@ "3dsmax/**": "#include", "7za.exe": "#include", "7za_legal_notice.txt": "#include", - "CrySCompileServer/**": "#include", "PakShaders/**": "#include", "Python/**": "#include", "Redistributables": {