diff options
Diffstat (limited to 'Source')
120 files changed, 2537 insertions, 1787 deletions
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index c57f713..24370aa 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -484,6 +484,8 @@ set(SRCS cmBuildCommand.h cmBuildNameCommand.cxx cmBuildNameCommand.h + cmCMakeCommand.cxx + cmCMakeCommand.h cmCMakeHostSystemInformationCommand.cxx cmCMakeHostSystemInformationCommand.h cmCMakeMinimumRequired.cxx diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake index f6b0112..e87ad32 100644 --- a/Source/CMakeVersion.cmake +++ b/Source/CMakeVersion.cmake @@ -1,8 +1,8 @@ # CMake version number components. set(CMake_VERSION_MAJOR 3) set(CMake_VERSION_MINOR 17) -set(CMake_VERSION_PATCH 0) -set(CMake_VERSION_RC 2) +set(CMake_VERSION_PATCH 20200312) +#set(CMake_VERSION_RC 0) set(CMake_VERSION_IS_DIRTY 0) # Start with the full version number used in tags. It has no dev info. diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx index 21d27a0..bdaf779 100644 --- a/Source/CPack/OSXScriptLauncher.cxx +++ b/Source/CPack/OSXScriptLauncher.cxx @@ -5,6 +5,8 @@ #include <string> #include <vector> +#include <cm/memory> + #include <CoreFoundation/CoreFoundation.h> #include "cmsys/FStream.hxx" @@ -26,7 +28,6 @@ int main(int argc, char* argv[]) CFStringRef fileName; CFBundleRef appBundle; CFURLRef scriptFileURL; - UInt8* path; // get CF URL for script if (!(appBundle = CFBundleGetMainBundle())) { @@ -41,13 +42,15 @@ int main(int argc, char* argv[]) } // create path string - if (!(path = new UInt8[PATH_MAX])) { + auto path = cm::make_unique<UInt8[]>(PATH_MAX); + if (!path) { return 1; } // get the file system path of the url as a cstring // in an encoding suitable for posix apis - if (!CFURLGetFileSystemRepresentation(scriptFileURL, true, path, PATH_MAX)) { + if (!CFURLGetFileSystemRepresentation(scriptFileURL, true, path.get(), + PATH_MAX)) { DebugError("CFURLGetFileSystemRepresentation failed"); return 1; } @@ -55,10 +58,10 @@ int main(int argc, char* argv[]) // dispose of the CF variable CFRelease(scriptFileURL); - std::string fullScriptPath = reinterpret_cast<char*>(path); - delete[] path; + std::string fullScriptPath = reinterpret_cast<char*>(path.get()); + path.reset(); - if (!cmsys::SystemTools::FileExists(fullScriptPath.c_str())) { + if (!cmsys::SystemTools::FileExists(fullScriptPath)) { return 1; } @@ -80,7 +83,6 @@ int main(int argc, char* argv[]) cmsysProcess_SetTimeout(cp, 0); cmsysProcess_Execute(cp); - std::vector<char> tempOutput; char* data; int length; while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) { diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx index e71a38f..67d3d32 100644 --- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx +++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx @@ -4,6 +4,7 @@ #include <algorithm> +#include <cm/memory> #include <cm/string_view> #include "cmsys/Directory.hxx" @@ -35,22 +36,16 @@ #include "cmCMakeToWixPath.h" cmCPackWIXGenerator::cmCPackWIXGenerator() - : Patch(0) - , ComponentGuidType(cmWIXSourceWriter::WIX_GENERATED_GUID) + : ComponentGuidType(cmWIXSourceWriter::WIX_GENERATED_GUID) { } -cmCPackWIXGenerator::~cmCPackWIXGenerator() -{ - if (this->Patch) { - delete this->Patch; - } -} +cmCPackWIXGenerator::~cmCPackWIXGenerator() = default; int cmCPackWIXGenerator::InitializeInternal() { componentPackageMethod = ONE_PACKAGE; - this->Patch = new cmWIXPatch(this->Logger); + this->Patch = cm::make_unique<cmWIXPatch>(this->Logger); return this->Superclass::InitializeInternal(); } diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.h b/Source/CPack/WiX/cmCPackWIXGenerator.h index d193348..d5a16ec 100644 --- a/Source/CPack/WiX/cmCPackWIXGenerator.h +++ b/Source/CPack/WiX/cmCPackWIXGenerator.h @@ -4,6 +4,7 @@ #define cmCPackWIXGenerator_h #include <map> +#include <memory> #include <string> #include "cmCPackGenerator.h" @@ -24,6 +25,8 @@ public: cmCPackTypeMacro(cmCPackWIXGenerator, cmCPackGenerator); cmCPackWIXGenerator(); + cmCPackWIXGenerator(const cmCPackWIXGenerator&) = delete; + const cmCPackWIXGenerator& operator=(const cmCPackWIXGenerator&) = delete; ~cmCPackWIXGenerator(); protected: @@ -157,7 +160,7 @@ private: std::string CPackTopLevel; - cmWIXPatch* Patch; + std::unique_ptr<cmWIXPatch> Patch; cmWIXSourceWriter::GuidType ComponentGuidType; }; diff --git a/Source/CPack/WiX/cmWIXPatch.cxx b/Source/CPack/WiX/cmWIXPatch.cxx index ca232f9..122ffaf 100644 --- a/Source/CPack/WiX/cmWIXPatch.cxx +++ b/Source/CPack/WiX/cmWIXPatch.cxx @@ -41,7 +41,7 @@ void cmWIXPatch::ApplyFragment(std::string const& id, void cmWIXPatch::ApplyElementChildren(const cmWIXPatchElement& element, cmWIXSourceWriter& writer) { - for (cmWIXPatchNode* node : element.children) { + for (const auto& node : element.children) { switch (node->type()) { case cmWIXPatchNode::ELEMENT: ApplyElement(dynamic_cast<const cmWIXPatchElement&>(*node), writer); diff --git a/Source/CPack/WiX/cmWIXPatchParser.cxx b/Source/CPack/WiX/cmWIXPatchParser.cxx index fd9103b..5588d2d 100644 --- a/Source/CPack/WiX/cmWIXPatchParser.cxx +++ b/Source/CPack/WiX/cmWIXPatchParser.cxx @@ -2,6 +2,10 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmWIXPatchParser.h" +#include <utility> + +#include <cm/memory> + #include "cm_expat.h" #include "cmCPackGenerator.h" @@ -20,12 +24,8 @@ cmWIXPatchNode::~cmWIXPatchNode() { } -cmWIXPatchElement::~cmWIXPatchElement() -{ - for (cmWIXPatchNode* child : children) { - delete child; - } -} +cmWIXPatchElement::cmWIXPatchElement() = default; +cmWIXPatchElement::~cmWIXPatchElement() = default; cmWIXPatchParser::cmWIXPatchParser(fragment_map_t& fragments, cmCPackLog* logger) @@ -54,8 +54,7 @@ void cmWIXPatchParser::StartElement(const std::string& name, const char** atts) } else if (State == INSIDE_FRAGMENT) { cmWIXPatchElement& parent = *ElementStack.back(); - cmWIXPatchElement* element = new cmWIXPatchElement; - parent.children.push_back(element); + auto element = cm::make_unique<cmWIXPatchElement>(); element->name = name; @@ -66,7 +65,8 @@ void cmWIXPatchParser::StartElement(const std::string& name, const char** atts) element->attributes[key] = value; } - ElementStack.push_back(element); + ElementStack.push_back(element.get()); + parent.children.push_back(std::move(element)); } } @@ -130,10 +130,10 @@ void cmWIXPatchParser::CharacterDataHandler(const char* data, int length) std::string::size_type last = text.find_last_not_of(whitespace); if (first != std::string::npos && last != std::string::npos) { - cmWIXPatchText* text_node = new cmWIXPatchText; + auto text_node = cm::make_unique<cmWIXPatchText>(); text_node->text = text.substr(first, last - first + 1); - parent.children.push_back(text_node); + parent.children.push_back(std::move(text_node)); } } } diff --git a/Source/CPack/WiX/cmWIXPatchParser.h b/Source/CPack/WiX/cmWIXPatchParser.h index 87dd892..8d5d2ad 100644 --- a/Source/CPack/WiX/cmWIXPatchParser.h +++ b/Source/CPack/WiX/cmWIXPatchParser.h @@ -4,6 +4,7 @@ #define cmCPackWIXPatchParser_h #include <map> +#include <memory> #include <vector> #include "cmCPackLog.h" @@ -33,9 +34,14 @@ struct cmWIXPatchElement : cmWIXPatchNode { virtual Type type(); + cmWIXPatchElement(); + + cmWIXPatchElement(const cmWIXPatchElement&) = delete; + const cmWIXPatchElement& operator=(const cmWIXPatchElement&) = delete; + ~cmWIXPatchElement(); - using child_list_t = std::vector<cmWIXPatchNode*>; + using child_list_t = std::vector<std::unique_ptr<cmWIXPatchNode>>; using attributes_t = std::map<std::string, std::string>; std::string name; diff --git a/Source/CPack/cmCPackLog.cxx b/Source/CPack/cmCPackLog.cxx index ca675fd..49e4113 100644 --- a/Source/CPack/cmCPackLog.cxx +++ b/Source/CPack/cmCPackLog.cxx @@ -4,54 +4,38 @@ #include <iostream> +#include <cm/memory> + #include "cmGeneratedFileStream.h" #include "cmSystemTools.h" cmCPackLog::cmCPackLog() { - this->Verbose = false; - this->Debug = false; - this->Quiet = false; - this->NewLine = true; - - this->LastTag = cmCPackLog::NOTAG; this->DefaultOutput = &std::cout; this->DefaultError = &std::cerr; - - this->LogOutput = nullptr; - this->LogOutputCleanup = false; } -cmCPackLog::~cmCPackLog() -{ - this->SetLogOutputStream(nullptr); -} +cmCPackLog::~cmCPackLog() = default; void cmCPackLog::SetLogOutputStream(std::ostream* os) { - if (this->LogOutputCleanup && this->LogOutput) { - delete this->LogOutput; - } - this->LogOutputCleanup = false; + this->LogOutputStream.reset(); this->LogOutput = os; } bool cmCPackLog::SetLogOutputFile(const char* fname) { - cmGeneratedFileStream* cg = nullptr; + this->LogOutputStream.reset(); if (fname) { - cg = new cmGeneratedFileStream(fname); - } - if (cg && !*cg) { - delete cg; - cg = nullptr; + this->LogOutputStream = cm::make_unique<cmGeneratedFileStream>(fname); } - this->SetLogOutputStream(cg); - if (!cg) { - return false; + if (this->LogOutputStream && !*this->LogOutputStream) { + this->LogOutputStream.reset(); } - this->LogOutputCleanup = true; - return true; + + this->LogOutput = this->LogOutputStream.get(); + + return this->LogOutput != nullptr; } void cmCPackLog::Log(int tag, const char* file, int line, const char* msg, diff --git a/Source/CPack/cmCPackLog.h b/Source/CPack/cmCPackLog.h index 1cb1643..68ffcce 100644 --- a/Source/CPack/cmCPackLog.h +++ b/Source/CPack/cmCPackLog.h @@ -5,6 +5,7 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include <memory> #include <ostream> #include <string> @@ -97,13 +98,13 @@ public: void SetErrorPrefix(std::string const& pfx) { this->ErrorPrefix = pfx; } private: - bool Verbose; - bool Debug; - bool Quiet; + bool Verbose = false; + bool Debug = false; + bool Quiet = false; - bool NewLine; + bool NewLine = true; - int LastTag; + int LastTag = cmCPackLog::NOTAG; std::string Prefix; std::string OutputPrefix; @@ -112,13 +113,11 @@ private: std::string WarningPrefix; std::string ErrorPrefix; - std::ostream* DefaultOutput; - std::ostream* DefaultError; + std::ostream* DefaultOutput = nullptr; + std::ostream* DefaultError = nullptr; - std::string LogOutputFileName; - std::ostream* LogOutput; - // Do we need to cleanup log output stream - bool LogOutputCleanup; + std::ostream* LogOutput = nullptr; + std::unique_ptr<std::ostream> LogOutputStream; }; class cmCPackLogWrite diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx index 7803e37..5be9332 100644 --- a/Source/CTest/cmCTestScriptHandler.cxx +++ b/Source/CTest/cmCTestScriptHandler.cxx @@ -6,7 +6,6 @@ #include <cstdlib> #include <cstring> #include <map> -#include <memory> #include <ratio> #include <sstream> #include <utility> @@ -51,22 +50,7 @@ #define CTEST_INITIAL_CMAKE_OUTPUT_FILE_NAME "CTestInitialCMakeOutput.log" -cmCTestScriptHandler::cmCTestScriptHandler() -{ - this->Backup = false; - this->EmptyBinDir = false; - this->EmptyBinDirOnce = false; - this->Makefile = nullptr; - this->ParentMakefile = nullptr; - this->CMake = nullptr; - this->GlobalGenerator = nullptr; - - this->ScriptStartTime = std::chrono::steady_clock::time_point(); - - // the *60 is because the settings are in minutes but GetTime is seconds - this->MinimumInterval = 30 * 60; - this->ContinuousDuration = -1; -} +cmCTestScriptHandler::cmCTestScriptHandler() = default; void cmCTestScriptHandler::Initialize() { @@ -95,22 +79,15 @@ void cmCTestScriptHandler::Initialize() // what time in seconds did this script start running this->ScriptStartTime = std::chrono::steady_clock::time_point(); - delete this->Makefile; - this->Makefile = nullptr; + this->Makefile.reset(); this->ParentMakefile = nullptr; - delete this->GlobalGenerator; - this->GlobalGenerator = nullptr; + this->GlobalGenerator.reset(); - delete this->CMake; + this->CMake.reset(); } -cmCTestScriptHandler::~cmCTestScriptHandler() -{ - delete this->Makefile; - delete this->GlobalGenerator; - delete this->CMake; -} +cmCTestScriptHandler::~cmCTestScriptHandler() = default; // just adds an argument to the vector void cmCTestScriptHandler::AddConfigurationScript(const char* script, @@ -247,23 +224,20 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg) void cmCTestScriptHandler::CreateCMake() { // create a cmake instance to read the configuration script - if (this->CMake) { - delete this->CMake; - delete this->GlobalGenerator; - delete this->Makefile; - } - this->CMake = new cmake(cmake::RoleScript, cmState::CTest); + this->CMake = cm::make_unique<cmake>(cmake::RoleScript, cmState::CTest); this->CMake->SetHomeDirectory(""); this->CMake->SetHomeOutputDirectory(""); this->CMake->GetCurrentSnapshot().SetDefaultDefinitions(); this->CMake->AddCMakePaths(); - this->GlobalGenerator = new cmGlobalGenerator(this->CMake); + this->GlobalGenerator = + cm::make_unique<cmGlobalGenerator>(this->CMake.get()); cmStateSnapshot snapshot = this->CMake->GetCurrentSnapshot(); std::string cwd = cmSystemTools::GetCurrentWorkingDirectory(); snapshot.GetDirectory().SetCurrentSource(cwd); snapshot.GetDirectory().SetCurrentBinary(cwd); - this->Makefile = new cmMakefile(this->GlobalGenerator, snapshot); + this->Makefile = + cm::make_unique<cmMakefile>(this->GlobalGenerator.get(), snapshot); if (this->ParentMakefile) { this->Makefile->SetRecursionDepth( this->ParentMakefile->GetRecursionDepth()); @@ -878,7 +852,7 @@ bool cmCTestScriptHandler::RunScript(cmCTest* ctest, cmMakefile* mf, const char* sname, bool InProcess, int* returnValue) { - cmCTestScriptHandler* sh = new cmCTestScriptHandler(); + auto sh = cm::make_unique<cmCTestScriptHandler>(); sh->SetCTestInstance(ctest); sh->ParentMakefile = mf; sh->AddConfigurationScript(sname, InProcess); @@ -886,7 +860,6 @@ bool cmCTestScriptHandler::RunScript(cmCTest* ctest, cmMakefile* mf, if (returnValue) { *returnValue = res; } - delete sh; return true; } diff --git a/Source/CTest/cmCTestScriptHandler.h b/Source/CTest/cmCTestScriptHandler.h index d003199..ebb7905 100644 --- a/Source/CTest/cmCTestScriptHandler.h +++ b/Source/CTest/cmCTestScriptHandler.h @@ -101,12 +101,14 @@ public: cmDuration GetRemainingTimeAllowed(); cmCTestScriptHandler(); + cmCTestScriptHandler(const cmCTestScriptHandler&) = delete; + const cmCTestScriptHandler& operator=(const cmCTestScriptHandler&) = delete; ~cmCTestScriptHandler() override; void Initialize() override; void CreateCMake(); - cmake* GetCMake() { return this->CMake; } + cmake* GetCMake() { return this->CMake.get(); } void SetRunCurrentScript(bool value); @@ -143,9 +145,9 @@ private: bool ShouldRunCurrentScript; - bool Backup; - bool EmptyBinDir; - bool EmptyBinDirOnce; + bool Backup = false; + bool EmptyBinDir = false; + bool EmptyBinDirOnce = false; std::string SourceDir; std::string BinaryDir; @@ -161,16 +163,18 @@ private: std::string CMOutFile; std::vector<std::string> ExtraUpdates; - double MinimumInterval; - double ContinuousDuration; + // the *60 is because the settings are in minutes but GetTime is seconds + double MinimumInterval = 30 * 60; + double ContinuousDuration = -1; // what time in seconds did this script start running - std::chrono::steady_clock::time_point ScriptStartTime; + std::chrono::steady_clock::time_point ScriptStartTime = + std::chrono::steady_clock::time_point(); - cmMakefile* Makefile; - cmMakefile* ParentMakefile; - cmGlobalGenerator* GlobalGenerator; - cmake* CMake; + std::unique_ptr<cmMakefile> Makefile; + cmMakefile* ParentMakefile = nullptr; + std::unique_ptr<cmGlobalGenerator> GlobalGenerator; + std::unique_ptr<cmake> CMake; }; #endif diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx index 4f324ea..8513f4b 100644 --- a/Source/CTest/cmCTestTestHandler.cxx +++ b/Source/CTest/cmCTestTestHandler.cxx @@ -1267,7 +1267,7 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed, this->StartTestTime = std::chrono::system_clock::now(); auto elapsed_time_start = std::chrono::steady_clock::now(); - cmCTestMultiProcessHandler* parallel = new cmCTestMultiProcessHandler; + auto parallel = cm::make_unique<cmCTestMultiProcessHandler>(); parallel->SetCTest(this->CTest); parallel->SetParallelLevel(this->CTest->GetParallelLevel()); parallel->SetTestHandler(this); @@ -1338,7 +1338,6 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed, } else { parallel->RunTests(); } - delete parallel; this->EndTest = this->CTest->CurrentTime(); this->EndTestTime = std::chrono::system_clock::now(); this->ElapsedTestingTime = @@ -2016,13 +2015,13 @@ void cmCTestTestHandler::GenerateRegressionImages(cmXMLWriter& xml, | std::ios::binary #endif ); - unsigned char* file_buffer = new unsigned char[len + 1]; - ifs.read(reinterpret_cast<char*>(file_buffer), len); - unsigned char* encoded_buffer = new unsigned char[static_cast<int>( - static_cast<double>(len) * 1.5 + 5.0)]; + auto file_buffer = cm::make_unique<unsigned char[]>(len + 1); + ifs.read(reinterpret_cast<char*>(file_buffer.get()), len); + auto encoded_buffer = cm::make_unique<unsigned char[]>( + static_cast<int>(static_cast<double>(len) * 1.5 + 5.0)); - size_t rlen = - cmsysBase64_Encode(file_buffer, len, encoded_buffer, 1); + size_t rlen = cmsysBase64_Encode(file_buffer.get(), len, + encoded_buffer.get(), 1); xml.StartElement("NamedMeasurement"); xml.Attribute(measurementfile.match(1).c_str(), @@ -2039,8 +2038,6 @@ void cmCTestTestHandler::GenerateRegressionImages(cmXMLWriter& xml, } xml.Element("Value", ostr.str()); xml.EndElement(); // NamedMeasurement - delete[] file_buffer; - delete[] encoded_buffer; } } else { int idx = 4; @@ -2085,11 +2082,10 @@ void cmCTestTestHandler::SetTestsToRunInformation(const char* in) if (cmSystemTools::FileExists(in)) { cmsys::ifstream fin(in); unsigned long filelen = cmSystemTools::FileLength(in); - char* buff = new char[filelen + 1]; - fin.getline(buff, filelen); + auto buff = cm::make_unique<char[]>(filelen + 1); + fin.getline(buff.get(), filelen); buff[fin.gcount()] = 0; - this->TestsToRunString = buff; - delete[] buff; + this->TestsToRunString = buff.get(); } } diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx index 6026c69..452d714 100644 --- a/Source/CTest/cmCTestVC.cxx +++ b/Source/CTest/cmCTestVC.cxx @@ -38,7 +38,7 @@ void cmCTestVC::SetSourceDirectory(std::string const& dir) this->SourceDirectory = dir; } -bool cmCTestVC::InitialCheckout(const char* command) +bool cmCTestVC::InitialCheckout(const std::string& command) { cmCTestLog(this->CTest, HANDLER_OUTPUT, " First perform the initial checkout: " << command << "\n"); diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h index 2a4765d..3037e01 100644 --- a/Source/CTest/cmCTestVC.h +++ b/Source/CTest/cmCTestVC.h @@ -36,7 +36,7 @@ public: std::string GetNightlyTime(); /** Prepare the work tree. */ - bool InitialCheckout(const char* command); + bool InitialCheckout(const std::string& command); /** Perform cleanup operations on the work tree. */ void Cleanup(); diff --git a/Source/CTest/cmParsePHPCoverage.cxx b/Source/CTest/cmParsePHPCoverage.cxx index a494b92..044f518 100644 --- a/Source/CTest/cmParsePHPCoverage.cxx +++ b/Source/CTest/cmParsePHPCoverage.cxx @@ -3,6 +3,8 @@ #include <cstdlib> #include <cstring> +#include <cm/memory> + #include "cmsys/Directory.hxx" #include "cmsys/FStream.hxx" @@ -142,17 +144,15 @@ bool cmParsePHPCoverage::ReadFileInformation(std::istream& in) int size = 0; if (this->ReadInt(in, size)) { size++; // add one for null termination - char* s = new char[size + 1]; + auto s = cm::make_unique<char[]>(size + 1); // read open quote if (in.get(c) && c != '"') { - delete[] s; return false; } // read the string data - in.read(s, size - 1); + in.read(s.get(), size - 1); s[size - 1] = 0; - std::string fileName = s; - delete[] s; + std::string fileName = s.get(); // read close quote if (in.get(c) && c != '"') { cmCTestLog(this->CTest, ERROR_MESSAGE, diff --git a/Source/LexerParser/cmListFileLexer.c b/Source/LexerParser/cmListFileLexer.c index 15dcda0..ec7424c 100644 --- a/Source/LexerParser/cmListFileLexer.c +++ b/Source/LexerParser/cmListFileLexer.c @@ -2787,7 +2787,7 @@ int cmListFileLexer_SetString(cmListFileLexer* lexer, const char* text) /*--------------------------------------------------------------------------*/ cmListFileLexer_Token* cmListFileLexer_Scan(cmListFileLexer* lexer) { - if (!lexer->file) { + if (!lexer->file && !lexer->string_buffer) { return 0; } if (cmListFileLexer_yylex(lexer->scanner, lexer)) { @@ -2801,21 +2801,13 @@ cmListFileLexer_Token* cmListFileLexer_Scan(cmListFileLexer* lexer) /*--------------------------------------------------------------------------*/ long cmListFileLexer_GetCurrentLine(cmListFileLexer* lexer) { - if (lexer->file) { - return lexer->line; - } else { - return 0; - } + return lexer->line; } /*--------------------------------------------------------------------------*/ long cmListFileLexer_GetCurrentColumn(cmListFileLexer* lexer) { - if (lexer->file) { - return lexer->column; - } else { - return 0; - } + return lexer->column; } /*--------------------------------------------------------------------------*/ diff --git a/Source/LexerParser/cmListFileLexer.in.l b/Source/LexerParser/cmListFileLexer.in.l index fdf14d2..94cf8a5 100644 --- a/Source/LexerParser/cmListFileLexer.in.l +++ b/Source/LexerParser/cmListFileLexer.in.l @@ -500,7 +500,7 @@ int cmListFileLexer_SetString(cmListFileLexer* lexer, const char* text) /*--------------------------------------------------------------------------*/ cmListFileLexer_Token* cmListFileLexer_Scan(cmListFileLexer* lexer) { - if (!lexer->file) { + if (!lexer->file && !lexer->string_buffer) { return 0; } if (cmListFileLexer_yylex(lexer->scanner, lexer)) { @@ -514,21 +514,13 @@ cmListFileLexer_Token* cmListFileLexer_Scan(cmListFileLexer* lexer) /*--------------------------------------------------------------------------*/ long cmListFileLexer_GetCurrentLine(cmListFileLexer* lexer) { - if (lexer->file) { - return lexer->line; - } else { - return 0; - } + return lexer->line; } /*--------------------------------------------------------------------------*/ long cmListFileLexer_GetCurrentColumn(cmListFileLexer* lexer) { - if (lexer->file) { - return lexer->column; - } else { - return 0; - } + return lexer->column; } /*--------------------------------------------------------------------------*/ diff --git a/Source/QtDialog/CMakeSetupDialog.cxx b/Source/QtDialog/CMakeSetupDialog.cxx index 436a904..276bf64 100644 --- a/Source/QtDialog/CMakeSetupDialog.cxx +++ b/Source/QtDialog/CMakeSetupDialog.cxx @@ -2,6 +2,8 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "CMakeSetupDialog.h" +#include <cm/memory> + #include <QCloseEvent> #include <QCoreApplication> #include <QDesktopServices> @@ -39,23 +41,21 @@ QCMakeThread::QCMakeThread(QObject* p) : QThread(p) - , CMakeInstance(nullptr) { } QCMake* QCMakeThread::cmakeInstance() const { - return this->CMakeInstance; + return this->CMakeInstance.get(); } void QCMakeThread::run() { - this->CMakeInstance = new QCMake; + this->CMakeInstance = cm::make_unique<QCMake>(); // emit that this cmake thread is ready for use emit this->cmakeInitialized(); this->exec(); - delete this->CMakeInstance; - this->CMakeInstance = nullptr; + this->CMakeInstance.reset(); } CMakeSetupDialog::CMakeSetupDialog() @@ -1206,7 +1206,7 @@ void CMakeSetupDialog::setSearchFilter(const QString& str) void CMakeSetupDialog::doOutputContextMenu(QPoint pt) { - QMenu* menu = this->Output->createStandardContextMenu(); + std::unique_ptr<QMenu> menu(this->Output->createStandardContextMenu()); menu->addSeparator(); menu->addAction(tr("Find..."), this, SLOT(doOutputFindDialog()), @@ -1220,7 +1220,6 @@ void CMakeSetupDialog::doOutputContextMenu(QPoint pt) QKeySequence(Qt::Key_F8)); menu->exec(this->Output->mapToGlobal(pt)); - delete menu; } void CMakeSetupDialog::doOutputFindDialog() diff --git a/Source/QtDialog/CMakeSetupDialog.h b/Source/QtDialog/CMakeSetupDialog.h index f23aee6..d1e2035 100644 --- a/Source/QtDialog/CMakeSetupDialog.h +++ b/Source/QtDialog/CMakeSetupDialog.h @@ -3,6 +3,8 @@ #ifndef CMakeSetupDialog_h #define CMakeSetupDialog_h +#include <memory> + #include "QCMake.h" #include <QEventLoop> #include <QMainWindow> @@ -143,7 +145,7 @@ signals: protected: virtual void run(); - QCMake* CMakeInstance; + std::unique_ptr<QCMake> CMakeInstance; }; #endif // CMakeSetupDialog_h diff --git a/Source/QtDialog/FirstConfigure.cxx b/Source/QtDialog/FirstConfigure.cxx index ca28b19..3c24b9b 100644 --- a/Source/QtDialog/FirstConfigure.cxx +++ b/Source/QtDialog/FirstConfigure.cxx @@ -10,8 +10,12 @@ #include "Compilers.h" -StartCompilerSetup::StartCompilerSetup(QWidget* p) +StartCompilerSetup::StartCompilerSetup(QString defaultGeneratorPlatform, + QString defaultGeneratorToolset, + QWidget* p) : QWizardPage(p) + , DefaultGeneratorPlatform(std::move(defaultGeneratorPlatform)) + , DefaultGeneratorToolset(std::move(defaultGeneratorToolset)) { QVBoxLayout* l = new QVBoxLayout(this); l->addWidget(new QLabel(tr("Specify the generator for this project"))); @@ -68,6 +72,10 @@ QFrame* StartCompilerSetup::CreateToolsetWidgets() Toolset = new QLineEdit(frame); l->addWidget(Toolset); + // Default to CMAKE_GENERATOR_TOOLSET env var if set + if (!DefaultGeneratorToolset.isEmpty()) { + this->Toolset->setText(DefaultGeneratorToolset); + } return frame; } @@ -199,6 +207,14 @@ void StartCompilerSetup::onGeneratorChanged(QString const& name) this->PlatformOptions->addItems(platform_list); PlatformFrame->show(); + + // Default to generator platform from environment + if (!DefaultGeneratorPlatform.isEmpty()) { + int platform_index = platforms.indexOf(DefaultGeneratorPlatform); + if (platform_index != -1) { + this->PlatformOptions->setCurrentIndex(platform_index); + } + } } else { PlatformFrame->hide(); } @@ -421,8 +437,26 @@ void ToolchainCompilerSetup::setToolchainFile(const QString& t) FirstConfigure::FirstConfigure() { + const char* env_generator = std::getenv("CMAKE_GENERATOR"); + const char* env_generator_platform = nullptr; + const char* env_generator_toolset = nullptr; + if (env_generator && std::strlen(env_generator)) { + mDefaultGenerator = env_generator; + env_generator_platform = std::getenv("CMAKE_GENERATOR_PLATFORM"); + env_generator_toolset = std::getenv("CMAKE_GENERATOR_TOOLSET"); + } + + if (!env_generator_platform) { + env_generator_platform = ""; + } + + if (!env_generator_toolset) { + env_generator_toolset = ""; + } + // this->setOption(QWizard::HaveFinishButtonOnEarlyPages, true); - this->mStartCompilerSetupPage = new StartCompilerSetup(this); + this->mStartCompilerSetupPage = new StartCompilerSetup( + env_generator_platform, env_generator_toolset, this); this->setPage(Start, this->mStartCompilerSetupPage); QObject::connect(this->mStartCompilerSetupPage, SIGNAL(selectionChanged()), this, SLOT(restart())); @@ -504,6 +538,17 @@ void FirstConfigure::loadFromSettings() this->mCrossCompilerSetupPage->setIncludeMode( settings.value("IncludeMode", 0).toInt()); settings.endGroup(); + + // environment variables take precedence over application settings because... + // - they're harder to set + // - settings always exist after the program is run once, so the environment + // variables would never be used otherwise + // - platform and toolset are populated only from environment variables, so + // this prevents them from being taken from environment, while the + // generator is taken from application settings + if (!mDefaultGenerator.isEmpty()) { + this->mStartCompilerSetupPage->setCurrentGenerator(mDefaultGenerator); + } } void FirstConfigure::saveToSettings() diff --git a/Source/QtDialog/FirstConfigure.h b/Source/QtDialog/FirstConfigure.h index d1db5bf..c26f489 100644 --- a/Source/QtDialog/FirstConfigure.h +++ b/Source/QtDialog/FirstConfigure.h @@ -29,7 +29,8 @@ class StartCompilerSetup : public QWizardPage { Q_OBJECT public: - StartCompilerSetup(QWidget* p); + StartCompilerSetup(QString defaultGeneratorPlatform, + QString defaultGeneratorToolset, QWidget* p); ~StartCompilerSetup(); void setGenerators(std::vector<cmake::GeneratorInfo> const& gens); void setCurrentGenerator(const QString& gen); @@ -64,6 +65,7 @@ protected: QStringList GeneratorsSupportingPlatform; QMultiMap<QString, QString> GeneratorSupportedPlatforms; QMap<QString, QString> GeneratorDefaultPlatform; + QString DefaultGeneratorPlatform, DefaultGeneratorToolset; private: QFrame* CreateToolsetWidgets(); @@ -197,6 +199,7 @@ protected: NativeCompilerSetup* mNativeCompilerSetupPage; CrossCompilerSetup* mCrossCompilerSetupPage; ToolchainCompilerSetup* mToolchainCompilerSetupPage; + QString mDefaultGenerator; }; #endif // FirstConfigure_h diff --git a/Source/QtDialog/QCMake.cxx b/Source/QtDialog/QCMake.cxx index 3b5dc04..c3e9c84 100644 --- a/Source/QtDialog/QCMake.cxx +++ b/Source/QtDialog/QCMake.cxx @@ -2,6 +2,8 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "QCMake.h" +#include <cm/memory> + #include <QCoreApplication> #include <QDir> @@ -35,7 +37,8 @@ QCMake::QCMake(QObject* p) cmSystemTools::SetStderrCallback( [this](std::string const& msg) { this->stderrCallback(msg); }); - this->CMakeInstance = new cmake(cmake::RoleProject, cmState::Project); + this->CMakeInstance = + cm::make_unique<cmake>(cmake::RoleProject, cmState::Project); this->CMakeInstance->SetCMakeEditCommand( cmSystemTools::GetCMakeGUICommand()); this->CMakeInstance->SetProgressCallback( @@ -55,11 +58,7 @@ QCMake::QCMake(QObject* p) } } -QCMake::~QCMake() -{ - delete this->CMakeInstance; - // cmDynamicLoader::FlushCache(); -} +QCMake::~QCMake() = default; void QCMake::loadCache(const QString& dir) { diff --git a/Source/QtDialog/QCMake.h b/Source/QtDialog/QCMake.h index fa4451b..110a971 100644 --- a/Source/QtDialog/QCMake.h +++ b/Source/QtDialog/QCMake.h @@ -12,6 +12,7 @@ # pragma warning(disable : 4512) #endif +#include <memory> #include <vector> #include <QAtomicInt> @@ -165,7 +166,7 @@ signals: void openPossible(bool possible); protected: - cmake* CMakeInstance; + std::unique_ptr<cmake> CMakeInstance; bool interruptCallback(); void progressCallback(std::string const& msg, float percent); diff --git a/Source/cmCMakeCommand.cxx b/Source/cmCMakeCommand.cxx new file mode 100644 index 0000000..c11a003 --- /dev/null +++ b/Source/cmCMakeCommand.cxx @@ -0,0 +1,68 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmCMakeCommand.h" + +#include <algorithm> +#include <cstddef> + +#include "cmExecutionStatus.h" +#include "cmListFileCache.h" +#include "cmMakefile.h" +#include "cmRange.h" +#include "cmStringAlgorithms.h" + +bool cmCMakeCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + if (args.empty()) { + status.SetError("called with incorrect number of arguments"); + return false; + } + + cmMakefile& makefile = status.GetMakefile(); + cmListFileContext context = makefile.GetExecutionContext(); + + bool result = false; + + if (args[0] == "INVOKE") { + if (args.size() == 1) { + status.SetError("called with incorrect number of arguments"); + return false; + } + + // First argument is the name of the function to call + cmListFileFunction func; + func.Name = args[1]; + func.Line = context.Line; + + // The rest of the arguments are passed to the function call above + func.Arguments.resize(args.size() - 1); + for (size_t i = 2; i < args.size(); ++i) { + cmListFileArgument lfarg; + lfarg.Line = context.Line; + lfarg.Value = args[i]; + func.Arguments.emplace_back(lfarg); + } + + result = makefile.ExecuteCommand(func, status); + } else if (args[0] == "EVAL") { + if (args.size() < 2) { + status.SetError("called with incorrect number of arguments"); + return false; + } + + auto code_iter = std::find(args.begin(), args.end(), "CODE"); + if (code_iter == args.end()) { + status.SetError("called without CODE argument"); + return false; + } + + const std::string code = cmJoin(cmMakeRange(++code_iter, args.end()), " "); + result = makefile.ReadListFileAsString( + code, cmStrCat(context.FilePath, ":", context.Line, ":EVAL")); + } else { + status.SetError("called with unknown meta-operation"); + } + + return result; +} diff --git a/Source/cmCMakeCommand.h b/Source/cmCMakeCommand.h new file mode 100644 index 0000000..cf9f4c3 --- /dev/null +++ b/Source/cmCMakeCommand.h @@ -0,0 +1,20 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmCMakeCommand_h +#define cmCMakeCommand_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include <string> +#include <vector> + +class cmExecutionStatus; + +/** + * \brief Calls a scripted or build-in command + * + */ +bool cmCMakeCommand(std::vector<std::string> const& args, + cmExecutionStatus& status); + +#endif diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx index b5c7e96..f6c1e47 100644 --- a/Source/cmCPluginAPI.cxx +++ b/Source/cmCPluginAPI.cxx @@ -488,24 +488,8 @@ struct cmCPluginAPISourceFile // Keep a map from real cmSourceFile instances stored in a makefile to // the CPluginAPI proxy source file. -class cmCPluginAPISourceFileMap - : public std::map<cmSourceFile*, cmCPluginAPISourceFile*> -{ -public: - using derived = std::map<cmSourceFile*, cmCPluginAPISourceFile*>; - using iterator = derived::iterator; - using value_type = derived::value_type; - cmCPluginAPISourceFileMap() = default; - ~cmCPluginAPISourceFileMap() - { - for (auto const& i : *this) { - delete i.second; - } - } - cmCPluginAPISourceFileMap(const cmCPluginAPISourceFileMap&) = delete; - cmCPluginAPISourceFileMap& operator=(const cmCPluginAPISourceFileMap&) = - delete; -}; +using cmCPluginAPISourceFileMap = + std::map<cmSourceFile*, std::unique_ptr<cmCPluginAPISourceFile>>; cmCPluginAPISourceFileMap cmCPluginAPISourceFiles; void* CCONV cmCreateSourceFile(void) @@ -536,7 +520,7 @@ void CCONV* cmGetSource(void* arg, const char* name) auto i = cmCPluginAPISourceFiles.find(rsf); if (i == cmCPluginAPISourceFiles.end()) { // Create a proxy source file object for this source. - cmCPluginAPISourceFile* sf = new cmCPluginAPISourceFile; + auto sf = cm::make_unique<cmCPluginAPISourceFile>(); sf->RealSourceFile = rsf; sf->FullPath = rsf->ResolveFullPath(); sf->SourceName = @@ -545,10 +529,9 @@ void CCONV* cmGetSource(void* arg, const char* name) cmSystemTools::GetFilenameLastExtension(sf->FullPath); // Store the proxy in the map so it can be re-used and deleted later. - cmCPluginAPISourceFileMap::value_type entry(rsf, sf); - i = cmCPluginAPISourceFiles.insert(entry).first; + i = cmCPluginAPISourceFiles.emplace(rsf, std::move(sf)).first; } - return i->second; + return i->second.get(); } return nullptr; } @@ -569,15 +552,16 @@ void* CCONV cmAddSource(void* arg, void* arg2) } // Create the proxy for the real source file. - cmCPluginAPISourceFile* sf = new cmCPluginAPISourceFile; + auto sf = cm::make_unique<cmCPluginAPISourceFile>(); sf->RealSourceFile = rsf; sf->FullPath = osf->FullPath; sf->SourceName = osf->SourceName; sf->SourceExtension = osf->SourceExtension; // Store the proxy in the map so it can be re-used and deleted later. - cmCPluginAPISourceFiles[rsf] = sf; - return sf; + auto value = sf.get(); + cmCPluginAPISourceFiles[rsf] = std::move(sf); + return value; } const char* CCONV cmSourceFileGetSourceName(void* arg) diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx index 04f75bd..fb100b1 100644 --- a/Source/cmCTest.cxx +++ b/Source/cmCTest.cxx @@ -16,6 +16,9 @@ #include <utility> #include <vector> +#include <cm/memory> +#include <cmext/algorithm> + #include "cmsys/Base64.h" #include "cmsys/Directory.hxx" #include "cmsys/FStream.hxx" @@ -32,9 +35,6 @@ # include <unistd.h> // IWYU pragma: keep #endif -#include <cm/memory> -#include <cmext/algorithm> - #include "cmCTestBuildAndTestHandler.h" #include "cmCTestBuildHandler.h" #include "cmCTestConfigureHandler.h" @@ -201,7 +201,7 @@ struct cmCTest::Private int SubmitIndex = 0; - cmGeneratedFileStream* OutputLogFile = nullptr; + std::unique_ptr<cmGeneratedFileStream> OutputLogFile; int OutputLogFileLastTag = -1; bool OutputTestOutputOnTestFailure = false; @@ -362,10 +362,7 @@ cmCTest::cmCTest() cmSystemTools::EnableVSConsoleOutput(); } -cmCTest::~cmCTest() -{ - delete this->Impl->OutputLogFile; -} +cmCTest::~cmCTest() = default; int cmCTest::GetParallelLevel() const { @@ -3086,12 +3083,10 @@ bool cmCTest::RunCommand(std::vector<std::string> const& args, void cmCTest::SetOutputLogFileName(const char* name) { - if (this->Impl->OutputLogFile) { - delete this->Impl->OutputLogFile; - this->Impl->OutputLogFile = nullptr; - } if (name) { - this->Impl->OutputLogFile = new cmGeneratedFileStream(name); + this->Impl->OutputLogFile = cm::make_unique<cmGeneratedFileStream>(name); + } else { + this->Impl->OutputLogFile.reset(); } } diff --git a/Source/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx index 613ae06..379836a 100644 --- a/Source/cmCommandArgumentParserHelper.cxx +++ b/Source/cmCommandArgumentParserHelper.cxx @@ -5,6 +5,9 @@ #include <cstring> #include <iostream> #include <sstream> +#include <utility> + +#include <cm/memory> #include "cmCommandArgumentLexer.h" #include "cmMakefile.h" @@ -40,10 +43,10 @@ const char* cmCommandArgumentParserHelper::AddString(const std::string& str) if (str.empty()) { return ""; } - char* stVal = new char[str.size() + 1]; - strcpy(stVal, str.c_str()); - this->Variables.push_back(stVal); - return stVal; + auto stVal = cm::make_unique<char[]>(str.size() + 1); + strcpy(stVal.get(), str.c_str()); + this->Variables.push_back(std::move(stVal)); + return this->Variables.back().get(); } const char* cmCommandArgumentParserHelper::ExpandSpecialVariable( @@ -136,11 +139,11 @@ const char* cmCommandArgumentParserHelper::CombineUnions(const char* in1, return in1; } size_t len = strlen(in1) + strlen(in2) + 1; - char* out = new char[len]; - strcpy(out, in1); - strcat(out, in2); - this->Variables.push_back(out); - return out; + auto out = cm::make_unique<char[]>(len); + strcpy(out.get(), in1); + strcat(out.get(), in2); + this->Variables.push_back(std::move(out)); + return this->Variables.back().get(); } void cmCommandArgumentParserHelper::AllocateParserType( @@ -153,11 +156,11 @@ void cmCommandArgumentParserHelper::AllocateParserType( if (len == 0) { return; } - char* out = new char[len + 1]; - memcpy(out, str, len); - out[len] = 0; - pt->str = out; - this->Variables.push_back(out); + auto out = cm::make_unique<char[]>(len + 1); + memcpy(out.get(), str, len); + out.get()[len] = 0; + pt->str = out.get(); + this->Variables.push_back(std::move(out)); } bool cmCommandArgumentParserHelper::HandleEscapeSymbol( @@ -235,10 +238,7 @@ int cmCommandArgumentParserHelper::ParseString(const char* str, int verb) void cmCommandArgumentParserHelper::CleanupParser() { - for (char* var : this->Variables) { - delete[] var; - } - this->Variables.erase(this->Variables.begin(), this->Variables.end()); + this->Variables.clear(); } int cmCommandArgumentParserHelper::LexInput(char* buf, int maxlen) diff --git a/Source/cmCommandArgumentParserHelper.h b/Source/cmCommandArgumentParserHelper.h index 25e6892..b46edcb 100644 --- a/Source/cmCommandArgumentParserHelper.h +++ b/Source/cmCommandArgumentParserHelper.h @@ -5,6 +5,7 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include <memory> #include <string> #include <vector> @@ -69,7 +70,7 @@ private: void CleanupParser(); void SetError(std::string const& msg); - std::vector<char*> Variables; + std::vector<std::unique_ptr<char[]>> Variables; const cmMakefile* Makefile; std::string Result; std::string ErrorString; diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx index 896b6a9..28b4267 100644 --- a/Source/cmCommands.cxx +++ b/Source/cmCommands.cxx @@ -91,6 +91,7 @@ # include "cmAddLinkOptionsCommand.h" # include "cmAuxSourceDirectoryCommand.h" # include "cmBuildNameCommand.h" +# include "cmCMakeCommand.h" # include "cmCMakeHostSystemInformationCommand.h" # include "cmExportCommand.h" # include "cmExportLibraryDependenciesCommand.h" @@ -196,6 +197,7 @@ void GetScriptingCommands(cmState* state) "match the opening WHILE command."); #if !defined(CMAKE_BOOTSTRAP) + state->AddBuiltinCommand("cmake_command", cmCMakeCommand); state->AddBuiltinCommand("cmake_host_system_information", cmCMakeHostSystemInformationCommand); state->AddBuiltinCommand("load_cache", cmLoadCacheCommand); diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx index 5ff6f8c..033cb60 100644 --- a/Source/cmCommonTargetGenerator.cxx +++ b/Source/cmCommonTargetGenerator.cxx @@ -248,7 +248,7 @@ void cmCommonTargetGenerator::AppendOSXVerFlag(std::string& flags, int major; int minor; int patch; - std::string prop = cmStrCat("OSX_", name, "_VERSION"); + std::string prop = cmStrCat("MACHO_", name, "_VERSION"); std::string fallback_prop = so ? "SOVERSION" : "VERSION"; this->GeneratorTarget->GetTargetVersionFallback(prop, fallback_prop, major, minor, patch); diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx index a98a608..41f5346 100644 --- a/Source/cmComputeTargetDepends.cxx +++ b/Source/cmComputeTargetDepends.cxx @@ -198,6 +198,20 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) std::vector<std::string> const& configs = depender->Makefile->GetGeneratorConfigs(); for (std::string const& it : configs) { + cmLinkImplementation const* impl = depender->GetLinkImplementation(it); + + // A target should not depend on itself. + emitted.insert(cmLinkItem(depender, false, cmListFileBacktrace())); + emitted.insert(cmLinkItem(depender, true, cmListFileBacktrace())); + for (cmLinkImplItem const& lib : impl->Libraries) { + // Don't emit the same library twice for this target. + if (emitted.insert(lib).second) { + this->AddTargetDepend(depender_index, lib, true, false); + this->AddInterfaceDepends(depender_index, lib, it, emitted); + } + } + + // Add dependencies on object libraries not otherwise handled above. std::vector<cmSourceFile const*> objectFiles; depender->GetExternalObjects(objectFiles, it); for (cmSourceFile const* o : objectFiles) { @@ -222,19 +236,6 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) } } } - - cmLinkImplementation const* impl = depender->GetLinkImplementation(it); - - // A target should not depend on itself. - emitted.insert(cmLinkItem(depender, false, cmListFileBacktrace())); - emitted.insert(cmLinkItem(depender, true, cmListFileBacktrace())); - for (cmLinkImplItem const& lib : impl->Libraries) { - // Don't emit the same library twice for this target. - if (emitted.insert(lib).second) { - this->AddTargetDepend(depender_index, lib, true, false); - this->AddInterfaceDepends(depender_index, lib, it, emitted); - } - } } } diff --git a/Source/cmConvertMSBuildXMLToJSON.py b/Source/cmConvertMSBuildXMLToJSON.py index 02074ba..2be3781 100644 --- a/Source/cmConvertMSBuildXMLToJSON.py +++ b/Source/cmConvertMSBuildXMLToJSON.py @@ -35,12 +35,14 @@ def vsflags(*args): return values -def read_msbuild_xml(path, values={}): +def read_msbuild_xml(path, values=None): """Reads the MS Build XML file at the path and returns its contents. Keyword arguments: values -- The map to append the contents to (default {}) """ + if values is None: + values = {} # Attempt to read the file contents try: @@ -76,12 +78,15 @@ def read_msbuild_xml(path, values={}): return values -def read_msbuild_json(path, values=[]): +def read_msbuild_json(path, values=None): """Reads the MS Build JSON file at the path and returns its contents. Keyword arguments: values -- The list to append the contents to (default []) """ + if values is None: + values = [] + if not os.path.exists(path): logging.info('Could not find MS Build JSON file at %s', path) return values diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx index 3692202..983a684 100644 --- a/Source/cmDependsFortran.cxx +++ b/Source/cmDependsFortran.cxx @@ -102,10 +102,7 @@ cmDependsFortran::cmDependsFortran(cmLocalGenerator* lg) this->SModExt = mf->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT"); } -cmDependsFortran::~cmDependsFortran() -{ - delete this->Internal; -} +cmDependsFortran::~cmDependsFortran() = default; bool cmDependsFortran::WriteDependencies(const std::set<std::string>& sources, const std::string& obj, diff --git a/Source/cmDependsFortran.h b/Source/cmDependsFortran.h index 0485115..e3e0d05 100644 --- a/Source/cmDependsFortran.h +++ b/Source/cmDependsFortran.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <iosfwd> +#include <memory> #include <set> #include <string> #include <vector> @@ -84,7 +85,7 @@ protected: std::set<std::string> PPDefinitions; // Internal implementation details. - cmDependsFortranInternals* Internal = nullptr; + std::unique_ptr<cmDependsFortranInternals> Internal; private: std::string MaybeConvertToRelativePath(std::string const& base, diff --git a/Source/cmDependsJavaParserHelper.cxx b/Source/cmDependsJavaParserHelper.cxx index 516bbbf..fc1bbdd 100644 --- a/Source/cmDependsJavaParserHelper.cxx +++ b/Source/cmDependsJavaParserHelper.cxx @@ -8,6 +8,7 @@ #include <iostream> #include <utility> +#include <cm/memory> #include <cm/string_view> #include "cmsys/FStream.hxx" @@ -169,10 +170,11 @@ void cmDependsJavaParserHelper::AllocateParserType( return; } this->UnionsAvailable++; - pt->str = new char[len + 1]; + auto up = cm::make_unique<char[]>(len + 1); + pt->str = up.get(); strncpy(pt->str, str, len); pt->str[len] = 0; - this->Allocates.push_back(pt->str); + this->Allocates.push_back(std::move(up)); } void cmDependsJavaParserHelper::StartClass(const char* cls) @@ -275,10 +277,7 @@ int cmDependsJavaParserHelper::ParseString(const char* str, int verb) void cmDependsJavaParserHelper::CleanupParser() { - for (char* allocate : this->Allocates) { - delete[] allocate; - } - this->Allocates.erase(this->Allocates.begin(), this->Allocates.end()); + this->Allocates.clear(); } int cmDependsJavaParserHelper::LexInput(char* buf, int maxlen) diff --git a/Source/cmDependsJavaParserHelper.h b/Source/cmDependsJavaParserHelper.h index a673b5b..c545ee2 100644 --- a/Source/cmDependsJavaParserHelper.h +++ b/Source/cmDependsJavaParserHelper.h @@ -5,6 +5,7 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include <memory> #include <string> #include <vector> @@ -81,7 +82,7 @@ private: int CurrentDepth; int Verbose; - std::vector<char*> Allocates; + std::vector<std::unique_ptr<char[]>> Allocates; void PrintClasses(); diff --git a/Source/cmDynamicLoader.cxx b/Source/cmDynamicLoader.cxx index 0b72a94..a3731c1 100644 --- a/Source/cmDynamicLoader.cxx +++ b/Source/cmDynamicLoader.cxx @@ -6,6 +6,7 @@ #include <string> #include <utility> +namespace { class cmDynamicLoaderCache { public: @@ -15,14 +16,15 @@ public: cmsys::DynamicLoader::LibraryHandle& /*p*/); bool FlushCache(const char* path); void FlushCache(); - static cmDynamicLoaderCache* GetInstance(); + static cmDynamicLoaderCache& GetInstance(); private: std::map<std::string, cmsys::DynamicLoader::LibraryHandle> CacheMap; - static cmDynamicLoaderCache* Instance; + static cmDynamicLoaderCache Instance; }; -cmDynamicLoaderCache* cmDynamicLoaderCache::Instance = nullptr; +cmDynamicLoaderCache cmDynamicLoaderCache::Instance; +} cmDynamicLoaderCache::~cmDynamicLoaderCache() = default; @@ -64,15 +66,11 @@ void cmDynamicLoaderCache::FlushCache() for (auto const& it : this->CacheMap) { cmsys::DynamicLoader::CloseLibrary(it.second); } - delete cmDynamicLoaderCache::Instance; - cmDynamicLoaderCache::Instance = nullptr; + this->CacheMap.clear(); } -cmDynamicLoaderCache* cmDynamicLoaderCache::GetInstance() +cmDynamicLoaderCache& cmDynamicLoaderCache::GetInstance() { - if (!cmDynamicLoaderCache::Instance) { - cmDynamicLoaderCache::Instance = new cmDynamicLoaderCache; - } return cmDynamicLoaderCache::Instance; } @@ -80,15 +78,15 @@ cmsys::DynamicLoader::LibraryHandle cmDynamicLoader::OpenLibrary( const char* libname) { cmsys::DynamicLoader::LibraryHandle lh; - if (cmDynamicLoaderCache::GetInstance()->GetCacheFile(libname, lh)) { + if (cmDynamicLoaderCache::GetInstance().GetCacheFile(libname, lh)) { return lh; } lh = cmsys::DynamicLoader::OpenLibrary(libname); - cmDynamicLoaderCache::GetInstance()->CacheFile(libname, lh); + cmDynamicLoaderCache::GetInstance().CacheFile(libname, lh); return lh; } void cmDynamicLoader::FlushCache() { - cmDynamicLoaderCache::GetInstance()->FlushCache(); + cmDynamicLoaderCache::GetInstance().FlushCache(); } diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx index 5be5bce..08a0f7e 100644 --- a/Source/cmExecuteProcessCommand.cxx +++ b/Source/cmExecuteProcessCommand.cxx @@ -61,6 +61,8 @@ bool cmExecuteProcessCommand(std::vector<std::string> const& args, bool ErrorQuiet = false; bool OutputStripTrailingWhitespace = false; bool ErrorStripTrailingWhitespace = false; + bool EchoOutputVariable = false; + bool EchoErrorVariable = false; std::string Encoding; }; @@ -83,7 +85,9 @@ bool cmExecuteProcessCommand(std::vector<std::string> const& args, &Arguments::OutputStripTrailingWhitespace) .Bind("ERROR_STRIP_TRAILING_WHITESPACE"_s, &Arguments::ErrorStripTrailingWhitespace) - .Bind("ENCODING"_s, &Arguments::Encoding); + .Bind("ENCODING"_s, &Arguments::Encoding) + .Bind("ECHO_OUTPUT_VARIABLE"_s, &Arguments::EchoOutputVariable) + .Bind("ECHO_ERROR_VARIABLE"_s, &Arguments::EchoErrorVariable); std::vector<std::string> unparsedArguments; std::vector<std::string> keywordsMissingValue; @@ -241,28 +245,32 @@ bool cmExecuteProcessCommand(std::vector<std::string> const& args, while ((p = cmsysProcess_WaitForData(cp, &data, &length, nullptr))) { // Put the output in the right place. if (p == cmsysProcess_Pipe_STDOUT && !arguments.OutputQuiet) { - if (arguments.OutputVariable.empty()) { + if (arguments.OutputVariable.empty() || arguments.EchoOutputVariable) { processOutput.DecodeText(data, length, strdata, 1); cmSystemTools::Stdout(strdata); - } else { + } + if (!arguments.OutputVariable.empty()) { cmExecuteProcessCommandAppend(tempOutput, data, length); } } else if (p == cmsysProcess_Pipe_STDERR && !arguments.ErrorQuiet) { - if (arguments.ErrorVariable.empty()) { + if (arguments.ErrorVariable.empty() || arguments.EchoErrorVariable) { processOutput.DecodeText(data, length, strdata, 2); cmSystemTools::Stderr(strdata); - } else { + } + if (!arguments.ErrorVariable.empty()) { cmExecuteProcessCommandAppend(tempError, data, length); } } } - if (!arguments.OutputQuiet && arguments.OutputVariable.empty()) { + if (!arguments.OutputQuiet && + (arguments.OutputVariable.empty() || arguments.EchoOutputVariable)) { processOutput.DecodeText(std::string(), strdata, 1); if (!strdata.empty()) { cmSystemTools::Stdout(strdata); } } - if (!arguments.ErrorQuiet && arguments.ErrorVariable.empty()) { + if (!arguments.ErrorQuiet && + (arguments.ErrorVariable.empty() || arguments.EchoErrorVariable)) { processOutput.DecodeText(std::string(), strdata, 2); if (!strdata.empty()) { cmSystemTools::Stderr(strdata); diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx index 79110ab..3b532c8 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -33,12 +33,14 @@ #include "cmFileInstaller.h" #include "cmFileLockPool.h" #include "cmFileTimes.h" +#include "cmGeneratedFileStream.h" #include "cmGeneratorExpression.h" #include "cmGlobalGenerator.h" #include "cmHexFileConverter.h" #include "cmListFileCache.h" #include "cmMakefile.h" #include "cmMessageType.h" +#include "cmNewLineStyle.h" #include "cmPolicies.h" #include "cmRange.h" #include "cmRuntimeDependencyArchive.h" @@ -2776,6 +2778,121 @@ bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args, return true; } +bool HandleConfigureCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + if (args.size() < 5) { + status.SetError("Incorrect arguments to CONFIGURE subcommand."); + return false; + } + if (args[1] != "OUTPUT") { + status.SetError("Incorrect arguments to CONFIGURE subcommand."); + return false; + } + if (args[3] != "CONTENT") { + status.SetError("Incorrect arguments to CONFIGURE subcommand."); + return false; + } + + std::string errorMessage; + cmNewLineStyle newLineStyle; + if (!newLineStyle.ReadFromArguments(args, errorMessage)) { + status.SetError(cmStrCat("CONFIGURE ", errorMessage)); + return false; + } + + bool escapeQuotes = false; + bool atOnly = false; + for (unsigned int i = 5; i < args.size(); ++i) { + if (args[i] == "@ONLY") { + atOnly = true; + } else if (args[i] == "ESCAPE_QUOTES") { + escapeQuotes = true; + } else if (args[i] == "NEWLINE_STYLE" || args[i] == "LF" || + args[i] == "UNIX" || args[i] == "CRLF" || args[i] == "WIN32" || + args[i] == "DOS") { + /* Options handled by NewLineStyle member above. */ + } else { + status.SetError( + cmStrCat("CONFIGURE Unrecognized argument \"", args[i], "\"")); + return false; + } + } + + // Check for generator expressions + const std::string input = args[4]; + std::string outputFile = args[2]; + + std::string::size_type pos = input.find_first_of("<>"); + if (pos != std::string::npos) { + status.SetError(cmStrCat("CONFIGURE called with CONTENT containing a \"", + input[pos], + "\". This character is not allowed.")); + return false; + } + + pos = outputFile.find_first_of("<>"); + if (pos != std::string::npos) { + status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"", + outputFile[pos], + "\". This character is not allowed.")); + return false; + } + + cmMakefile& makeFile = status.GetMakefile(); + if (!makeFile.CanIWriteThisFile(outputFile)) { + cmSystemTools::Error("Attempt to write file: " + outputFile + + " into a source directory."); + return false; + } + + cmSystemTools::ConvertToUnixSlashes(outputFile); + + // Re-generate if non-temporary outputs are missing. + // when we finalize the configuration we will remove all + // output files that now don't exist. + makeFile.AddCMakeOutputFile(outputFile); + + // Create output directory + const std::string::size_type slashPos = outputFile.rfind('/'); + if (slashPos != std::string::npos) { + const std::string path = outputFile.substr(0, slashPos); + cmSystemTools::MakeDirectory(path); + } + + std::string newLineCharacters; + bool open_with_binary_flag = false; + if (newLineStyle.IsValid()) { + open_with_binary_flag = true; + newLineCharacters = newLineStyle.GetCharacters(); + } + + cmGeneratedFileStream fout; + fout.Open(outputFile, false, open_with_binary_flag); + if (!fout) { + cmSystemTools::Error("Could not open file for write in copy operation " + + outputFile); + cmSystemTools::ReportLastSystemError(""); + return false; + } + fout.SetCopyIfDifferent(true); + + // copy intput to output and expand variables from input at the same time + std::stringstream sin(input, std::ios::in); + std::string inLine; + std::string outLine; + while (cmSystemTools::GetLineFromStream(sin, inLine)) { + outLine.clear(); + makeFile.ConfigureString(inLine, outLine, atOnly, escapeQuotes); + fout << outLine << newLineCharacters; + } + + // close file before attempting to copy + fout.close(); + + return true; +} + } // namespace bool cmFileCommand(std::vector<std::string> const& args, @@ -2829,6 +2946,7 @@ bool cmFileCommand(std::vector<std::string> const& args, { "READ_SYMLINK"_s, HandleReadSymlinkCommand }, { "CREATE_LINK"_s, HandleCreateLinkCommand }, { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand }, + { "CONFIGURE"_s, HandleConfigureCommand }, }; return subcommand(args[0], args, status); diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx index bec99bb..fb09b33 100644 --- a/Source/cmFindBase.cxx +++ b/Source/cmFindBase.cxx @@ -22,10 +22,6 @@ class cmExecutionStatus; cmFindBase::cmFindBase(cmExecutionStatus& status) : cmFindCommon(status) { - this->AlreadyInCache = false; - this->AlreadyInCacheWithoutMetaInfo = false; - this->NamesPerDir = false; - this->NamesPerDirAllowed = false; } bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn) @@ -115,6 +111,10 @@ bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn) } else if (args[j] == "NO_SYSTEM_PATH") { doing = DoingNone; this->NoDefaultPath = true; + } else if (args[j] == "REQUIRED") { + doing = DoingNone; + this->Required = true; + newStyle = true; } else if (this->CheckCommonArgument(args[j])) { doing = DoingNone; } else { diff --git a/Source/cmFindBase.h b/Source/cmFindBase.h index fce0b11..4cbf09e 100644 --- a/Source/cmFindBase.h +++ b/Source/cmFindBase.h @@ -44,14 +44,16 @@ protected: std::string VariableDocumentation; std::string VariableName; std::vector<std::string> Names; - bool NamesPerDir; - bool NamesPerDirAllowed; + bool NamesPerDir = false; + bool NamesPerDirAllowed = false; // CMAKE_*_PATH CMAKE_SYSTEM_*_PATH FRAMEWORK|LIBRARY|INCLUDE|PROGRAM std::string EnvironmentPath; // LIB,INCLUDE - bool AlreadyInCache; - bool AlreadyInCacheWithoutMetaInfo; + bool AlreadyInCache = false; + bool AlreadyInCacheWithoutMetaInfo = false; + + bool Required = false; private: // Add pieces of the search. diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx index d5a4bde..6f9f7a2 100644 --- a/Source/cmFindLibraryCommand.cxx +++ b/Source/cmFindLibraryCommand.cxx @@ -12,6 +12,7 @@ #include "cmGlobalGenerator.h" #include "cmMakefile.h" +#include "cmMessageType.h" #include "cmState.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" @@ -84,6 +85,13 @@ bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn) this->Makefile->AddCacheDefinition(this->VariableName, notfound.c_str(), this->VariableDocumentation.c_str(), cmStateEnums::FILEPATH); + if (this->Required) { + this->Makefile->IssueMessage( + MessageType::FATAL_ERROR, + "Could not find " + this->VariableName + + " using the following names: " + cmJoin(this->Names, ", ")); + cmSystemTools::SetFatalErrorOccured(); + } return true; } diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx index 908f0c1..f5b52c2 100644 --- a/Source/cmFindPathCommand.cxx +++ b/Source/cmFindPathCommand.cxx @@ -5,6 +5,7 @@ #include "cmsys/Glob.hxx" #include "cmMakefile.h" +#include "cmMessageType.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" @@ -51,6 +52,13 @@ bool cmFindPathCommand::InitialPass(std::vector<std::string> const& argsIn) this->VariableName, (this->VariableName + "-NOTFOUND").c_str(), this->VariableDocumentation.c_str(), (this->IncludeFileInPath) ? cmStateEnums::FILEPATH : cmStateEnums::PATH); + if (this->Required) { + this->Makefile->IssueMessage( + MessageType::FATAL_ERROR, + "Could not find " + this->VariableName + + " using the following files: " + cmJoin(this->Names, ", ")); + cmSystemTools::SetFatalErrorOccured(); + } return true; } diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx index 3e49172..cbc3c78 100644 --- a/Source/cmFindProgramCommand.cxx +++ b/Source/cmFindProgramCommand.cxx @@ -3,6 +3,7 @@ #include "cmFindProgramCommand.h" #include "cmMakefile.h" +#include "cmMessageType.h" #include "cmStateTypes.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" @@ -136,6 +137,13 @@ bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn) this->Makefile->AddCacheDefinition( this->VariableName, (this->VariableName + "-NOTFOUND").c_str(), this->VariableDocumentation.c_str(), cmStateEnums::FILEPATH); + if (this->Required) { + this->Makefile->IssueMessage( + MessageType::FATAL_ERROR, + "Could not find " + this->VariableName + + " using the following names: " + cmJoin(this->Names, ", ")); + cmSystemTools::SetFatalErrorOccured(); + } return true; } diff --git a/Source/cmGeneratedFileStream.cxx b/Source/cmGeneratedFileStream.cxx index 2af04b6..f76e205 100644 --- a/Source/cmGeneratedFileStream.cxx +++ b/Source/cmGeneratedFileStream.cxx @@ -180,6 +180,7 @@ int cmGeneratedFileStreamBase::CompressFile(std::string const& oldname, } FILE* ifs = cmsys::SystemTools::Fopen(oldname, "r"); if (!ifs) { + gzclose(gf); return 0; } size_t res; diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx index 81d1e46..6e293d5 100644 --- a/Source/cmGeneratorExpression.cxx +++ b/Source/cmGeneratorExpression.cxx @@ -32,12 +32,6 @@ std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( new cmCompiledGeneratorExpression(this->Backtrace, std::move(input))); } -std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse( - const char* input) const -{ - return this->Parse(std::string(input ? input : "")); -} - std::string cmGeneratorExpression::Evaluate( std::string input, cmLocalGenerator* lg, const std::string& config, cmGeneratorTarget const* headTarget, @@ -52,17 +46,6 @@ std::string cmGeneratorExpression::Evaluate( return input; } -std::string cmGeneratorExpression::Evaluate( - const char* input, cmLocalGenerator* lg, const std::string& config, - cmGeneratorTarget const* headTarget, - cmGeneratorExpressionDAGChecker* dagChecker, - cmGeneratorTarget const* currentTarget, std::string const& language) -{ - return input ? Evaluate(std::string(input), lg, config, headTarget, - dagChecker, currentTarget, language) - : ""; -} - const std::string& cmCompiledGeneratorExpression::Evaluate( cmLocalGenerator* lg, const std::string& config, const cmGeneratorTarget* headTarget, @@ -103,6 +86,8 @@ const std::string& cmCompiledGeneratorExpression::EvaluateWithContext( if (!context.HadError) { this->HadContextSensitiveCondition = context.HadContextSensitiveCondition; this->HadHeadSensitiveCondition = context.HadHeadSensitiveCondition; + this->HadLinkLanguageSensitiveCondition = + context.HadLinkLanguageSensitiveCondition; this->SourceSensitiveTargets = context.SourceSensitiveTargets; } @@ -119,6 +104,7 @@ cmCompiledGeneratorExpression::cmCompiledGeneratorExpression( , Quiet(false) , HadContextSensitiveCondition(false) , HadHeadSensitiveCondition(false) + , HadLinkLanguageSensitiveCondition(false) { cmGeneratorExpressionLexer l; std::vector<cmGeneratorExpressionToken> tokens = l.Tokenize(this->Input); diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h index c4be3a1..75bba02 100644 --- a/Source/cmGeneratorExpression.h +++ b/Source/cmGeneratorExpression.h @@ -42,8 +42,6 @@ public: std::unique_ptr<cmCompiledGeneratorExpression> Parse( std::string input) const; - std::unique_ptr<cmCompiledGeneratorExpression> Parse( - const char* input) const; static std::string Evaluate( std::string input, cmLocalGenerator* lg, const std::string& config, @@ -51,12 +49,6 @@ public: cmGeneratorExpressionDAGChecker* dagChecker = nullptr, cmGeneratorTarget const* currentTarget = nullptr, std::string const& language = std::string()); - static std::string Evaluate( - const char* input, cmLocalGenerator* lg, const std::string& config, - cmGeneratorTarget const* headTarget = nullptr, - cmGeneratorExpressionDAGChecker* dagChecker = nullptr, - cmGeneratorTarget const* currentTarget = nullptr, - std::string const& language = std::string()); enum PreprocessContext { @@ -137,6 +129,10 @@ public: { return this->HadHeadSensitiveCondition; } + bool GetHadLinkLanguageSensitiveCondition() const + { + return this->HadLinkLanguageSensitiveCondition; + } std::set<cmGeneratorTarget const*> GetSourceSensitiveTargets() const { return this->SourceSensitiveTargets; @@ -178,6 +174,7 @@ private: mutable std::string Output; mutable bool HadContextSensitiveCondition; mutable bool HadHeadSensitiveCondition; + mutable bool HadLinkLanguageSensitiveCondition; mutable std::set<cmGeneratorTarget const*> SourceSensitiveTargets; }; diff --git a/Source/cmGeneratorExpressionContext.cxx b/Source/cmGeneratorExpressionContext.cxx index 6d97331..42cbe2a 100644 --- a/Source/cmGeneratorExpressionContext.cxx +++ b/Source/cmGeneratorExpressionContext.cxx @@ -19,6 +19,7 @@ cmGeneratorExpressionContext::cmGeneratorExpressionContext( , HadError(false) , HadContextSensitiveCondition(false) , HadHeadSensitiveCondition(false) + , HadLinkLanguageSensitiveCondition(false) , EvaluateForBuildsystem(evaluateForBuildsystem) { } diff --git a/Source/cmGeneratorExpressionContext.h b/Source/cmGeneratorExpressionContext.h index 4709fa0..bceff12 100644 --- a/Source/cmGeneratorExpressionContext.h +++ b/Source/cmGeneratorExpressionContext.h @@ -40,6 +40,7 @@ struct cmGeneratorExpressionContext bool HadError; bool HadContextSensitiveCondition; bool HadHeadSensitiveCondition; + bool HadLinkLanguageSensitiveCondition; bool EvaluateForBuildsystem; }; diff --git a/Source/cmGeneratorExpressionDAGChecker.cxx b/Source/cmGeneratorExpressionDAGChecker.cxx index 643ba34..2c73289 100644 --- a/Source/cmGeneratorExpressionDAGChecker.cxx +++ b/Source/cmGeneratorExpressionDAGChecker.cxx @@ -6,6 +6,10 @@ #include <sstream> #include <utility> +#include <cm/string_view> + +#include "cm_static_string_view.hxx" + #include "cmGeneratorExpressionContext.h" #include "cmGeneratorExpressionEvaluator.h" #include "cmGeneratorTarget.h" @@ -170,6 +174,21 @@ bool cmGeneratorExpressionDAGChecker::EvaluatingPICExpression() return top->Property == "INTERFACE_POSITION_INDEPENDENT_CODE"; } +bool cmGeneratorExpressionDAGChecker::EvaluatingLinkExpression() +{ + const cmGeneratorExpressionDAGChecker* top = this; + const cmGeneratorExpressionDAGChecker* parent = this->Parent; + while (parent) { + top = parent; + parent = parent->Parent; + } + + cm::string_view property(top->Property); + + return property == "LINK_DIRECTORIES"_s || property == "LINK_OPTIONS"_s || + property == "LINK_DEPENDS"_s; +} + bool cmGeneratorExpressionDAGChecker::EvaluatingLinkLibraries( cmGeneratorTarget const* tgt) { @@ -180,18 +199,17 @@ bool cmGeneratorExpressionDAGChecker::EvaluatingLinkLibraries( parent = parent->Parent; } - const char* prop = top->Property.c_str(); + cm::string_view prop(top->Property); if (tgt) { - return top->Target == tgt && strcmp(prop, "LINK_LIBRARIES") == 0; + return top->Target == tgt && prop == "LINK_LIBRARIES"_s; } - return (strcmp(prop, "LINK_LIBRARIES") == 0 || - strcmp(prop, "LINK_INTERFACE_LIBRARIES") == 0 || - strcmp(prop, "IMPORTED_LINK_INTERFACE_LIBRARIES") == 0 || - cmHasLiteralPrefix(prop, "LINK_INTERFACE_LIBRARIES_") || - cmHasLiteralPrefix(prop, "IMPORTED_LINK_INTERFACE_LIBRARIES_")) || - strcmp(prop, "INTERFACE_LINK_LIBRARIES") == 0; + return prop == "LINK_LIBRARIES"_s || prop == "LINK_INTERFACE_LIBRARIES"_s || + prop == "IMPORTED_LINK_INTERFACE_LIBRARIES"_s || + cmHasLiteralPrefix(prop, "LINK_INTERFACE_LIBRARIES_") || + cmHasLiteralPrefix(prop, "IMPORTED_LINK_INTERFACE_LIBRARIES_") || + prop == "INTERFACE_LINK_LIBRARIES"_s; } cmGeneratorTarget const* cmGeneratorExpressionDAGChecker::TopTarget() const diff --git a/Source/cmGeneratorExpressionDAGChecker.h b/Source/cmGeneratorExpressionDAGChecker.h index f2c49bb..2a06596 100644 --- a/Source/cmGeneratorExpressionDAGChecker.h +++ b/Source/cmGeneratorExpressionDAGChecker.h @@ -68,6 +68,7 @@ struct cmGeneratorExpressionDAGChecker bool EvaluatingGenexExpression(); bool EvaluatingPICExpression(); + bool EvaluatingLinkExpression(); bool EvaluatingLinkLibraries(cmGeneratorTarget const* tgt = nullptr); #define DECLARE_TRANSITIVE_PROPERTY_METHOD(METHOD) bool METHOD() const; diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx index 14478c2..8831d0f 100644 --- a/Source/cmGeneratorExpressionNode.cxx +++ b/Source/cmGeneratorExpressionNode.cxx @@ -62,6 +62,9 @@ std::string cmGeneratorExpressionNode::EvaluateDependentExpression( if (cge->GetHadHeadSensitiveCondition()) { context->HadHeadSensitiveCondition = true; } + if (cge->GetHadLinkLanguageSensitiveCondition()) { + context->HadLinkLanguageSensitiveCondition = true; + } return result; } @@ -1039,6 +1042,150 @@ static const struct CompileLanguageAndIdNode : public cmGeneratorExpressionNode } } languageAndIdNode; +static const struct LinkLanguageNode : public cmGeneratorExpressionNode +{ + LinkLanguageNode() {} // NOLINT(modernize-use-equals-default) + + int NumExpectedParameters() const override { return ZeroOrMoreParameters; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override + { + if (!context->HeadTarget || !dagChecker || + !(dagChecker->EvaluatingLinkExpression() || + dagChecker->EvaluatingLinkLibraries())) { + reportError(context, content->GetOriginalExpression(), + "$<LINK_LANGUAGE:...> may only be used with binary targets " + "to specify link libraries, link directories, link options " + "and link depends."); + return std::string(); + } + if (dagChecker->EvaluatingLinkLibraries() && parameters.empty()) { + reportError( + context, content->GetOriginalExpression(), + "$<LINK_LANGUAGE> is not supported in link libraries expression."); + return std::string(); + } + + cmGlobalGenerator* gg = context->LG->GetGlobalGenerator(); + std::string genName = gg->GetName(); + if (genName.find("Makefiles") == std::string::npos && + genName.find("Ninja") == std::string::npos && + genName.find("Visual Studio") == std::string::npos && + genName.find("Xcode") == std::string::npos && + genName.find("Watcom WMake") == std::string::npos) { + reportError(context, content->GetOriginalExpression(), + "$<LINK_LANGUAGE:...> not supported for this generator."); + return std::string(); + } + + if (dagChecker->EvaluatingLinkLibraries()) { + context->HadHeadSensitiveCondition = true; + context->HadLinkLanguageSensitiveCondition = true; + } + + if (parameters.empty()) { + return context->Language; + } + + for (auto& param : parameters) { + if (context->Language == param) { + return "1"; + } + } + return "0"; + } +} linkLanguageNode; + +namespace { +struct LinkerId +{ + static std::string Evaluate(const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + const std::string& lang) + { + std::string const& linkerId = + context->LG->GetMakefile()->GetSafeDefinition("CMAKE_" + lang + + "_COMPILER_ID"); + if (parameters.empty()) { + return linkerId; + } + if (linkerId.empty()) { + return parameters.front().empty() ? "1" : "0"; + } + static cmsys::RegularExpression linkerIdValidator("^[A-Za-z0-9_]*$"); + + for (auto& param : parameters) { + if (!linkerIdValidator.find(param)) { + reportError(context, content->GetOriginalExpression(), + "Expression syntax not recognized."); + return std::string(); + } + + if (param == linkerId) { + return "1"; + } + } + return "0"; + } +}; +} + +static const struct LinkLanguageAndIdNode : public cmGeneratorExpressionNode +{ + LinkLanguageAndIdNode() {} // NOLINT(modernize-use-equals-default) + + int NumExpectedParameters() const override { return TwoOrMoreParameters; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagChecker) const override + { + if (!context->HeadTarget || !dagChecker || + !(dagChecker->EvaluatingLinkExpression() || + dagChecker->EvaluatingLinkLibraries())) { + reportError( + context, content->GetOriginalExpression(), + "$<LINK_LANG_AND_ID:lang,id> may only be used with binary targets " + "to specify link libraries, link directories, link options, and link " + "depends."); + return std::string(); + } + + cmGlobalGenerator* gg = context->LG->GetGlobalGenerator(); + std::string genName = gg->GetName(); + if (genName.find("Makefiles") == std::string::npos && + genName.find("Ninja") == std::string::npos && + genName.find("Visual Studio") == std::string::npos && + genName.find("Xcode") == std::string::npos && + genName.find("Watcom WMake") == std::string::npos) { + reportError( + context, content->GetOriginalExpression(), + "$<LINK_LANG_AND_ID:lang,id> not supported for this generator."); + return std::string(); + } + + if (dagChecker->EvaluatingLinkLibraries()) { + context->HadHeadSensitiveCondition = true; + context->HadLinkLanguageSensitiveCondition = true; + } + + const std::string& lang = context->Language; + if (lang == parameters.front()) { + std::vector<std::string> idParameter((parameters.cbegin() + 1), + parameters.cend()); + return LinkerId::Evaluate(idParameter, context, content, lang); + } + return "0"; + } +} linkLanguageAndIdNode; + std::string getLinkedTargetsContent( cmGeneratorTarget const* target, std::string const& prop, cmGeneratorExpressionContext* context, @@ -2314,6 +2461,8 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode( { "LINK_ONLY", &linkOnlyNode }, { "COMPILE_LANG_AND_ID", &languageAndIdNode }, { "COMPILE_LANGUAGE", &languageNode }, + { "LINK_LANG_AND_ID", &linkLanguageAndIdNode }, + { "LINK_LANGUAGE", &linkLanguageNode }, { "SHELL_PATH", &shellPathNode } }; diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx index ba2e314..ad142d7 100644 --- a/Source/cmGeneratorTarget.cxx +++ b/Source/cmGeneratorTarget.cxx @@ -17,6 +17,7 @@ #include <cm/memory> #include <cm/string_view> +#include <cmext/algorithm> #include "cmsys/RegularExpression.hxx" @@ -308,6 +309,13 @@ cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg) this->SourceEntries, true); this->PolicyMap = t->GetPolicyMap(); + + // Get hard-coded linker language + if (this->Target->GetProperty("HAS_CXX")) { + this->LinkerLanguage = "CXX"; + } else { + this->LinkerLanguage = this->Target->GetSafeProperty("LINKER_LANGUAGE"); + } } cmGeneratorTarget::~cmGeneratorTarget() = default; @@ -531,15 +539,43 @@ std::string cmGeneratorTarget::GetFileSuffix( std::string cmGeneratorTarget::GetFilePostfix(const std::string& config) const { const char* postfix = nullptr; + std::string frameworkPostfix; if (!config.empty()) { std::string configProp = cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX"); postfix = this->GetProperty(configProp); - // Mac application bundles and frameworks have no postfix. + + // Mac application bundles and frameworks have no regular postfix like + // libraries do. if (!this->IsImported() && postfix && (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) { postfix = nullptr; } + + // Frameworks created by multi config generators can have a special + // framework postfix. + frameworkPostfix = GetFrameworkMultiConfigPostfix(config); + if (!frameworkPostfix.empty()) { + postfix = frameworkPostfix.c_str(); + } + } + return postfix ? postfix : std::string(); +} + +std::string cmGeneratorTarget::GetFrameworkMultiConfigPostfix( + const std::string& config) const +{ + const char* postfix = nullptr; + if (!config.empty()) { + std::string configProp = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_", + cmSystemTools::UpperCase(config)); + postfix = this->GetProperty(configProp); + + if (!this->IsImported() && postfix && + (this->IsFrameworkOnApple() && + !GetGlobalGenerator()->IsMultiConfig())) { + postfix = nullptr; + } } return postfix ? postfix : std::string(); } @@ -2223,11 +2259,12 @@ public: cmTargetCollectLinkLanguages(cmGeneratorTarget const* target, std::string config, std::unordered_set<std::string>& languages, - cmGeneratorTarget const* head) + cmGeneratorTarget const* head, bool secondPass) : Config(std::move(config)) , Languages(languages) , HeadTarget(head) , Target(target) + , SecondPass(secondPass) { this->Visited.insert(target); } @@ -2269,11 +2306,14 @@ public: if (!this->Visited.insert(item.Target).second) { return; } - cmLinkInterface const* iface = - item.Target->GetLinkInterface(this->Config, this->HeadTarget); + cmLinkInterface const* iface = item.Target->GetLinkInterface( + this->Config, this->HeadTarget, this->SecondPass); if (!iface) { return; } + if (iface->HadLinkLanguageSensitiveCondition) { + this->HadLinkLanguageSensitiveCondition = true; + } for (std::string const& language : iface->Languages) { this->Languages.insert(language); @@ -2284,12 +2324,19 @@ public: } } + bool GetHadLinkLanguageSensitiveCondition() + { + return HadLinkLanguageSensitiveCondition; + } + private: std::string Config; std::unordered_set<std::string>& Languages; cmGeneratorTarget const* HeadTarget; const cmGeneratorTarget* Target; std::set<cmGeneratorTarget const*> Visited; + bool SecondPass; + bool HadLinkLanguageSensitiveCondition = false; }; cmGeneratorTarget::LinkClosure const* cmGeneratorTarget::GetLinkClosure( @@ -2320,7 +2367,7 @@ public: { this->GG = this->Target->GetLocalGenerator()->GetGlobalGenerator(); } - void Consider(const char* lang) + void Consider(const std::string& lang) { int preference = this->GG->GetLinkerPreference(lang); if (preference > this->Preference) { @@ -2353,40 +2400,36 @@ public: } }; -void cmGeneratorTarget::ComputeLinkClosure(const std::string& config, - LinkClosure& lc) const +bool cmGeneratorTarget::ComputeLinkClosure(const std::string& config, + LinkClosure& lc, + bool secondPass) const { // Get languages built in this target. std::unordered_set<std::string> languages; - cmLinkImplementation const* impl = this->GetLinkImplementation(config); + cmLinkImplementation const* impl = + this->GetLinkImplementation(config, secondPass); assert(impl); - for (std::string const& li : impl->Languages) { - languages.insert(li); - } + languages.insert(impl->Languages.cbegin(), impl->Languages.cend()); // Add interface languages from linked targets. - cmTargetCollectLinkLanguages cll(this, config, languages, this); + // cmTargetCollectLinkLanguages cll(this, config, languages, this, + // secondPass); + cmTargetCollectLinkLanguages cll(this, config, languages, this, secondPass); for (cmLinkImplItem const& lib : impl->Libraries) { cll.Visit(lib); } // Store the transitive closure of languages. - for (std::string const& lang : languages) { - lc.Languages.push_back(lang); - } + cm::append(lc.Languages, languages); // Choose the language whose linker should be used. - if (this->GetProperty("HAS_CXX")) { - lc.LinkerLanguage = "CXX"; - } else if (const char* linkerLang = this->GetProperty("LINKER_LANGUAGE")) { - lc.LinkerLanguage = linkerLang; - } else { + if (secondPass || lc.LinkerLanguage.empty()) { // Find the language with the highest preference value. cmTargetSelectLinker tsl(this); // First select from the languages compiled directly in this target. for (std::string const& l : impl->Languages) { - tsl.Consider(l.c_str()); + tsl.Consider(l); } // Now consider languages that propagate from linked targets. @@ -2394,12 +2437,50 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config, std::string propagates = "CMAKE_" + lang + "_LINKER_PREFERENCE_PROPAGATES"; if (this->Makefile->IsOn(propagates)) { - tsl.Consider(lang.c_str()); + tsl.Consider(lang); } } lc.LinkerLanguage = tsl.Choose(); } + + return impl->HadLinkLanguageSensitiveCondition || + cll.GetHadLinkLanguageSensitiveCondition(); +} + +void cmGeneratorTarget::ComputeLinkClosure(const std::string& config, + LinkClosure& lc) const +{ + bool secondPass = false; + + { + LinkClosure linkClosure; + linkClosure.LinkerLanguage = this->LinkerLanguage; + + // Get languages built in this target. + secondPass = this->ComputeLinkClosure(config, linkClosure, false); + this->LinkerLanguage = linkClosure.LinkerLanguage; + if (!secondPass) { + lc = std::move(linkClosure); + } + } + + if (secondPass) { + LinkClosure linkClosure; + + this->ComputeLinkClosure(config, linkClosure, secondPass); + lc = std::move(linkClosure); + + // linker language must not be changed between the two passes + if (this->LinkerLanguage != lc.LinkerLanguage) { + std::ostringstream e; + e << "Evaluation of $<LINK_LANGUAGE:...> or $<LINK_LAND_AND_ID:...> " + "changes\nthe linker language for target \"" + << this->GetName() << "\" (from '" << this->LinkerLanguage << "' to '" + << lc.LinkerLanguage << "') which is invalid."; + cmSystemTools::Error(e.str()); + } + } } void cmGeneratorTarget::GetFullNameComponents( @@ -4188,8 +4269,8 @@ cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames( targetNames.Real += this->GetFrameworkVersion(); targetNames.Real += "/"; } - targetNames.Real += targetNames.Base; - targetNames.SharedObject = targetNames.Real; + targetNames.Real += targetNames.Base + suffix; + targetNames.SharedObject = targetNames.Real + suffix; } else { // The library's soname. this->ComputeVersionedName(targetNames.SharedObject, prefix, @@ -4364,7 +4445,15 @@ void cmGeneratorTarget::GetFullNameInternal( outBase += this->GetOutputName(config, artifact); // Append the per-configuration postfix. - outBase += configPostfix; + // When using Xcode, the postfix should be part of the suffix rather than the + // base, because the suffix ends up being used in Xcode's EXECUTABLE_SUFFIX + // attribute. + if (this->IsFrameworkOnApple() && + GetGlobalGenerator()->GetName() == "Xcode") { + targetSuffix = configPostfix.c_str(); + } else { + outBase += configPostfix; + } // Name shared libraries with their version number on some platforms. if (const char* soversion = this->GetProperty("SOVERSION")) { @@ -5492,7 +5581,8 @@ void cmGeneratorTarget::LookupLinkItems(std::vector<std::string> const& names, void cmGeneratorTarget::ExpandLinkItems( std::string const& prop, std::string const& value, std::string const& config, cmGeneratorTarget const* headTarget, bool usage_requirements_only, - std::vector<cmLinkItem>& items, bool& hadHeadSensitiveCondition) const + std::vector<cmLinkItem>& items, bool& hadHeadSensitiveCondition, + bool& hadLinkLanguageSensitiveCondition) const { // Keep this logic in sync with ComputeLinkImplementationLibraries. cmGeneratorExpression ge; @@ -5504,19 +5594,28 @@ void cmGeneratorTarget::ExpandLinkItems( } std::vector<std::string> libs; std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value); - cmExpandList( - cge->Evaluate(this->LocalGenerator, config, headTarget, &dagChecker, this), - libs); + cmExpandList(cge->Evaluate(this->LocalGenerator, config, headTarget, + &dagChecker, this, headTarget->LinkerLanguage), + libs); this->LookupLinkItems(libs, cge->GetBacktrace(), items); hadHeadSensitiveCondition = cge->GetHadHeadSensitiveCondition(); + hadLinkLanguageSensitiveCondition = + cge->GetHadLinkLanguageSensitiveCondition(); } cmLinkInterface const* cmGeneratorTarget::GetLinkInterface( const std::string& config, cmGeneratorTarget const* head) const { + return this->GetLinkInterface(config, head, false); +} + +cmLinkInterface const* cmGeneratorTarget::GetLinkInterface( + const std::string& config, cmGeneratorTarget const* head, + bool secondPass) const +{ // Imported targets have their own link interface. if (this->IsImported()) { - return this->GetImportLinkInterface(config, head, false); + return this->GetImportLinkInterface(config, head, false, secondPass); } // Link interfaces are not supported for executables that do not @@ -5529,6 +5628,10 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface( // Lookup any existing link interface for this configuration. cmHeadToLinkInterfaceMap& hm = this->GetHeadToLinkInterfaceMap(config); + if (secondPass) { + hm.erase(head); + } + // If the link interface does not depend on the head target // then return the one we computed first. if (!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition) { @@ -5543,7 +5646,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface( if (!iface.AllDone) { iface.AllDone = true; if (iface.Exists) { - this->ComputeLinkInterface(config, iface, head); + this->ComputeLinkInterface(config, iface, head, secondPass); } } @@ -5554,6 +5657,13 @@ void cmGeneratorTarget::ComputeLinkInterface( const std::string& config, cmOptionalLinkInterface& iface, cmGeneratorTarget const* headTarget) const { + this->ComputeLinkInterface(config, iface, headTarget, false); +} + +void cmGeneratorTarget::ComputeLinkInterface( + const std::string& config, cmOptionalLinkInterface& iface, + cmGeneratorTarget const* headTarget, bool secondPass) const +{ if (iface.Explicit) { if (this->GetType() == cmStateEnums::SHARED_LIBRARY || this->GetType() == cmStateEnums::STATIC_LIBRARY || @@ -5565,7 +5675,8 @@ void cmGeneratorTarget::ComputeLinkInterface( emitted.insert(lib); } if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) { - cmLinkImplementation const* impl = this->GetLinkImplementation(config); + cmLinkImplementation const* impl = + this->GetLinkImplementation(config, secondPass); for (cmLinkImplItem const& lib : impl->Libraries) { if (emitted.insert(lib).second) { if (lib.Target) { @@ -5595,7 +5706,7 @@ void cmGeneratorTarget::ComputeLinkInterface( if (this->LinkLanguagePropagatesToDependents()) { // Targets using this archive need its language runtime libraries. if (cmLinkImplementation const* impl = - this->GetLinkImplementation(config)) { + this->GetLinkImplementation(config, secondPass)) { iface.Languages = impl->Languages; } } @@ -5991,7 +6102,8 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries( // The interface libraries have been explicitly set. this->ExpandLinkItems(linkIfaceProp, explicitLibraries, config, headTarget, usage_requirements_only, iface.Libraries, - iface.HadHeadSensitiveCondition); + iface.HadHeadSensitiveCondition, + iface.HadLinkLanguageSensitiveCondition); } else if (!cmp0022NEW) // If CMP0022 is NEW then the plain tll signature sets the // INTERFACE_LINK_LIBRARIES, so if we get here then the project @@ -6011,9 +6123,11 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries( static const std::string newProp = "INTERFACE_LINK_LIBRARIES"; if (const char* newExplicitLibraries = this->GetProperty(newProp)) { bool hadHeadSensitiveConditionDummy = false; + bool hadLinkLanguageSensitiveConditionDummy = false; this->ExpandLinkItems(newProp, newExplicitLibraries, config, headTarget, usage_requirements_only, ifaceLibs, - hadHeadSensitiveConditionDummy); + hadHeadSensitiveConditionDummy, + hadLinkLanguageSensitiveConditionDummy); } if (ifaceLibs != iface.Libraries) { std::string oldLibraries = cmJoin(impl->Libraries, ";"); @@ -6050,7 +6164,7 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries( const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface( const std::string& config, cmGeneratorTarget const* headTarget, - bool usage_requirements_only) const + bool usage_requirements_only, bool secondPass) const { cmGeneratorTarget::ImportInfo const* info = this->GetImportInfo(config); if (!info) { @@ -6063,6 +6177,10 @@ const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface( ? this->GetHeadToLinkInterfaceUsageRequirementsMap(config) : this->GetHeadToLinkInterfaceMap(config)); + if (secondPass) { + hm.erase(headTarget); + } + // If the link interface does not depend on the head target // then return the one we computed first. if (!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition) { @@ -6076,7 +6194,8 @@ const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface( cmExpandList(info->Languages, iface.Languages); this->ExpandLinkItems(info->LibrariesProp, info->Libraries, config, headTarget, usage_requirements_only, iface.Libraries, - iface.HadHeadSensitiveCondition); + iface.HadHeadSensitiveCondition, + iface.HadLinkLanguageSensitiveCondition); std::vector<std::string> deps = cmExpandedList(info->SharedDeps); this->LookupLinkItems(deps, cmListFileBacktrace(), iface.SharedDeps); } @@ -6281,6 +6400,12 @@ cmGeneratorTarget::GetHeadToLinkInterfaceUsageRequirementsMap( const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation( const std::string& config) const { + return this->GetLinkImplementation(config, false); +} + +const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation( + const std::string& config, bool secondPass) const +{ // There is no link implementation for imported targets. if (this->IsImported()) { return nullptr; @@ -6288,6 +6413,9 @@ const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation( std::string CONFIG = cmSystemTools::UpperCase(config); cmOptionalLinkImplementation& impl = this->LinkImplMap[CONFIG][this]; + if (secondPass) { + impl = cmOptionalLinkImplementation(); + } if (!impl.LibrariesDone) { impl.LibrariesDone = true; this->ComputeLinkImplementationLibraries(config, impl, this); @@ -6585,11 +6713,15 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries( cmGeneratorExpression ge(*btIt); std::unique_ptr<cmCompiledGeneratorExpression> const cge = ge.Parse(*le); std::string const& evaluated = - cge->Evaluate(this->LocalGenerator, config, head, &dagChecker); + cge->Evaluate(this->LocalGenerator, config, head, &dagChecker, nullptr, + this->LinkerLanguage); cmExpandList(evaluated, llibs); if (cge->GetHadHeadSensitiveCondition()) { impl.HadHeadSensitiveCondition = true; } + if (cge->GetHadLinkLanguageSensitiveCondition()) { + impl.HadLinkLanguageSensitiveCondition = true; + } for (std::string const& lib : llibs) { if (this->IsLinkLookupScope(lib, lg)) { diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h index d81bb3d..12d30c5 100644 --- a/Source/cmGeneratorTarget.h +++ b/Source/cmGeneratorTarget.h @@ -357,7 +357,6 @@ public: }; LinkClosure const* GetLinkClosure(const std::string& config) const; - void ComputeLinkClosure(const std::string& config, LinkClosure& lc) const; cmLinkImplementation const* GetLinkImplementation( const std::string& config) const; @@ -589,6 +588,9 @@ public: /** Get target file postfix */ std::string GetFilePostfix(const std::string& config) const; + /** Get framework multi-config-specific postfix */ + std::string GetFrameworkMultiConfigPostfix(const std::string& config) const; + /** Clears cached meta data for local and external source files. * The meta data will be recomputed on demand. */ @@ -816,6 +818,7 @@ private: std::string& outPrefix, std::string& outBase, std::string& outSuffix) const; + mutable std::string LinkerLanguage; using LinkClosureMapType = std::map<std::string, LinkClosure>; mutable LinkClosureMapType LinkClosureMap; @@ -850,6 +853,10 @@ private: void CheckPropertyCompatibility(cmComputeLinkInformation& info, const std::string& config) const; + void ComputeLinkClosure(const std::string& config, LinkClosure& lc) const; + bool ComputeLinkClosure(const std::string& config, LinkClosure& lc, + bool secondPass) const; + struct LinkImplClosure : public std::vector<cmGeneratorTarget const*> { bool Done = false; @@ -868,6 +875,17 @@ private: std::string GetLinkInterfaceDependentStringAsBoolProperty( const std::string& p, const std::string& config) const; + friend class cmTargetCollectLinkLanguages; + cmLinkInterface const* GetLinkInterface(const std::string& config, + const cmGeneratorTarget* headTarget, + bool secondPass) const; + void ComputeLinkInterface(const std::string& config, + cmOptionalLinkInterface& iface, + const cmGeneratorTarget* head, + bool secondPass) const; + cmLinkImplementation const* GetLinkImplementation(const std::string& config, + bool secondPass) const; + // Cache import information from properties for each configuration. struct ImportInfo { @@ -894,9 +912,10 @@ private: the link dependencies of this target. */ std::string CheckCMP0004(std::string const& item) const; - cmLinkInterface const* GetImportLinkInterface( - const std::string& config, const cmGeneratorTarget* head, - bool usage_requirements_only) const; + cmLinkInterface const* GetImportLinkInterface(const std::string& config, + const cmGeneratorTarget* head, + bool usage_requirements_only, + bool secondPass = false) const; using KindedSourcesMapType = std::map<std::string, KindedSources>; mutable KindedSourcesMapType KindedSourcesMap; @@ -940,7 +959,8 @@ private: const cmGeneratorTarget* headTarget, bool usage_requirements_only, std::vector<cmLinkItem>& items, - bool& hadHeadSensitiveCondition) const; + bool& hadHeadSensitiveCondition, + bool& hadLinkLanguageSensitiveCondition) const; void LookupLinkItems(std::vector<std::string> const& names, cmListFileBacktrace const& bt, std::vector<cmLinkItem>& items) const; diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx index 5e2248e..6470ea1 100644 --- a/Source/cmGhsMultiTargetGenerator.cxx +++ b/Source/cmGhsMultiTargetGenerator.cxx @@ -180,15 +180,12 @@ void cmGhsMultiTargetGenerator::SetCompilerFlags(std::string const& config, auto i = this->FlagsByLanguage.find(language); if (i == this->FlagsByLanguage.end()) { std::string flags; - const char* lang = language.c_str(); - - this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget, lang, - config); - - this->LocalGenerator->AddCMP0018Flags(flags, this->GeneratorTarget, lang, - config); + this->LocalGenerator->AddLanguageFlags(flags, this->GeneratorTarget, + language, config); + this->LocalGenerator->AddCMP0018Flags(flags, this->GeneratorTarget, + language, config); this->LocalGenerator->AddVisibilityPresetFlags( - flags, this->GeneratorTarget, lang); + flags, this->GeneratorTarget, language); // Append old-style preprocessor definition flags. if (this->Makefile->GetDefineFlags() != " ") { @@ -197,8 +194,8 @@ void cmGhsMultiTargetGenerator::SetCompilerFlags(std::string const& config, } // Add target-specific flags. - this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, lang, - config); + this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, + language, config); std::map<std::string, std::string>::value_type entry(language, flags); i = this->FlagsByLanguage.insert(entry).first; @@ -211,13 +208,12 @@ std::string cmGhsMultiTargetGenerator::GetDefines(const std::string& language, auto i = this->DefinesByLanguage.find(language); if (i == this->DefinesByLanguage.end()) { std::set<std::string> defines; - const char* lang = language.c_str(); // Add preprocessor definitions for this target and configuration. this->LocalGenerator->GetTargetDefines(this->GeneratorTarget, config, language, defines); std::string definesString; - this->LocalGenerator->JoinDefines(defines, definesString, lang); + this->LocalGenerator->JoinDefines(defines, definesString, language); std::map<std::string, std::string>::value_type entry(language, definesString); @@ -235,7 +231,7 @@ void cmGhsMultiTargetGenerator::WriteCompilerFlags(std::ostream& fout, if (!flagsByLangI->second.empty()) { std::vector<std::string> ghsCompFlags = cmSystemTools::ParseArguments(flagsByLangI->second); - for (auto& f : ghsCompFlags) { + for (const std::string& f : ghsCompFlags) { fout << " " << f << std::endl; } } @@ -290,14 +286,14 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLine(std::ostream& fout, // write out link options std::vector<std::string> lopts = cmSystemTools::ParseArguments(linkFlags); - for (auto& l : lopts) { + for (const std::string& l : lopts) { fout << " " << l << std::endl; } // write out link search paths // must be quoted for paths that contain spaces std::vector<std::string> lpath = cmSystemTools::ParseArguments(linkPath); - for (auto& l : lpath) { + for (const std::string& l : lpath) { fout << " -L\"" << l << "\"" << std::endl; } @@ -307,7 +303,7 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLine(std::ostream& fout, std::vector<std::string> llibs = cmSystemTools::ParseArguments(linkLibraries); - for (auto& l : llibs) { + for (const std::string& l : llibs) { if (l.compare(0, 2, "-l") == 0) { fout << " \"" << l << "\"" << std::endl; } else { @@ -463,7 +459,7 @@ void cmGhsMultiTargetGenerator::WriteSourceProperty( const char* prop = sf->GetProperty(propName); if (prop) { std::vector<std::string> list = cmExpandedList(prop); - for (auto& p : list) { + for (const std::string& p : list) { fout << " " << propFlag << p << std::endl; } } @@ -483,7 +479,7 @@ void cmGhsMultiTargetGenerator::WriteSources(std::ostream& fout_proj) /* for each source file assign it to its group */ std::map<std::string, std::vector<cmSourceFile*>> groupFiles; std::set<std::string> groupNames; - for (auto& sf : sources) { + for (cmSourceFile* sf : sources) { cmSourceGroup* sourceGroup = this->Makefile->FindSourceGroup(sf->ResolveFullPath(), sourceGroups); std::string gn = sourceGroup->GetFullName(); @@ -730,7 +726,7 @@ bool cmGhsMultiTargetGenerator::DetermineIfIntegrityApp() } std::vector<cmSourceFile*> sources; this->GeneratorTarget->GetSourceFiles(sources, this->ConfigName); - for (auto& sf : sources) { + for (const cmSourceFile* sf : sources) { if ("int" == sf->GetExtension()) { return true; } diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx index bb9dd37..78e3b43 100644 --- a/Source/cmGlobalGhsMultiGenerator.cxx +++ b/Source/cmGlobalGhsMultiGenerator.cxx @@ -9,6 +9,7 @@ #include <utility> #include <cm/memory> +#include <cm/string> #include "cmAlgorithms.h" #include "cmDocumentationEntry.h" @@ -651,21 +652,16 @@ void cmGlobalGhsMultiGenerator::WriteHighLevelDirectives( char const* const customization = this->GetCMakeInstance()->GetCacheDefinition("GHS_CUSTOMIZATION"); if (nullptr != customization && strlen(customization) > 0) { - fout << "customization=" << this->TrimQuotes(customization) << std::endl; + fout << "customization=" + << cmGlobalGhsMultiGenerator::TrimQuotes(customization) << std::endl; this->GetCMakeInstance()->MarkCliAsUsed("GHS_CUSTOMIZATION"); } } -std::string cmGlobalGhsMultiGenerator::TrimQuotes(std::string const& str) +std::string cmGlobalGhsMultiGenerator::TrimQuotes(std::string str) { - std::string result; - result.reserve(str.size()); - for (const char* ch = str.c_str(); *ch != '\0'; ++ch) { - if (*ch != '"') { - result += *ch; - } - } - return result; + cm::erase(str, '"'); + return str; } bool cmGlobalGhsMultiGenerator::TargetCompare::operator()( diff --git a/Source/cmGlobalGhsMultiGenerator.h b/Source/cmGlobalGhsMultiGenerator.h index b82e9f5..12ca8b6 100644 --- a/Source/cmGlobalGhsMultiGenerator.h +++ b/Source/cmGlobalGhsMultiGenerator.h @@ -111,7 +111,7 @@ private: std::vector<cmLocalGenerator*>& generators, std::string& all_target); - std::string TrimQuotes(std::string const& str); + static std::string TrimQuotes(std::string str); std::string OsDir; static const char* DEFAULT_BUILD_PROGRAM; diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx index f4d102e..d58113c 100644 --- a/Source/cmGlobalNinjaGenerator.cxx +++ b/Source/cmGlobalNinjaGenerator.cxx @@ -46,7 +46,8 @@ #include "cmake.h" const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja"; -const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja"; +const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = + "CMakeFiles/rules.ninja"; const char* cmGlobalNinjaGenerator::INDENT = " "; #ifdef _WIN32 std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "cd ."; @@ -147,15 +148,15 @@ void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os, { // Make sure there is a rule. if (build.Rule.empty()) { - cmSystemTools::Error("No rule for WriteBuild! called with comment: " + - build.Comment); + cmSystemTools::Error(cmStrCat( + "No rule for WriteBuild! called with comment: ", build.Comment)); return; } // Make sure there is at least one output file. if (build.Outputs.empty()) { - cmSystemTools::Error( - "No output files for WriteBuild! called with comment: " + build.Comment); + cmSystemTools::Error(cmStrCat( + "No output files for WriteBuild! called with comment: ", build.Comment)); return; } @@ -166,7 +167,7 @@ void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os, { // Write explicit outputs for (std::string const& output : build.Outputs) { - buildStr += " " + EncodePath(output); + buildStr += cmStrCat(' ', EncodePath(output)); if (this->ComputingUnknownDependencies) { this->CombinedBuildOutputs.insert(output); } @@ -175,14 +176,13 @@ void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os, if (!build.ImplicitOuts.empty()) { buildStr += " |"; for (std::string const& implicitOut : build.ImplicitOuts) { - buildStr += " " + EncodePath(implicitOut); + buildStr += cmStrCat(' ', EncodePath(implicitOut)); } } - buildStr += ":"; + buildStr += ':'; // Write the rule. - buildStr += " "; - buildStr += build.Rule; + buildStr += cmStrCat(' ', build.Rule); } std::string arguments; @@ -191,14 +191,14 @@ void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os, // Write explicit dependencies. for (std::string const& explicitDep : build.ExplicitDeps) { - arguments += " " + EncodePath(explicitDep); + arguments += cmStrCat(' ', EncodePath(explicitDep)); } // Write implicit dependencies. if (!build.ImplicitDeps.empty()) { arguments += " |"; for (std::string const& implicitDep : build.ImplicitDeps) { - arguments += " " + EncodePath(implicitDep); + arguments += cmStrCat(' ', EncodePath(implicitDep)); } } @@ -206,11 +206,11 @@ void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os, if (!build.OrderOnlyDeps.empty()) { arguments += " ||"; for (std::string const& orderOnlyDep : build.OrderOnlyDeps) { - arguments += " " + EncodePath(orderOnlyDep); + arguments += cmStrCat(' ', EncodePath(orderOnlyDep)); } } - arguments += "\n"; + arguments += '\n'; } // Write the variables bound to this build statement. @@ -309,7 +309,7 @@ void cmGlobalNinjaGenerator::WriteCustomCommandBuild( void cmGlobalNinjaGenerator::AddMacOSXContentRule() { cmNinjaRule rule("COPY_OSX_CONTENT"); - rule.Command = CMakeCmd() + " -E copy $in $out"; + rule.Command = cmStrCat(CMakeCmd(), " -E copy $in $out"); rule.Description = "Copying OS X Content $out"; rule.Comment = "Rule for copying OS X bundle content file."; this->AddRule(rule); @@ -334,23 +334,24 @@ void cmGlobalNinjaGenerator::WriteRule(std::ostream& os, // -- Parameter checks // Make sure the rule has a name. if (rule.Name.empty()) { - cmSystemTools::Error("No name given for WriteRule! called with comment: " + - rule.Comment); + cmSystemTools::Error(cmStrCat( + "No name given for WriteRule! called with comment: ", rule.Comment)); return; } // Make sure a command is given. if (rule.Command.empty()) { - cmSystemTools::Error( - "No command given for WriteRule! called with comment: " + rule.Comment); + cmSystemTools::Error(cmStrCat( + "No command given for WriteRule! called with comment: ", rule.Comment)); return; } // Make sure response file content is given if (!rule.RspFile.empty() && rule.RspContent.empty()) { - cmSystemTools::Error("rspfile but no rspfile_content given for WriteRule! " - "called with comment: " + - rule.Comment); + cmSystemTools::Error( + cmStrCat("rspfile but no rspfile_content given for WriteRule! " + "called with comment: ", + rule.Comment)); return; } @@ -392,9 +393,9 @@ void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os, { // Make sure we have a name. if (name.empty()) { - cmSystemTools::Error("No name given for WriteVariable! called " - "with comment: " + - comment); + cmSystemTools::Error(cmStrCat("No name given for WriteVariable! called " + "with comment: ", + comment)); return; } @@ -558,11 +559,11 @@ void cmGlobalNinjaGenerator::CleanMetaData() nullptr, cmSystemTools::OUTPUT_NONE)) { this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, - "Running\n '" + - cmJoin(command, "' '") + - "'\n" - "failed with:\n " + - error); + cmStrCat("Running\n '", + cmJoin(command, "' '"), + "'\n" + "failed with:\n ", + error)); cmSystemTools::SetFatalErrorOccured(); } }; @@ -626,10 +627,10 @@ bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf) nullptr, cmSystemTools::OUTPUT_NONE)) { mf->IssueMessage(MessageType::FATAL_ERROR, - "Running\n '" + cmJoin(command, "' '") + - "'\n" - "failed with:\n " + - error); + cmStrCat("Running\n '", cmJoin(command, "' '"), + "'\n" + "failed with:\n ", + error)); cmSystemTools::SetFatalErrorOccured(); return false; } @@ -713,7 +714,7 @@ bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const /* clang-format off */ e << "The Ninja generator does not support Fortran using Ninja version\n" - " " + this->NinjaVersion + "\n" + " " << this->NinjaVersion << "\n" "due to lack of required features. " "Kitware has implemented the required features and they have been " "merged to upstream ninja for inclusion in Ninja 1.10 and higher. " @@ -998,7 +999,8 @@ void cmGlobalNinjaGenerator::AddCXXCompileCommand( std::string buildFileDir = this->GetCMakeInstance()->GetHomeOutputDirectory(); if (!this->CompileCommandsStream) { - std::string buildFilePath = buildFileDir + "/compile_commands.json"; + std::string buildFilePath = + cmStrCat(buildFileDir, "/compile_commands.json"); if (this->ComputingUnknownDependencies) { this->CombinedBuildOutputs.insert( this->NinjaOutputPath("compile_commands.json")); @@ -1064,8 +1066,8 @@ void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies() std::string cmGlobalNinjaGenerator::OrderDependsTargetForTarget( cmGeneratorTarget const* target, const std::string& config) { - return "cmake_object_order_depends_target_" + target->GetName() + "_" + - config; + return cmStrCat("cmake_object_order_depends_target_", target->GetName(), '_', + config); } void cmGlobalNinjaGenerator::AppendTargetOutputs( @@ -1103,8 +1105,8 @@ void cmGlobalNinjaGenerator::AppendTargetOutputs( case cmStateEnums::GLOBAL_TARGET: case cmStateEnums::UTILITY: { std::string path = - target->GetLocalGenerator()->GetCurrentBinaryDirectory() + - std::string("/") + target->GetName(); + cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/', + target->GetName()); std::string output = this->ConvertToNinjaPath(path); if (target->Target->IsPerConfig()) { output = this->BuildAlias(output, config); @@ -1128,8 +1130,8 @@ void cmGlobalNinjaGenerator::AppendTargetDepends( for (BT<std::pair<std::string, bool>> const& util : target->GetUtilities()) { std::string d = - target->GetLocalGenerator()->GetCurrentBinaryDirectory() + "/" + - util.Value.first; + cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/', + util.Value.first); outputs.push_back(this->BuildAlias(this->ConvertToNinjaPath(d), config)); } } else { @@ -1356,12 +1358,13 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) // Setup target cmNinjaDeps configDeps; - build.Comment = "Folder: " + currentBinaryDir; + build.Comment = cmStrCat("Folder: ", currentBinaryDir); build.Outputs.emplace_back(); + std::string const buildDirAllTarget = + this->ConvertToNinjaPath(cmStrCat(currentBinaryDir, "/all")); for (auto const& config : configs) { build.ExplicitDeps.clear(); - build.Outputs.front() = this->BuildAlias( - this->ConvertToNinjaPath(currentBinaryDir + "/all"), config); + build.Outputs.front() = this->BuildAlias(buildDirAllTarget, config); configDeps.emplace_back(build.Outputs.front()); for (DirectoryTarget::Target const& t : dt.Targets) { if (!t.ExcludeFromAll) { @@ -1371,7 +1374,7 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) for (DirectoryTarget::Dir const& d : dt.Children) { if (!d.ExcludeFromAll) { build.ExplicitDeps.emplace_back(this->BuildAlias( - this->ConvertToNinjaPath(d.Path + "/all"), config)); + this->ConvertToNinjaPath(cmStrCat(d.Path, "/all")), config)); } } // Write target @@ -1385,21 +1388,18 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) // Add shortcut target if (this->IsMultiConfig()) { for (auto const& config : configs) { - build.ExplicitDeps = { this->BuildAlias( - this->ConvertToNinjaPath(currentBinaryDir + "/all"), config) }; - build.Outputs.front() = - this->ConvertToNinjaPath(currentBinaryDir + "/all"); + build.ExplicitDeps = { this->BuildAlias(buildDirAllTarget, config) }; + build.Outputs.front() = buildDirAllTarget; this->WriteBuild(*this->GetConfigFileStream(config), build); } if (!this->DefaultFileConfig.empty()) { build.ExplicitDeps.clear(); for (auto const& config : this->DefaultConfigs) { - build.ExplicitDeps.push_back(this->BuildAlias( - this->ConvertToNinjaPath(currentBinaryDir + "/all"), config)); + build.ExplicitDeps.push_back( + this->BuildAlias(buildDirAllTarget, config)); } - build.Outputs.front() = - this->ConvertToNinjaPath(currentBinaryDir + "/all"); + build.Outputs.front() = buildDirAllTarget; this->WriteBuild(*this->GetDefaultFileStream(), build); } } @@ -1408,11 +1408,10 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) if (this->EnableCrossConfigBuild()) { build.ExplicitDeps.clear(); for (auto const& config : this->CrossConfigs) { - build.ExplicitDeps.push_back(this->BuildAlias( - this->ConvertToNinjaPath(currentBinaryDir + "/all"), config)); + build.ExplicitDeps.push_back( + this->BuildAlias(buildDirAllTarget, config)); } - build.Outputs.front() = this->BuildAlias( - this->ConvertToNinjaPath(currentBinaryDir + "/all"), "all"); + build.Outputs.front() = this->BuildAlias(buildDirAllTarget, "all"); this->WriteBuild(os, build); } } @@ -1624,7 +1623,8 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) cmNinjaBuild phonyBuild("phony"); phonyBuild.Comment = "Phony target to force glob verification run."; - phonyBuild.Outputs.push_back(cm->GetGlobVerifyScript() + "_force"); + phonyBuild.Outputs.push_back( + cmStrCat(cm->GetGlobVerifyScript(), "_force")); this->WriteBuild(os, phonyBuild); reBuild.Variables["restat"] = "1"; @@ -1815,7 +1815,7 @@ void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os) // Write rule { cmNinjaRule rule("CLEAN"); - rule.Command = NinjaCmd() + " $FILE_ARG -t clean $TARGETS"; + rule.Command = cmStrCat(NinjaCmd(), " $FILE_ARG -t clean $TARGETS"); rule.Description = "Cleaning all built files..."; rule.Comment = "Rule for cleaning all built files."; WriteRule(*this->RulesFileStream, rule); @@ -1929,7 +1929,7 @@ void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os) { { cmNinjaRule rule("HELP"); - rule.Command = NinjaCmd() + " -t targets"; + rule.Command = cmStrCat(NinjaCmd(), " -t targets"); rule.Description = "All primary targets available:"; rule.Comment = "Rule for printing all primary targets available."; WriteRule(*this->RulesFileStream, rule); @@ -1956,7 +1956,7 @@ std::string cmGlobalNinjaGenerator::NinjaOutputPath( if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) { return path; } - return this->OutputPathPrefix + path; + return cmStrCat(this->OutputPathPrefix, path); } void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix( @@ -2084,7 +2084,8 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg, } else if (cmHasLiteralPrefix(arg, "--lang=")) { arg_lang = arg.substr(7); } else { - cmSystemTools::Error("-E cmake_ninja_depends unknown argument: " + arg); + cmSystemTools::Error( + cmStrCat("-E cmake_ninja_depends unknown argument: ", arg)); return 1; } } @@ -2155,7 +2156,8 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg, cmGeneratedFileStream ddif(arg_ddi); ddif << ddi; if (!ddif) { - cmSystemTools::Error("-E cmake_ninja_depends failed to write " + arg_ddi); + cmSystemTools::Error( + cmStrCat("-E cmake_ninja_depends failed to write ", arg_ddi)); return 1; } return 0; @@ -2201,7 +2203,8 @@ std::unique_ptr<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran( std::set<std::string> defines; cmFortranParser parser(fc, includes, defines, finfo); if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) { - cmSystemTools::Error("-E cmake_ninja_depends failed to open " + arg_pp); + cmSystemTools::Error( + cmStrCat("-E cmake_ninja_depends failed to open ", arg_pp)); return nullptr; } if (cmFortran_yyparse(parser.Scanner) != 0) { @@ -2304,7 +2307,7 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( Json::Value tm = Json::objectValue; for (cmDyndepObjectInfo const& object : objects) { for (std::string const& p : object.Provides) { - std::string const mod = module_dir + p; + std::string const mod = cmStrCat(module_dir, p); mod_files[p] = mod; tm[p] = mod; } @@ -2340,8 +2343,8 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( // Store the map of modules provided by this target in a file for // use by dependents that reference this target in linked-target-dirs. - std::string const target_mods_file = - cmSystemTools::GetFilenamePath(arg_dd) + "/" + arg_lang + "Modules.json"; + std::string const target_mods_file = cmStrCat( + cmSystemTools::GetFilenamePath(arg_dd), '/', arg_lang, "Modules.json"); cmGeneratedFileStream tmf(target_mods_file); tmf << tm; @@ -2374,7 +2377,8 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg, cmHasLiteralSuffix(arg, ".ddi")) { arg_ddis.push_back(arg); } else { - cmSystemTools::Error("-E cmake_ninja_dyndep unknown argument: " + arg); + cmSystemTools::Error( + cmStrCat("-E cmake_ninja_dyndep unknown argument: ", arg)); return 1; } } @@ -2410,7 +2414,7 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg, std::string const dir_top_src = tdi["dir-top-src"].asString(); std::string module_dir = tdi["module-dir"].asString(); if (!module_dir.empty() && !cmHasLiteralSuffix(module_dir, "/")) { - module_dir += "/"; + module_dir += '/'; } std::vector<std::string> linked_target_dirs; Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"]; @@ -2438,9 +2442,7 @@ void cmGlobalNinjaGenerator::AppendDirectoryForConfig( const std::string& suffix, std::string& dir) { if (!config.empty() && this->IsMultiConfig()) { - dir += prefix; - dir += config; - dir += suffix; + dir += cmStrCat(prefix, config, suffix); } } diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx index 90c9ef0..7daca74 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.cxx +++ b/Source/cmGlobalUnixMakefileGenerator3.cxx @@ -41,7 +41,6 @@ cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm) #else this->UseLinkScript = true; #endif - this->CommandDatabase = nullptr; this->IncludeDirective = "include"; this->DefineWindowsNULL = false; @@ -49,6 +48,8 @@ cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm) this->UnixCD = true; } +cmGlobalUnixMakefileGenerator3::~cmGlobalUnixMakefileGenerator3() = default; + void cmGlobalUnixMakefileGenerator3::EnableLanguage( std::vector<std::string> const& languages, cmMakefile* mf, bool optional) { @@ -157,10 +158,9 @@ void cmGlobalUnixMakefileGenerator3::Generate() this->WriteMainMakefile2(); this->WriteMainCMakefile(); - if (this->CommandDatabase != nullptr) { + if (this->CommandDatabase) { *this->CommandDatabase << std::endl << "]"; - delete this->CommandDatabase; - this->CommandDatabase = nullptr; + this->CommandDatabase.reset(); } } @@ -168,11 +168,12 @@ void cmGlobalUnixMakefileGenerator3::AddCXXCompileCommand( const std::string& sourceFile, const std::string& workingDirectory, const std::string& compileCommand) { - if (this->CommandDatabase == nullptr) { + if (!this->CommandDatabase) { std::string commandDatabaseName = this->GetCMakeInstance()->GetHomeOutputDirectory() + "/compile_commands.json"; - this->CommandDatabase = new cmGeneratedFileStream(commandDatabaseName); + this->CommandDatabase = + cm::make_unique<cmGeneratedFileStream>(commandDatabaseName); *this->CommandDatabase << "[" << std::endl; } else { *this->CommandDatabase << "," << std::endl; @@ -343,19 +344,18 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() const std::string& binDir = lg.GetBinaryDirectory(); // CMake must rerun if a byproduct is missing. - { - cmakefileStream << "# Byproducts of CMake generate step:\n" - << "set(CMAKE_MAKEFILE_PRODUCTS\n"; - for (std::string const& outfile : lg.GetMakefile()->GetOutputFiles()) { + cmakefileStream << "# Byproducts of CMake generate step:\n" + << "set(CMAKE_MAKEFILE_PRODUCTS\n"; + + // add in any byproducts and all the directory information files + std::string tmpStr; + for (const auto& localGen : this->LocalGenerators) { + for (std::string const& outfile : + localGen->GetMakefile()->GetOutputFiles()) { cmakefileStream << " \"" << lg.MaybeConvertToRelativePath(binDir, outfile) << "\"\n"; } - } - - // add in all the directory information files - std::string tmpStr; - for (const auto& localGen : this->LocalGenerators) { tmpStr = cmStrCat(localGen->GetCurrentBinaryDirectory(), "/CMakeFiles/CMakeDirectoryInformation.cmake"); cmakefileStream << " \"" diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h index 340a7ef..19b2b85 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.h +++ b/Source/cmGlobalUnixMakefileGenerator3.h @@ -68,6 +68,13 @@ public: new cmGlobalGeneratorSimpleFactory<cmGlobalUnixMakefileGenerator3>()); } + ~cmGlobalUnixMakefileGenerator3() override; + + cmGlobalUnixMakefileGenerator3(const cmGlobalUnixMakefileGenerator3&) = + delete; + cmGlobalUnixMakefileGenerator3& operator=( + const cmGlobalUnixMakefileGenerator3&) = delete; + //! Get the name for the generator. std::string GetName() const override { @@ -232,7 +239,7 @@ protected: std::set<cmGeneratorTarget const*>& emitted); size_t CountProgressMarksInAll(const cmLocalGenerator& lg); - cmGeneratedFileStream* CommandDatabase; + std::unique_ptr<cmGeneratedFileStream> CommandDatabase; private: const char* GetBuildIgnoreErrorsFlag() const override { return "-i"; } diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index 9799124..eb33825 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -676,7 +676,8 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild( for (std::string const& i : configs) { const char* propertyValue = target->Target->GetMakefile()->GetDefinition(propertyName); - if (cmIsOn(cmGeneratorExpression::Evaluate( + if (propertyValue && + cmIsOn(cmGeneratorExpression::Evaluate( propertyValue, target->GetLocalGenerator(), i))) { activeConfigs.insert(i); } diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx index 1c62fbd..fa0e935 100644 --- a/Source/cmGlobalVisualStudio8Generator.cxx +++ b/Source/cmGlobalVisualStudio8Generator.cxx @@ -275,23 +275,31 @@ void cmGlobalVisualStudio8Generator::WriteProjectConfigurations( bool cmGlobalVisualStudio8Generator::NeedsDeploy( cmGeneratorTarget const& target, const char* config) const { - cmStateEnums::TargetType type = target.GetType(); - bool noDeploy = DeployInhibited(target, config); - return !noDeploy && - (type == cmStateEnums::EXECUTABLE || - type == cmStateEnums::SHARED_LIBRARY) && - this->TargetSystemSupportsDeployment(); -} + cmStateEnums::TargetType const type = target.GetType(); + if (type != cmStateEnums::EXECUTABLE && + type != cmStateEnums::SHARED_LIBRARY) { + // deployment only valid on executables and shared libraries. + return false; + } -bool cmGlobalVisualStudio8Generator::DeployInhibited( - cmGeneratorTarget const& target, const char* config) const -{ - bool rVal = false; - if (const char* prop = target.GetProperty("VS_NO_SOLUTION_DEPLOY")) { - rVal = cmIsOn( + if (const char* prop = target.GetProperty("VS_SOLUTION_DEPLOY")) { + // If set, it dictates behavior + return cmIsOn( cmGeneratorExpression::Evaluate(prop, target.LocalGenerator, config)); } - return rVal; + + // To be deprecated, disable deployment even if target supports it. + if (const char* prop = target.GetProperty("VS_NO_SOLUTION_DEPLOY")) { + if (cmIsOn(cmGeneratorExpression::Evaluate(prop, target.LocalGenerator, + config))) { + // If true, always disable deployment + return false; + } + } + + // Legacy behavior, enabled deployment based on 'hard-coded' target + // platforms. + return this->TargetSystemSupportsDeployment(); } bool cmGlobalVisualStudio8Generator::TargetSystemSupportsDeployment() const diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h index 8f8e33b..6ce67d3 100644 --- a/Source/cmGlobalVisualStudio8Generator.h +++ b/Source/cmGlobalVisualStudio8Generator.h @@ -57,10 +57,6 @@ protected: virtual bool NeedsDeploy(cmGeneratorTarget const& target, const char* config) const; - /** Returns true if deployment has been disabled in cmake file. */ - bool DeployInhibited(cmGeneratorTarget const& target, - const char* config) const; - /** Returns true if the target system support debugging deployment. */ virtual bool TargetSystemSupportsDeployment() const; diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx index c48a376..9db4817 100644 --- a/Source/cmGlobalXCodeGenerator.cxx +++ b/Source/cmGlobalXCodeGenerator.cxx @@ -8,6 +8,7 @@ #include <cstring> #include <iomanip> #include <sstream> +#include <utility> #include <cm/memory> #include <cmext/algorithm> @@ -642,7 +643,8 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile( << "\n"; } -static bool objectIdLessThan(cmXCodeObject* l, cmXCodeObject* r) +static bool objectIdLessThan(const std::unique_ptr<cmXCodeObject>& l, + const std::unique_ptr<cmXCodeObject>& r) { return l->GetId() < r->GetId(); } @@ -656,9 +658,6 @@ void cmGlobalXCodeGenerator::SortXCodeObjects() void cmGlobalXCodeGenerator::ClearXCodeObjects() { this->TargetDoneSet.clear(); - for (auto& obj : this->XCodeObjects) { - delete obj; - } this->XCodeObjects.clear(); this->XCodeObjectIDs.clear(); this->XCodeObjectMap.clear(); @@ -668,7 +667,7 @@ void cmGlobalXCodeGenerator::ClearXCodeObjects() this->FileRefs.clear(); } -void cmGlobalXCodeGenerator::addObject(cmXCodeObject* obj) +void cmGlobalXCodeGenerator::addObject(std::unique_ptr<cmXCodeObject> obj) { if (obj->GetType() == cmXCodeObject::OBJECT) { const std::string& id = obj->GetId(); @@ -683,22 +682,24 @@ void cmGlobalXCodeGenerator::addObject(cmXCodeObject* obj) this->XCodeObjectIDs.insert(id); } - this->XCodeObjects.push_back(obj); + this->XCodeObjects.push_back(std::move(obj)); } cmXCodeObject* cmGlobalXCodeGenerator::CreateObject( cmXCodeObject::PBXType ptype) { - cmXCodeObject* obj = new cmXCode21Object(ptype, cmXCodeObject::OBJECT); - this->addObject(obj); - return obj; + auto obj = cm::make_unique<cmXCode21Object>(ptype, cmXCodeObject::OBJECT); + auto ptr = obj.get(); + this->addObject(std::move(obj)); + return ptr; } cmXCodeObject* cmGlobalXCodeGenerator::CreateObject(cmXCodeObject::Type type) { - cmXCodeObject* obj = new cmXCodeObject(cmXCodeObject::None, type); - this->addObject(obj); - return obj; + auto obj = cm::make_unique<cmXCodeObject>(cmXCodeObject::None, type); + auto ptr = obj.get(); + this->addObject(std::move(obj)); + return ptr; } cmXCodeObject* cmGlobalXCodeGenerator::CreateString(const std::string& s) @@ -2368,8 +2369,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, int minor; int patch; - // OSX_CURRENT_VERSION or VERSION -> current_version - gtgt->GetTargetVersionFallback("OSX_CURRENT_VERSION", "VERSION", major, + // MACHO_CURRENT_VERSION or VERSION -> current_version + gtgt->GetTargetVersionFallback("MACHO_CURRENT_VERSION", "VERSION", major, minor, patch); std::ostringstream v; @@ -2380,8 +2381,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, buildSettings->AddAttribute("DYLIB_CURRENT_VERSION", this->CreateString(v.str())); - // OSX_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version - gtgt->GetTargetVersionFallback("OSX_COMPATIBILITY_VERSION", "SOVERSION", + // MACHO_COMPATIBILITY_VERSION or SOVERSION -> compatibility_version + gtgt->GetTargetVersionFallback("MACHO_COMPATIBILITY_VERSION", "SOVERSION", major, minor, patch); std::ostringstream vso; @@ -2410,8 +2411,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt, std::string attribute = prop.substr(16); this->FilterConfigurationAttribute(configName, attribute); if (!attribute.empty()) { + const char* pr = gtgt->GetProperty(prop); std::string processed = cmGeneratorExpression::Evaluate( - gtgt->GetProperty(prop), this->CurrentLocalGenerator, configName); + pr ? pr : "", this->CurrentLocalGenerator, configName); buildSettings->AddAttribute(attribute, this->CreateString(processed)); } @@ -3146,7 +3148,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects( this->FilterConfigurationAttribute(config.first, attribute); if (!attribute.empty()) { std::string processed = cmGeneratorExpression::Evaluate( - this->CurrentMakefile->GetDefinition(var), + this->CurrentMakefile->GetSafeDefinition(var), this->CurrentLocalGenerator, config.first); buildSettingsForCfg->AddAttribute(attribute, this->CreateString(processed)); @@ -3390,7 +3392,7 @@ bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes( // collect all tests for the targets std::map<std::string, cmXCodeScheme::TestObjects> testables; - for (auto obj : this->XCodeObjects) { + for (const auto& obj : this->XCodeObjects) { if (obj->GetType() != cmXCodeObject::OBJECT || obj->GetIsA() != cmXCodeObject::PBXNativeTarget) { continue; @@ -3405,7 +3407,7 @@ bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes( continue; } - testables[testee].push_back(obj); + testables[testee].push_back(obj.get()); } // generate scheme @@ -3414,14 +3416,14 @@ bool cmGlobalXCodeGenerator::OutputXCodeSharedSchemes( // Since the lowest available Xcode version for testing was 6.4, // I'm setting this as a limit then if (this->XcodeVersion >= 64) { - for (auto obj : this->XCodeObjects) { + for (const auto& obj : this->XCodeObjects) { if (obj->GetType() == cmXCodeObject::OBJECT && (obj->GetIsA() == cmXCodeObject::PBXNativeTarget || obj->GetIsA() == cmXCodeObject::PBXAggregateTarget) && (root->GetMakefile()->GetCMakeInstance()->GetIsInTryCompile() || obj->GetTarget()->GetPropertyAsBool("XCODE_GENERATE_SCHEME"))) { const std::string& targetName = obj->GetTarget()->GetName(); - cmXCodeScheme schm(root, obj, testables[targetName], + cmXCodeScheme schm(root, obj.get(), testables[targetName], this->CurrentConfigurationTypes, this->XcodeVersion); schm.WriteXCodeSharedScheme(xcProjDir, diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h index df68f80..e380f1c 100644 --- a/Source/cmGlobalXCodeGenerator.h +++ b/Source/cmGlobalXCodeGenerator.h @@ -37,6 +37,10 @@ public: unsigned int version_number); static std::unique_ptr<cmGlobalGeneratorFactory> NewFactory(); + cmGlobalXCodeGenerator(const cmGlobalXCodeGenerator&) = delete; + const cmGlobalXCodeGenerator& operator=(const cmGlobalXCodeGenerator&) = + delete; + //! Get the name for the generator. std::string GetName() const override { @@ -249,7 +253,7 @@ protected: unsigned int XcodeVersion; std::string VersionString; std::set<std::string> XCodeObjectIDs; - std::vector<cmXCodeObject*> XCodeObjects; + std::vector<std::unique_ptr<cmXCodeObject>> XCodeObjects; cmXCodeObject* RootObject; private: @@ -273,7 +277,7 @@ private: void ComputeArchitectures(cmMakefile* mf); void ComputeObjectDirArch(cmMakefile* mf); - void addObject(cmXCodeObject* obj); + void addObject(std::unique_ptr<cmXCodeObject> obj); std::string PostBuildMakeTarget(std::string const& tName, std::string const& configName); cmXCodeObject* MainGroupChildren; diff --git a/Source/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx index 2c53a28..6e3508c 100644 --- a/Source/cmInstallExportGenerator.cxx +++ b/Source/cmInstallExportGenerator.cxx @@ -7,6 +7,8 @@ #include <sstream> #include <utility> +#include <cm/memory> + #ifndef CMAKE_BOOTSTRAP # include "cmExportInstallAndroidMKGenerator.h" #endif @@ -33,18 +35,15 @@ cmInstallExportGenerator::cmInstallExportGenerator( { if (android) { #ifndef CMAKE_BOOTSTRAP - this->EFGen = new cmExportInstallAndroidMKGenerator(this); + this->EFGen = cm::make_unique<cmExportInstallAndroidMKGenerator>(this); #endif } else { - this->EFGen = new cmExportInstallFileGenerator(this); + this->EFGen = cm::make_unique<cmExportInstallFileGenerator>(this); } exportSet->AddInstallation(this); } -cmInstallExportGenerator::~cmInstallExportGenerator() -{ - delete this->EFGen; -} +cmInstallExportGenerator::~cmInstallExportGenerator() = default; bool cmInstallExportGenerator::Compute(cmLocalGenerator* lg) { diff --git a/Source/cmInstallExportGenerator.h b/Source/cmInstallExportGenerator.h index cf28b35..43dd00d 100644 --- a/Source/cmInstallExportGenerator.h +++ b/Source/cmInstallExportGenerator.h @@ -7,6 +7,7 @@ #include <cstddef> #include <iosfwd> +#include <memory> #include <string> #include <vector> @@ -30,8 +31,12 @@ public: bool exclude_from_all, std::string filename, std::string name_space, bool exportOld, bool android); + cmInstallExportGenerator(const cmInstallExportGenerator&) = delete; ~cmInstallExportGenerator() override; + cmInstallExportGenerator& operator=(const cmInstallExportGenerator&) = + delete; + cmExportSet* GetExportSet() { return this->ExportSet; } bool Compute(cmLocalGenerator* lg) override; @@ -61,7 +66,7 @@ protected: std::string TempDir; std::string MainImportFile; - cmExportInstallFileGenerator* EFGen; + std::unique_ptr<cmExportInstallFileGenerator> EFGen; }; #endif diff --git a/Source/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx index a65ae03..32395d1 100644 --- a/Source/cmInstalledFile.cxx +++ b/Source/cmInstalledFile.cxx @@ -42,7 +42,8 @@ void cmInstalledFile::RemoveProperty(const std::string& prop) } void cmInstalledFile::SetProperty(cmMakefile const* mf, - const std::string& prop, const char* value) + const std::string& prop, + const std::string& value) { this->RemoveProperty(prop); this->AppendProperty(mf, prop, value); @@ -50,7 +51,8 @@ void cmInstalledFile::SetProperty(cmMakefile const* mf, void cmInstalledFile::AppendProperty(cmMakefile const* mf, const std::string& prop, - const char* value, bool /*asString*/) + const std::string& value, + bool /*asString*/) { cmListFileBacktrace backtrace = mf->GetBacktrace(); cmGeneratorExpression ge(backtrace); diff --git a/Source/cmInstalledFile.h b/Source/cmInstalledFile.h index 698151e..07f7081 100644 --- a/Source/cmInstalledFile.h +++ b/Source/cmInstalledFile.h @@ -49,10 +49,10 @@ public: void RemoveProperty(const std::string& prop); void SetProperty(cmMakefile const* mf, const std::string& prop, - const char* value); + const std::string& value); void AppendProperty(cmMakefile const* mf, const std::string& prop, - const char* value, bool asString = false); + const std::string& value, bool asString = false); bool HasProperty(const std::string& prop) const; diff --git a/Source/cmLinkItem.h b/Source/cmLinkItem.h index 0ea25c0..ae87e45 100644 --- a/Source/cmLinkItem.h +++ b/Source/cmLinkItem.h @@ -81,6 +81,9 @@ struct cmLinkInterface : public cmLinkInterfaceLibraries std::vector<cmLinkItem> WrongConfigLibraries; bool ImplementationIsInterface = false; + + // Whether the list depends on a link language genex. + bool HadLinkLanguageSensitiveCondition = false; }; struct cmOptionalLinkInterface : public cmLinkInterface @@ -100,6 +103,9 @@ struct cmLinkImplementation : public cmLinkImplementationLibraries { // Languages whose runtime libraries must be linked. std::vector<std::string> Languages; + + // Whether the list depends on a link language genex. + bool HadLinkLanguageSensitiveCondition = false; }; // Cache link implementation computation from each configuration. diff --git a/Source/cmListFileCache.cxx b/Source/cmListFileCache.cxx index 47679c9..7ebb02f 100644 --- a/Source/cmListFileCache.cxx +++ b/Source/cmListFileCache.cxx @@ -26,13 +26,15 @@ cmCommandContext::cmCommandName& cmCommandContext::cmCommandName::operator=( struct cmListFileParser { cmListFileParser(cmListFile* lf, cmListFileBacktrace lfbt, - cmMessenger* messenger, const char* filename); + cmMessenger* messenger); ~cmListFileParser(); cmListFileParser(const cmListFileParser&) = delete; cmListFileParser& operator=(const cmListFileParser&) = delete; void IssueFileOpenError(std::string const& text) const; void IssueError(std::string const& text) const; - bool ParseFile(); + bool ParseFile(const char* filename); + bool ParseString(const char* str, const char* virtual_filename); + bool Parse(); bool ParseFunction(const char* name, long line); bool AddArgument(cmListFileLexer_Token* token, cmListFileArgument::Delimiter delim); @@ -51,12 +53,11 @@ struct cmListFileParser }; cmListFileParser::cmListFileParser(cmListFile* lf, cmListFileBacktrace lfbt, - cmMessenger* messenger, - const char* filename) + cmMessenger* messenger) : ListFile(lf) , Backtrace(std::move(lfbt)) , Messenger(messenger) - , FileName(filename) + , FileName(nullptr) , Lexer(cmListFileLexer_New()) { } @@ -83,8 +84,10 @@ void cmListFileParser::IssueError(const std::string& text) const cmSystemTools::SetFatalErrorOccured(); } -bool cmListFileParser::ParseFile() +bool cmListFileParser::ParseFile(const char* filename) { + this->FileName = filename; + // Open the file. cmListFileLexer_BOM bom; if (!cmListFileLexer_SetFileName(this->Lexer, this->FileName, &bom)) { @@ -107,6 +110,24 @@ bool cmListFileParser::ParseFile() return false; } + return Parse(); +} + +bool cmListFileParser::ParseString(const char* str, + const char* virtual_filename) +{ + this->FileName = virtual_filename; + + if (!cmListFileLexer_SetString(this->Lexer, str)) { + this->IssueFileOpenError("cmListFileCache: cannot allocate buffer."); + return false; + } + + return Parse(); +} + +bool cmListFileParser::Parse() +{ // Use a simple recursive-descent parser to process the token // stream. bool haveNewline = true; @@ -155,8 +176,22 @@ bool cmListFile::ParseFile(const char* filename, cmMessenger* messenger, bool parseError = false; { - cmListFileParser parser(this, lfbt, messenger, filename); - parseError = !parser.ParseFile(); + cmListFileParser parser(this, lfbt, messenger); + parseError = !parser.ParseFile(filename); + } + + return !parseError; +} + +bool cmListFile::ParseString(const char* str, const char* virtual_filename, + cmMessenger* messenger, + const cmListFileBacktrace& lfbt) +{ + bool parseError = false; + + { + cmListFileParser parser(this, lfbt, messenger); + parseError = !parser.ParseString(str, virtual_filename); } return !parseError; diff --git a/Source/cmListFileCache.h b/Source/cmListFileCache.h index 9cae827..89902ff 100644 --- a/Source/cmListFileCache.h +++ b/Source/cmListFileCache.h @@ -184,6 +184,9 @@ struct cmListFile bool ParseFile(const char* path, cmMessenger* messenger, cmListFileBacktrace const& lfbt); + bool ParseString(const char* str, const char* virtual_filename, + cmMessenger* messenger, cmListFileBacktrace const& lfbt); + std::vector<cmListFileFunction> Functions; }; diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx index 025ef7e..278ec8b 100644 --- a/Source/cmLocalCommonGenerator.cxx +++ b/Source/cmLocalCommonGenerator.cxx @@ -50,6 +50,15 @@ std::string cmLocalCommonGenerator::GetTargetFortranFlags( this->Makefile->GetRequiredDefinition("CMAKE_Fortran_MODDIR_FLAG"), mod_dir); this->AppendFlags(flags, modflag); + // Some compilers do not search their own module output directory + // for using other modules. Add an include directory explicitly + // for consistency with compilers that do search it. + std::string incflag = + this->Makefile->GetSafeDefinition("CMAKE_Fortran_MODDIR_INCLUDE_FLAG"); + if (!incflag.empty()) { + incflag = cmStrCat(incflag, mod_dir); + this->AppendFlags(flags, incflag); + } } // If there is a separate module path flag then duplicate the diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index cf6802d..a7799b6 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -2914,11 +2914,11 @@ void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines, // command line without any escapes. However we still have to // get the '$' and '#' characters through WMake as '$$' and // '$#'. - for (const char* c = define.c_str(); *c; ++c) { - if (*c == '$' || *c == '#') { + for (char c : define) { + if (c == '$' || c == '#') { def += '$'; } - def += *c; + def += c; } } else { // Make the definition appear properly on the command line. Use diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index 9aa3991..74219b5 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -2,6 +2,8 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmLocalVisualStudio7Generator.h" +#include <cm/memory> + #include <windows.h> #include <ctype.h> // for isspace @@ -52,14 +54,11 @@ extern cmVS7FlagTable cmLocalVisualStudio7GeneratorFlagTable[]; cmLocalVisualStudio7Generator::cmLocalVisualStudio7Generator( cmGlobalGenerator* gg, cmMakefile* mf) : cmLocalVisualStudioGenerator(gg, mf) + , Internal(cm::make_unique<cmLocalVisualStudio7GeneratorInternals>(this)) { - this->Internal = new cmLocalVisualStudio7GeneratorInternals(this); } -cmLocalVisualStudio7Generator::~cmLocalVisualStudio7Generator() -{ - delete this->Internal; -} +cmLocalVisualStudio7Generator::~cmLocalVisualStudio7Generator() = default; void cmLocalVisualStudio7Generator::AddHelperCommands() { @@ -1511,10 +1510,9 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo( if (const char* deps = sf.GetProperty("OBJECT_DEPENDS")) { std::vector<std::string> depends = cmExpandedList(deps); const char* sep = ""; - for (std::vector<std::string>::iterator j = depends.begin(); - j != depends.end(); ++j) { + for (const std::string& d : depends) { fc.AdditionalDeps += sep; - fc.AdditionalDeps += lg->ConvertToXMLOutputPath(*j); + fc.AdditionalDeps += lg->ConvertToXMLOutputPath(d); sep = ";"; needfc = true; } diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h index 745766c..8b9b8ad 100644 --- a/Source/cmLocalVisualStudio7Generator.h +++ b/Source/cmLocalVisualStudio7Generator.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <iosfwd> +#include <memory> #include <string> #include <vector> @@ -48,6 +49,10 @@ public: virtual ~cmLocalVisualStudio7Generator(); + cmLocalVisualStudio7Generator(const cmLocalVisualStudio7Generator&) = delete; + const cmLocalVisualStudio7Generator& operator=( + const cmLocalVisualStudio7Generator&) = delete; + void AddHelperCommands() override; /** @@ -144,7 +149,7 @@ private: bool FortranProject; bool WindowsCEProject; - cmLocalVisualStudio7GeneratorInternals* Internal; + std::unique_ptr<cmLocalVisualStudio7GeneratorInternals> Internal; }; #endif diff --git a/Source/cmMachO.cxx b/Source/cmMachO.cxx index 6cbed36..53112e0 100644 --- a/Source/cmMachO.cxx +++ b/Source/cmMachO.cxx @@ -79,14 +79,14 @@ public: // A load_command and its associated data struct RawLoadCommand { - uint32_t type(const cmMachOHeaderAndLoadCommands* m) const + uint32_t type(const cmMachOHeaderAndLoadCommands& m) const { if (this->LoadCommand.size() < sizeof(load_command)) { return 0; } const load_command* cmd = reinterpret_cast<const load_command*>(&this->LoadCommand[0]); - return m->swap(cmd->cmd); + return m.swap(cmd->cmd); } std::vector<char> LoadCommand; }; @@ -186,8 +186,11 @@ class cmMachOInternal { public: cmMachOInternal(const char* fname); + cmMachOInternal(const cmMachOInternal&) = delete; ~cmMachOInternal(); + cmMachOInternal& operator=(const cmMachOInternal&) = delete; + // read a Mach-O file bool read_mach_o(uint32_t file_offset); @@ -202,7 +205,7 @@ public: std::string ErrorMessage; // the list of Mach-O's - std::vector<cmMachOHeaderAndLoadCommands*> MachOList; + std::vector<std::unique_ptr<cmMachOHeaderAndLoadCommands>> MachOList; }; cmMachOInternal::cmMachOInternal(const char* fname) @@ -260,12 +263,7 @@ cmMachOInternal::cmMachOInternal(const char* fname) } } -cmMachOInternal::~cmMachOInternal() -{ - for (auto& i : this->MachOList) { - delete i; - } -} +cmMachOInternal::~cmMachOInternal() = default; bool cmMachOInternal::read_mach_o(uint32_t file_offset) { @@ -280,25 +278,25 @@ bool cmMachOInternal::read_mach_o(uint32_t file_offset) return false; } - cmMachOHeaderAndLoadCommands* f = nullptr; + std::unique_ptr<cmMachOHeaderAndLoadCommands> f; if (magic == MH_CIGAM || magic == MH_MAGIC) { bool swap = false; if (magic == MH_CIGAM) { swap = true; } - f = new cmMachOHeaderAndLoadCommandsImpl<mach_header>(swap); + f = cm::make_unique<cmMachOHeaderAndLoadCommandsImpl<mach_header>>(swap); } else if (magic == MH_CIGAM_64 || magic == MH_MAGIC_64) { bool swap = false; if (magic == MH_CIGAM_64) { swap = true; } - f = new cmMachOHeaderAndLoadCommandsImpl<mach_header_64>(swap); + f = + cm::make_unique<cmMachOHeaderAndLoadCommandsImpl<mach_header_64>>(swap); } if (f && f->read_mach_o(this->Fin)) { - this->MachOList.push_back(f); + this->MachOList.push_back(std::move(f)); } else { - delete f; this->ErrorMessage = "Failed to read Mach-O header."; return false; } @@ -333,11 +331,12 @@ bool cmMachO::GetInstallName(std::string& install_name) } // grab the first Mach-O and get the install name from that one - cmMachOHeaderAndLoadCommands* macho = this->Internal->MachOList[0]; + std::unique_ptr<cmMachOHeaderAndLoadCommands>& macho = + this->Internal->MachOList[0]; for (size_t i = 0; i < macho->load_commands().size(); i++) { const cmMachOHeaderAndLoadCommands::RawLoadCommand& cmd = macho->load_commands()[i]; - uint32_t lc_cmd = cmd.type(macho); + uint32_t lc_cmd = cmd.type(*macho); if (lc_cmd == LC_ID_DYLIB || lc_cmd == LC_LOAD_WEAK_DYLIB || lc_cmd == LC_LOAD_DYLIB) { if (sizeof(dylib_command) < cmd.LoadCommand.size()) { diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx index b2e59bd..94d99b7 100644 --- a/Source/cmMakefile.cxx +++ b/Source/cmMakefile.cxx @@ -684,6 +684,27 @@ bool cmMakefile::ReadListFile(const std::string& filename) return true; } +bool cmMakefile::ReadListFileAsString(const std::string& content, + const std::string& virtualFileName) +{ + std::string filenametoread = cmSystemTools::CollapseFullPath( + virtualFileName, this->GetCurrentSourceDirectory()); + + ListFileScope scope(this, filenametoread); + + cmListFile listFile; + if (!listFile.ParseString(content.c_str(), virtualFileName.c_str(), + this->GetMessenger(), this->Backtrace)) { + return false; + } + + this->ReadListFile(listFile, filenametoread); + if (cmSystemTools::GetFatalErrorOccured()) { + scope.Quiet(); + } + return true; +} + void cmMakefile::ReadListFile(cmListFile const& listFile, std::string const& filenametoread) { @@ -4492,7 +4513,7 @@ bool cmMakefile::SetPolicy(cmPolicies::PolicyID id, // Deprecate old policies, especially those that require a lot // of code to maintain the old behavior. - if (status == cmPolicies::OLD && id <= cmPolicies::CMP0069 && + if (status == cmPolicies::OLD && id <= cmPolicies::CMP0071 && !(this->GetCMakeInstance()->GetIsInTryCompile() && ( // Policies set by cmCoreTryCompile::TryCompileCode. diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h index f1a68c2..9c6dca6 100644 --- a/Source/cmMakefile.h +++ b/Source/cmMakefile.h @@ -117,6 +117,9 @@ public: bool ReadListFile(const std::string& filename); + bool ReadListFileAsString(const std::string& content, + const std::string& virtualFileName); + bool ReadDependentFile(const std::string& filename, bool noPolicyScope = true); diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx index d7e2de6..451f19e 100644 --- a/Source/cmMakefileTargetGenerator.cxx +++ b/Source/cmMakefileTargetGenerator.cxx @@ -155,7 +155,7 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules() // Evaluates generator expressions and expands prop_value auto evaluatedFiles = - [this](const char* prop_value) -> std::vector<std::string> { + [this](const std::string& prop_value) -> std::vector<std::string> { std::vector<std::string> files; cmExpandList(cmGeneratorExpression::Evaluate( prop_value, this->LocalGenerator, this->GetConfigName(), diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx index 885703f..062c46c 100644 --- a/Source/cmNinjaNormalTargetGenerator.cxx +++ b/Source/cmNinjaNormalTargetGenerator.cxx @@ -812,8 +812,20 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement( targetOutputReal = this->ConvertToNinjaPath(targetOutputReal); } else if (gt->IsFrameworkOnApple()) { // Create the library framework. + + cmOSXBundleGenerator::SkipParts bundleSkipParts; + if (globalGen->GetName() == "Ninja Multi-Config") { + const auto postFix = this->GeneratorTarget->GetFilePostfix(config); + // Skip creating Info.plist when there are multiple configurations, and + // the current configuration has a postfix. The non-postfix configuration + // Info.plist can be used by all the other configurations. + if (!postFix.empty()) { + bundleSkipParts.infoPlist = true; + } + } + this->OSXBundleGenerator->CreateFramework( - tgtNames.Output, gt->GetDirectory(config), config); + tgtNames.Output, gt->GetDirectory(config), config, bundleSkipParts); } else if (gt->IsCFBundleOnApple()) { // Create the core foundation bundle. this->OSXBundleGenerator->CreateCFBundle(tgtNames.Output, diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx index abf12f8..0e1136f 100644 --- a/Source/cmNinjaTargetGenerator.cxx +++ b/Source/cmNinjaTargetGenerator.cxx @@ -94,17 +94,19 @@ cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const std::string cmNinjaTargetGenerator::LanguageCompilerRule( const std::string& lang, const std::string& config) const { - return lang + "_COMPILER__" + - cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()) + - "_" + config; + return cmStrCat( + lang, "_COMPILER__", + cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()), + '_', config); } std::string cmNinjaTargetGenerator::LanguagePreprocessRule( std::string const& lang, const std::string& config) const { - return lang + "_PREPROCESS__" + - cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()) + - "_" + config; + return cmStrCat( + lang, "_PREPROCESS__", + cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()), + '_', config); } bool cmNinjaTargetGenerator::NeedExplicitPreprocessing( @@ -129,9 +131,10 @@ bool cmNinjaTargetGenerator::CompilePreprocessedSourceWithDefines( std::string cmNinjaTargetGenerator::LanguageDyndepRule( const std::string& lang, const std::string& config) const { - return lang + "_DYNDEP__" + - cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()) + - "_" + config; + return cmStrCat( + lang, "_DYNDEP__", + cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()), + '_', config); } bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const @@ -219,8 +222,8 @@ void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags, bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const { - std::string const& deptype = - this->GetMakefile()->GetSafeDefinition("CMAKE_NINJA_DEPTYPE_" + lang); + std::string const& deptype = this->GetMakefile()->GetSafeDefinition( + cmStrCat("CMAKE_NINJA_DEPTYPE_", lang)); if (deptype == "msvc") { return true; } @@ -355,13 +358,12 @@ std::string cmNinjaTargetGenerator::GetObjectFilePath( { std::string path = this->LocalGenerator->GetHomeRelativeOutputPath(); if (!path.empty()) { - path += "/"; + path += '/'; } std::string const& objectName = this->GeneratorTarget->GetObjectName(source); - path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - path += this->GetGlobalGenerator()->ConfigDirectory(config); - path += "/"; - path += objectName; + path += cmStrCat( + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + this->GetGlobalGenerator()->ConfigDirectory(config), '/', objectName); return path; } @@ -389,16 +391,15 @@ std::string cmNinjaTargetGenerator::GetPreprocessedFilePath( this->GetGlobalGenerator()->GetLanguageOutputExtension(*source); assert(objName.size() >= objExt.size()); std::string const ppName = - objName.substr(0, objName.size() - objExt.size()) + "-pp." + ppExt; + cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt); std::string path = this->LocalGenerator->GetHomeRelativeOutputPath(); if (!path.empty()) { - path += "/"; + path += '/'; } - path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - path += this->GetGlobalGenerator()->ConfigDirectory(config); - path += "/"; - path += ppName; + path += + cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName); return path; } @@ -407,13 +408,11 @@ std::string cmNinjaTargetGenerator::GetDyndepFilePath( { std::string path = this->LocalGenerator->GetHomeRelativeOutputPath(); if (!path.empty()) { - path += "/"; + path += '/'; } - path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); - path += this->GetGlobalGenerator()->ConfigDirectory(config); - path += "/"; - path += lang; - path += ".dd"; + path += cmStrCat( + this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget), + this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd"); return path; } @@ -442,8 +441,7 @@ std::string cmNinjaTargetGenerator::GetTargetFilePath( if (path.empty() || path == ".") { return name; } - path += "/"; - path += name; + path += cmStrCat('/', name); return path; } @@ -522,7 +520,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, bool const lang_supports_response = lang != "RC"; if (lang_supports_response && this->ForceResponseFile()) { std::string const responseFlagVar = - "CMAKE_" + lang + "_RESPONSE_FILE_FLAG"; + cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG"); responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar); if (responseFlag.empty() && lang != "CUDA") { responseFlag = "@"; @@ -587,7 +585,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, rule.RspFile = "$RSP_FILE"; rule.RspContent = cmStrCat(' ', ppVars.Defines, ' ', ppVars.Includes, ' ', ppFlags); - ppFlags = responseFlag + rule.RspFile; + ppFlags = cmStrCat(responseFlag, rule.RspFile); ppVars.Defines = ""; ppVars.Includes = ""; } @@ -658,7 +656,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, rule.RspFile = "$RSP_FILE"; rule.RspContent = cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags); - flags = responseFlag + rule.RspFile; + flags = cmStrCat(responseFlag, rule.RspFile); vars.Defines = ""; vars.Includes = ""; } @@ -671,7 +669,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, rule.DepType = "msvc"; rule.DepFile.clear(); flags += " /showIncludes"; - } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) { + } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) { // For the MS resource compiler we need cmcldeps, but skip dependencies // for source-file try_compile cases because they are always fresh. if (!mf->GetIsSourceFileTryCompile()) { @@ -688,14 +686,14 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, } else { rule.DepType = "gcc"; rule.DepFile = "$DEP_FILE"; - const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang; + const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang); std::string depfileFlags = mf->GetSafeDefinition(flagsName); if (!depfileFlags.empty()) { cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE"); cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out"); cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>", mf->GetDefinition("CMAKE_C_COMPILER")); - flags += " " + depfileFlags; + flags += cmStrCat(' ', depfileFlags); } } @@ -718,7 +716,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar); cmExpandList(compileCmd, compileCmds); } else { - const std::string cmdVar = "CMAKE_" + lang + "_COMPILE_OBJECT"; + const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT"); const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar); cmExpandList(compileCmd, compileCmds); } @@ -728,7 +726,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, if (!compileCmds.empty() && (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" || lang == "OBJC" || lang == "OBJCXX")) { - std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER"; + std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER"); const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop); if (clauncher && *clauncher) { compilerLauncher = clauncher; @@ -737,13 +735,13 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, // Maybe insert an include-what-you-use runner. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) { - std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE"; + std::string const iwyu_prop = cmStrCat(lang, "_INCLUDE_WHAT_YOU_USE"); const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop); - std::string const tidy_prop = lang + "_CLANG_TIDY"; + std::string const tidy_prop = cmStrCat(lang, "_CLANG_TIDY"); const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop); - std::string const cpplint_prop = lang + "_CPPLINT"; + std::string const cpplint_prop = cmStrCat(lang, "_CPPLINT"); const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop); - std::string const cppcheck_prop = lang + "_CPPCHECK"; + std::string const cppcheck_prop = cmStrCat(lang, "_CPPCHECK"); const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop); if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) || (cppcheck && *cppcheck)) { @@ -751,18 +749,19 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, if (!compilerLauncher.empty()) { // In __run_co_compile case the launcher command is supplied // via --launcher=<maybe-list> and consumed - run_iwyu += " --launcher="; - run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher); + run_iwyu += + cmStrCat(" --launcher=", + this->LocalGenerator->EscapeForShell(compilerLauncher)); compilerLauncher.clear(); } if (iwyu && *iwyu) { - run_iwyu += " --iwyu="; - run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu); + run_iwyu += cmStrCat(" --iwyu=", + this->GetLocalGenerator()->EscapeForShell(iwyu)); } if (tidy && *tidy) { run_iwyu += " --tidy="; const char* driverMode = this->Makefile->GetDefinition( - "CMAKE_" + lang + "_CLANG_TIDY_DRIVER_MODE"); + cmStrCat("CMAKE_", lang, "_CLANG_TIDY_DRIVER_MODE")); if (!(driverMode && *driverMode)) { driverMode = lang == "C" ? "gcc" : "g++"; } @@ -770,12 +769,12 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, cmStrCat(tidy, ";--extra-arg-before=--driver-mode=", driverMode)); } if (cpplint && *cpplint) { - run_iwyu += " --cpplint="; - run_iwyu += this->GetLocalGenerator()->EscapeForShell(cpplint); + run_iwyu += cmStrCat( + " --cpplint=", this->GetLocalGenerator()->EscapeForShell(cpplint)); } if (cppcheck && *cppcheck) { - run_iwyu += " --cppcheck="; - run_iwyu += this->GetLocalGenerator()->EscapeForShell(cppcheck); + run_iwyu += cmStrCat( + " --cppcheck=", this->GetLocalGenerator()->EscapeForShell(cppcheck)); } if ((tidy && *tidy) || (cpplint && *cpplint) || (cppcheck && *cppcheck)) { @@ -797,7 +796,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang, i = this->LocalGenerator->EscapeForShell(i); } } - compileCmds.front().insert(0, cmJoin(args, " ") + " "); + compileCmds.front().insert(0, cmStrCat(cmJoin(args, " "), ' ')); } if (!compileCmds.empty()) { @@ -872,7 +871,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements( { cmNinjaBuild build("phony"); - build.Comment = "Order-only phony target for " + this->GetTargetName(); + build.Comment = + cmStrCat("Order-only phony target for ", this->GetTargetName()); build.Outputs.push_back(this->OrderDependsTargetForTarget(config)); cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps; @@ -960,9 +960,9 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements( if (const char* name = target->GetProperty("Swift_DEPENDENCIES_FILE")) { return name; } - return this->ConvertToNinjaPath(target->GetSupportDirectory() + "/" + - config + "/" + target->GetName() + - ".swiftdeps"); + return this->ConvertToNinjaPath( + cmStrCat(target->GetSupportDirectory(), '/', config, '/', + target->GetName(), ".swiftdeps")); }(); // build the global target dependencies @@ -994,7 +994,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( std::string cmakeVarLang = cmStrCat("CMAKE_", language); // build response file name - std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_FLAG"; + std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG"); const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar); @@ -1019,14 +1019,15 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( if (!replaceExt) { // use original code vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat( - objectFileName + ".d", cmOutputConverter::SHELL); + cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL); } else { // Replace the original source file extension with the // depend file extension. - std::string dependFileName = - cmSystemTools::GetFilenameWithoutLastExtension(objectFileName) + ".d"; + std::string dependFileName = cmStrCat( + cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d"); vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat( - objectFileDir + "/" + dependFileName, cmOutputConverter::SHELL); + cmStrCat(objectFileDir, '/', dependFileName), + cmOutputConverter::SHELL); } } @@ -1101,7 +1102,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( this->ConvertToNinjaPath(this->GetPreprocessedFilePath(source, config)); ppBuild.Outputs.push_back(ppFileName); - ppBuild.RspFile = ppFileName + ".rsp"; + ppBuild.RspFile = cmStrCat(ppFileName, ".rsp"); bool const compilePP = this->UsePreprocessedSource(language); bool const compilePPWithDefines = @@ -1130,7 +1131,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( // In case compilation requires flags that are incompatible with // preprocessing, include them here. std::string const& postFlag = this->Makefile->GetSafeDefinition( - "CMAKE_" + language + "_POSTPROCESS_FLAG"); + cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG")); this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag); } @@ -1158,13 +1159,13 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( sourceDirectory, this->GeneratorTarget, language, false, false, config); - vars["INCLUDES"] = sourceDirectoryFlag + " " + vars["INCLUDES"]; + vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]); } // Explicit preprocessing always uses a depfile. ppBuild.Variables["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat( - objectFileName + ".pp.d", cmOutputConverter::SHELL); + cmStrCat(objectFileName, ".pp.d"), cmOutputConverter::SHELL); if (compilePP) { // The actual compilation does not need a depfile because it // depends on the already-preprocessed source. @@ -1177,7 +1178,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( ppBuild.Variables["OBJ_FILE"] = objectFileName; // Tell dependency scanner where to store dyndep intermediate results. - std::string const ddiFile = objectFileName + ".ddi"; + std::string const ddiFile = cmStrCat(objectFileName, ".ddi"); ppBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFile; ppBuild.ImplicitOuts.push_back(ddiFile); if (firstForConfig) { @@ -1216,7 +1217,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( this->SetMsvcTargetPdbVariable(vars, config); - objBuild.RspFile = objectFileName + ".rsp"; + objBuild.RspFile = cmStrCat(objectFileName, ".rsp"); if (language == "Swift") { this->EmitSwiftDependencyInfo(source, config); @@ -1242,8 +1243,8 @@ void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang, { Json::Value tdi(Json::objectValue); tdi["language"] = lang; - tdi["compiler-id"] = - this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID"); + tdi["compiler-id"] = this->Makefile->GetSafeDefinition( + cmStrCat("CMAKE_", lang, "_COMPILER_ID")); if (lang == "Fortran") { std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory( @@ -1295,13 +1296,13 @@ void cmNinjaTargetGenerator::EmitSwiftDependencyInfo( if (const char* name = source->GetProperty("Swift_DEPENDENCIES_FILE")) { return name; } - return objectFilePath + ".swiftdeps"; + return cmStrCat(objectFilePath, ".swiftdeps"); }(); std::string const swiftDiaPath = [source, objectFilePath]() -> std::string { if (const char* name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) { return name; } - return objectFilePath + ".dia"; + return cmStrCat(objectFilePath, ".dia"); }(); std::string const makeDepsPath = [this, source, config]() -> std::string { cmLocalNinjaGenerator const* local = this->GetLocalGenerator(); @@ -1311,12 +1312,13 @@ void cmNinjaTargetGenerator::EmitSwiftDependencyInfo( cmSystemTools::GetFilenamePath(objectFileName); if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) { - std::string dependFileName = - cmSystemTools::GetFilenameWithoutLastExtension(objectFileName) + ".d"; - return local->ConvertToOutputFormat(objectFileDir + "/" + dependFileName, - cmOutputConverter::SHELL); + std::string dependFileName = cmStrCat( + cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d"); + return local->ConvertToOutputFormat( + cmStrCat(objectFileDir, '/', dependFileName), + cmOutputConverter::SHELL); } - return local->ConvertToOutputFormat(objectFileName + ".d", + return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL); }(); @@ -1381,7 +1383,7 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand( this->GetMakefile()->GetRequiredDefinition(cmdVar); cmExpandList(compileCmd, compileCmds); } else { - const std::string cmdVar = "CMAKE_" + language + "_COMPILE_OBJECT"; + const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT"); const std::string& compileCmd = this->GetMakefile()->GetRequiredDefinition(cmdVar); cmExpandList(compileCmd, compileCmds); diff --git a/Source/cmOSXBundleGenerator.cxx b/Source/cmOSXBundleGenerator.cxx index 382b563..7eea4b2 100644 --- a/Source/cmOSXBundleGenerator.cxx +++ b/Source/cmOSXBundleGenerator.cxx @@ -56,9 +56,9 @@ void cmOSXBundleGenerator::CreateAppBundle(const std::string& targetName, outpath = out; } -void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, - const std::string& outpath, - const std::string& config) +void cmOSXBundleGenerator::CreateFramework( + const std::string& targetName, const std::string& outpath, + const std::string& config, const cmOSXBundleGenerator::SkipParts& skipParts) { if (this->MustSkip()) { return; @@ -77,16 +77,18 @@ void cmOSXBundleGenerator::CreateFramework(const std::string& targetName, std::string frameworkVersion = this->GT->GetFrameworkVersion(); - // Configure the Info.plist file - std::string plist = newoutpath; - if (!this->Makefile->PlatformIsAppleEmbedded()) { - // Put the Info.plist file into the Resources directory. - this->MacContentFolders->insert("Resources"); - plist += "/Resources"; - } - plist += "/Info.plist"; std::string name = cmSystemTools::GetFilenameName(targetName); - this->LocalGenerator->GenerateFrameworkInfoPList(this->GT, name, plist); + if (!skipParts.infoPlist) { + // Configure the Info.plist file + std::string plist = newoutpath; + if (!this->Makefile->PlatformIsAppleEmbedded()) { + // Put the Info.plist file into the Resources directory. + this->MacContentFolders->insert("Resources"); + plist += "/Resources"; + } + plist += "/Info.plist"; + this->LocalGenerator->GenerateFrameworkInfoPList(this->GT, name, plist); + } // Generate Versions directory only for MacOSX frameworks if (this->Makefile->PlatformIsAppleEmbedded()) { diff --git a/Source/cmOSXBundleGenerator.h b/Source/cmOSXBundleGenerator.h index 232be48..5bf1d98 100644 --- a/Source/cmOSXBundleGenerator.h +++ b/Source/cmOSXBundleGenerator.h @@ -19,6 +19,15 @@ class cmOSXBundleGenerator public: cmOSXBundleGenerator(cmGeneratorTarget* target); + struct SkipParts + { + SkipParts() + : infoPlist(false) + { + } + bool infoPlist; // NOLINT(modernize-use-default-member-init) + }; + // create an app bundle at a given root, and return // the directory within the bundle that contains the executable void CreateAppBundle(const std::string& targetName, std::string& root, @@ -26,7 +35,8 @@ public: // create a framework at a given root void CreateFramework(const std::string& targetName, const std::string& root, - const std::string& config); + const std::string& config, + const SkipParts& skipParts = SkipParts()); // create a cf bundle at a given root void CreateCFBundle(const std::string& targetName, const std::string& root, diff --git a/Source/cmProcessOutput.cxx b/Source/cmProcessOutput.cxx index e80ea5c..0fb4ff7 100644 --- a/Source/cmProcessOutput.cxx +++ b/Source/cmProcessOutput.cxx @@ -4,7 +4,10 @@ #include "cmProcessOutput.h" #if defined(_WIN32) +# include <cm/memory> + # include <windows.h> + unsigned int cmProcessOutput::defaultCodepage = KWSYS_ENCODING_DEFAULT_CODEPAGE; #endif @@ -143,9 +146,9 @@ bool cmProcessOutput::DoDecodeText(std::string raw, std::string& decoded, bool success = false; const int wlength = MultiByteToWideChar(codepage, 0, raw.c_str(), int(raw.size()), NULL, 0); - wchar_t* wdata = new wchar_t[wlength]; - int r = MultiByteToWideChar(codepage, 0, raw.c_str(), int(raw.size()), wdata, - wlength); + auto wdata = cm::make_unique<wchar_t[]>(wlength); + int r = MultiByteToWideChar(codepage, 0, raw.c_str(), int(raw.size()), + wdata.get(), wlength); if (r > 0) { if (lastChar) { *lastChar = 0; @@ -154,18 +157,16 @@ bool cmProcessOutput::DoDecodeText(std::string raw, std::string& decoded, *lastChar = wdata[wlength - 1]; } } - int length = WideCharToMultiByte(defaultCodepage, 0, wdata, wlength, NULL, - 0, NULL, NULL); - char* data = new char[length]; - r = WideCharToMultiByte(defaultCodepage, 0, wdata, wlength, data, length, - NULL, NULL); + int length = WideCharToMultiByte(defaultCodepage, 0, wdata.get(), wlength, + NULL, 0, NULL, NULL); + auto data = cm::make_unique<char[]>(length); + r = WideCharToMultiByte(defaultCodepage, 0, wdata.get(), wlength, + data.get(), length, NULL, NULL); if (r > 0) { - decoded = std::string(data, length); + decoded = std::string(data.get(), length); success = true; } - delete[] data; } - delete[] wdata; return success; } #endif diff --git a/Source/cmServer.cxx b/Source/cmServer.cxx index 3b2e5f3..434fb68 100644 --- a/Source/cmServer.cxx +++ b/Source/cmServer.cxx @@ -59,16 +59,12 @@ cmServer::cmServer(cmConnection* conn, bool supportExperimental) , SupportExperimental(supportExperimental) { // Register supported protocols: - this->RegisterProtocol(new cmServerProtocol1); + this->RegisterProtocol(cm::make_unique<cmServerProtocol1>()); } cmServer::~cmServer() { Close(); - - for (cmServerProtocol* p : this->SupportedProtocols) { - delete p; - } } void cmServer::ProcessRequest(cmConnection* connection, @@ -117,22 +113,22 @@ void cmServer::ProcessRequest(cmConnection* connection, } } -void cmServer::RegisterProtocol(cmServerProtocol* protocol) +void cmServer::RegisterProtocol(std::unique_ptr<cmServerProtocol> protocol) { if (protocol->IsExperimental() && !this->SupportExperimental) { - delete protocol; + protocol.reset(); return; } auto version = protocol->ProtocolVersion(); assert(version.first >= 0); assert(version.second >= 0); - auto it = std::find_if(this->SupportedProtocols.begin(), - this->SupportedProtocols.end(), - [version](cmServerProtocol* p) { - return p->ProtocolVersion() == version; - }); + auto it = std::find_if( + this->SupportedProtocols.begin(), this->SupportedProtocols.end(), + [version](const std::unique_ptr<cmServerProtocol>& p) { + return p->ProtocolVersion() == version; + }); if (it == this->SupportedProtocols.end()) { - this->SupportedProtocols.push_back(protocol); + this->SupportedProtocols.push_back(std::move(protocol)); } } @@ -297,19 +293,20 @@ void cmServer::WriteJsonObject(cmConnection* connection, } cmServerProtocol* cmServer::FindMatchingProtocol( - const std::vector<cmServerProtocol*>& protocols, int major, int minor) + const std::vector<std::unique_ptr<cmServerProtocol>>& protocols, int major, + int minor) { cmServerProtocol* bestMatch = nullptr; - for (auto protocol : protocols) { + for (const auto& protocol : protocols) { auto version = protocol->ProtocolVersion(); if (major != version.first) { continue; } if (minor == version.second) { - return protocol; + return protocol.get(); } if (!bestMatch || bestMatch->ProtocolVersion().second < version.second) { - bestMatch = protocol; + bestMatch = protocol.get(); } } return minor < 0 ? bestMatch : nullptr; diff --git a/Source/cmServer.h b/Source/cmServer.h index 3d7027b..ec40738 100644 --- a/Source/cmServer.h +++ b/Source/cmServer.h @@ -103,7 +103,7 @@ public: cmFileMonitor* FileMonitor() const; private: - void RegisterProtocol(cmServerProtocol* protocol); + void RegisterProtocol(std::unique_ptr<cmServerProtocol> protocol); // Callbacks from cmServerConnection: @@ -149,12 +149,13 @@ private: const DebugInfo* debug) const; static cmServerProtocol* FindMatchingProtocol( - const std::vector<cmServerProtocol*>& protocols, int major, int minor); + const std::vector<std::unique_ptr<cmServerProtocol>>& protocols, int major, + int minor); const bool SupportExperimental; cmServerProtocol* Protocol = nullptr; - std::vector<cmServerProtocol*> SupportedProtocols; + std::vector<std::unique_ptr<cmServerProtocol>> SupportedProtocols; friend class cmServerProtocol; friend class cmServerRequest; diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx index 3705727..ce534e1 100644 --- a/Source/cmSetPropertyCommand.cxx +++ b/Source/cmSetPropertyCommand.cxx @@ -307,7 +307,7 @@ bool HandleTarget(cmTarget* target, cmMakefile& makefile, if (remove) { target->SetProperty(propertyName, nullptr); } else { - target->SetProperty(propertyName, propertyValue.c_str()); + target->SetProperty(propertyName, propertyValue); } } @@ -460,16 +460,15 @@ bool HandleCacheEntry(std::string const& cacheKey, const cmMakefile& makefile, bool appendMode, bool remove) { // Set or append the property. - const char* value = propertyValue.c_str(); cmState* state = makefile.GetState(); if (remove) { state->RemoveCacheEntryProperty(cacheKey, propertyName); } if (appendMode) { - state->AppendCacheEntryProperty(cacheKey, propertyName, value, + state->AppendCacheEntryProperty(cacheKey, propertyName, propertyValue, appendAsString); } else { - state->SetCacheEntryProperty(cacheKey, propertyName, value); + state->SetCacheEntryProperty(cacheKey, propertyName, propertyValue); } return true; @@ -505,13 +504,13 @@ bool HandleInstall(cmInstalledFile* file, cmMakefile& makefile, bool appendMode, bool remove) { // Set or append the property. - const char* value = propertyValue.c_str(); if (remove) { file->RemoveProperty(propertyName); } else if (appendMode) { - file->AppendProperty(&makefile, propertyName, value, appendAsString); + file->AppendProperty(&makefile, propertyName, propertyValue, + appendAsString); } else { - file->SetProperty(&makefile, propertyName, value); + file->SetProperty(&makefile, propertyName, propertyValue); } return true; } diff --git a/Source/cmSourceGroup.cxx b/Source/cmSourceGroup.cxx index 8c3ec9f..155068cb 100644 --- a/Source/cmSourceGroup.cxx +++ b/Source/cmSourceGroup.cxx @@ -4,6 +4,8 @@ #include <utility> +#include <cm/memory> + #include "cmStringAlgorithms.h" class cmSourceGroupInternals @@ -16,7 +18,7 @@ cmSourceGroup::cmSourceGroup(std::string name, const char* regex, const char* parentName) : Name(std::move(name)) { - this->Internal = new cmSourceGroupInternals; + this->Internal = cm::make_unique<cmSourceGroupInternals>(); this->SetGroupRegex(regex); if (parentName) { this->FullName = cmStrCat(parentName, '\\'); @@ -24,10 +26,7 @@ cmSourceGroup::cmSourceGroup(std::string name, const char* regex, this->FullName += this->Name; } -cmSourceGroup::~cmSourceGroup() -{ - delete this->Internal; -} +cmSourceGroup::~cmSourceGroup() = default; cmSourceGroup::cmSourceGroup(cmSourceGroup const& r) { @@ -36,7 +35,7 @@ cmSourceGroup::cmSourceGroup(cmSourceGroup const& r) this->GroupRegex = r.GroupRegex; this->GroupFiles = r.GroupFiles; this->SourceFiles = r.SourceFiles; - this->Internal = new cmSourceGroupInternals(*r.Internal); + this->Internal = cm::make_unique<cmSourceGroupInternals>(*r.Internal); } cmSourceGroup& cmSourceGroup::operator=(cmSourceGroup const& r) diff --git a/Source/cmSourceGroup.h b/Source/cmSourceGroup.h index 581dc5d..623cded 100644 --- a/Source/cmSourceGroup.h +++ b/Source/cmSourceGroup.h @@ -5,6 +5,7 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include <memory> #include <set> #include <string> #include <vector> @@ -122,7 +123,7 @@ private: */ std::vector<const cmSourceFile*> SourceFiles; - cmSourceGroupInternals* Internal; + std::unique_ptr<cmSourceGroupInternals> Internal; }; #endif diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index 9212195..7662204 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -124,6 +124,27 @@ bool HandleAsciiCommand(std::vector<std::string> const& args, return true; } +bool HandleHexCommand(std::vector<std::string> const& args, + cmExecutionStatus& status) +{ + if (args.size() != 3) { + status.SetError("Incorrect number of arguments"); + return false; + } + auto const& instr = args[1]; + auto const& outvar = args[2]; + std::string output(instr.size() * 2, ' '); + + std::string::size_type hexIndex = 0; + for (auto const& c : instr) { + sprintf(&output[hexIndex], "%.2x", static_cast<unsigned char>(c) & 0xFF); + hexIndex += 2; + } + + status.GetMakefile().AddDefinition(outvar, output); + return true; +} + bool HandleConfigureCommand(std::vector<std::string> const& args, cmExecutionStatus& status) { @@ -936,6 +957,7 @@ bool cmStringCommand(std::vector<std::string> const& args, { "TOUPPER"_s, HandleToUpperCommand }, { "COMPARE"_s, HandleCompareCommand }, { "ASCII"_s, HandleAsciiCommand }, + { "HEX"_s, HandleHexCommand }, { "CONFIGURE"_s, HandleConfigureCommand }, { "LENGTH"_s, HandleLengthCommand }, { "APPEND"_s, HandleAppendCommand }, diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index 9127c50..d8cd705 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -25,6 +25,9 @@ #endif #if !defined(CMAKE_BOOTSTRAP) +# if defined(_WIN32) +# include <cm/memory> +# endif # include "cmCryptoHash.h" #endif @@ -908,7 +911,6 @@ std::string cmSystemTools::ComputeCertificateThumbprint( std::string thumbprint; #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) - BYTE* certData = NULL; CRYPT_INTEGER_BLOB cryptBlob; HCERTSTORE certStore = NULL; PCCERT_CONTEXT certContext = NULL; @@ -920,12 +922,12 @@ std::string cmSystemTools::ComputeCertificateThumbprint( if (certFile != INVALID_HANDLE_VALUE && certFile != NULL) { DWORD fileSize = GetFileSize(certFile, NULL); if (fileSize != INVALID_FILE_SIZE) { - certData = new BYTE[fileSize]; + auto certData = cm::make_unique<BYTE[]>(fileSize); if (certData != NULL) { DWORD dwRead = 0; - if (ReadFile(certFile, certData, fileSize, &dwRead, NULL)) { + if (ReadFile(certFile, certData.get(), fileSize, &dwRead, NULL)) { cryptBlob.cbData = fileSize; - cryptBlob.pbData = certData; + cryptBlob.pbData = certData.get(); // Verify that this is a valid cert if (PFXIsPFXBlob(&cryptBlob)) { @@ -961,7 +963,6 @@ std::string cmSystemTools::ComputeCertificateThumbprint( } } } - delete[] certData; } } CloseHandle(certFile); diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx index 97d7fce..987f526 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -300,6 +300,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, initProp("PDB_OUTPUT_DIRECTORY"); initProp("COMPILE_PDB_OUTPUT_DIRECTORY"); initProp("FRAMEWORK"); + initProp("FRAMEWORK_MULTI_CONFIG_POSTFIX"); initProp("Fortran_FORMAT"); initProp("Fortran_MODULE_DIRECTORY"); initProp("Fortran_COMPILER_LAUNCHER"); @@ -435,6 +436,13 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, cmStrCat(cmSystemTools::UpperCase(configName), "_POSTFIX"); initProp(property); } + + if (impl->TargetType == cmStateEnums::SHARED_LIBRARY || + impl->TargetType == cmStateEnums::STATIC_LIBRARY) { + std::string property = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_", + cmSystemTools::UpperCase(configName)); + initProp(property); + } } } diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index 8da113e..121ff6e 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -981,17 +981,11 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup(Elem& e0) // If the resource was NOT added using a relative path (which should // be the default), we have to provide a link here if (!useRelativePath) { - std::string link; - if (obj.find(srcDir) == 0) { - link = obj.substr(srcDir.length() + 1); - } else if (obj.find(binDir) == 0) { - link = obj.substr(binDir.length() + 1); - } else { + std::string link = this->GetCSharpSourceLink(oi); + if (link.empty()) { link = cmsys::SystemTools::GetFilenameName(obj); } - if (!link.empty()) { - e2.Element("Link", link); - } + e2.Element("Link", link); } // Determine if this is a generated resource from a .Designer.cs file std::string designerResource = @@ -1054,25 +1048,6 @@ void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup(Elem& e0) Elem e2(e1, xamlType); this->WriteSource(e2, oi); e2.SetHasElements(); - if (this->ProjectType == csproj && !this->InSourceBuild) { - // add <Link> tag to written XAML source if necessary - const std::string& srcDir = - this->Makefile->GetCurrentSourceDirectory(); - const std::string& binDir = - this->Makefile->GetCurrentBinaryDirectory(); - std::string link; - if (obj.find(srcDir) == 0) { - link = obj.substr(srcDir.length() + 1); - } else if (obj.find(binDir) == 0) { - link = obj.substr(binDir.length() + 1); - } else { - link = cmsys::SystemTools::GetFilenameName(obj); - } - if (!link.empty()) { - ConvertToWindowsSlash(link); - e2.Element("Link", link); - } - } e2.Element("SubType", "Designer"); } } @@ -1442,13 +1417,8 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule( } else { Elem e1(e0, "ItemGroup"); Elem e2(e1, "None"); - std::string link; - this->GetCSharpSourceLink(source, link); this->WriteSource(e2, source); e2.SetHasElements(); - if (!link.empty()) { - e2.Element("Link", link); - } } for (std::string const& c : this->Configurations) { cmCustomCommandGenerator ccg(command, c, lg); @@ -1805,30 +1775,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1, std::string copyToOutDir; std::string includeInVsix; std::string ext = cmSystemTools::LowerCase(sf->GetExtension()); - if (this->ProjectType == csproj) { - // EVERY extra source file must have a <Link>, otherwise it might not - // be visible in Visual Studio at all. The path relative to current - // source- or binary-dir is used within the link, if the file is - // in none of these paths, it is added with the plain filename without - // any path. This means the file will show up at root-level of the csproj - // (where CMakeLists.txt etc. are). - if (!this->InSourceBuild) { - toolHasSettings = true; - std::string fullFileName = sf->GetFullPath(); - std::string srcDir = this->Makefile->GetCurrentSourceDirectory(); - std::string binDir = this->Makefile->GetCurrentBinaryDirectory(); - if (fullFileName.find(binDir) != std::string::npos) { - sourceLink.clear(); - } else if (fullFileName.find(srcDir) != std::string::npos) { - sourceLink = fullFileName.substr(srcDir.length() + 1); - } else { - // fallback: add plain filename without any path - sourceLink = cmsys::SystemTools::GetFilenameName(fullFileName); - } - if (!sourceLink.empty()) { - ConvertToWindowsSlash(sourceLink); - } - } + if (this->ProjectType == csproj && !this->InSourceBuild) { + toolHasSettings = true; } if (ext == "hlsl") { tool = "FXCompile"; @@ -2047,9 +1995,6 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1, if (!settingsLastGenOutput.empty()) { e2.Element("LastGenOutput", settingsLastGenOutput); } - if (!sourceLink.empty()) { - e2.Element("Link", sourceLink); - } if (!subType.empty()) { e2.Element("SubType", subType); } @@ -2102,6 +2047,20 @@ void cmVisualStudio10TargetGenerator::WriteSource(Elem& e2, ConvertToWindowsSlash(sourceFile); e2.Attribute("Include", sourceFile); + if (this->ProjectType == csproj && !this->InSourceBuild) { + // For out of source projects we have to provide a link (if not specified + // via property) for every source file (besides .cs files) otherwise they + // will not be visible in VS at all. + // First we check if the file is in a source group, then we check if the + // file path is relative to current source- or binary-dir, otherwise it is + // added with the plain filename without any path. This means the file will + // show up at root-level of the csproj (where CMakeLists.txt etc. are). + std::string link = this->GetCSharpSourceLink(sf); + if (link.empty()) + link = cmsys::SystemTools::GetFilenameName(sf->GetFullPath()); + e2.Element("Link", link); + } + ToolSource toolSource = { sf, forceRelative }; this->Tools[e2.Tag].push_back(toolSource); } @@ -2461,12 +2420,6 @@ void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( std::string f = source->GetFullPath(); using CsPropMap = std::map<std::string, std::string>; CsPropMap sourceFileTags; - // set <Link> tag if necessary - std::string link; - this->GetCSharpSourceLink(source, link); - if (!link.empty()) { - sourceFileTags["Link"] = link; - } this->GetCSharpSourceProperties(&sf, sourceFileTags); // write source file specific tags if (!sourceFileTags.empty()) { @@ -4869,24 +4822,34 @@ void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties( } } -void cmVisualStudio10TargetGenerator::GetCSharpSourceLink( - cmSourceFile const* sf, std::string& link) +std::string cmVisualStudio10TargetGenerator::GetCSharpSourceLink( + cmSourceFile const* source) { - std::string const& sourceFilePath = sf->GetFullPath(); - std::string const& binaryDir = LocalGenerator->GetCurrentBinaryDirectory(); - - if (!cmSystemTools::IsSubDirectory(sourceFilePath, binaryDir)) { - const std::string& stripFromPath = - this->Makefile->GetCurrentSourceDirectory(); - if (sourceFilePath.find(stripFromPath) == 0) { - if (const char* l = sf->GetProperty("VS_CSHARP_Link")) { - link = l; - } else { - link = sourceFilePath.substr(stripFromPath.length() + 1); - } - ConvertToWindowsSlash(link); - } - } + // For out of source files, we first check if a matching source group + // for this file exists, otherwise we check if the path relative to current + // source- or binary-dir is used within the link and return that + std::string link; + std::string const& fullFileName = source->GetFullPath(); + std::string const& srcDir = this->Makefile->GetCurrentSourceDirectory(); + std::string const& binDir = this->Makefile->GetCurrentBinaryDirectory(); + // unfortunately we have to copy the source groups, because + // FindSourceGroup uses a regex which is modifying the group + std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups(); + cmSourceGroup* sourceGroup = + this->Makefile->FindSourceGroup(fullFileName, sourceGroups); + if (sourceGroup && !sourceGroup->GetFullName().empty()) { + link = sourceGroup->GetFullName() + "/" + + cmsys::SystemTools::GetFilenameName(fullFileName); + } else if (fullFileName.find(srcDir) == 0) { + link = fullFileName.substr(srcDir.length() + 1); + } else if (fullFileName.find(binDir) == 0) { + link = fullFileName.substr(binDir.length() + 1); + } else if (const char* l = source->GetProperty("VS_CSHARP_Link")) { + link = l; + } + + ConvertToWindowsSlash(link); + return link; } std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath( diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h index 30027c9..4977c1a 100644 --- a/Source/cmVisualStudio10TargetGenerator.h +++ b/Source/cmVisualStudio10TargetGenerator.h @@ -183,7 +183,7 @@ private: std::map<std::string, std::string>& tags); void WriteCSharpSourceProperties( Elem& e2, const std::map<std::string, std::string>& tags); - void GetCSharpSourceLink(cmSourceFile const* sf, std::string& link); + std::string GetCSharpSourceLink(cmSourceFile const* source); private: friend class cmVS10GeneratorOptions; diff --git a/Source/cmXCode21Object.cxx b/Source/cmXCode21Object.cxx index a9bb2ef..6b133a9 100644 --- a/Source/cmXCode21Object.cxx +++ b/Source/cmXCode21Object.cxx @@ -30,11 +30,12 @@ void cmXCode21Object::PrintComment(std::ostream& out) out << " */"; } -void cmXCode21Object::PrintList(std::vector<cmXCodeObject*> const& v, - std::ostream& out, PBXType t) +void cmXCode21Object::PrintList( + std::vector<std::unique_ptr<cmXCodeObject>> const& v, std::ostream& out, + PBXType t) { bool hasOne = false; - for (auto obj : v) { + for (const auto& obj : v) { if (obj->GetType() == OBJECT && obj->GetIsA() == t) { hasOne = true; break; @@ -44,7 +45,7 @@ void cmXCode21Object::PrintList(std::vector<cmXCodeObject*> const& v, return; } out << "\n/* Begin " << PBXTypeNames[t] << " section */\n"; - for (auto obj : v) { + for (const auto& obj : v) { if (obj->GetType() == OBJECT && obj->GetIsA() == t) { obj->Print(out); } @@ -52,8 +53,8 @@ void cmXCode21Object::PrintList(std::vector<cmXCodeObject*> const& v, out << "/* End " << PBXTypeNames[t] << " section */\n"; } -void cmXCode21Object::PrintList(std::vector<cmXCodeObject*> const& v, - std::ostream& out) +void cmXCode21Object::PrintList( + std::vector<std::unique_ptr<cmXCodeObject>> const& v, std::ostream& out) { cmXCodeObject::Indent(1, out); out << "objects = {\n"; diff --git a/Source/cmXCode21Object.h b/Source/cmXCode21Object.h index 8e4b80f..76fad23 100644 --- a/Source/cmXCode21Object.h +++ b/Source/cmXCode21Object.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include <iosfwd> +#include <memory> #include <vector> #include "cmXCodeObject.h" @@ -15,8 +16,9 @@ class cmXCode21Object : public cmXCodeObject public: cmXCode21Object(PBXType ptype, Type type); void PrintComment(std::ostream&) override; - static void PrintList(std::vector<cmXCodeObject*> const&, std::ostream& out, - PBXType t); - static void PrintList(std::vector<cmXCodeObject*> const&, std::ostream& out); + static void PrintList(std::vector<std::unique_ptr<cmXCodeObject>> const&, + std::ostream& out, PBXType t); + static void PrintList(std::vector<std::unique_ptr<cmXCodeObject>> const&, + std::ostream& out); }; #endif diff --git a/Source/cm_get_date.c b/Source/cm_get_date.c index 4bef803..49f5577 100644 --- a/Source/cm_get_date.c +++ b/Source/cm_get_date.c @@ -2,6 +2,10 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cm_get_date.h" +// FIXME: This suppresses use of localtime_r because archive_getdate.c +// depends the rest of libarchive's checks for that. +#define CM_GET_DATE + #define __archive_get_date cm_get_date #include "../Utilities/cmlibarchive/libarchive/archive_getdate.c" diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt index 09bcdb9..5de2776 100644 --- a/Source/kwsys/CMakeLists.txt +++ b/Source/kwsys/CMakeLists.txt @@ -11,9 +11,9 @@ # be used. All classes are disabled by default. The CMake listfile # above this one configures the library as follows: # -# SET(KWSYS_NAMESPACE foosys) -# SET(KWSYS_USE_Directory 1) # Enable Directory class. -# SUBDIRS(kwsys) +# set(KWSYS_NAMESPACE foosys) +# set(KWSYS_USE_Directory 1) # Enable Directory class. +# add_subdirectory(kwsys) # # Optional settings are as follows: # @@ -39,8 +39,8 @@ # # Example: # -# SET(KWSYS_HEADER_ROOT ${PROJECT_BINARY_DIR}) -# INCLUDE_DIRECTORIES(${PROJECT_BINARY_DIR}) +# set(KWSYS_HEADER_ROOT ${PROJECT_BINARY_DIR}) +# include_directories(${PROJECT_BINARY_DIR}) # # KWSYS_CXX_STANDARD = A value for CMAKE_CXX_STANDARD within KWSys. # Set to empty string to use no default value. @@ -65,11 +65,11 @@ # # Example: # -# SET(KWSYS_INSTALL_BIN_DIR bin) -# SET(KWSYS_INSTALL_LIB_DIR lib) -# SET(KWSYS_INSTALL_INCLUDE_DIR include) -# SET(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME Runtime) -# SET(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT Development) +# set(KWSYS_INSTALL_BIN_DIR bin) +# set(KWSYS_INSTALL_LIB_DIR lib) +# set(KWSYS_INSTALL_INCLUDE_DIR include) +# set(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME Runtime) +# set(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT Development) # Once configured, kwsys should be used as follows from C or C++ code: # @@ -86,33 +86,33 @@ # any outside mailing list and no documentation of the change will be # written. -CMAKE_MINIMUM_REQUIRED(VERSION 3.1 FATAL_ERROR) -FOREACH(p +cmake_minimum_required(VERSION 3.1 FATAL_ERROR) +foreach(p CMP0056 # CMake 3.2, Honor link flags in try_compile() source-file signature. CMP0063 # CMake 3.3, Honor visibility properties for all target types. CMP0067 # CMake 3.8, Honor language standard in try_compile source-file signature. CMP0069 # CMake 3.9, INTERPROCEDURAL_OPTIMIZATION is enforced when enabled. ) - IF(POLICY ${p}) - CMAKE_POLICY(SET ${p} NEW) - ENDIF() -ENDFOREACH() + if(POLICY ${p}) + cmake_policy(SET ${p} NEW) + endif() +endforeach() #----------------------------------------------------------------------------- # If a namespace is not specified, use "kwsys" and enable testing. # This should be the case only when kwsys is not included inside # another project and is being tested. -IF(NOT KWSYS_NAMESPACE) - SET(KWSYS_NAMESPACE "kwsys") - SET(KWSYS_STANDALONE 1) -ENDIF() +if(NOT KWSYS_NAMESPACE) + set(KWSYS_NAMESPACE "kwsys") + set(KWSYS_STANDALONE 1) +endif() #----------------------------------------------------------------------------- # The project name is that of the specified namespace. -PROJECT(${KWSYS_NAMESPACE}) +project(${KWSYS_NAMESPACE}) # Tell CMake how to follow dependencies of sources in this directory. -SET_PROPERTY(DIRECTORY +set_property(DIRECTORY PROPERTY IMPLICIT_DEPENDS_INCLUDE_TRANSFORM "KWSYS_HEADER(%)=<${KWSYS_NAMESPACE}/%>" ) @@ -131,229 +131,229 @@ elseif(NOT DEFINED CMAKE_CXX_STANDARD AND NOT DEFINED KWSYS_CXX_STANDARD) endif() # Select library components. -IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) - SET(KWSYS_ENABLE_C 1) +if(KWSYS_STANDALONE OR CMake_SOURCE_DIR) + set(KWSYS_ENABLE_C 1) # Enable all components. - SET(KWSYS_USE_Base64 1) - SET(KWSYS_USE_Directory 1) - SET(KWSYS_USE_DynamicLoader 1) - SET(KWSYS_USE_Encoding 1) - SET(KWSYS_USE_Glob 1) - SET(KWSYS_USE_MD5 1) - SET(KWSYS_USE_Process 1) - SET(KWSYS_USE_RegularExpression 1) - SET(KWSYS_USE_System 1) - SET(KWSYS_USE_SystemTools 1) - SET(KWSYS_USE_CommandLineArguments 1) - SET(KWSYS_USE_Terminal 1) - SET(KWSYS_USE_IOStream 1) - SET(KWSYS_USE_FStream 1) - SET(KWSYS_USE_String 1) - SET(KWSYS_USE_SystemInformation 1) - SET(KWSYS_USE_ConsoleBuf 1) -ENDIF() + set(KWSYS_USE_Base64 1) + set(KWSYS_USE_Directory 1) + set(KWSYS_USE_DynamicLoader 1) + set(KWSYS_USE_Encoding 1) + set(KWSYS_USE_Glob 1) + set(KWSYS_USE_MD5 1) + set(KWSYS_USE_Process 1) + set(KWSYS_USE_RegularExpression 1) + set(KWSYS_USE_System 1) + set(KWSYS_USE_SystemTools 1) + set(KWSYS_USE_CommandLineArguments 1) + set(KWSYS_USE_Terminal 1) + set(KWSYS_USE_IOStream 1) + set(KWSYS_USE_FStream 1) + set(KWSYS_USE_String 1) + set(KWSYS_USE_SystemInformation 1) + set(KWSYS_USE_ConsoleBuf 1) +endif() # Enforce component dependencies. -IF(KWSYS_USE_SystemTools) - SET(KWSYS_USE_Directory 1) - SET(KWSYS_USE_FStream 1) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_Glob) - SET(KWSYS_USE_Directory 1) - SET(KWSYS_USE_SystemTools 1) - SET(KWSYS_USE_RegularExpression 1) - SET(KWSYS_USE_FStream 1) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_Process) - SET(KWSYS_USE_System 1) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_SystemInformation) - SET(KWSYS_USE_Process 1) -ENDIF() -IF(KWSYS_USE_System) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_Directory) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_DynamicLoader) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_FStream) - SET(KWSYS_USE_Encoding 1) -ENDIF() -IF(KWSYS_USE_ConsoleBuf) - SET(KWSYS_USE_Encoding 1) -ENDIF() +if(KWSYS_USE_SystemTools) + set(KWSYS_USE_Directory 1) + set(KWSYS_USE_FStream 1) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_Glob) + set(KWSYS_USE_Directory 1) + set(KWSYS_USE_SystemTools 1) + set(KWSYS_USE_RegularExpression 1) + set(KWSYS_USE_FStream 1) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_Process) + set(KWSYS_USE_System 1) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_SystemInformation) + set(KWSYS_USE_Process 1) +endif() +if(KWSYS_USE_System) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_Directory) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_DynamicLoader) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_FStream) + set(KWSYS_USE_Encoding 1) +endif() +if(KWSYS_USE_ConsoleBuf) + set(KWSYS_USE_Encoding 1) +endif() # Specify default 8 bit encoding for Windows -IF(NOT KWSYS_ENCODING_DEFAULT_CODEPAGE) - SET(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_ACP) -ENDIF() +if(NOT KWSYS_ENCODING_DEFAULT_CODEPAGE) + set(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_ACP) +endif() # Enable testing if building standalone. -IF(KWSYS_STANDALONE) - INCLUDE(Dart) - MARK_AS_ADVANCED(BUILD_TESTING DART_ROOT TCL_TCLSH) - IF(BUILD_TESTING) - ENABLE_TESTING() - ENDIF() -ENDIF() +if(KWSYS_STANDALONE) + include(Dart) + mark_as_advanced(BUILD_TESTING DART_ROOT TCL_TCLSH) + if(BUILD_TESTING) + enable_testing() + endif() +endif() # Choose default shared/static build if not specified. -IF(NOT DEFINED KWSYS_BUILD_SHARED) - SET(KWSYS_BUILD_SHARED ${BUILD_SHARED_LIBS}) -ENDIF() +if(NOT DEFINED KWSYS_BUILD_SHARED) + set(KWSYS_BUILD_SHARED ${BUILD_SHARED_LIBS}) +endif() # Include helper macros. -INCLUDE(${CMAKE_CURRENT_SOURCE_DIR}/kwsysPlatformTests.cmake) -INCLUDE(CheckTypeSize) +include(${CMAKE_CURRENT_SOURCE_DIR}/kwsysPlatformTests.cmake) +include(CheckTypeSize) # Do full dependency headers. -INCLUDE_REGULAR_EXPRESSION("^.*$") +include_regular_expression("^.*$") # Use new KWSYS_INSTALL_*_DIR variable names to control installation. # Take defaults from the old names. Note that there was no old name # for the bin dir, so we take the old lib dir name so DLLs will be # installed in a compatible way for old code. -IF(NOT KWSYS_INSTALL_INCLUDE_DIR) - STRING(REGEX REPLACE "^/" "" KWSYS_INSTALL_INCLUDE_DIR +if(NOT KWSYS_INSTALL_INCLUDE_DIR) + string(REGEX REPLACE "^/" "" KWSYS_INSTALL_INCLUDE_DIR "${KWSYS_HEADER_INSTALL_DIR}") -ENDIF() -IF(NOT KWSYS_INSTALL_LIB_DIR) - STRING(REGEX REPLACE "^/" "" KWSYS_INSTALL_LIB_DIR +endif() +if(NOT KWSYS_INSTALL_LIB_DIR) + string(REGEX REPLACE "^/" "" KWSYS_INSTALL_LIB_DIR "${KWSYS_LIBRARY_INSTALL_DIR}") -ENDIF() -IF(NOT KWSYS_INSTALL_BIN_DIR) - STRING(REGEX REPLACE "^/" "" KWSYS_INSTALL_BIN_DIR +endif() +if(NOT KWSYS_INSTALL_BIN_DIR) + string(REGEX REPLACE "^/" "" KWSYS_INSTALL_BIN_DIR "${KWSYS_LIBRARY_INSTALL_DIR}") -ENDIF() +endif() # Setup header install rules. -SET(KWSYS_INSTALL_INCLUDE_OPTIONS) -IF(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT) - SET(KWSYS_INSTALL_INCLUDE_OPTIONS ${KWSYS_INSTALL_INCLUDE_OPTIONS} +set(KWSYS_INSTALL_INCLUDE_OPTIONS) +if(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT) + set(KWSYS_INSTALL_INCLUDE_OPTIONS ${KWSYS_INSTALL_INCLUDE_OPTIONS} COMPONENT ${KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT} ) -ENDIF() +endif() # Setup library install rules. -SET(KWSYS_INSTALL_LIBRARY_RULE) -SET(KWSYS_INSTALL_NAMELINK_RULE) -IF(KWSYS_INSTALL_LIB_DIR) - IF(KWSYS_INSTALL_EXPORT_NAME) - LIST(APPEND KWSYS_INSTALL_LIBRARY_RULE EXPORT ${KWSYS_INSTALL_EXPORT_NAME}) - ENDIF() +set(KWSYS_INSTALL_LIBRARY_RULE) +set(KWSYS_INSTALL_NAMELINK_RULE) +if(KWSYS_INSTALL_LIB_DIR) + if(KWSYS_INSTALL_EXPORT_NAME) + list(APPEND KWSYS_INSTALL_LIBRARY_RULE EXPORT ${KWSYS_INSTALL_EXPORT_NAME}) + endif() # Install the shared library to the lib directory. - SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} + set(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} LIBRARY DESTINATION ${KWSYS_INSTALL_LIB_DIR} NAMELINK_SKIP ) # Assign the shared library to the runtime component. - IF(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME) - SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} + if(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME) + set(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} COMPONENT ${KWSYS_INSTALL_COMPONENT_NAME_RUNTIME} ) - ENDIF() - IF(KWSYS_BUILD_SHARED) - SET(KWSYS_INSTALL_NAMELINK_RULE ${KWSYS_INSTALL_NAMELINK_RULE} + endif() + if(KWSYS_BUILD_SHARED) + set(KWSYS_INSTALL_NAMELINK_RULE ${KWSYS_INSTALL_NAMELINK_RULE} LIBRARY DESTINATION ${KWSYS_INSTALL_LIB_DIR} NAMELINK_ONLY ) # Assign the namelink to the development component. - IF(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT) - SET(KWSYS_INSTALL_NAMELINK_RULE ${KWSYS_INSTALL_NAMELINK_RULE} + if(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT) + set(KWSYS_INSTALL_NAMELINK_RULE ${KWSYS_INSTALL_NAMELINK_RULE} COMPONENT ${KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT} ) - ENDIF() - ENDIF() + endif() + endif() # Install the archive to the lib directory. - SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} + set(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} ARCHIVE DESTINATION ${KWSYS_INSTALL_LIB_DIR} ) # Assign the archive to the development component. - IF(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT) - SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} + if(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT) + set(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} COMPONENT ${KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT} ) - ENDIF() -ENDIF() -IF(KWSYS_INSTALL_BIN_DIR) + endif() +endif() +if(KWSYS_INSTALL_BIN_DIR) # Install the runtime library to the bin directory. - SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} + set(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} RUNTIME DESTINATION ${KWSYS_INSTALL_BIN_DIR} ) # Assign the runtime library to the runtime component. - IF(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME) - SET(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} + if(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME) + set(KWSYS_INSTALL_LIBRARY_RULE ${KWSYS_INSTALL_LIBRARY_RULE} COMPONENT ${KWSYS_INSTALL_COMPONENT_NAME_RUNTIME} ) - ENDIF() -ENDIF() + endif() +endif() # Do not support old KWSYS_*a_INSTALL_DIR variable names. -SET(KWSYS_HEADER_INSTALL_DIR) -SET(KWSYS_LIBRARY_INSTALL_DIR) +set(KWSYS_HEADER_INSTALL_DIR) +set(KWSYS_LIBRARY_INSTALL_DIR) # Generated source files will need this header. -STRING(COMPARE EQUAL "${PROJECT_SOURCE_DIR}" "${PROJECT_BINARY_DIR}" +string(COMPARE EQUAL "${PROJECT_SOURCE_DIR}" "${PROJECT_BINARY_DIR}" KWSYS_IN_SOURCE_BUILD) -IF(NOT KWSYS_IN_SOURCE_BUILD) - CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/kwsysPrivate.h +if(NOT KWSYS_IN_SOURCE_BUILD) + configure_file(${PROJECT_SOURCE_DIR}/kwsysPrivate.h ${PROJECT_BINARY_DIR}/kwsysPrivate.h COPYONLY IMMEDIATE) -ENDIF() +endif() # Select plugin module file name convention. -IF(NOT KWSYS_DynamicLoader_PREFIX) - SET(KWSYS_DynamicLoader_PREFIX ${CMAKE_SHARED_MODULE_PREFIX}) -ENDIF() -IF(NOT KWSYS_DynamicLoader_SUFFIX) - SET(KWSYS_DynamicLoader_SUFFIX ${CMAKE_SHARED_MODULE_SUFFIX}) -ENDIF() +if(NOT KWSYS_DynamicLoader_PREFIX) + set(KWSYS_DynamicLoader_PREFIX ${CMAKE_SHARED_MODULE_PREFIX}) +endif() +if(NOT KWSYS_DynamicLoader_SUFFIX) + set(KWSYS_DynamicLoader_SUFFIX ${CMAKE_SHARED_MODULE_SUFFIX}) +endif() #----------------------------------------------------------------------------- # We require ANSI support from the C compiler. Add any needed flags. -IF(CMAKE_ANSI_CFLAGS) - SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_ANSI_CFLAGS}") -ENDIF() +if(CMAKE_ANSI_CFLAGS) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_ANSI_CFLAGS}") +endif() #----------------------------------------------------------------------------- # Adjust compiler flags for some platforms. -IF(NOT CMAKE_COMPILER_IS_GNUCXX) - IF(CMAKE_SYSTEM MATCHES "OSF1-V.*") - STRING(REGEX MATCH "-timplicit_local" +if(NOT CMAKE_COMPILER_IS_GNUCXX) + if(CMAKE_SYSTEM MATCHES "OSF1-V.*") + string(REGEX MATCH "-timplicit_local" KWSYS_CXX_FLAGS_HAVE_IMPLICIT_LOCAL "${CMAKE_CXX_FLAGS}") - STRING(REGEX MATCH "-no_implicit_include" + string(REGEX MATCH "-no_implicit_include" KWSYS_CXX_FLAGS_HAVE_NO_IMPLICIT_INCLUDE "${CMAKE_CXX_FLAGS}") - IF(NOT KWSYS_CXX_FLAGS_HAVE_IMPLICIT_LOCAL) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -timplicit_local") - ENDIF() - IF(NOT KWSYS_CXX_FLAGS_HAVE_NO_IMPLICIT_INCLUDE) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -no_implicit_include") - ENDIF() - ENDIF() - IF(CMAKE_SYSTEM MATCHES "HP-UX") - SET(KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS "+p") - IF(CMAKE_CXX_COMPILER_ID MATCHES "HP") + if(NOT KWSYS_CXX_FLAGS_HAVE_IMPLICIT_LOCAL) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -timplicit_local") + endif() + if(NOT KWSYS_CXX_FLAGS_HAVE_NO_IMPLICIT_INCLUDE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -no_implicit_include") + endif() + endif() + if(CMAKE_SYSTEM MATCHES "HP-UX") + set(KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS "+p") + if(CMAKE_CXX_COMPILER_ID MATCHES "HP") # it is known that version 3.85 fails and 6.25 works without these flags - IF(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4) + if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4) # use new C++ library and improved template support - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA +hpxstd98") - ENDIF() - ENDIF() - ENDIF() -ENDIF() -IF(KWSYS_STANDALONE) - IF(CMAKE_CXX_COMPILER_ID STREQUAL SunPro) - IF(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++03") - ELSE() - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -library=stlport4") - ENDIF() - ENDIF() -ENDIF() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA +hpxstd98") + endif() + endif() + endif() +endif() +if(KWSYS_STANDALONE) + if(CMAKE_CXX_COMPILER_ID STREQUAL SunPro) + if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++03") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -library=stlport4") + endif() + endif() +endif() #----------------------------------------------------------------------------- # Configure the standard library header wrappers based on compiler's @@ -365,75 +365,75 @@ KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_LONG_LONG "Checking whether C++ compiler has 'long long'" DIRECT) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS___INT64 "Checking whether C++ compiler has '__int64'" DIRECT) -IF(KWSYS_CXX_HAS___INT64) +if(KWSYS_CXX_HAS___INT64) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_SAME_LONG_AND___INT64 "Checking whether long and __int64 are the same type" DIRECT) - IF(KWSYS_CXX_HAS_LONG_LONG) + if(KWSYS_CXX_HAS_LONG_LONG) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_SAME_LONG_LONG_AND___INT64 "Checking whether long long and __int64 are the same type" DIRECT) - ENDIF() -ENDIF() + endif() +endif() # Enable the "long long" type if it is available. It is standard in # C99 and C++03 but not in earlier standards. -IF(KWSYS_CXX_HAS_LONG_LONG) - SET(KWSYS_USE_LONG_LONG 1) -ELSE() - SET(KWSYS_USE_LONG_LONG 0) -ENDIF() +if(KWSYS_CXX_HAS_LONG_LONG) + set(KWSYS_USE_LONG_LONG 1) +else() + set(KWSYS_USE_LONG_LONG 0) +endif() # Enable the "__int64" type if it is available and unique. It is not # standard. -SET(KWSYS_USE___INT64 0) -IF(KWSYS_CXX_HAS___INT64) - IF(NOT KWSYS_CXX_SAME_LONG_AND___INT64) - IF(NOT KWSYS_CXX_SAME_LONG_LONG_AND___INT64) - SET(KWSYS_USE___INT64 1) - ENDIF() - ENDIF() -ENDIF() - -IF(KWSYS_USE_Encoding) +set(KWSYS_USE___INT64 0) +if(KWSYS_CXX_HAS___INT64) + if(NOT KWSYS_CXX_SAME_LONG_AND___INT64) + if(NOT KWSYS_CXX_SAME_LONG_LONG_AND___INT64) + set(KWSYS_USE___INT64 1) + endif() + endif() +endif() + +if(KWSYS_USE_Encoding) # Look for type size helper macros. KWSYS_PLATFORM_CXX_TEST(KWSYS_STL_HAS_WSTRING "Checking whether wstring is available" DIRECT) -ENDIF() +endif() -IF(KWSYS_USE_IOStream) +if(KWSYS_USE_IOStream) # Determine whether iostreams support long long. - IF(KWSYS_CXX_HAS_LONG_LONG) + if(KWSYS_CXX_HAS_LONG_LONG) KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_ISTREAM_LONG_LONG "Checking if istream supports long long" DIRECT) KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_OSTREAM_LONG_LONG "Checking if ostream supports long long" DIRECT) - ELSE() - SET(KWSYS_IOS_HAS_ISTREAM_LONG_LONG 0) - SET(KWSYS_IOS_HAS_OSTREAM_LONG_LONG 0) - ENDIF() - IF(KWSYS_CXX_HAS___INT64) + else() + set(KWSYS_IOS_HAS_ISTREAM_LONG_LONG 0) + set(KWSYS_IOS_HAS_OSTREAM_LONG_LONG 0) + endif() + if(KWSYS_CXX_HAS___INT64) KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_ISTREAM___INT64 "Checking if istream supports __int64" DIRECT) KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_OSTREAM___INT64 "Checking if ostream supports __int64" DIRECT) - ELSE() - SET(KWSYS_IOS_HAS_ISTREAM___INT64 0) - SET(KWSYS_IOS_HAS_OSTREAM___INT64 0) - ENDIF() -ENDIF() - -IF(KWSYS_NAMESPACE MATCHES "^kwsys$") - SET(KWSYS_NAME_IS_KWSYS 1) -ELSE() - SET(KWSYS_NAME_IS_KWSYS 0) -ENDIF() - -IF(KWSYS_BUILD_SHARED) - SET(KWSYS_BUILD_SHARED 1) - SET(KWSYS_LIBRARY_TYPE SHARED) -ELSE() - SET(KWSYS_BUILD_SHARED 0) - SET(KWSYS_LIBRARY_TYPE STATIC) -ENDIF() + else() + set(KWSYS_IOS_HAS_ISTREAM___INT64 0) + set(KWSYS_IOS_HAS_OSTREAM___INT64 0) + endif() +endif() + +if(KWSYS_NAMESPACE MATCHES "^kwsys$") + set(KWSYS_NAME_IS_KWSYS 1) +else() + set(KWSYS_NAME_IS_KWSYS 0) +endif() + +if(KWSYS_BUILD_SHARED) + set(KWSYS_BUILD_SHARED 1) + set(KWSYS_LIBRARY_TYPE SHARED) +else() + set(KWSYS_BUILD_SHARED 0) + set(KWSYS_LIBRARY_TYPE STATIC) +endif() if(NOT DEFINED KWSYS_BUILD_PIC) set(KWSYS_BUILD_PIC 0) @@ -446,32 +446,32 @@ KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_PTRDIFF_T "Checking whether C compiler has ptrdiff_t in stddef.h" DIRECT) KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_SSIZE_T "Checking whether C compiler has ssize_t in unistd.h" DIRECT) -IF(KWSYS_USE_Process) +if(KWSYS_USE_Process) KWSYS_PLATFORM_C_TEST(KWSYS_C_HAS_CLOCK_GETTIME_MONOTONIC "Checking whether C compiler has clock_gettime" DIRECT) -ENDIF() +endif() -SET_SOURCE_FILES_PROPERTIES(ProcessUNIX.c System.c PROPERTIES +set_source_files_properties(ProcessUNIX.c System.c PROPERTIES COMPILE_FLAGS "-DKWSYS_C_HAS_PTRDIFF_T=${KWSYS_C_HAS_PTRDIFF_T} -DKWSYS_C_HAS_SSIZE_T=${KWSYS_C_HAS_SSIZE_T} -DKWSYS_C_HAS_CLOCK_GETTIME_MONOTONIC=${KWSYS_C_HAS_CLOCK_GETTIME_MONOTONIC}" ) -IF(DEFINED KWSYS_PROCESS_USE_SELECT) - GET_PROPERTY(ProcessUNIX_FLAGS SOURCE ProcessUNIX.c PROPERTY COMPILE_FLAGS) - SET_PROPERTY(SOURCE ProcessUNIX.c PROPERTY COMPILE_FLAGS "${ProcessUNIX_FLAGS} -DKWSYSPE_USE_SELECT=${KWSYSPE_USE_SELECT}") -ENDIF() - -IF(KWSYS_USE_DynamicLoader) - GET_PROPERTY(KWSYS_SUPPORTS_SHARED_LIBS GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS) - IF(KWSYS_SUPPORTS_SHARED_LIBS) - SET(KWSYS_SUPPORTS_SHARED_LIBS 1) - ELSE() - SET(KWSYS_SUPPORTS_SHARED_LIBS 0) - ENDIF() - SET_PROPERTY(SOURCE DynamicLoader.cxx APPEND PROPERTY COMPILE_DEFINITIONS +if(DEFINED KWSYS_PROCESS_USE_SELECT) + get_property(ProcessUNIX_FLAGS SOURCE ProcessUNIX.c PROPERTY COMPILE_FLAGS) + set_property(SOURCE ProcessUNIX.c PROPERTY COMPILE_FLAGS "${ProcessUNIX_FLAGS} -DKWSYSPE_USE_SELECT=${KWSYSPE_USE_SELECT}") +endif() + +if(KWSYS_USE_DynamicLoader) + get_property(KWSYS_SUPPORTS_SHARED_LIBS GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS) + if(KWSYS_SUPPORTS_SHARED_LIBS) + set(KWSYS_SUPPORTS_SHARED_LIBS 1) + else() + set(KWSYS_SUPPORTS_SHARED_LIBS 0) + endif() + set_property(SOURCE DynamicLoader.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SUPPORTS_SHARED_LIBS=${KWSYS_SUPPORTS_SHARED_LIBS}) -ENDIF() +endif() -IF(KWSYS_USE_SystemTools) +if(KWSYS_USE_SystemTools) if (NOT DEFINED KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP) set(KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP 1) endif () @@ -494,7 +494,7 @@ IF(KWSYS_USE_SystemTools) "Checking whether CXX compiler struct stat has st_mtim member" DIRECT) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_STAT_HAS_ST_MTIMESPEC "Checking whether CXX compiler struct stat has st_mtimespec member" DIRECT) - SET_PROPERTY(SOURCE SystemTools.cxx APPEND PROPERTY COMPILE_DEFINITIONS + set_property(SOURCE SystemTools.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_SETENV=${KWSYS_CXX_HAS_SETENV} KWSYS_CXX_HAS_UNSETENV=${KWSYS_CXX_HAS_UNSETENV} KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H=${KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H} @@ -503,623 +503,623 @@ IF(KWSYS_USE_SystemTools) KWSYS_CXX_STAT_HAS_ST_MTIM=${KWSYS_CXX_STAT_HAS_ST_MTIM} KWSYS_CXX_STAT_HAS_ST_MTIMESPEC=${KWSYS_CXX_STAT_HAS_ST_MTIMESPEC} ) - IF(NOT WIN32) - IF(KWSYS_STANDALONE) - OPTION(KWSYS_SYSTEMTOOLS_SUPPORT_WINDOWS_SLASHES "If true, Windows paths will be supported on Unix as well" ON) - ENDIF() - IF(KWSYS_SYSTEMTOOLS_SUPPORT_WINDOWS_SLASHES) - SET_PROPERTY(SOURCE SystemTools.cxx testSystemTools.cxx APPEND PROPERTY COMPILE_DEFINITIONS + if(NOT WIN32) + if(KWSYS_STANDALONE) + option(KWSYS_SYSTEMTOOLS_SUPPORT_WINDOWS_SLASHES "If true, Windows paths will be supported on Unix as well" ON) + endif() + if(KWSYS_SYSTEMTOOLS_SUPPORT_WINDOWS_SLASHES) + set_property(SOURCE SystemTools.cxx testSystemTools.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYSTEMTOOLS_SUPPORT_WINDOWS_SLASHES ) - ENDIF() - ENDIF() + endif() + endif() # Disable getpwnam for static linux builds since it depends on shared glibc - GET_PROPERTY(SHARED_LIBS_SUPPORTED GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS) - IF(CMAKE_SYSTEM_NAME MATCHES "Linux" AND NOT SHARED_LIBS_SUPPORTED) - SET_PROPERTY(SOURCE SystemTools.cxx APPEND PROPERTY COMPILE_DEFINITIONS + get_property(SHARED_LIBS_SUPPORTED GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS) + if(CMAKE_SYSTEM_NAME MATCHES "Linux" AND NOT SHARED_LIBS_SUPPORTED) + set_property(SOURCE SystemTools.cxx APPEND PROPERTY COMPILE_DEFINITIONS HAVE_GETPWNAM=0 ) - ENDIF() -ENDIF() + endif() +endif() -IF(KWSYS_USE_SystemInformation) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY +if(KWSYS_USE_SystemInformation) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS SIZEOF_VOID_P=${CMAKE_SIZEOF_VOID_P}) - IF(NOT CYGWIN) - INCLUDE(CheckIncludeFiles) + if(NOT CYGWIN) + include(CheckIncludeFiles) CHECK_INCLUDE_FILES("sys/types.h;ifaddrs.h" KWSYS_SYS_HAS_IFADDRS_H) - IF(KWSYS_SYS_HAS_IFADDRS_H) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_SYS_HAS_IFADDRS_H) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYS_HAS_IFADDRS_H=1) - ENDIF() - ENDIF() - IF(WIN32) - INCLUDE(CheckSymbolExists) - SET(CMAKE_REQUIRED_LIBRARIES Psapi) + endif() + endif() + if(WIN32) + include(CheckSymbolExists) + set(CMAKE_REQUIRED_LIBRARIES psapi) CHECK_SYMBOL_EXISTS(GetProcessMemoryInfo "windows.h;psapi.h" KWSYS_SYS_HAS_PSAPI) - UNSET(CMAKE_REQUIRED_LIBRARIES) - IF(KWSYS_SYS_HAS_PSAPI) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + unset(CMAKE_REQUIRED_LIBRARIES) + if(KWSYS_SYS_HAS_PSAPI) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYS_HAS_PSAPI=1) - IF(MSVC70 OR MSVC71) + if(MSVC70 OR MSVC71) # Suppress LNK4089: all references to 'PSAPI.DLL' discarded by /OPT:REF - SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /IGNORE:4089") - ENDIF() - ENDIF() - ENDIF() - IF(CMAKE_SYSTEM MATCHES "HP-UX") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /IGNORE:4089") + endif() + endif() + endif() + if(CMAKE_SYSTEM MATCHES "HP-UX") CHECK_INCLUDE_FILES("sys/mpctl.h" KWSYS_SYS_HAS_MPCTL_H) - IF(KWSYS_SYS_HAS_MPCTL_H) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_SYS_HAS_MPCTL_H) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYS_HAS_MPCTL_H=1) - ENDIF() - ENDIF() - IF(CMAKE_SYSTEM MATCHES "BSD") + endif() + endif() + if(CMAKE_SYSTEM MATCHES "BSD") CHECK_INCLUDE_FILES("machine/cpu.h" KWSYS_SYS_HAS_MACHINE_CPU_H) - IF(KWSYS_SYS_HAS_MACHINE_CPU_H) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_SYS_HAS_MACHINE_CPU_H) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYS_HAS_MACHINE_CPU_H=1) - ENDIF() - ENDIF() + endif() + endif() KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_RLIMIT64 "Checking whether CXX compiler has rlimit64" DIRECT) - SET(KWSYS_PLATFORM_CXX_TEST_DEFINES) - IF(KWSYS_CXX_HAS_RLIMIT64) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + set(KWSYS_PLATFORM_CXX_TEST_DEFINES) + if(KWSYS_CXX_HAS_RLIMIT64) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_RLIMIT64=1) - ENDIF() + endif() KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_ATOL "Checking whether CXX compiler has atol" DIRECT) - IF(KWSYS_CXX_HAS_ATOL) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_CXX_HAS_ATOL) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_ATOL=1) - ENDIF() + endif() KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_ATOLL "Checking whether CXX compiler has atoll" DIRECT) - IF(KWSYS_CXX_HAS_ATOLL) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_CXX_HAS_ATOLL) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_ATOLL=1) - ENDIF() + endif() KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS__ATOI64 "Checking whether CXX compiler has _atoi64" DIRECT) - IF(KWSYS_CXX_HAS__ATOI64) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_CXX_HAS__ATOI64) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS__ATOI64=1) - ENDIF() - IF(UNIX) - INCLUDE(CheckIncludeFileCXX) + endif() + if(UNIX) + include(CheckIncludeFileCXX) # check for simple stack trace # usually it's in libc but on FreeBSD # it's in libexecinfo - FIND_LIBRARY(EXECINFO_LIB "execinfo") - MARK_AS_ADVANCED(EXECINFO_LIB) - IF (NOT EXECINFO_LIB) - SET(EXECINFO_LIB "") - ENDIF() + find_library(EXECINFO_LIB "execinfo") + mark_as_advanced(EXECINFO_LIB) + if (NOT EXECINFO_LIB) + set(EXECINFO_LIB "") + endif() CHECK_INCLUDE_FILE_CXX("execinfo.h" KWSYS_CXX_HAS_EXECINFOH) - IF (KWSYS_CXX_HAS_EXECINFOH) + if (KWSYS_CXX_HAS_EXECINFOH) # we have the backtrace header check if it # can be used with this compiler - SET(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES ${EXECINFO_LIB}) + set(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES ${EXECINFO_LIB}) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_BACKTRACE "Checking whether backtrace works with this C++ compiler" DIRECT) - SET(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES) - IF (KWSYS_CXX_HAS_BACKTRACE) + set(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES) + if (KWSYS_CXX_HAS_BACKTRACE) # backtrace is supported by this system and compiler. # now check for the more advanced capabilities. - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE=1) # check for symbol lookup using dladdr CHECK_INCLUDE_FILE_CXX("dlfcn.h" KWSYS_CXX_HAS_DLFCNH) - IF (KWSYS_CXX_HAS_DLFCNH) + if (KWSYS_CXX_HAS_DLFCNH) # we have symbol lookup libraries and headers # check if they can be used with this compiler - SET(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES ${CMAKE_DL_LIBS}) + set(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES ${CMAKE_DL_LIBS}) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_DLADDR "Checking whether dladdr works with this C++ compiler" DIRECT) - SET(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES) - IF (KWSYS_CXX_HAS_DLADDR) + set(KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES) + if (KWSYS_CXX_HAS_DLADDR) # symbol lookup is supported by this system # and compiler. - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP=1) - ENDIF() - ENDIF() + endif() + endif() # c++ demangling support # check for cxxabi headers CHECK_INCLUDE_FILE_CXX("cxxabi.h" KWSYS_CXX_HAS_CXXABIH) - IF (KWSYS_CXX_HAS_CXXABIH) + if (KWSYS_CXX_HAS_CXXABIH) # check if cxxabi can be used with this # system and compiler. KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_CXXABI "Checking whether cxxabi works with this C++ compiler" DIRECT) - IF (KWSYS_CXX_HAS_CXXABI) + if (KWSYS_CXX_HAS_CXXABI) # c++ demangle using cxxabi is supported with # this system and compiler - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE=1) - ENDIF() - ENDIF() + endif() + endif() # basic backtrace works better with release build # don't bother with advanced features for release - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS_DEBUG KWSYS_SYSTEMINFORMATION_HAS_DEBUG_BUILD=1) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS_RELWITHDEBINFO KWSYS_SYSTEMINFORMATION_HAS_DEBUG_BUILD=1) - ENDIF() - ENDIF() - ENDIF() - IF(BORLAND) + endif() + endif() + endif() + if(BORLAND) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_BORLAND_ASM "Checking whether Borland CXX compiler supports assembler instructions" DIRECT) - IF(KWSYS_CXX_HAS_BORLAND_ASM) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_CXX_HAS_BORLAND_ASM) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_BORLAND_ASM=1) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_BORLAND_ASM_CPUID "Checking whether Borland CXX compiler supports CPUID assembler instruction" DIRECT) - IF(KWSYS_CXX_HAS_BORLAND_ASM_CPUID) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_CXX_HAS_BORLAND_ASM_CPUID) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_BORLAND_ASM_CPUID=1) - ENDIF() - ENDIF() - ENDIF() - IF(KWSYS_USE___INT64) - SET_PROPERTY(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY + endif() + endif() + endif() + if(KWSYS_USE___INT64) + set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_USE___INT64=1) - ENDIF() - IF(KWSYS_USE_LONG_LONG) - SET_PROPERTY(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY + endif() + if(KWSYS_USE_LONG_LONG) + set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_USE_LONG_LONG=1) - ENDIF() - IF(KWSYS_IOS_HAS_OSTREAM_LONG_LONG) - SET_PROPERTY(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY + endif() + if(KWSYS_IOS_HAS_OSTREAM_LONG_LONG) + set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_IOS_HAS_OSTREAM_LONG_LONG=1) - ENDIF() - IF(KWSYS_IOS_HAS_OSTREAM___INT64) - SET_PROPERTY(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY + endif() + if(KWSYS_IOS_HAS_OSTREAM___INT64) + set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_IOS_HAS_OSTREAM___INT64=1) - ENDIF() - IF(KWSYS_BUILD_SHARED) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + endif() + if(KWSYS_BUILD_SHARED) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_BUILD_SHARED=1) - ENDIF() + endif() - IF(UNIX AND NOT CYGWIN) + if(UNIX AND NOT CYGWIN) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_GETLOADAVG "Checking whether CXX compiler has getloadavg" DIRECT) - IF(KWSYS_CXX_HAS_GETLOADAVG) - SET_PROPERTY(SOURCE SystemInformation.cxx APPEND PROPERTY + if(KWSYS_CXX_HAS_GETLOADAVG) + set_property(SOURCE SystemInformation.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_CXX_HAS_GETLOADAVG=1) - ENDIF() - ENDIF() -ENDIF() + endif() + endif() +endif() -IF(KWSYS_USE_FStream) +if(KWSYS_USE_FStream) KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H "Checking whether <ext/stdio_filebuf.h> is available" DIRECT) -ENDIF() +endif() #----------------------------------------------------------------------------- # Choose a directory for the generated headers. -IF(NOT KWSYS_HEADER_ROOT) - SET(KWSYS_HEADER_ROOT "${PROJECT_BINARY_DIR}") -ENDIF() -SET(KWSYS_HEADER_DIR "${KWSYS_HEADER_ROOT}/${KWSYS_NAMESPACE}") -INCLUDE_DIRECTORIES(${KWSYS_HEADER_ROOT}) +if(NOT KWSYS_HEADER_ROOT) + set(KWSYS_HEADER_ROOT "${PROJECT_BINARY_DIR}") +endif() +set(KWSYS_HEADER_DIR "${KWSYS_HEADER_ROOT}/${KWSYS_NAMESPACE}") +include_directories(${KWSYS_HEADER_ROOT}) #----------------------------------------------------------------------------- -IF(KWSYS_INSTALL_DOC_DIR) +if(KWSYS_INSTALL_DOC_DIR) # Assign the license to the runtime component since it must be # distributed with binary forms of this software. - IF(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME) - SET(KWSYS_INSTALL_LICENSE_OPTIONS ${KWSYS_INSTALL_LICENSE_OPTIONS} + if(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME) + set(KWSYS_INSTALL_LICENSE_OPTIONS ${KWSYS_INSTALL_LICENSE_OPTIONS} COMPONENT ${KWSYS_INSTALL_COMPONENT_NAME_RUNTIME} ) - ENDIF() + endif() # Install the license under the documentation directory. - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt + install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt DESTINATION ${KWSYS_INSTALL_DOC_DIR}/${KWSYS_NAMESPACE} ${KWSYS_INSTALL_LICENSE_OPTIONS}) -ENDIF() +endif() #----------------------------------------------------------------------------- # Build a list of classes and headers we need to implement the # selected components. Initialize with required components. -SET(KWSYS_CLASSES) -SET(KWSYS_H_FILES Configure SharedForward) -SET(KWSYS_HXX_FILES Configure String) +set(KWSYS_CLASSES) +set(KWSYS_H_FILES Configure SharedForward) +set(KWSYS_HXX_FILES Configure String) -IF(NOT CMake_SOURCE_DIR) - SET(KWSYS_HXX_FILES ${KWSYS_HXX_FILES} +if(NOT CMake_SOURCE_DIR) + set(KWSYS_HXX_FILES ${KWSYS_HXX_FILES} hashtable hash_fun hash_map hash_set ) -ENDIF() +endif() # Add selected C++ classes. -SET(cppclasses +set(cppclasses Directory DynamicLoader Encoding Glob RegularExpression SystemTools CommandLineArguments IOStream FStream SystemInformation ConsoleBuf ) -FOREACH(cpp ${cppclasses}) - IF(KWSYS_USE_${cpp}) +foreach(cpp ${cppclasses}) + if(KWSYS_USE_${cpp}) # Use the corresponding class. - SET(KWSYS_CLASSES ${KWSYS_CLASSES} ${cpp}) + set(KWSYS_CLASSES ${KWSYS_CLASSES} ${cpp}) # Load component-specific CMake code. - IF(EXISTS ${PROJECT_SOURCE_DIR}/kwsys${cpp}.cmake) - INCLUDE(${PROJECT_SOURCE_DIR}/kwsys${cpp}.cmake) - ENDIF() - ENDIF() -ENDFOREACH() + if(EXISTS ${PROJECT_SOURCE_DIR}/kwsys${cpp}.cmake) + include(${PROJECT_SOURCE_DIR}/kwsys${cpp}.cmake) + endif() + endif() +endforeach() # Add selected C components. -FOREACH(c +foreach(c Process Base64 Encoding MD5 Terminal System String ) - IF(KWSYS_USE_${c}) + if(KWSYS_USE_${c}) # Use the corresponding header file. - SET(KWSYS_H_FILES ${KWSYS_H_FILES} ${c}) + set(KWSYS_H_FILES ${KWSYS_H_FILES} ${c}) # Load component-specific CMake code. - IF(EXISTS ${PROJECT_SOURCE_DIR}/kwsys${c}.cmake) - INCLUDE(${PROJECT_SOURCE_DIR}/kwsys${c}.cmake) - ENDIF() - ENDIF() -ENDFOREACH() + if(EXISTS ${PROJECT_SOURCE_DIR}/kwsys${c}.cmake) + include(${PROJECT_SOURCE_DIR}/kwsys${c}.cmake) + endif() + endif() +endforeach() #----------------------------------------------------------------------------- # Build a list of sources for the library based on components that are # included. -SET(KWSYS_C_SRCS) -SET(KWSYS_CXX_SRCS) +set(KWSYS_C_SRCS) +set(KWSYS_CXX_SRCS) # Add the proper sources for this platform's Process implementation. -IF(KWSYS_USE_Process) - IF(NOT UNIX) +if(KWSYS_USE_Process) + if(NOT UNIX) # Use the Windows implementation. - SET(KWSYS_C_SRCS ${KWSYS_C_SRCS} ProcessWin32.c) - ELSE() + set(KWSYS_C_SRCS ${KWSYS_C_SRCS} ProcessWin32.c) + else() # Use the UNIX implementation. - SET(KWSYS_C_SRCS ${KWSYS_C_SRCS} ProcessUNIX.c) - ENDIF() -ENDIF() + set(KWSYS_C_SRCS ${KWSYS_C_SRCS} ProcessUNIX.c) + endif() +endif() # Add selected C sources. -FOREACH(c Base64 Encoding MD5 Terminal System String) - IF(KWSYS_USE_${c}) - IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${c}C.c) - LIST(APPEND KWSYS_C_SRCS ${c}C.c) - ELSE() - LIST(APPEND KWSYS_C_SRCS ${c}.c) - ENDIF() - ENDIF() -ENDFOREACH() +foreach(c Base64 Encoding MD5 Terminal System String) + if(KWSYS_USE_${c}) + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${c}C.c) + list(APPEND KWSYS_C_SRCS ${c}C.c) + else() + list(APPEND KWSYS_C_SRCS ${c}.c) + endif() + endif() +endforeach() # Configure headers of C++ classes and construct the list of sources. -FOREACH(c ${KWSYS_CLASSES}) +foreach(c ${KWSYS_CLASSES}) # Add this source to the list of source files for the library. - IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${c}CXX.cxx) - LIST(APPEND KWSYS_CXX_SRCS ${c}CXX.cxx) - ELSEIF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${c}.cxx) - LIST(APPEND KWSYS_CXX_SRCS ${c}.cxx) - ENDIF() + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${c}CXX.cxx) + list(APPEND KWSYS_CXX_SRCS ${c}CXX.cxx) + elseif(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${c}.cxx) + list(APPEND KWSYS_CXX_SRCS ${c}.cxx) + endif() # Configure the header for this class. - CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/${c}.hxx.in ${KWSYS_HEADER_DIR}/${c}.hxx + configure_file(${PROJECT_SOURCE_DIR}/${c}.hxx.in ${KWSYS_HEADER_DIR}/${c}.hxx @ONLY IMMEDIATE) - SET(KWSYS_CXX_SRCS ${KWSYS_CXX_SRCS} ${KWSYS_HEADER_DIR}/${c}.hxx) + set(KWSYS_CXX_SRCS ${KWSYS_CXX_SRCS} ${KWSYS_HEADER_DIR}/${c}.hxx) # Create an install target for the header. - IF(KWSYS_INSTALL_INCLUDE_DIR) - INSTALL(FILES ${KWSYS_HEADER_DIR}/${c}.hxx + if(KWSYS_INSTALL_INCLUDE_DIR) + install(FILES ${KWSYS_HEADER_DIR}/${c}.hxx DESTINATION ${KWSYS_INSTALL_INCLUDE_DIR}/${KWSYS_NAMESPACE} ${KWSYS_INSTALL_INCLUDE_OPTIONS}) - ENDIF() -ENDFOREACH() + endif() +endforeach() # Configure C headers. -FOREACH(h ${KWSYS_H_FILES}) +foreach(h ${KWSYS_H_FILES}) # Configure the header into the given directory. - CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/${h}.h.in ${KWSYS_HEADER_DIR}/${h}.h + configure_file(${PROJECT_SOURCE_DIR}/${h}.h.in ${KWSYS_HEADER_DIR}/${h}.h @ONLY IMMEDIATE) - SET(KWSYS_C_SRCS ${KWSYS_C_SRCS} ${KWSYS_HEADER_DIR}/${h}.h) + set(KWSYS_C_SRCS ${KWSYS_C_SRCS} ${KWSYS_HEADER_DIR}/${h}.h) # Create an install target for the header. - IF(KWSYS_INSTALL_INCLUDE_DIR) - INSTALL(FILES ${KWSYS_HEADER_DIR}/${h}.h + if(KWSYS_INSTALL_INCLUDE_DIR) + install(FILES ${KWSYS_HEADER_DIR}/${h}.h DESTINATION ${KWSYS_INSTALL_INCLUDE_DIR}/${KWSYS_NAMESPACE} ${KWSYS_INSTALL_INCLUDE_OPTIONS}) - ENDIF() -ENDFOREACH() + endif() +endforeach() # Configure other C++ headers. -FOREACH(h ${KWSYS_HXX_FILES}) +foreach(h ${KWSYS_HXX_FILES}) # Configure the header into the given directory. - CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/${h}.hxx.in ${KWSYS_HEADER_DIR}/${h}.hxx + configure_file(${PROJECT_SOURCE_DIR}/${h}.hxx.in ${KWSYS_HEADER_DIR}/${h}.hxx @ONLY IMMEDIATE) - SET(KWSYS_CXX_SRCS ${KWSYS_CXX_SRCS} ${KWSYS_HEADER_DIR}/${h}.hxx) + set(KWSYS_CXX_SRCS ${KWSYS_CXX_SRCS} ${KWSYS_HEADER_DIR}/${h}.hxx) # Create an install target for the header. - IF(KWSYS_INSTALL_INCLUDE_DIR) - INSTALL(FILES ${KWSYS_HEADER_DIR}/${h}.hxx + if(KWSYS_INSTALL_INCLUDE_DIR) + install(FILES ${KWSYS_HEADER_DIR}/${h}.hxx DESTINATION ${KWSYS_INSTALL_INCLUDE_DIR}/${KWSYS_NAMESPACE} ${KWSYS_INSTALL_INCLUDE_OPTIONS}) - ENDIF() -ENDFOREACH() + endif() +endforeach() #----------------------------------------------------------------------------- # Add the library with the configured name and list of sources. -IF(KWSYS_C_SRCS OR KWSYS_CXX_SRCS) - IF(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE) - SET(KWSYS_TARGET_INTERFACE ${KWSYS_NAMESPACE}) - SET(KWSYS_TARGET_OBJECT ${KWSYS_NAMESPACE}_objects) - SET(KWSYS_TARGET_LINK ${KWSYS_NAMESPACE}_private) - SET(KWSYS_TARGET_INSTALL ${KWSYS_TARGET_INTERFACE} ${KWSYS_TARGET_LINK}) - SET(KWSYS_LINK_DEPENDENCY INTERFACE) - ADD_LIBRARY(${KWSYS_TARGET_OBJECT} OBJECT +if(KWSYS_C_SRCS OR KWSYS_CXX_SRCS) + if(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE) + set(KWSYS_TARGET_INTERFACE ${KWSYS_NAMESPACE}) + set(KWSYS_TARGET_OBJECT ${KWSYS_NAMESPACE}_objects) + set(KWSYS_TARGET_LINK ${KWSYS_NAMESPACE}_private) + set(KWSYS_TARGET_INSTALL ${KWSYS_TARGET_INTERFACE} ${KWSYS_TARGET_LINK}) + set(KWSYS_LINK_DEPENDENCY INTERFACE) + add_library(${KWSYS_TARGET_OBJECT} OBJECT ${KWSYS_C_SRCS} ${KWSYS_CXX_SRCS}) - IF(KWSYS_BUILD_SHARED OR KWSYS_BUILD_PIC) - SET_PROPERTY(TARGET ${KWSYS_TARGET_OBJECT} PROPERTY + if(KWSYS_BUILD_SHARED OR KWSYS_BUILD_PIC) + set_property(TARGET ${KWSYS_TARGET_OBJECT} PROPERTY POSITION_INDEPENDENT_CODE TRUE) - ENDIF() - ADD_LIBRARY(${KWSYS_TARGET_INTERFACE} INTERFACE) - ADD_LIBRARY(${KWSYS_TARGET_LINK} INTERFACE) - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_LINK} INTERFACE + endif() + add_library(${KWSYS_TARGET_INTERFACE} INTERFACE) + add_library(${KWSYS_TARGET_LINK} INTERFACE) + target_link_libraries(${KWSYS_TARGET_LINK} INTERFACE ${KWSYS_TARGET_INTERFACE}) - TARGET_SOURCES(${KWSYS_TARGET_LINK} INTERFACE + target_sources(${KWSYS_TARGET_LINK} INTERFACE $<TARGET_OBJECTS:${KWSYS_TARGET_OBJECT}>) target_compile_features(${KWSYS_TARGET_OBJECT} PRIVATE ${KWSYS_CXX_COMPILE_FEATURES}) target_compile_features(${KWSYS_TARGET_INTERFACE} INTERFACE ${KWSYS_CXX_COMPILE_FEATURES}) - ELSE() - SET(KWSYS_TARGET_INTERFACE ${KWSYS_NAMESPACE}) - SET(KWSYS_TARGET_OBJECT ${KWSYS_NAMESPACE}) - SET(KWSYS_TARGET_LINK ${KWSYS_NAMESPACE}) + else() + set(KWSYS_TARGET_INTERFACE ${KWSYS_NAMESPACE}) + set(KWSYS_TARGET_OBJECT ${KWSYS_NAMESPACE}) + set(KWSYS_TARGET_LINK ${KWSYS_NAMESPACE}) set(KWSYS_TARGET_INSTALL ${KWSYS_TARGET_LINK}) - SET(KWSYS_LINK_DEPENDENCY PUBLIC) - ADD_LIBRARY(${KWSYS_TARGET_INTERFACE} ${KWSYS_LIBRARY_TYPE} + set(KWSYS_LINK_DEPENDENCY PUBLIC) + add_library(${KWSYS_TARGET_INTERFACE} ${KWSYS_LIBRARY_TYPE} ${KWSYS_C_SRCS} ${KWSYS_CXX_SRCS}) target_compile_features(${KWSYS_TARGET_INTERFACE} PUBLIC ${KWSYS_CXX_COMPILE_FEATURES}) - ENDIF() + endif() if (KWSYS_ALIAS_TARGET) add_library(${KWSYS_ALIAS_TARGET} ALIAS ${KWSYS_TARGET_INTERFACE}) endif () - SET_TARGET_PROPERTIES(${KWSYS_TARGET_OBJECT} PROPERTIES + set_target_properties(${KWSYS_TARGET_OBJECT} PROPERTIES C_CLANG_TIDY "" CXX_CLANG_TIDY "" C_INCLUDE_WHAT_YOU_USE "" CXX_INCLUDE_WHAT_YOU_USE "" LABELS "${KWSYS_LABELS_LIB}") - IF(KWSYS_USE_DynamicLoader) - IF(UNIX) - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} + if(KWSYS_USE_DynamicLoader) + if(UNIX) + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} ${CMAKE_DL_LIBS}) - ENDIF() - ENDIF() + endif() + endif() - IF(KWSYS_USE_SystemInformation) - IF(WIN32) - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} ws2_32) + if(KWSYS_USE_SystemInformation) + if(WIN32) + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} ws2_32) # link in dbghelp.dll for symbol lookup if MSVC 1800 or later # Note that the dbghelp runtime is part of MS Windows OS - IF(MSVC_VERSION AND NOT MSVC_VERSION VERSION_LESS 1800) - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} dbghelp) - ENDIF() - IF(KWSYS_SYS_HAS_PSAPI) - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} - Psapi) - ENDIF() - ELSEIF(UNIX) - IF (EXECINFO_LIB AND KWSYS_CXX_HAS_BACKTRACE) + if(MSVC_VERSION AND NOT MSVC_VERSION VERSION_LESS 1800) + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} dbghelp) + endif() + if(KWSYS_SYS_HAS_PSAPI) + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} + psapi) + endif() + elseif(UNIX) + if (EXECINFO_LIB AND KWSYS_CXX_HAS_BACKTRACE) # backtrace on FreeBSD is not in libc - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} ${EXECINFO_LIB}) - ENDIF() - IF (KWSYS_CXX_HAS_DLADDR) + endif() + if (KWSYS_CXX_HAS_DLADDR) # for symbol lookup using dladdr - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} ${CMAKE_DL_LIBS}) - ENDIF() - IF (CMAKE_SYSTEM_NAME STREQUAL "SunOS") - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} + endif() + if (CMAKE_SYSTEM_NAME STREQUAL "SunOS") + target_link_libraries(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} socket) - ENDIF() - ENDIF() - ENDIF() + endif() + endif() + endif() # Apply user-defined target properties to the library. - IF(KWSYS_PROPERTIES_CXX) - SET_TARGET_PROPERTIES(${KWSYS_TARGET_INTERFACE} PROPERTIES + if(KWSYS_PROPERTIES_CXX) + set_target_properties(${KWSYS_TARGET_INTERFACE} PROPERTIES ${KWSYS_PROPERTIES_CXX}) - ENDIF() + endif() # Set up include usage requirement - IF(COMMAND TARGET_INCLUDE_DIRECTORIES) - TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_INTERFACE} INTERFACE + if(COMMAND TARGET_INCLUDE_DIRECTORIES) + target_include_directories(${KWSYS_TARGET_INTERFACE} INTERFACE $<BUILD_INTERFACE:${KWSYS_HEADER_ROOT}>) - IF(KWSYS_INSTALL_INCLUDE_DIR) - TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_INTERFACE} INTERFACE + if(KWSYS_INSTALL_INCLUDE_DIR) + target_include_directories(${KWSYS_TARGET_INTERFACE} INTERFACE $<INSTALL_INTERFACE:${KWSYS_INSTALL_INCLUDE_DIR}>) - ENDIF() - ENDIF() + endif() + endif() # Create an install target for the library. - IF(KWSYS_INSTALL_LIBRARY_RULE) - INSTALL(TARGETS ${KWSYS_TARGET_INSTALL} ${KWSYS_INSTALL_LIBRARY_RULE}) - ENDIF() - IF(KWSYS_INSTALL_NAMELINK_RULE) - INSTALL(TARGETS ${KWSYS_TARGET_INSTALL} ${KWSYS_INSTALL_NAMELINK_RULE}) - ENDIF() -ENDIF() + if(KWSYS_INSTALL_LIBRARY_RULE) + install(TARGETS ${KWSYS_TARGET_INSTALL} ${KWSYS_INSTALL_LIBRARY_RULE}) + endif() + if(KWSYS_INSTALL_NAMELINK_RULE) + install(TARGETS ${KWSYS_TARGET_INSTALL} ${KWSYS_INSTALL_NAMELINK_RULE}) + endif() +endif() # Add a C-only library if requested. -IF(KWSYS_ENABLE_C AND KWSYS_C_SRCS) - IF(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE) - SET(KWSYS_TARGET_C_INTERFACE ${KWSYS_NAMESPACE}_c) - SET(KWSYS_TARGET_C_OBJECT ${KWSYS_NAMESPACE}_c_objects) - SET(KWSYS_TARGET_C_LINK ${KWSYS_NAMESPACE}_c_private) - SET(KWSYS_TARGET_C_INSTALL +if(KWSYS_ENABLE_C AND KWSYS_C_SRCS) + if(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE) + set(KWSYS_TARGET_C_INTERFACE ${KWSYS_NAMESPACE}_c) + set(KWSYS_TARGET_C_OBJECT ${KWSYS_NAMESPACE}_c_objects) + set(KWSYS_TARGET_C_LINK ${KWSYS_NAMESPACE}_c_private) + set(KWSYS_TARGET_C_INSTALL ${KWSYS_TARGET_C_INTERFACE} ${KWSYS_TARGET_C_LINK}) - SET(KWSYS_LINK_DEPENDENCY INTERFACE) - ADD_LIBRARY(${KWSYS_TARGET_C_OBJECT} OBJECT ${KWSYS_C_SRCS}) - IF(KWSYS_BUILD_SHARED OR KWSYS_BUILD_PIC) - SET_PROPERTY(TARGET ${KWSYS_TARGET_C_OBJECT} PROPERTY + set(KWSYS_LINK_DEPENDENCY INTERFACE) + add_library(${KWSYS_TARGET_C_OBJECT} OBJECT ${KWSYS_C_SRCS}) + if(KWSYS_BUILD_SHARED OR KWSYS_BUILD_PIC) + set_property(TARGET ${KWSYS_TARGET_C_OBJECT} PROPERTY POSITION_INDEPENDENT_CODE TRUE) - ENDIF() - ADD_LIBRARY(${KWSYS_TARGET_C_INTERFACE} INTERFACE) - ADD_LIBRARY(${KWSYS_TARGET_C_LINK} INTERFACE) - TARGET_LINK_LIBRARIES(${KWSYS_TARGET_C_LINK} INTERFACE + endif() + add_library(${KWSYS_TARGET_C_INTERFACE} INTERFACE) + add_library(${KWSYS_TARGET_C_LINK} INTERFACE) + target_link_libraries(${KWSYS_TARGET_C_LINK} INTERFACE ${KWSYS_TARGET_C_INTERFACE}) - TARGET_SOURCES(${KWSYS_TARGET_C_LINK} INTERFACE + target_sources(${KWSYS_TARGET_C_LINK} INTERFACE $<TARGET_OBJECTS:${KWSYS_TARGET_C_OBJECT}>) - ELSE() - SET(KWSYS_TARGET_C_INTERFACE ${KWSYS_NAMESPACE}_c) - SET(KWSYS_TARGET_C_OBJECT ${KWSYS_NAMESPACE}_c) - SET(KWSYS_TARGET_C_LINK ${KWSYS_NAMESPACE}_c) - SET(KWSYS_TARGET_C_INSTALL ${KWSYS_TARGET_C_LINK}) - SET(KWSYS_LINK_DEPENDENCY PUBLIC) - ADD_LIBRARY(${KWSYS_TARGET_C_INTERFACE} ${KWSYS_LIBRARY_TYPE} + else() + set(KWSYS_TARGET_C_INTERFACE ${KWSYS_NAMESPACE}_c) + set(KWSYS_TARGET_C_OBJECT ${KWSYS_NAMESPACE}_c) + set(KWSYS_TARGET_C_LINK ${KWSYS_NAMESPACE}_c) + set(KWSYS_TARGET_C_INSTALL ${KWSYS_TARGET_C_LINK}) + set(KWSYS_LINK_DEPENDENCY PUBLIC) + add_library(${KWSYS_TARGET_C_INTERFACE} ${KWSYS_LIBRARY_TYPE} ${KWSYS_C_SRCS}) - ENDIF() - SET_TARGET_PROPERTIES(${KWSYS_TARGET_C_OBJECT} PROPERTIES + endif() + set_target_properties(${KWSYS_TARGET_C_OBJECT} PROPERTIES LABELS "${KWSYS_LABELS_LIB}") # Apply user-defined target properties to the library. - IF(KWSYS_PROPERTIES_C) - SET_TARGET_PROPERTIES(${KWSYS_TARGET_C_INTERFACE} PROPERTIES + if(KWSYS_PROPERTIES_C) + set_target_properties(${KWSYS_TARGET_C_INTERFACE} PROPERTIES ${KWSYS_PROPERTIES_C}) - ENDIF() + endif() # Set up include usage requirement - IF(COMMAND TARGET_INCLUDE_DIRECTORIES) - TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_C_INTERFACE} INTERFACE + if(COMMAND TARGET_INCLUDE_DIRECTORIES) + target_include_directories(${KWSYS_TARGET_C_INTERFACE} INTERFACE $<BUILD_INTERFACE:${KWSYS_HEADER_ROOT}>) - IF(KWSYS_INSTALL_INCLUDE_DIR) - TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_C_INTERFACE} INTERFACE + if(KWSYS_INSTALL_INCLUDE_DIR) + target_include_directories(${KWSYS_TARGET_C_INTERFACE} INTERFACE $<INSTALL_INTERFACE:${KWSYS_INSTALL_INCLUDE_DIR}>) - ENDIF() - ENDIF() + endif() + endif() # Create an install target for the library. - IF(KWSYS_INSTALL_LIBRARY_RULE) - INSTALL(TARGETS ${KWSYS_TARGET_C_INSTALL}) - ENDIF() -ENDIF() + if(KWSYS_INSTALL_LIBRARY_RULE) + install(TARGETS ${KWSYS_TARGET_C_INSTALL}) + endif() +endif() # For building kwsys itself, we use a macro defined on the command # line to configure the namespace in the C and C++ source files. -ADD_DEFINITIONS("-DKWSYS_NAMESPACE=${KWSYS_NAMESPACE}") +add_definitions("-DKWSYS_NAMESPACE=${KWSYS_NAMESPACE}") # Disable deprecation warnings for standard C functions. -IF(MSVC OR (WIN32 AND (CMAKE_C_COMPILER_ID STREQUAL "Intel" OR +if(MSVC OR (WIN32 AND (CMAKE_C_COMPILER_ID STREQUAL "Intel" OR (CMAKE_C_COMPILER_ID STREQUAL "Clang" AND CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")))) - ADD_DEFINITIONS( + add_definitions( -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS -D_SCL_SECURE_NO_DEPRECATE ) -ENDIF() +endif() -IF(WIN32) +if(WIN32) # Help enforce the use of wide Windows apis. - ADD_DEFINITIONS(-DUNICODE -D_UNICODE) -ENDIF() + add_definitions(-DUNICODE -D_UNICODE) +endif() -IF(KWSYS_USE_String) +if(KWSYS_USE_String) # Activate code in "String.c". See the comment in the source. - SET_SOURCE_FILES_PROPERTIES(String.c PROPERTIES + set_source_files_properties(String.c PROPERTIES COMPILE_FLAGS "-DKWSYS_STRING_C") -ENDIF() +endif() -IF(KWSYS_USE_Encoding) +if(KWSYS_USE_Encoding) # Set default 8 bit encoding in "EndcodingC.c". - SET_PROPERTY(SOURCE EncodingC.c EncodingCXX.cxx APPEND PROPERTY COMPILE_DEFINITIONS + set_property(SOURCE EncodingC.c EncodingCXX.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_ENCODING_DEFAULT_CODEPAGE=${KWSYS_ENCODING_DEFAULT_CODEPAGE}) -ENDIF() +endif() #----------------------------------------------------------------------------- # Setup testing if not being built as part of another project. -IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) - IF(BUILD_TESTING) +if(KWSYS_STANDALONE OR CMake_SOURCE_DIR) + if(BUILD_TESTING) # Compute the location of executables. - SET(EXEC_DIR "${CMAKE_CURRENT_BINARY_DIR}") - IF(EXECUTABLE_OUTPUT_PATH) - SET(EXEC_DIR "${EXECUTABLE_OUTPUT_PATH}") - ENDIF() + set(EXEC_DIR "${CMAKE_CURRENT_BINARY_DIR}") + if(CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(EXEC_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") + endif() # C tests - SET(KWSYS_C_TESTS + set(KWSYS_C_TESTS testEncode.c testTerminal.c ) - IF(KWSYS_STANDALONE) - SET(KWSYS_C_TESTS ${KWSYS_C_TESTS} testFail.c) - ENDIF() - CREATE_TEST_SOURCELIST( + if(KWSYS_STANDALONE) + set(KWSYS_C_TESTS ${KWSYS_C_TESTS} testFail.c) + endif() + create_test_sourcelist( KWSYS_C_TEST_SRCS ${KWSYS_NAMESPACE}TestsC.c ${KWSYS_C_TESTS} ) - ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestsC ${KWSYS_C_TEST_SRCS}) - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsC PROPERTY LABELS ${KWSYS_LABELS_EXE}) - TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsC ${KWSYS_TARGET_C_LINK}) - FOREACH(testfile ${KWSYS_C_TESTS}) + add_executable(${KWSYS_NAMESPACE}TestsC ${KWSYS_C_TEST_SRCS}) + set_property(TARGET ${KWSYS_NAMESPACE}TestsC PROPERTY LABELS ${KWSYS_LABELS_EXE}) + target_link_libraries(${KWSYS_NAMESPACE}TestsC ${KWSYS_TARGET_C_LINK}) + foreach(testfile ${KWSYS_C_TESTS}) get_filename_component(test "${testfile}" NAME_WE) - ADD_TEST(kwsys.${test} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestsC ${test} ${KWSYS_TEST_ARGS_${test}}) - SET_PROPERTY(TEST kwsys.${test} PROPERTY LABELS ${KWSYS_LABELS_TEST}) - ENDFOREACH() + add_test(kwsys.${test} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestsC ${test} ${KWSYS_TEST_ARGS_${test}}) + set_property(TEST kwsys.${test} PROPERTY LABELS ${KWSYS_LABELS_TEST}) + endforeach() # C++ tests - IF(NOT WATCOM AND NOT CMake_SOURCE_DIR) - SET(KWSYS_CXX_TESTS + if(NOT WATCOM AND NOT CMake_SOURCE_DIR) + set(KWSYS_CXX_TESTS testHashSTL.cxx ) - ENDIF() - SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} + endif() + set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testConfigure.cxx testSystemTools.cxx testCommandLineArguments.cxx testCommandLineArguments1.cxx testDirectory.cxx ) - IF(KWSYS_STL_HAS_WSTRING) - SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} + if(KWSYS_STL_HAS_WSTRING) + set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testEncoding.cxx ) - ENDIF() - IF(KWSYS_USE_FStream) - SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} + endif() + if(KWSYS_USE_FStream) + set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testFStream.cxx ) - ENDIF() - IF(KWSYS_USE_ConsoleBuf) - ADD_EXECUTABLE(testConsoleBufChild testConsoleBufChild.cxx) - SET_PROPERTY(TARGET testConsoleBufChild PROPERTY C_CLANG_TIDY "") - SET_PROPERTY(TARGET testConsoleBufChild PROPERTY CXX_CLANG_TIDY "") - SET_PROPERTY(TARGET testConsoleBufChild PROPERTY C_INCLUDE_WHAT_YOU_USE "") - SET_PROPERTY(TARGET testConsoleBufChild PROPERTY CXX_INCLUDE_WHAT_YOU_USE "") - SET_PROPERTY(TARGET testConsoleBufChild PROPERTY LABELS ${KWSYS_LABELS_EXE}) - TARGET_LINK_LIBRARIES(testConsoleBufChild ${KWSYS_TARGET_LINK}) - SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} + endif() + if(KWSYS_USE_ConsoleBuf) + add_executable(testConsoleBufChild testConsoleBufChild.cxx) + set_property(TARGET testConsoleBufChild PROPERTY C_CLANG_TIDY "") + set_property(TARGET testConsoleBufChild PROPERTY CXX_CLANG_TIDY "") + set_property(TARGET testConsoleBufChild PROPERTY C_INCLUDE_WHAT_YOU_USE "") + set_property(TARGET testConsoleBufChild PROPERTY CXX_INCLUDE_WHAT_YOU_USE "") + set_property(TARGET testConsoleBufChild PROPERTY LABELS ${KWSYS_LABELS_EXE}) + target_link_libraries(testConsoleBufChild ${KWSYS_TARGET_LINK}) + set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testConsoleBuf.cxx ) - IF(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND + if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "19.0.23506") set_property(SOURCE testConsoleBuf.cxx testConsoleBufChild.cxx PROPERTY COMPILE_FLAGS /utf-8) - ENDIF() - SET_PROPERTY(SOURCE testConsoleBuf.cxx APPEND PROPERTY COMPILE_DEFINITIONS + endif() + set_property(SOURCE testConsoleBuf.cxx APPEND PROPERTY COMPILE_DEFINITIONS KWSYS_ENCODING_DEFAULT_CODEPAGE=${KWSYS_ENCODING_DEFAULT_CODEPAGE}) - ENDIF() - IF(KWSYS_USE_SystemInformation) - SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testSystemInformation.cxx) - ENDIF() - IF(KWSYS_USE_DynamicLoader) - SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testDynamicLoader.cxx) + endif() + if(KWSYS_USE_SystemInformation) + set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testSystemInformation.cxx) + endif() + if(KWSYS_USE_DynamicLoader) + set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testDynamicLoader.cxx) # If kwsys contains the DynamicLoader, need extra library - ADD_LIBRARY(${KWSYS_NAMESPACE}TestDynload MODULE testDynload.c) - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestDynload PROPERTY LABELS ${KWSYS_LABELS_LIB}) - ADD_DEPENDENCIES(${KWSYS_NAMESPACE}TestDynload ${KWSYS_TARGET_INTERFACE}) + add_library(${KWSYS_NAMESPACE}TestDynload MODULE testDynload.c) + set_property(TARGET ${KWSYS_NAMESPACE}TestDynload PROPERTY LABELS ${KWSYS_LABELS_LIB}) + add_dependencies(${KWSYS_NAMESPACE}TestDynload ${KWSYS_TARGET_INTERFACE}) if (WIN32) # Windows tests supported flags. @@ -1134,33 +1134,33 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) add_dependencies(${KWSYS_NAMESPACE}TestDynloadUse ${KWSYS_TARGET_INTERFACE}) target_link_libraries(${KWSYS_NAMESPACE}TestDynloadUse PRIVATE ${KWSYS_NAMESPACE}TestDynloadImpl) endif () - ENDIF() - CREATE_TEST_SOURCELIST( + endif() + create_test_sourcelist( KWSYS_CXX_TEST_SRCS ${KWSYS_NAMESPACE}TestsCxx.cxx ${KWSYS_CXX_TESTS} ) - ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_CXX_TEST_SRCS}) - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY C_CLANG_TIDY "") - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY CXX_CLANG_TIDY "") - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY C_INCLUDE_WHAT_YOU_USE "") - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY CXX_INCLUDE_WHAT_YOU_USE "") - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY LABELS ${KWSYS_LABELS_EXE}) - TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_TARGET_LINK}) - - SET(TEST_SYSTEMTOOLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") - SET(TEST_SYSTEMTOOLS_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}") - CONFIGURE_FILE( + add_executable(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_CXX_TEST_SRCS}) + set_property(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY C_CLANG_TIDY "") + set_property(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY CXX_CLANG_TIDY "") + set_property(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY C_INCLUDE_WHAT_YOU_USE "") + set_property(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY CXX_INCLUDE_WHAT_YOU_USE "") + set_property(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY LABELS ${KWSYS_LABELS_EXE}) + target_link_libraries(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_TARGET_LINK}) + + set(TEST_SYSTEMTOOLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + set(TEST_SYSTEMTOOLS_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}") + configure_file( ${PROJECT_SOURCE_DIR}/testSystemTools.h.in ${PROJECT_BINARY_DIR}/testSystemTools.h) - INCLUDE_DIRECTORIES(${PROJECT_BINARY_DIR}) + include_directories(${PROJECT_BINARY_DIR}) - IF(CTEST_TEST_KWSYS) - CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/ExtraTest.cmake.in" + if(CTEST_TEST_KWSYS) + configure_file("${CMAKE_CURRENT_SOURCE_DIR}/ExtraTest.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/ExtraTest.cmake") - SET_DIRECTORY_PROPERTIES(PROPERTIES TEST_INCLUDE_FILE "${CMAKE_CURRENT_BINARY_DIR}/ExtraTest.cmake") - ENDIF() + set_directory_properties(PROPERTIES TEST_INCLUDE_FILE "${CMAKE_CURRENT_BINARY_DIR}/ExtraTest.cmake") + endif() - SET(KWSYS_TEST_ARGS_testCommandLineArguments + set(KWSYS_TEST_ARGS_testCommandLineArguments --another-bool-variable --long3=opt --set-bool-arg1 @@ -1179,7 +1179,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) -C=test --long2 hello ) - SET(KWSYS_TEST_ARGS_testCommandLineArguments1 + set(KWSYS_TEST_ARGS_testCommandLineArguments1 --ignored -n 24 --second-ignored @@ -1188,73 +1188,73 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) -p some junk at the end ) - FOREACH(testfile ${KWSYS_CXX_TESTS}) + foreach(testfile ${KWSYS_CXX_TESTS}) get_filename_component(test "${testfile}" NAME_WE) - ADD_TEST(kwsys.${test} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestsCxx ${test} ${KWSYS_TEST_ARGS_${test}}) - SET_PROPERTY(TEST kwsys.${test} PROPERTY LABELS ${KWSYS_LABELS_TEST}) - ENDFOREACH() + add_test(kwsys.${test} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestsCxx ${test} ${KWSYS_TEST_ARGS_${test}}) + set_property(TEST kwsys.${test} PROPERTY LABELS ${KWSYS_LABELS_TEST}) + endforeach() # Process tests. - ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestProcess testProcess.c) - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestProcess PROPERTY LABELS ${KWSYS_LABELS_EXE}) - TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestProcess ${KWSYS_TARGET_C_LINK}) - IF(NOT CYGWIN) - SET(KWSYS_TEST_PROCESS_7 7) - ENDIF() - FOREACH(n 1 2 3 4 5 6 ${KWSYS_TEST_PROCESS_7} 9 10) - ADD_TEST(kwsys.testProcess-${n} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestProcess ${n}) - SET_PROPERTY(TEST kwsys.testProcess-${n} PROPERTY LABELS ${KWSYS_LABELS_TEST}) - SET_TESTS_PROPERTIES(kwsys.testProcess-${n} PROPERTIES TIMEOUT 120) - ENDFOREACH() - - SET(testProcess_COMPILE_FLAGS "") + add_executable(${KWSYS_NAMESPACE}TestProcess testProcess.c) + set_property(TARGET ${KWSYS_NAMESPACE}TestProcess PROPERTY LABELS ${KWSYS_LABELS_EXE}) + target_link_libraries(${KWSYS_NAMESPACE}TestProcess ${KWSYS_TARGET_C_LINK}) + if(NOT CYGWIN) + set(KWSYS_TEST_PROCESS_7 7) + endif() + foreach(n 1 2 3 4 5 6 ${KWSYS_TEST_PROCESS_7} 9 10) + add_test(kwsys.testProcess-${n} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestProcess ${n}) + set_property(TEST kwsys.testProcess-${n} PROPERTY LABELS ${KWSYS_LABELS_TEST}) + set_tests_properties(kwsys.testProcess-${n} PROPERTIES TIMEOUT 120) + endforeach() + + set(testProcess_COMPILE_FLAGS "") # Some Apple compilers produce bad optimizations in this source. - IF(APPLE AND CMAKE_C_COMPILER_ID MATCHES "^(GNU|LLVM)$") - SET(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -O0") - ELSEIF(CMAKE_C_COMPILER_ID STREQUAL "XL") + if(APPLE AND CMAKE_C_COMPILER_ID MATCHES "^(GNU|LLVM)$") + set(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -O0") + elseif(CMAKE_C_COMPILER_ID STREQUAL "XL") # Tell IBM XL not to warn about our test infinite loop - IF(CMAKE_SYSTEM MATCHES "Linux.*ppc64le" + if(CMAKE_SYSTEM MATCHES "Linux.*ppc64le" AND CMAKE_C_COMPILER_VERSION VERSION_LESS "16.1.0" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS "13.1.1") # v13.1.[1-6] on Linux ppc64le is clang based and does not accept # the -qsuppress option, so just suppress all warnings. - SET(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -w") - ELSE() - SET(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -qsuppress=1500-010") - ENDIF() - ENDIF() - IF(CMAKE_C_FLAGS MATCHES "-fsanitize=") - SET(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -DCRASH_USING_ABORT") - ENDIF() - SET_PROPERTY(SOURCE testProcess.c PROPERTY COMPILE_FLAGS "${testProcess_COMPILE_FLAGS}") + set(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -w") + else() + set(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -qsuppress=1500-010") + endif() + endif() + if(CMAKE_C_FLAGS MATCHES "-fsanitize=") + set(testProcess_COMPILE_FLAGS "${testProcess_COMPILE_FLAGS} -DCRASH_USING_ABORT") + endif() + set_property(SOURCE testProcess.c PROPERTY COMPILE_FLAGS "${testProcess_COMPILE_FLAGS}") # Test SharedForward - CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/testSharedForward.c.in + configure_file(${PROJECT_SOURCE_DIR}/testSharedForward.c.in ${PROJECT_BINARY_DIR}/testSharedForward.c @ONLY IMMEDIATE) - ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestSharedForward + add_executable(${KWSYS_NAMESPACE}TestSharedForward ${PROJECT_BINARY_DIR}/testSharedForward.c) - SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestSharedForward PROPERTY LABELS ${KWSYS_LABELS_EXE}) - ADD_DEPENDENCIES(${KWSYS_NAMESPACE}TestSharedForward ${KWSYS_TARGET_C_LINK}) - ADD_TEST(kwsys.testSharedForward ${EXEC_DIR}/${KWSYS_NAMESPACE}TestSharedForward 1) - SET_PROPERTY(TEST kwsys.testSharedForward PROPERTY LABELS ${KWSYS_LABELS_TEST}) + set_property(TARGET ${KWSYS_NAMESPACE}TestSharedForward PROPERTY LABELS ${KWSYS_LABELS_EXE}) + add_dependencies(${KWSYS_NAMESPACE}TestSharedForward ${KWSYS_TARGET_C_LINK}) + add_test(kwsys.testSharedForward ${EXEC_DIR}/${KWSYS_NAMESPACE}TestSharedForward 1) + set_property(TEST kwsys.testSharedForward PROPERTY LABELS ${KWSYS_LABELS_TEST}) # Configure some test properties. - IF(KWSYS_STANDALONE) + if(KWSYS_STANDALONE) # We expect test to fail - SET_TESTS_PROPERTIES(kwsys.testFail PROPERTIES WILL_FAIL ON) - GET_TEST_PROPERTY(kwsys.testFail WILL_FAIL wfv) - SET_TESTS_PROPERTIES(kwsys.testFail PROPERTIES MEASUREMENT "Some Key=Some Value") - MESSAGE(STATUS "GET_TEST_PROPERTY returned: ${wfv}") - ENDIF() + set_tests_properties(kwsys.testFail PROPERTIES WILL_FAIL ON) + get_test_property(kwsys.testFail WILL_FAIL wfv) + set_tests_properties(kwsys.testFail PROPERTIES MEASUREMENT "Some Key=Some Value") + message(STATUS "GET_TEST_PROPERTY returned: ${wfv}") + endif() # Set up ctest custom configuration file. - CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/CTestCustom.cmake.in + configure_file(${PROJECT_SOURCE_DIR}/CTestCustom.cmake.in ${PROJECT_BINARY_DIR}/CTestCustom.cmake @ONLY) # Suppress known consistent failures on buggy systems. - IF(KWSYS_TEST_BOGUS_FAILURES) - SET_TESTS_PROPERTIES(${KWSYS_TEST_BOGUS_FAILURES} PROPERTIES WILL_FAIL ON) - ENDIF() + if(KWSYS_TEST_BOGUS_FAILURES) + set_tests_properties(${KWSYS_TEST_BOGUS_FAILURES} PROPERTIES WILL_FAIL ON) + endif() - ENDIF() -ENDIF() + endif() +endif() diff --git a/Source/kwsys/CommandLineArguments.cxx b/Source/kwsys/CommandLineArguments.cxx index 3fd1955..a2ed874 100644 --- a/Source/kwsys/CommandLineArguments.cxx +++ b/Source/kwsys/CommandLineArguments.cxx @@ -66,26 +66,21 @@ class CommandLineArgumentsMapOfStrucs class CommandLineArgumentsInternal { public: - CommandLineArgumentsInternal() - : UnknownArgumentCallback{ nullptr } - , ClientData{ nullptr } - , LastArgument{ 0 } - { - } + CommandLineArgumentsInternal() = default; - typedef CommandLineArgumentsVectorOfStrings VectorOfStrings; - typedef CommandLineArgumentsMapOfStrucs CallbacksMap; - typedef kwsys::String String; - typedef CommandLineArgumentsSetOfStrings SetOfStrings; + using VectorOfStrings = CommandLineArgumentsVectorOfStrings; + using CallbacksMap = CommandLineArgumentsMapOfStrucs; + using String = kwsys::String; + using SetOfStrings = CommandLineArgumentsSetOfStrings; VectorOfStrings Argv; String Argv0; CallbacksMap Callbacks; - CommandLineArguments::ErrorCallbackType UnknownArgumentCallback; - void* ClientData; + CommandLineArguments::ErrorCallbackType UnknownArgumentCallback{ nullptr }; + void* ClientData{ nullptr }; - VectorOfStrings::size_type LastArgument; + VectorOfStrings::size_type LastArgument{ 0 }; VectorOfStrings UnusedArguments; }; @@ -424,8 +419,7 @@ void CommandLineArguments::SetUnknownArgumentCallback( const char* CommandLineArguments::GetHelp(const char* arg) { - CommandLineArguments::Internal::CallbacksMap::iterator it = - this->Internals->Callbacks.find(arg); + auto it = this->Internals->Callbacks.find(arg); if (it == this->Internals->Callbacks.end()) { return nullptr; } @@ -434,8 +428,7 @@ const char* CommandLineArguments::GetHelp(const char* arg) // one point to if this one is pointing to another argument. CommandLineArgumentsCallbackStructure* cs = &(it->second); for (;;) { - CommandLineArguments::Internal::CallbacksMap::iterator hit = - this->Internals->Callbacks.find(cs->Help); + auto hit = this->Internals->Callbacks.find(cs->Help); if (hit == this->Internals->Callbacks.end()) { break; } @@ -470,9 +463,8 @@ void CommandLineArguments::GenerateHelp() // Collapse all arguments into the map of vectors of all arguments that do // the same thing. CommandLineArguments::Internal::CallbacksMap::iterator it; - typedef std::map<CommandLineArguments::Internal::String, - CommandLineArguments::Internal::SetOfStrings> - MapArgs; + using MapArgs = std::map<CommandLineArguments::Internal::String, + CommandLineArguments::Internal::SetOfStrings>; MapArgs mp; MapArgs::iterator mpit, smpit; for (it = this->Internals->Callbacks.begin(); @@ -709,7 +701,7 @@ bool CommandLineArguments::PopulateVariable( if (cs->Callback) { if (!cs->Callback(cs->Argument, value, cs->CallData)) { this->Internals->LastArgument--; - return 0; + return false; } } CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to " @@ -759,10 +751,10 @@ bool CommandLineArguments::PopulateVariable( std::cerr << "Got unknown variable type: \"" << cs->VariableType << "\"" << std::endl; this->Internals->LastArgument--; - return 0; + return false; } } - return 1; + return true; } } // namespace KWSYS_NAMESPACE diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx index e379182..1a772b4 100644 --- a/Source/kwsys/Directory.cxx +++ b/Source/kwsys/Directory.cxx @@ -204,15 +204,15 @@ bool Directory::Load(const std::string& name) DIR* dir = opendir(name.c_str()); if (!dir) { - return 0; + return false; } for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) { - this->Internal->Files.push_back(d->d_name); + this->Internal->Files.emplace_back(d->d_name); } this->Internal->Path = name; closedir(dir); - return 1; + return true; } unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name) diff --git a/Source/kwsys/ExtraTest.cmake.in b/Source/kwsys/ExtraTest.cmake.in index e8c0a1c..4cec9e2 100644 --- a/Source/kwsys/ExtraTest.cmake.in +++ b/Source/kwsys/ExtraTest.cmake.in @@ -1 +1 @@ -MESSAGE("*** This message is generated by message inside a file that is included in DartTestfile.txt ***") +message("*** This message is generated by message inside a file that is included in DartTestfile.txt ***") diff --git a/Source/kwsys/Glob.cxx b/Source/kwsys/Glob.cxx index 34bb0d0..658b816 100644 --- a/Source/kwsys/Glob.cxx +++ b/Source/kwsys/Glob.cxx @@ -415,8 +415,7 @@ bool Glob::FindFiles(const std::string& inexpr, GlobMessages* messages) void Glob::AddExpression(const std::string& expr) { - this->Internals->Expressions.push_back( - kwsys::RegularExpression(this->PatternToRegex(expr))); + this->Internals->Expressions.emplace_back(this->PatternToRegex(expr)); } void Glob::SetRelative(const char* dir) diff --git a/Source/kwsys/Process.h.in b/Source/kwsys/Process.h.in index 73ea9db..9f2162b 100644 --- a/Source/kwsys/Process.h.in +++ b/Source/kwsys/Process.h.in @@ -180,8 +180,8 @@ kwsysEXPORT void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, * write end of the pipe will be closed in the parent process and the * read end will be closed in the child process. */ -kwsysEXPORT void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, - kwsysProcess_Pipe_Handle p[2]); +kwsysEXPORT void kwsysProcess_SetPipeNative( + kwsysProcess* cp, int pipe, const kwsysProcess_Pipe_Handle p[2]); /** * Get/Set a possibly platform-specific option. Possible options are: diff --git a/Source/kwsys/ProcessUNIX.c b/Source/kwsys/ProcessUNIX.c index f65690b..5fde0b0 100644 --- a/Source/kwsys/ProcessUNIX.c +++ b/Source/kwsys/ProcessUNIX.c @@ -152,10 +152,11 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex, static void kwsysProcessDestroy(kwsysProcess* cp); static int kwsysProcessSetupOutputPipeFile(int* p, const char* name); static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]); -static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout, +static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, + const double* userTimeout, kwsysProcessTime* timeoutTime); static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime, - double* userTimeout, + const double* userTimeout, kwsysProcessTimeNative* timeoutLength, int zeroIsExpired); static kwsysProcessTime kwsysProcessTimeGetCurrent(void); @@ -571,7 +572,7 @@ void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared) } } -void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2]) +void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, const int p[2]) { int* pPipeNative = 0; @@ -1959,7 +1960,8 @@ static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]) /* Get the time at which either the process or user timeout will expire. Returns 1 if the user timeout is first, and 0 otherwise. */ -static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout, +static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, + const double* userTimeout, kwsysProcessTime* timeoutTime) { /* The first time this is called, we need to calculate the time at @@ -1991,7 +1993,7 @@ static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout, /* Get the length of time before the given timeout time arrives. Returns 1 if the time has already arrived, and 0 otherwise. */ static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime, - double* userTimeout, + const double* userTimeout, kwsysProcessTimeNative* timeoutLength, int zeroIsExpired) { diff --git a/Source/kwsys/ProcessWin32.c b/Source/kwsys/ProcessWin32.c index 68c5218..56bbd20 100644 --- a/Source/kwsys/ProcessWin32.c +++ b/Source/kwsys/ProcessWin32.c @@ -761,7 +761,7 @@ void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, int shared) } } -void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, HANDLE p[2]) +void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, const HANDLE p[2]) { HANDLE* pPipeNative = 0; diff --git a/Source/kwsys/System.c b/Source/kwsys/System.c index d43cc6f..dbfd2fd 100644 --- a/Source/kwsys/System.c +++ b/Source/kwsys/System.c @@ -22,7 +22,7 @@ typedef ptrdiff_t kwsysSystem_ptrdiff_t; typedef int kwsysSystem_ptrdiff_t; #endif -static int kwsysSystem__AppendByte(char* local, char** begin, char** end, +static int kwsysSystem__AppendByte(const char* local, char** begin, char** end, int* size, char c) { /* Allocate space for the character. */ diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx index 6ec6e48..3cf64a8 100644 --- a/Source/kwsys/SystemInformation.cxx +++ b/Source/kwsys/SystemInformation.cxx @@ -132,7 +132,7 @@ typedef int siginfo_t; # endif # endif # if defined(KWSYS_CXX_HAS_RLIMIT64) -typedef struct rlimit64 ResourceLimitType; +using ResourceLimitType = struct rlimit64; # define GetResourceLimit getrlimit64 # else typedef struct rlimit ResourceLimitType; @@ -303,34 +303,34 @@ T min(T a, T b) } extern "C" { -typedef void (*SigAction)(int, siginfo_t*, void*); +using SigAction = void (*)(int, siginfo_t*, void*); } // Define SystemInformationImplementation class -typedef void (*DELAY_FUNC)(unsigned int uiMS); +using DELAY_FUNC = void (*)(unsigned int); class SystemInformationImplementation { public: - typedef SystemInformation::LongLong LongLong; + using LongLong = SystemInformation::LongLong; SystemInformationImplementation(); - ~SystemInformationImplementation(); + ~SystemInformationImplementation() = default; - const char* GetVendorString(); + const char* GetVendorString() const; const char* GetVendorID(); - std::string GetTypeID(); - std::string GetFamilyID(); - std::string GetModelID(); - std::string GetModelName(); - std::string GetSteppingCode(); - const char* GetExtendedProcessorName(); - const char* GetProcessorSerialNumber(); - int GetProcessorCacheSize(); - unsigned int GetLogicalProcessorsPerPhysical(); - float GetProcessorClockFrequency(); - int GetProcessorAPICID(); - int GetProcessorCacheXSize(long int); - bool DoesCPUSupportFeature(long int); + std::string GetTypeID() const; + std::string GetFamilyID() const; + std::string GetModelID() const; + std::string GetModelName() const; + std::string GetSteppingCode() const; + const char* GetExtendedProcessorName() const; + const char* GetProcessorSerialNumber() const; + int GetProcessorCacheSize() const; + unsigned int GetLogicalProcessorsPerPhysical() const; + float GetProcessorClockFrequency() const; + int GetProcessorAPICID() const; + int GetProcessorCacheXSize(long int) const; + bool DoesCPUSupportFeature(long int) const; const char* GetOSName(); const char* GetHostname(); @@ -339,24 +339,24 @@ public: const char* GetOSVersion(); const char* GetOSPlatform(); - bool Is64Bits(); + bool Is64Bits() const; - unsigned int GetNumberOfLogicalCPU(); // per physical cpu - unsigned int GetNumberOfPhysicalCPU(); + unsigned int GetNumberOfLogicalCPU() const; // per physical cpu + unsigned int GetNumberOfPhysicalCPU() const; bool DoesCPUSupportCPUID(); // Retrieve memory information in MiB. - size_t GetTotalVirtualMemory(); - size_t GetAvailableVirtualMemory(); - size_t GetTotalPhysicalMemory(); - size_t GetAvailablePhysicalMemory(); + size_t GetTotalVirtualMemory() const; + size_t GetAvailableVirtualMemory() const; + size_t GetTotalPhysicalMemory() const; + size_t GetAvailablePhysicalMemory() const; LongLong GetProcessId(); // Retrieve memory information in KiB. LongLong GetHostMemoryTotal(); - LongLong GetHostMemoryAvailable(const char* envVarName); + LongLong GetHostMemoryAvailable(const char* hostLimitEnvVarName); LongLong GetHostMemoryUsed(); LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName, @@ -377,60 +377,103 @@ public: void RunMemoryCheck(); public: - typedef struct tagID + using ID = struct tagID + { + int Type; + int Family; + int Model; + int Revision; + int ExtendedFamily; + int ExtendedModel; + std::string ProcessorName; + std::string Vendor; + std::string SerialNumber; + std::string ModelName; - } ID; + }; + + using CPUPowerManagement = struct tagCPUPowerManagement - typedef struct tagCPUPowerManagement { + bool HasVoltageID; + bool HasFrequencyID; + bool HasTempSenseDiode; - } CPUPowerManagement; + }; + + using CPUExtendedFeatures = struct tagCPUExtendedFeatures - typedef struct tagCPUExtendedFeatures { + bool Has3DNow; + bool Has3DNowPlus; + bool SupportsMP; + bool HasMMXPlus; + bool HasSSEMMX; + unsigned int LogicalProcessorsPerPhysical; + int APIC_ID; + CPUPowerManagement PowerManagement; - } CPUExtendedFeatures; + }; + + using CPUFeatures = struct CPUtagFeatures - typedef struct CPUtagFeatures { + bool HasFPU; + bool HasTSC; + bool HasMMX; + bool HasSSE; + bool HasSSEFP; + bool HasSSE2; + bool HasIA64; + bool HasAPIC; + bool HasCMOV; + bool HasMTRR; + bool HasACPI; + bool HasSerial; + bool HasThermal; + int CPUSpeed; + int L1CacheSize; + int L2CacheSize; + int L3CacheSize; + CPUExtendedFeatures ExtendedFeatures; - } CPUFeatures; + }; enum Manufacturer { @@ -476,7 +519,7 @@ protected: void CPUCountWindows(); // For windows unsigned char GetAPICId(); // For windows - bool IsSMTSupported(); + bool IsSMTSupported() const; static LongLong GetCyclesDifference(DELAY_FUNC, unsigned int); // For windows // For Linux and Cygwin, /proc/cpuinfo formats are slightly different @@ -885,7 +928,7 @@ int LoadLines(FILE* file, std::vector<std::string>& lines) *pBuf = '\0'; pBuf += 1; } - lines.push_back(buf); + lines.emplace_back(buf); ++nRead; } if (ferror(file)) { @@ -899,7 +942,7 @@ int LoadLines(FILE* file, std::vector<std::string>& lines) int LoadLines(const char* fileName, std::vector<std::string>& lines) { FILE* file = fopen(fileName, "r"); - if (file == 0) { + if (file == nullptr) { return 0; } int nRead = LoadLines(file, lines); @@ -1464,10 +1507,6 @@ SystemInformationImplementation::SystemInformationImplementation() this->OSIs64Bit = (sizeof(void*) == 8); } -SystemInformationImplementation::~SystemInformationImplementation() -{ -} - void SystemInformationImplementation::RunCPUCheck() { #ifdef _WIN32 @@ -1564,7 +1603,7 @@ void SystemInformationImplementation::RunMemoryCheck() } /** Get the vendor string */ -const char* SystemInformationImplementation::GetVendorString() +const char* SystemInformationImplementation::GetVendorString() const { return this->ChipID.Vendor.c_str(); } @@ -1760,7 +1799,7 @@ const char* SystemInformationImplementation::GetVendorID() } /** Return the type ID of the CPU */ -std::string SystemInformationImplementation::GetTypeID() +std::string SystemInformationImplementation::GetTypeID() const { std::ostringstream str; str << this->ChipID.Type; @@ -1768,7 +1807,7 @@ std::string SystemInformationImplementation::GetTypeID() } /** Return the family of the CPU present */ -std::string SystemInformationImplementation::GetFamilyID() +std::string SystemInformationImplementation::GetFamilyID() const { std::ostringstream str; str << this->ChipID.Family; @@ -1776,7 +1815,7 @@ std::string SystemInformationImplementation::GetFamilyID() } // Return the model of CPU present */ -std::string SystemInformationImplementation::GetModelID() +std::string SystemInformationImplementation::GetModelID() const { std::ostringstream str; str << this->ChipID.Model; @@ -1784,13 +1823,13 @@ std::string SystemInformationImplementation::GetModelID() } // Return the model name of CPU present */ -std::string SystemInformationImplementation::GetModelName() +std::string SystemInformationImplementation::GetModelName() const { return this->ChipID.ModelName; } /** Return the stepping code of the CPU present. */ -std::string SystemInformationImplementation::GetSteppingCode() +std::string SystemInformationImplementation::GetSteppingCode() const { std::ostringstream str; str << this->ChipID.Revision; @@ -1798,44 +1837,46 @@ std::string SystemInformationImplementation::GetSteppingCode() } /** Return the stepping code of the CPU present. */ -const char* SystemInformationImplementation::GetExtendedProcessorName() +const char* SystemInformationImplementation::GetExtendedProcessorName() const { return this->ChipID.ProcessorName.c_str(); } /** Return the serial number of the processor * in hexadecimal: xxxx-xxxx-xxxx-xxxx-xxxx-xxxx. */ -const char* SystemInformationImplementation::GetProcessorSerialNumber() +const char* SystemInformationImplementation::GetProcessorSerialNumber() const { return this->ChipID.SerialNumber.c_str(); } /** Return the logical processors per physical */ unsigned int SystemInformationImplementation::GetLogicalProcessorsPerPhysical() + const { return this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical; } /** Return the processor clock frequency. */ -float SystemInformationImplementation::GetProcessorClockFrequency() +float SystemInformationImplementation::GetProcessorClockFrequency() const { return this->CPUSpeedInMHz; } /** Return the APIC ID. */ -int SystemInformationImplementation::GetProcessorAPICID() +int SystemInformationImplementation::GetProcessorAPICID() const { return this->Features.ExtendedFeatures.APIC_ID; } /** Return the L1 cache size. */ -int SystemInformationImplementation::GetProcessorCacheSize() +int SystemInformationImplementation::GetProcessorCacheSize() const { return this->Features.L1CacheSize; } /** Return the chosen cache size. */ -int SystemInformationImplementation::GetProcessorCacheXSize(long int dwCacheID) +int SystemInformationImplementation::GetProcessorCacheXSize( + long int dwCacheID) const { switch (dwCacheID) { case SystemInformation::CPU_FEATURE_L1CACHE: @@ -1848,7 +1889,8 @@ int SystemInformationImplementation::GetProcessorCacheXSize(long int dwCacheID) return -1; } -bool SystemInformationImplementation::DoesCPUSupportFeature(long int dwFeature) +bool SystemInformationImplementation::DoesCPUSupportFeature( + long int dwFeature) const { bool bHasFeature = false; @@ -3409,7 +3451,7 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() // We want to record the total number of cores in this->NumberOfPhysicalCPU // (checking only the first proc) std::string Cores = this->ExtractValueFromCpuInfoFile(buffer, "cpu cores"); - unsigned int NumberOfCoresPerSocket = (unsigned int)atoi(Cores.c_str()); + auto NumberOfCoresPerSocket = (unsigned int)atoi(Cores.c_str()); NumberOfCoresPerSocket = std::max(NumberOfCoresPerSocket, 1u); this->NumberOfPhysicalCPU = NumberOfCoresPerSocket * (unsigned int)NumberOfSockets; @@ -3441,7 +3483,7 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() // Linux Sparc: CPU speed is in Hz and encoded in hexadecimal CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer, "Cpu0ClkTck"); this->CPUSpeedInMHz = - static_cast<float>(strtoull(CPUSpeed.c_str(), 0, 16)) / 1000000.0f; + static_cast<float>(strtoull(CPUSpeed.c_str(), nullptr, 16)) / 1000000.0f; } #endif @@ -3502,9 +3544,8 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() cachename.push_back("D-cache"); // e.g. PA-RISC this->Features.L1CacheSize = 0; - for (size_t index = 0; index < cachename.size(); index++) { - std::string cacheSize = - this->ExtractValueFromCpuInfoFile(buffer, cachename[index]); + for (auto& index : cachename) { + std::string cacheSize = this->ExtractValueFromCpuInfoFile(buffer, index); if (!cacheSize.empty()) { pos = cacheSize.find(" KB"); if (pos != std::string::npos) { @@ -4249,24 +4290,24 @@ bool SystemInformationImplementation::QueryMemory() } /** */ -size_t SystemInformationImplementation::GetTotalVirtualMemory() +size_t SystemInformationImplementation::GetTotalVirtualMemory() const { return this->TotalVirtualMemory; } /** */ -size_t SystemInformationImplementation::GetAvailableVirtualMemory() +size_t SystemInformationImplementation::GetAvailableVirtualMemory() const { return this->AvailableVirtualMemory; } -size_t SystemInformationImplementation::GetTotalPhysicalMemory() +size_t SystemInformationImplementation::GetTotalPhysicalMemory() const { return this->TotalPhysicalMemory; } /** */ -size_t SystemInformationImplementation::GetAvailablePhysicalMemory() +size_t SystemInformationImplementation::GetAvailablePhysicalMemory() const { return this->AvailablePhysicalMemory; } @@ -4350,7 +4391,7 @@ void SystemInformationImplementation::DelayOverhead(unsigned int uiMS) } /** Works only for windows */ -bool SystemInformationImplementation::IsSMTSupported() +bool SystemInformationImplementation::IsSMTSupported() const { return this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical > 1; } @@ -4432,13 +4473,13 @@ void SystemInformationImplementation::CPUCountWindows() } /** Return the number of logical CPUs on the system */ -unsigned int SystemInformationImplementation::GetNumberOfLogicalCPU() +unsigned int SystemInformationImplementation::GetNumberOfLogicalCPU() const { return this->NumberOfLogicalCPU; } /** Return the number of physical CPUs on the system */ -unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU() +unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU() const { return this->NumberOfPhysicalCPU; } @@ -4739,8 +4780,8 @@ std::string SystemInformationImplementation::ParseValueFromKStat( args.reserve(3 + args_string.size()); args.push_back("kstat"); args.push_back("-p"); - for (size_t i = 0; i < args_string.size(); ++i) { - args.push_back(args_string[i].c_str()); + for (auto& i : args_string) { + args.push_back(i.c_str()); } args.push_back(nullptr); @@ -5459,7 +5500,7 @@ void SystemInformationImplementation::TrimNewline(std::string& output) } /** Return true if the machine is 64 bits */ -bool SystemInformationImplementation::Is64Bits() +bool SystemInformationImplementation::Is64Bits() const { return this->OSIs64Bit; } diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx index d27081b..3fa1745 100644 --- a/Source/kwsys/SystemTools.cxx +++ b/Source/kwsys/SystemTools.cxx @@ -123,9 +123,9 @@ extern char** environ; #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)" #define VTK_URL_REGEX \ - "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/" \ + "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]*)(:([0-9]+))?/" \ "(.+)?" - +#define VTK_URL_BYTE_REGEX "%[0-9a-fA-F][0-9a-fA-F]" #ifdef _MSC_VER # include <sys/utime.h> #else @@ -350,7 +350,7 @@ extern int putenv(char* __string) __THROW; namespace KWSYS_NAMESPACE { -double SystemTools::GetTime(void) +double SystemTools::GetTime() { #if defined(_WIN32) && !defined(__CYGWIN__) FILETIME ft; @@ -368,7 +368,7 @@ double SystemTools::GetTime(void) #if defined(_WIN32) typedef wchar_t envchar; #else -typedef char envchar; +using envchar = char; #endif /* Order by environment key only (VAR from VAR=VALUE). */ @@ -421,7 +421,7 @@ public: const envchar* Release(const envchar* env) { const envchar* old = nullptr; - iterator i = this->find(env); + auto i = this->find(env); if (i != this->end()) { old = *i; this->erase(i); @@ -452,7 +452,7 @@ struct SystemToolsPathCaseCmp class SystemToolsStatic { public: - typedef std::map<std::string, std::string> StringMap; + using StringMap = std::map<std::string, std::string>; #if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP /** * Path translation table from dir to refdir @@ -488,7 +488,7 @@ public: */ static std::string FindName( const std::string& name, - const std::vector<std::string>& path = std::vector<std::string>(), + const std::vector<std::string>& userPaths = std::vector<std::string>(), bool no_system_path = false); }; @@ -613,8 +613,7 @@ void SystemTools::GetPath(std::vector<std::string>& path, const char* env) done = true; } } - for (std::vector<std::string>::iterator i = path.begin() + old_size; - i != path.end(); ++i) { + for (auto i = path.begin() + old_size; i != path.end(); ++i) { SystemTools::ConvertToUnixSlashes(*i); } } @@ -1858,7 +1857,7 @@ char* SystemTools::DuplicateString(const char* str) // Return a cropped string std::string SystemTools::CropString(const std::string& s, size_t max_len) { - if (!s.size() || max_len == 0 || max_len >= s.size()) { + if (s.empty() || max_len == 0 || max_len >= s.size()) { return s; } @@ -1893,7 +1892,7 @@ std::vector<std::string> SystemTools::SplitString(const std::string& p, } if (isPath && path[0] == '/') { path.erase(path.begin()); - paths.push_back("/"); + paths.emplace_back("/"); } std::string::size_type pos1 = 0; std::string::size_type pos2 = path.find(sep, pos1 + 1); @@ -3571,14 +3570,14 @@ void SystemTools::SplitPath(const std::string& p, for (; *last; ++last) { if (*last == '/' || *last == '\\') { // End of a component. Save it. - components.push_back(std::string(first, last)); + components.emplace_back(first, last); first = last + 1; } } // Save the last component unless there were no components. if (last != c) { - components.push_back(std::string(first, last)); + components.emplace_back(first, last); } } @@ -3594,7 +3593,7 @@ std::string SystemTools::JoinPath( // Construct result in a single string. std::string result; size_t len = 0; - for (std::vector<std::string>::const_iterator i = first; i != last; ++i) { + for (auto i = first; i != last; ++i) { len += 1 + i->size(); } result.reserve(len); @@ -3828,7 +3827,7 @@ SystemTools::FileTypeEnum SystemTools::DetectFileType(const char* filename, // Allocate buffer and read bytes - unsigned char* buffer = new unsigned char[length]; + auto* buffer = new unsigned char[length]; size_t read_length = fread(buffer, 1, length, fp); fclose(fp); if (read_length == 0) { @@ -4516,7 +4515,7 @@ std::string SystemTools::GetOperatingSystemNameAndVersion() bool SystemTools::ParseURLProtocol(const std::string& URL, std::string& protocol, - std::string& dataglom) + std::string& dataglom, bool decode) { // match 0 entire url // match 1 protocol @@ -4529,13 +4528,17 @@ bool SystemTools::ParseURLProtocol(const std::string& URL, protocol = urlRe.match(1); dataglom = urlRe.match(2); + if (decode) { + dataglom = DecodeURL(dataglom); + } + return true; } bool SystemTools::ParseURL(const std::string& URL, std::string& protocol, std::string& username, std::string& password, std::string& hostname, std::string& dataport, - std::string& database) + std::string& database, bool decode) { kwsys::RegularExpression urlRe(VTK_URL_REGEX); if (!urlRe.find(URL)) @@ -4559,9 +4562,35 @@ bool SystemTools::ParseURL(const std::string& URL, std::string& protocol, dataport = urlRe.match(8); database = urlRe.match(9); + if (decode) { + username = DecodeURL(username); + password = DecodeURL(password); + hostname = DecodeURL(hostname); + dataport = DecodeURL(dataport); + database = DecodeURL(database); + } + return true; } +// ---------------------------------------------------------------------- +std::string SystemTools::DecodeURL(const std::string& url) +{ + kwsys::RegularExpression urlByteRe(VTK_URL_BYTE_REGEX); + std::string ret; + for (size_t i = 0; i < url.length(); i++) { + if (urlByteRe.find(url.substr(i, 3))) { + ret += + static_cast<char>(strtoul(url.substr(i + 1, 2).c_str(), nullptr, 16)); + i += 2; + } else { + ret += url[i]; + } + } + return ret; +} + +// ---------------------------------------------------------------------- // These must NOT be initialized. Default initialization to zero is // necessary. static unsigned int SystemToolsManagerCount; diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in index c4ab9d4..d4a93fa 100644 --- a/Source/kwsys/SystemTools.hxx.in +++ b/Source/kwsys/SystemTools.hxx.in @@ -935,22 +935,32 @@ public: * Parse a character string : * protocol://dataglom * and fill protocol as appropriate. + * decode the dataglom using DecodeURL if set to true. * Return false if the URL does not have the required form, true otherwise. */ static bool ParseURLProtocol(const std::string& URL, std::string& protocol, - std::string& dataglom); + std::string& dataglom, bool decode = false); /** * Parse a string (a URL without protocol prefix) with the form: * protocol://[[username[':'password]'@']hostname[':'dataport]]'/'[datapath] * and fill protocol, username, password, hostname, dataport, and datapath * when values are found. + * decode all string except the protocol using DecodeUrl if set to true. * Return true if the string matches the format; false otherwise. */ static bool ParseURL(const std::string& URL, std::string& protocol, std::string& username, std::string& password, std::string& hostname, std::string& dataport, - std::string& datapath); + std::string& datapath, bool decode = false); + + /** + * Decode the percent-encoded string from an URL or an URI + * into their correct char values. + * Does not perform any other sort of validation. + * Return the decoded string + */ + static std::string DecodeURL(const std::string& url); private: /** diff --git a/Source/kwsys/kwsysPlatformTests.cmake b/Source/kwsys/kwsysPlatformTests.cmake index 28d3f68..89be4b8 100644 --- a/Source/kwsys/kwsysPlatformTests.cmake +++ b/Source/kwsys/kwsysPlatformTests.cmake @@ -1,185 +1,185 @@ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying # file Copyright.txt or https://cmake.org/licensing#kwsys for details. -SET(KWSYS_PLATFORM_TEST_FILE_C kwsysPlatformTestsC.c) -SET(KWSYS_PLATFORM_TEST_FILE_CXX kwsysPlatformTestsCXX.cxx) +set(KWSYS_PLATFORM_TEST_FILE_C kwsysPlatformTestsC.c) +set(KWSYS_PLATFORM_TEST_FILE_CXX kwsysPlatformTestsCXX.cxx) -MACRO(KWSYS_PLATFORM_TEST lang var description invert) - IF(NOT DEFINED ${var}_COMPILED) - MESSAGE(STATUS "${description}") +macro(KWSYS_PLATFORM_TEST lang var description invert) + if(NOT DEFINED ${var}_COMPILED) + message(STATUS "${description}") set(maybe_cxx_standard "") if(CMAKE_VERSION VERSION_LESS 3.8 AND CMAKE_CXX_STANDARD) set(maybe_cxx_standard "-DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}") endif() - TRY_COMPILE(${var}_COMPILED + try_compile(${var}_COMPILED ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${KWSYS_PLATFORM_TEST_FILE_${lang}} COMPILE_DEFINITIONS -DTEST_${var} ${KWSYS_PLATFORM_TEST_DEFINES} ${KWSYS_PLATFORM_TEST_EXTRA_FLAGS} CMAKE_FLAGS "-DLINK_LIBRARIES:STRING=${KWSYS_PLATFORM_TEST_LINK_LIBRARIES}" ${maybe_cxx_standard} OUTPUT_VARIABLE OUTPUT) - IF(${var}_COMPILED) - FILE(APPEND + if(${var}_COMPILED) + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log "${description} compiled with the following output:\n${OUTPUT}\n\n") - ELSE() - FILE(APPEND + else() + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "${description} failed to compile with the following output:\n${OUTPUT}\n\n") - ENDIF() - IF(${invert} MATCHES INVERT) - IF(${var}_COMPILED) - MESSAGE(STATUS "${description} - no") - ELSE() - MESSAGE(STATUS "${description} - yes") - ENDIF() - ELSE() - IF(${var}_COMPILED) - MESSAGE(STATUS "${description} - yes") - ELSE() - MESSAGE(STATUS "${description} - no") - ENDIF() - ENDIF() - ENDIF() - IF(${invert} MATCHES INVERT) - IF(${var}_COMPILED) - SET(${var} 0) - ELSE() - SET(${var} 1) - ENDIF() - ELSE() - IF(${var}_COMPILED) - SET(${var} 1) - ELSE() - SET(${var} 0) - ENDIF() - ENDIF() -ENDMACRO() + endif() + if(${invert} MATCHES INVERT) + if(${var}_COMPILED) + message(STATUS "${description} - no") + else() + message(STATUS "${description} - yes") + endif() + else() + if(${var}_COMPILED) + message(STATUS "${description} - yes") + else() + message(STATUS "${description} - no") + endif() + endif() + endif() + if(${invert} MATCHES INVERT) + if(${var}_COMPILED) + set(${var} 0) + else() + set(${var} 1) + endif() + else() + if(${var}_COMPILED) + set(${var} 1) + else() + set(${var} 0) + endif() + endif() +endmacro() -MACRO(KWSYS_PLATFORM_TEST_RUN lang var description invert) - IF(NOT DEFINED ${var}) - MESSAGE(STATUS "${description}") - TRY_RUN(${var} ${var}_COMPILED +macro(KWSYS_PLATFORM_TEST_RUN lang var description invert) + if(NOT DEFINED ${var}) + message(STATUS "${description}") + try_run(${var} ${var}_COMPILED ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${KWSYS_PLATFORM_TEST_FILE_${lang}} COMPILE_DEFINITIONS -DTEST_${var} ${KWSYS_PLATFORM_TEST_DEFINES} ${KWSYS_PLATFORM_TEST_EXTRA_FLAGS} OUTPUT_VARIABLE OUTPUT) # Note that ${var} will be a 0 return value on success. - IF(${var}_COMPILED) - IF(${var}) - FILE(APPEND + if(${var}_COMPILED) + if(${var}) + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "${description} compiled but failed to run with the following output:\n${OUTPUT}\n\n") - ELSE() - FILE(APPEND + else() + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log "${description} compiled and ran with the following output:\n${OUTPUT}\n\n") - ENDIF() - ELSE() - FILE(APPEND + endif() + else() + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "${description} failed to compile with the following output:\n${OUTPUT}\n\n") - SET(${var} -1 CACHE INTERNAL "${description} failed to compile.") - ENDIF() + set(${var} -1 CACHE INTERNAL "${description} failed to compile.") + endif() - IF(${invert} MATCHES INVERT) - IF(${var}_COMPILED) - IF(${var}) - MESSAGE(STATUS "${description} - yes") - ELSE() - MESSAGE(STATUS "${description} - no") - ENDIF() - ELSE() - MESSAGE(STATUS "${description} - failed to compile") - ENDIF() - ELSE() - IF(${var}_COMPILED) - IF(${var}) - MESSAGE(STATUS "${description} - no") - ELSE() - MESSAGE(STATUS "${description} - yes") - ENDIF() - ELSE() - MESSAGE(STATUS "${description} - failed to compile") - ENDIF() - ENDIF() - ENDIF() + if(${invert} MATCHES INVERT) + if(${var}_COMPILED) + if(${var}) + message(STATUS "${description} - yes") + else() + message(STATUS "${description} - no") + endif() + else() + message(STATUS "${description} - failed to compile") + endif() + else() + if(${var}_COMPILED) + if(${var}) + message(STATUS "${description} - no") + else() + message(STATUS "${description} - yes") + endif() + else() + message(STATUS "${description} - failed to compile") + endif() + endif() + endif() - IF(${invert} MATCHES INVERT) - IF(${var}_COMPILED) - IF(${var}) - SET(${var} 1) - ELSE() - SET(${var} 0) - ENDIF() - ELSE() - SET(${var} 1) - ENDIF() - ELSE() - IF(${var}_COMPILED) - IF(${var}) - SET(${var} 0) - ELSE() - SET(${var} 1) - ENDIF() - ELSE() - SET(${var} 0) - ENDIF() - ENDIF() -ENDMACRO() + if(${invert} MATCHES INVERT) + if(${var}_COMPILED) + if(${var}) + set(${var} 1) + else() + set(${var} 0) + endif() + else() + set(${var} 1) + endif() + else() + if(${var}_COMPILED) + if(${var}) + set(${var} 0) + else() + set(${var} 1) + endif() + else() + set(${var} 0) + endif() + endif() +endmacro() -MACRO(KWSYS_PLATFORM_C_TEST var description invert) - SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_C_TEST_DEFINES}) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_C_TEST_EXTRA_FLAGS}) +macro(KWSYS_PLATFORM_C_TEST var description invert) + set(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_C_TEST_DEFINES}) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_C_TEST_EXTRA_FLAGS}) KWSYS_PLATFORM_TEST(C "${var}" "${description}" "${invert}") - SET(KWSYS_PLATFORM_TEST_DEFINES) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) -ENDMACRO() + set(KWSYS_PLATFORM_TEST_DEFINES) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) +endmacro() -MACRO(KWSYS_PLATFORM_C_TEST_RUN var description invert) - SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_C_TEST_DEFINES}) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_C_TEST_EXTRA_FLAGS}) +macro(KWSYS_PLATFORM_C_TEST_RUN var description invert) + set(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_C_TEST_DEFINES}) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_C_TEST_EXTRA_FLAGS}) KWSYS_PLATFORM_TEST_RUN(C "${var}" "${description}" "${invert}") - SET(KWSYS_PLATFORM_TEST_DEFINES) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) -ENDMACRO() + set(KWSYS_PLATFORM_TEST_DEFINES) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) +endmacro() -MACRO(KWSYS_PLATFORM_CXX_TEST var description invert) - SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_CXX_TEST_DEFINES}) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS}) - SET(KWSYS_PLATFORM_TEST_LINK_LIBRARIES ${KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES}) +macro(KWSYS_PLATFORM_CXX_TEST var description invert) + set(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_CXX_TEST_DEFINES}) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS}) + set(KWSYS_PLATFORM_TEST_LINK_LIBRARIES ${KWSYS_PLATFORM_CXX_TEST_LINK_LIBRARIES}) KWSYS_PLATFORM_TEST(CXX "${var}" "${description}" "${invert}") - SET(KWSYS_PLATFORM_TEST_DEFINES) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) - SET(KWSYS_PLATFORM_TEST_LINK_LIBRARIES) -ENDMACRO() + set(KWSYS_PLATFORM_TEST_DEFINES) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) + set(KWSYS_PLATFORM_TEST_LINK_LIBRARIES) +endmacro() -MACRO(KWSYS_PLATFORM_CXX_TEST_RUN var description invert) - SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_CXX_TEST_DEFINES}) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS}) +macro(KWSYS_PLATFORM_CXX_TEST_RUN var description invert) + set(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_CXX_TEST_DEFINES}) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS}) KWSYS_PLATFORM_TEST_RUN(CXX "${var}" "${description}" "${invert}") - SET(KWSYS_PLATFORM_TEST_DEFINES) - SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) -ENDMACRO() + set(KWSYS_PLATFORM_TEST_DEFINES) + set(KWSYS_PLATFORM_TEST_EXTRA_FLAGS) +endmacro() #----------------------------------------------------------------------------- # KWSYS_PLATFORM_INFO_TEST(lang var description) # # Compile test named by ${var} and store INFO strings extracted from binary. -MACRO(KWSYS_PLATFORM_INFO_TEST lang var description) +macro(KWSYS_PLATFORM_INFO_TEST lang var description) # We can implement this macro on CMake 2.6 and above. - IF("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.6) - SET(${var} "") - ELSE() + if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.6) + set(${var} "") + else() # Choose a location for the result binary. - SET(KWSYS_PLATFORM_INFO_FILE + set(KWSYS_PLATFORM_INFO_FILE ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/${var}.bin) # Compile the test binary. - IF(NOT EXISTS ${KWSYS_PLATFORM_INFO_FILE}) - MESSAGE(STATUS "${description}") - TRY_COMPILE(${var}_COMPILED + if(NOT EXISTS ${KWSYS_PLATFORM_INFO_FILE}) + message(STATUS "${description}") + try_compile(${var}_COMPILED ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${KWSYS_PLATFORM_TEST_FILE_${lang}} COMPILE_DEFINITIONS -DTEST_${var} @@ -188,29 +188,29 @@ MACRO(KWSYS_PLATFORM_INFO_TEST lang var description) OUTPUT_VARIABLE OUTPUT COPY_FILE ${KWSYS_PLATFORM_INFO_FILE} ) - IF(${var}_COMPILED) - FILE(APPEND + if(${var}_COMPILED) + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log "${description} compiled with the following output:\n${OUTPUT}\n\n") - ELSE() - FILE(APPEND + else() + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "${description} failed to compile with the following output:\n${OUTPUT}\n\n") - ENDIF() - IF(${var}_COMPILED) - MESSAGE(STATUS "${description} - compiled") - ELSE() - MESSAGE(STATUS "${description} - failed") - ENDIF() - ENDIF() + endif() + if(${var}_COMPILED) + message(STATUS "${description} - compiled") + else() + message(STATUS "${description} - failed") + endif() + endif() # Parse info strings out of the compiled binary. - IF(${var}_COMPILED) - FILE(STRINGS ${KWSYS_PLATFORM_INFO_FILE} ${var} REGEX "INFO:[A-Za-z0-9]+\\[[^]]*\\]") - ELSE() - SET(${var} "") - ENDIF() + if(${var}_COMPILED) + file(STRINGS ${KWSYS_PLATFORM_INFO_FILE} ${var} REGEX "INFO:[A-Za-z0-9]+\\[[^]]*\\]") + else() + set(${var} "") + endif() - SET(KWSYS_PLATFORM_INFO_FILE) - ENDIF() -ENDMACRO() + set(KWSYS_PLATFORM_INFO_FILE) + endif() +endmacro() diff --git a/Source/kwsys/testCommandLineArguments.cxx b/Source/kwsys/testCommandLineArguments.cxx index 1778a9b..79ebe1a 100644 --- a/Source/kwsys/testCommandLineArguments.cxx +++ b/Source/kwsys/testCommandLineArguments.cxx @@ -98,7 +98,7 @@ int testCommandLineArguments(int argc, char* argv[]) std::vector<std::string> stl_strings_argument; std::string valid_stl_strings[] = { "ken", "brad", "bill", "andy" }; - typedef kwsys::CommandLineArguments argT; + using argT = kwsys::CommandLineArguments; arg.AddArgument("--some-int-variable", argT::SPACE_ARGUMENT, &some_int_variable, "Set some random int variable"); diff --git a/Source/kwsys/testCommandLineArguments1.cxx b/Source/kwsys/testCommandLineArguments1.cxx index 64561b1..cbc3002 100644 --- a/Source/kwsys/testCommandLineArguments1.cxx +++ b/Source/kwsys/testCommandLineArguments1.cxx @@ -25,7 +25,7 @@ int testCommandLineArguments1(int argc, char* argv[]) std::string p; int res = 0; - typedef kwsys::CommandLineArguments argT; + using argT = kwsys::CommandLineArguments; arg.AddArgument("-n", argT::SPACE_ARGUMENT, &n, "Argument N"); arg.AddArgument("-m", argT::EQUAL_ARGUMENT, &m, "Argument M"); arg.AddBooleanArgument("-p", &p, "Argument P"); diff --git a/Source/kwsys/testDynamicLoader.cxx b/Source/kwsys/testDynamicLoader.cxx index 2421ac0..703ad4d 100644 --- a/Source/kwsys/testDynamicLoader.cxx +++ b/Source/kwsys/testDynamicLoader.cxx @@ -25,7 +25,7 @@ static std::string GetLibName(const char* lname, const char* subdir = nullptr) { // Construct proper name of lib std::string slname; - slname = EXECUTABLE_OUTPUT_PATH; + slname = RUNTIME_OUTPUT_DIRECTORY; if (subdir) { slname += "/"; slname += subdir; diff --git a/Source/kwsys/testEncoding.cxx b/Source/kwsys/testEncoding.cxx index 988697b..d672aed 100644 --- a/Source/kwsys/testEncoding.cxx +++ b/Source/kwsys/testEncoding.cxx @@ -85,7 +85,7 @@ static int testRobustEncoding() std::wstring wstr = kwsys::Encoding::ToWide(cstr); wstr = kwsys::Encoding::ToWide(nullptr); - if (wstr != L"") { + if (!wstr.empty()) { const wchar_t* wcstr = wstr.c_str(); std::cout << "ToWide(NULL) returned"; for (size_t i = 0; i < wstr.size(); i++) { @@ -95,7 +95,7 @@ static int testRobustEncoding() ret++; } wstr = kwsys::Encoding::ToWide(""); - if (wstr != L"") { + if (!wstr.empty()) { const wchar_t* wcstr = wstr.c_str(); std::cout << "ToWide(\"\") returned"; for (size_t i = 0; i < wstr.size(); i++) { @@ -113,13 +113,13 @@ static int testRobustEncoding() #endif std::string str = kwsys::Encoding::ToNarrow(nullptr); - if (str != "") { + if (!str.empty()) { std::cout << "ToNarrow(NULL) returned " << str << std::endl; ret++; } str = kwsys::Encoding::ToNarrow(L""); - if (wstr != L"") { + if (!wstr.empty()) { std::cout << "ToNarrow(\"\") returned " << str << std::endl; ret++; } @@ -140,14 +140,13 @@ static int testWithNulls() strings.push_back(std::string("k") + '\0' + '\0'); strings.push_back(std::string("\0\0\0\0", 4) + "lmn" + std::string("\0\0\0\0", 4)); - for (std::vector<std::string>::iterator it = strings.begin(); - it != strings.end(); ++it) { - std::wstring wstr = kwsys::Encoding::ToWide(*it); + for (auto& string : strings) { + std::wstring wstr = kwsys::Encoding::ToWide(string); std::string str = kwsys::Encoding::ToNarrow(wstr); - std::string s(*it); + std::string s(string); std::replace(s.begin(), s.end(), '\0', ' '); - std::cout << "'" << s << "' (" << it->size() << ")" << std::endl; - if (str != *it) { + std::cout << "'" << s << "' (" << string.size() << ")" << std::endl; + if (str != string) { std::replace(str.begin(), str.end(), '\0', ' '); std::cout << "string with null was different: '" << str << "' (" << str.size() << ")" << std::endl; diff --git a/Source/kwsys/testHashSTL.cxx b/Source/kwsys/testHashSTL.cxx index 4ed2f89..18cae7f 100644 --- a/Source/kwsys/testHashSTL.cxx +++ b/Source/kwsys/testHashSTL.cxx @@ -27,30 +27,30 @@ template class kwsys::hash_set<int>; static bool test_hash_map() { - typedef kwsys::hash_map<const char*, int> mtype; + using mtype = kwsys::hash_map<const char*, int>; mtype m; const char* keys[] = { "hello", "world" }; m[keys[0]] = 1; m.insert(mtype::value_type(keys[1], 2)); int sum = 0; - for (mtype::iterator mi = m.begin(); mi != m.end(); ++mi) { - std::cout << "Found entry [" << mi->first << "," << mi->second << "]" + for (auto& mi : m) { + std::cout << "Found entry [" << mi.first << "," << mi.second << "]" << std::endl; - sum += mi->second; + sum += mi.second; } return sum == 3; } static bool test_hash_set() { - typedef kwsys::hash_set<int> stype; + using stype = kwsys::hash_set<int>; stype s; s.insert(1); s.insert(2); int sum = 0; - for (stype::iterator si = s.begin(); si != s.end(); ++si) { - std::cout << "Found entry [" << *si << "]" << std::endl; - sum += *si; + for (int si : s) { + std::cout << "Found entry [" << si << "]" << std::endl; + sum += si; } return sum == 3; } diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx index 3f6eeb8..670e8dc 100644 --- a/Source/kwsys/testSystemTools.cxx +++ b/Source/kwsys/testSystemTools.cxx @@ -721,8 +721,7 @@ static std::string StringVectorToString(const std::vector<std::string>& vec) { std::stringstream ss; ss << "vector("; - for (std::vector<std::string>::const_iterator i = vec.begin(); - i != vec.end(); ++i) { + for (auto i = vec.begin(); i != vec.end(); ++i) { if (i != vec.begin()) { ss << ", "; } @@ -743,16 +742,16 @@ static bool CheckGetPath() const char* registryPath = "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MyApp; MyKey]"; std::vector<std::string> originalPaths; - originalPaths.push_back(registryPath); + originalPaths.emplace_back(registryPath); std::vector<std::string> expectedPaths; - expectedPaths.push_back(registryPath); + expectedPaths.emplace_back(registryPath); #ifdef _WIN32 expectedPaths.push_back("C:/Somewhere/something"); expectedPaths.push_back("D:/Temp"); #else - expectedPaths.push_back("/Somewhere/something"); - expectedPaths.push_back("/tmp"); + expectedPaths.emplace_back("/Somewhere/something"); + expectedPaths.emplace_back("/tmp"); #endif bool res = true; @@ -817,7 +816,7 @@ static bool CheckFind() } std::vector<std::string> searchPaths; - searchPaths.push_back(TEST_SYSTEMTOOLS_BINARY_DIR); + searchPaths.emplace_back(TEST_SYSTEMTOOLS_BINARY_DIR); if (kwsys::SystemTools::FindFile(testFindFileName, searchPaths, true) .empty()) { std::cerr << "Problem with FindFile without system paths for: " @@ -1086,6 +1085,34 @@ static bool CheckCopyFileIfDifferent() return ret; } +static bool CheckURLParsing() +{ + bool ret = true; + std::string url = "http://user:pw@hostname:42/full/url.com"; + + std::string protocol, username, password, hostname, dataport, database; + kwsys::SystemTools::ParseURL(url, protocol, username, password, hostname, + dataport, database); + if (protocol != "http" || username != "user" || password != "pw" || + hostname != "hostname" || dataport != "42" || + database != "full/url.com") { + std::cerr << "Incorrect URL parsing" << std::endl; + ret = false; + } + + std::string uri = + "file://hostname/path/to/" + "a%20file%20with%20str%C3%A0ng%C3%A8%20ch%40r%20and%20s%C2%B5aces"; + kwsys::SystemTools::ParseURL(uri, protocol, username, password, hostname, + dataport, database, true); + if (protocol != "file" || hostname != "hostname" || + database != "path/to/a file with stràngè ch@r and sµaces") { + std::cerr << "Incorrect URL parsing or decoding" << std::endl; + ret = false; + } + return ret; +} + int testSystemTools(int, char* []) { bool res = true; @@ -1133,5 +1160,7 @@ int testSystemTools(int, char* []) res &= CheckCopyFileIfDifferent(); + res &= CheckURLParsing(); + return res ? 0 : 1; } diff --git a/Source/kwsys/testSystemTools.h.in b/Source/kwsys/testSystemTools.h.in index 022e36e..e4b89a7 100644 --- a/Source/kwsys/testSystemTools.h.in +++ b/Source/kwsys/testSystemTools.h.in @@ -3,7 +3,7 @@ #ifndef @KWSYS_NAMESPACE@_testSystemtools_h #define @KWSYS_NAMESPACE@_testSystemtools_h -#define EXECUTABLE_OUTPUT_PATH "@CMAKE_CURRENT_BINARY_DIR@" +#define RUNTIME_OUTPUT_DIRECTORY "@CMAKE_CURRENT_BINARY_DIR@" #define TEST_SYSTEMTOOLS_SOURCE_DIR "@TEST_SYSTEMTOOLS_SOURCE_DIR@" #define TEST_SYSTEMTOOLS_BINARY_DIR "@TEST_SYSTEMTOOLS_BINARY_DIR@" |