summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Auxiliary/CMakeLists.txt2
-rw-r--r--Auxiliary/vim/syntax/cmake.vim2
-rw-r--r--CMakeCPack.cmake76
-rw-r--r--CMakeCPackOptions.cmake.in58
-rw-r--r--CMakeLists.txt28
-rw-r--r--CTestCustom.cmake.in2
-rw-r--r--Help/command/ctest_memcheck.rst8
-rw-r--r--Help/command/execute_process.rst16
-rw-r--r--Help/command/file.rst13
-rw-r--r--Help/command/string.rst27
-rw-r--r--Help/command/target_link_libraries.rst5
-rw-r--r--Help/generator/Visual Studio 15 2017.rst (renamed from Help/generator/Visual Studio 15.rst)12
-rw-r--r--Help/manual/cmake-buildsystem.7.rst2
-rw-r--r--Help/manual/cmake-compile-features.7.rst29
-rw-r--r--Help/manual/cmake-generators.7.rst2
-rw-r--r--Help/manual/cmake-properties.7.rst5
-rw-r--r--Help/manual/cmake-qt.7.rst2
-rw-r--r--Help/manual/cmake-toolchains.7.rst2
-rw-r--r--Help/manual/cmake-variables.7.rst5
-rw-r--r--Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst9
-rw-r--r--Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst9
-rw-r--r--Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst13
-rw-r--r--Help/prop_tgt/IMPORTED_LIBNAME.rst23
-rw-r--r--Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst7
-rw-r--r--Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst6
-rw-r--r--Help/prop_tgt/VS_USER_PROPS_CXX.rst12
-rw-r--r--Help/release/3.7.rst6
-rw-r--r--Help/release/dev/CUDA-language-support.rst6
-rw-r--r--Help/release/dev/ExternalProject-GIT_CONFIG.rst5
-rw-r--r--Help/release/dev/UseSWIG-SWIG_OUTFILE_DIR.rst6
-rw-r--r--Help/release/dev/add-SHA-3.rst4
-rw-r--r--Help/release/dev/capture-clang-tidy-errors.rst6
-rw-r--r--Help/release/dev/compile-features-for-language-standards.rst7
-rw-r--r--Help/release/dev/cpack-ifw-options.rst7
-rw-r--r--Help/release/dev/cpack-rpm-omit-unsupported-tags.rst8
-rw-r--r--Help/release/dev/ctest_memcheck_defect_count.rst5
-rw-r--r--Help/release/dev/execute_process-encoding.rst5
-rw-r--r--Help/release/dev/fuchsia-platform.rst4
-rw-r--r--Help/release/dev/imported-interface-libname.rst7
-rw-r--r--Help/release/dev/imported-interface-no-system.rst5
-rw-r--r--Help/release/dev/intel-compile-features-windows.rst6
-rw-r--r--Help/release/dev/st2-env-settings.rst6
-rw-r--r--Help/release/dev/swig_add_library.rst8
-rw-r--r--Help/release/dev/try_compile-honor-CMAKE_WARN_DEPRECATED.rst6
-rw-r--r--Help/release/dev/vs-custom-msbuild-props.rst9
-rw-r--r--Help/release/dev/vs-debugger-config.rst6
-rw-r--r--Help/release/dev/vs-default-build-package.rst7
-rw-r--r--Help/release/dev/vs-flag-order.rst9
-rw-r--r--Help/release/dev/vs_targets_file_as_library.rst6
-rw-r--r--Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG.rst6
-rw-r--r--Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst3
-rw-r--r--Help/variable/CMAKE_INSTALL_PREFIX.rst2
-rw-r--r--Help/variable/CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT.rst14
-rw-r--r--Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_MACHINE.rst9
-rw-r--r--Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst3
-rw-r--r--Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst3
-rw-r--r--Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst25
-rw-r--r--Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst8
-rw-r--r--Modules/CMakeCUDACompiler.cmake.in20
-rw-r--r--Modules/CMakeCUDACompilerABI.cu16
-rw-r--r--Modules/CMakeCUDACompilerId.cu.in39
-rw-r--r--Modules/CMakeCUDAInformation.cmake193
-rw-r--r--Modules/CMakeCompilerIdDetection.cmake5
-rw-r--r--Modules/CMakeDetermineASMCompiler.cmake8
-rw-r--r--Modules/CMakeDetermineCUDACompiler.cmake115
-rw-r--r--Modules/CMakeDetermineCompilerId.cmake6
-rw-r--r--Modules/CMakeGraphVizOptions.cmake13
-rw-r--r--Modules/CMakeTestCUDACompiler.cmake71
-rw-r--r--Modules/CPack.cmake4
-rw-r--r--Modules/CPackDeb.cmake8
-rw-r--r--Modules/CPackIFW.cmake142
-rw-r--r--Modules/CPackRPM.cmake30
-rw-r--r--Modules/Compiler/ARMCC.cmake1
-rw-r--r--Modules/Compiler/AppleClang-C.cmake10
-rw-r--r--Modules/Compiler/AppleClang-CXX.cmake10
-rw-r--r--Modules/Compiler/Clang-C.cmake10
-rw-r--r--Modules/Compiler/Clang-CXX.cmake10
-rw-r--r--Modules/Compiler/GNU-C.cmake10
-rw-r--r--Modules/Compiler/GNU-CXX.cmake10
-rw-r--r--Modules/Compiler/Intel-C-FeatureTests.cmake9
-rw-r--r--Modules/Compiler/Intel-C.cmake13
-rw-r--r--Modules/Compiler/Intel-CXX-FeatureTests.cmake67
-rw-r--r--Modules/Compiler/Intel-CXX.cmake46
-rw-r--r--Modules/Compiler/MSVC-CXX.cmake9
-rw-r--r--Modules/Compiler/NVIDIA-CUDA.cmake24
-rw-r--r--Modules/Compiler/NVIDIA-DetermineCompiler.cmake7
-rw-r--r--Modules/Compiler/SunPro-CXX.cmake10
-rw-r--r--Modules/ExternalData.cmake9
-rw-r--r--Modules/ExternalProject.cmake153
-rw-r--r--Modules/FindALSA.cmake2
-rw-r--r--Modules/FindASPELL.cmake2
-rw-r--r--Modules/FindAVIFile.cmake2
-rw-r--r--Modules/FindArmadillo.cmake7
-rw-r--r--Modules/FindBISON.cmake4
-rw-r--r--Modules/FindBZip2.cmake2
-rw-r--r--Modules/FindBullet.cmake2
-rw-r--r--Modules/FindCURL.cmake2
-rw-r--r--Modules/FindCoin3D.cmake4
-rw-r--r--Modules/FindCurses.cmake2
-rw-r--r--Modules/FindDart.cmake2
-rw-r--r--Modules/FindDevIL.cmake4
-rw-r--r--Modules/FindEXPAT.cmake2
-rw-r--r--Modules/FindFLEX.cmake2
-rw-r--r--Modules/FindFreetype.cmake3
-rw-r--r--Modules/FindGIF.cmake2
-rw-r--r--Modules/FindGSL.cmake1
-rw-r--r--Modules/FindGTK2.cmake1
-rw-r--r--Modules/FindGit.cmake3
-rw-r--r--Modules/FindGnuTLS.cmake3
-rw-r--r--Modules/FindGnuplot.cmake3
-rw-r--r--Modules/FindHDF5.cmake12
-rw-r--r--Modules/FindHSPELL.cmake3
-rw-r--r--Modules/FindHg.cmake2
-rw-r--r--Modules/FindIcotool.cmake2
-rw-r--r--Modules/FindJPEG.cmake2
-rw-r--r--Modules/FindJasper.cmake2
-rw-r--r--Modules/FindJava.cmake1
-rw-r--r--Modules/FindLATEX.cmake1
-rw-r--r--Modules/FindLTTngUST.cmake2
-rw-r--r--Modules/FindLibArchive.cmake8
-rw-r--r--Modules/FindLibXml2.cmake2
-rw-r--r--Modules/FindMPEG.cmake2
-rw-r--r--Modules/FindMPEG2.cmake3
-rw-r--r--Modules/FindMPI.cmake1
-rw-r--r--Modules/FindMatlab.cmake3
-rw-r--r--Modules/FindMotif.cmake3
-rw-r--r--Modules/FindOpenAL.cmake2
-rw-r--r--Modules/FindOpenGL.cmake2
-rw-r--r--Modules/FindOpenSceneGraph.cmake1
-rw-r--r--Modules/FindPNG.cmake2
-rw-r--r--Modules/FindPerl.cmake2
-rw-r--r--Modules/FindPerlLibs.cmake2
-rw-r--r--Modules/FindPhysFS.cmake3
-rw-r--r--Modules/FindPkgConfig.cmake5
-rw-r--r--Modules/FindPythonInterp.cmake2
-rw-r--r--Modules/FindPythonLibs.cmake8
-rw-r--r--Modules/FindQuickTime.cmake2
-rw-r--r--Modules/FindSDL.cmake7
-rw-r--r--Modules/FindSDL_sound.cmake7
-rw-r--r--Modules/FindTCL.cmake2
-rw-r--r--Modules/FindTIFF.cmake2
-rw-r--r--Modules/FindTclsh.cmake2
-rw-r--r--Modules/FindWget.cmake4
-rw-r--r--Modules/FindZLIB.cmake2
-rw-r--r--Modules/FortranCInterface/CMakeLists.txt3
-rw-r--r--Modules/Internal/FeatureTesting.cmake12
-rw-r--r--Modules/MatlabTestsRedirect.cmake4
-rw-r--r--Modules/Platform/Android/Determine-Compiler-NDK.cmake17
-rw-r--r--Modules/Platform/Android/Determine-Compiler-Standalone.cmake7
-rw-r--r--Modules/Platform/Android/Determine-Compiler.cmake7
-rw-r--r--Modules/Platform/Darwin-Initialize.cmake8
-rw-r--r--Modules/Platform/Darwin-PGI-C.cmake2
-rw-r--r--Modules/Platform/Darwin-PGI-CXX.cmake2
-rw-r--r--Modules/Platform/Darwin-PGI-Fortran.cmake2
-rw-r--r--Modules/Platform/Darwin-PGI.cmake14
-rw-r--r--Modules/Platform/Darwin.cmake24
-rw-r--r--Modules/Platform/Fuchsia.cmake25
-rw-r--r--Modules/Platform/Windows-MSVC.cmake4
-rw-r--r--Modules/Platform/Windows.cmake1
-rw-r--r--Modules/UseSWIG.cmake81
-rw-r--r--Modules/WriteCompilerDetectionHeader.cmake7
-rw-r--r--Packaging/QtSDK/ToolsCMakeXX.cmake68
-rw-r--r--Packaging/QtSDK/qt.tools.cmake.xx.qs.in48
-rw-r--r--Source/.gitattributes3
-rw-r--r--Source/CMakeLists.txt26
-rw-r--r--Source/CMakeVersion.cmake2
-rw-r--r--Source/CPack/IFW/cmCPackIFWInstaller.cxx14
-rw-r--r--Source/CPack/IFW/cmCPackIFWPackage.cxx82
-rw-r--r--Source/CPack/IFW/cmCPackIFWPackage.h3
-rw-r--r--Source/CPack/OSXScriptLauncher.cxx4
-rw-r--r--Source/CPack/WiX/cmCPackWIXGenerator.cxx8
-rw-r--r--Source/CPack/WiX/cmWIXRichTextFormatWriter.h3
-rw-r--r--Source/CPack/WiX/cmWIXSourceWriter.cxx41
-rw-r--r--Source/CPack/WiX/cmWIXSourceWriter.h2
-rw-r--r--Source/CPack/cmCPackBundleGenerator.cxx5
-rw-r--r--Source/CPack/cmCPackBundleGenerator.h4
-rw-r--r--Source/CPack/cmCPackDragNDropGenerator.cxx4
-rw-r--r--Source/CPack/cmCPackDragNDropGenerator.h6
-rw-r--r--Source/CPack/cmCPackGenerator.cxx34
-rw-r--r--Source/CPack/cmCPackGenerator.h9
-rw-r--r--Source/CPack/cmCPackGeneratorFactory.cxx12
-rw-r--r--Source/CPack/cmCPackGeneratorFactory.h2
-rw-r--r--Source/CPack/cmCPackLog.cxx5
-rw-r--r--Source/CPack/cmCPackLog.h2
-rw-r--r--Source/CPack/cmCPackOSXX11Generator.cxx11
-rw-r--r--Source/CPack/cmCPackOSXX11Generator.h3
-rw-r--r--Source/CPack/cmCPackPKGGenerator.cxx11
-rw-r--r--Source/CPack/cmCPackPKGGenerator.h4
-rw-r--r--Source/CPack/cmCPackPackageMakerGenerator.cxx18
-rw-r--r--Source/CPack/cmCPackPackageMakerGenerator.h3
-rw-r--r--Source/CPack/cmCPackProductBuildGenerator.cxx11
-rw-r--r--Source/CPack/cmCPackProductBuildGenerator.h4
-rw-r--r--Source/CPack/cmCPackRPMGenerator.cxx11
-rw-r--r--Source/CPack/cmCPackSTGZGenerator.cxx8
-rw-r--r--Source/CPack/cpack.cxx31
-rw-r--r--Source/CTest/cmCTestBuildHandler.cxx23
-rw-r--r--Source/CTest/cmCTestBuildHandler.h7
-rw-r--r--Source/CTest/cmCTestGIT.cxx30
-rw-r--r--Source/CTest/cmCTestGenericHandler.cxx7
-rw-r--r--Source/CTest/cmCTestGenericHandler.h8
-rw-r--r--Source/CTest/cmCTestHandlerCommand.cxx5
-rw-r--r--Source/CTest/cmCTestHandlerCommand.h2
-rw-r--r--Source/CTest/cmCTestLaunch.cxx56
-rw-r--r--Source/CTest/cmCTestMemCheckCommand.cxx23
-rw-r--r--Source/CTest/cmCTestMemCheckCommand.h10
-rw-r--r--Source/CTest/cmCTestMemCheckHandler.cxx47
-rw-r--r--Source/CTest/cmCTestMemCheckHandler.h3
-rw-r--r--Source/CTest/cmCTestRunTest.cxx2
-rw-r--r--Source/CTest/cmCTestRunTest.h4
-rw-r--r--Source/CTest/cmCTestScriptHandler.cxx21
-rw-r--r--Source/CTest/cmCTestSubmitHandler.cxx54
-rw-r--r--Source/CTest/cmCTestTestHandler.cxx30
-rw-r--r--Source/CTest/cmCTestUploadCommand.cxx5
-rw-r--r--Source/CTest/cmCTestVC.cxx9
-rw-r--r--Source/CTest/cmCTestVC.h11
-rw-r--r--Source/CTest/cmProcess.cxx10
-rw-r--r--Source/CursesDialog/cmCursesMainForm.cxx91
-rw-r--r--Source/CursesDialog/cmCursesStringWidget.cxx4
-rw-r--r--Source/Modules/FindLibRHash.cmake73
-rw-r--r--Source/QtDialog/CMakeSetup.cxx4
-rw-r--r--Source/QtDialog/FirstConfigure.cxx2
-rw-r--r--Source/bindexplib.cxx3
-rw-r--r--Source/bindexplib.h5
-rw-r--r--Source/cmAlgorithms.h14
-rw-r--r--Source/cmAuxSourceDirectoryCommand.cxx2
-rw-r--r--Source/cmBuildCommand.cxx3
-rw-r--r--Source/cmCMakeMinimumRequired.cxx6
-rw-r--r--Source/cmCMakeMinimumRequired.h6
-rw-r--r--Source/cmCPluginAPI.cxx8
-rw-r--r--Source/cmCTest.cxx155
-rw-r--r--Source/cmCTest.h20
-rw-r--r--Source/cmCacheManager.cxx11
-rw-r--r--Source/cmCacheManager.h6
-rw-r--r--Source/cmCallVisualStudioMacro.cxx2
-rw-r--r--Source/cmCallVisualStudioMacro.h2
-rw-r--r--Source/cmCommandArgumentsHelper.h6
-rw-r--r--Source/cmCommands.cxx43
-rw-r--r--Source/cmCommonTargetGenerator.cxx3
-rw-r--r--Source/cmCommonTargetGenerator.h5
-rw-r--r--Source/cmComputeLinkInformation.cxx6
-rw-r--r--Source/cmComputeLinkInformation.h1
-rw-r--r--Source/cmConditionEvaluator.cxx12
-rw-r--r--Source/cmConditionEvaluator.h10
-rw-r--r--Source/cmConfigure.cmake.h.in1
-rw-r--r--Source/cmCoreTryCompile.cxx26
-rw-r--r--Source/cmCoreTryCompile.h5
-rw-r--r--Source/cmCreateTestSourceList.cxx4
-rw-r--r--Source/cmCreateTestSourceList.h7
-rw-r--r--Source/cmCryptoHash.cxx113
-rw-r--r--Source/cmCryptoHash.h74
-rw-r--r--Source/cmCustomCommandGenerator.cxx45
-rw-r--r--Source/cmCustomCommandGenerator.h4
-rw-r--r--Source/cmDefinitions.cxx1
-rw-r--r--Source/cmDefinitions.h8
-rw-r--r--Source/cmDependsC.cxx7
-rw-r--r--Source/cmDependsFortran.cxx17
-rw-r--r--Source/cmDependsJavaParserHelper.h2
-rw-r--r--Source/cmElseCommand.cxx14
-rw-r--r--Source/cmElseCommand.h45
-rw-r--r--Source/cmElseIfCommand.cxx13
-rw-r--r--Source/cmElseIfCommand.h45
-rw-r--r--Source/cmEndForEachCommand.cxx15
-rw-r--r--Source/cmEndForEachCommand.h56
-rw-r--r--Source/cmEndFunctionCommand.cxx15
-rw-r--r--Source/cmEndFunctionCommand.h56
-rw-r--r--Source/cmEndIfCommand.cxx24
-rw-r--r--Source/cmEndIfCommand.h45
-rw-r--r--Source/cmEndMacroCommand.cxx15
-rw-r--r--Source/cmEndMacroCommand.h56
-rw-r--r--Source/cmEndWhileCommand.cxx22
-rw-r--r--Source/cmEndWhileCommand.h56
-rw-r--r--Source/cmExecProgramCommand.cxx16
-rw-r--r--Source/cmExecProgramCommand.h5
-rw-r--r--Source/cmExecuteProcessCommand.cxx32
-rw-r--r--Source/cmExecutionStatus.h4
-rw-r--r--Source/cmExpandedCommandArgument.h4
-rw-r--r--Source/cmExportBuildAndroidMKGenerator.cxx18
-rw-r--r--Source/cmExportBuildAndroidMKGenerator.h10
-rw-r--r--Source/cmExportInstallAndroidMKGenerator.cxx13
-rw-r--r--Source/cmExportInstallAndroidMKGenerator.h10
-rw-r--r--Source/cmExtraCodeBlocksGenerator.cxx11
-rw-r--r--Source/cmExtraEclipseCDT4Generator.cxx25
-rw-r--r--Source/cmExtraSublimeTextGenerator.cxx48
-rw-r--r--Source/cmExtraSublimeTextGenerator.h1
-rw-r--r--Source/cmFLTKWrapUICommand.cxx4
-rw-r--r--Source/cmFileCommand.cxx57
-rw-r--r--Source/cmFileMonitor.cxx9
-rw-r--r--Source/cmFileMonitor.h2
-rw-r--r--Source/cmFilePathUuid.cxx4
-rw-r--r--Source/cmFileTimeComparison.cxx1
-rw-r--r--Source/cmFindBase.cxx6
-rw-r--r--Source/cmFindBase.h5
-rw-r--r--Source/cmFindCommon.cxx7
-rw-r--r--Source/cmFindCommon.h9
-rw-r--r--Source/cmFunctionBlocker.h7
-rw-r--r--Source/cmFunctionCommand.cxx1
-rw-r--r--Source/cmGeneratedFileStream.cxx5
-rw-r--r--Source/cmGeneratorExpression.cxx7
-rw-r--r--Source/cmGeneratorExpressionEvaluationFile.cxx11
-rw-r--r--Source/cmGeneratorExpressionEvaluationFile.h13
-rw-r--r--Source/cmGeneratorTarget.cxx37
-rw-r--r--Source/cmGeneratorTarget.h4
-rw-r--r--Source/cmGetCMakePropertyCommand.cxx1
-rw-r--r--Source/cmGhsMultiGpj.h2
-rw-r--r--Source/cmGlobalBorlandMakefileGenerator.cxx1
-rw-r--r--Source/cmGlobalGenerator.cxx54
-rw-r--r--Source/cmGlobalGenerator.h22
-rw-r--r--Source/cmGlobalGeneratorFactory.h7
-rw-r--r--Source/cmGlobalGhsMultiGenerator.cxx6
-rw-r--r--Source/cmGlobalJOMMakefileGenerator.cxx1
-rw-r--r--Source/cmGlobalMSYSMakefileGenerator.cxx4
-rw-r--r--Source/cmGlobalMinGWMakefileGenerator.cxx1
-rw-r--r--Source/cmGlobalNMakeMakefileGenerator.cxx1
-rw-r--r--Source/cmGlobalNinjaGenerator.cxx33
-rw-r--r--Source/cmGlobalNinjaGenerator.h25
-rw-r--r--Source/cmGlobalUnixMakefileGenerator3.cxx13
-rw-r--r--Source/cmGlobalUnixMakefileGenerator3.h10
-rw-r--r--Source/cmGlobalVisualStudio10Generator.cxx14
-rw-r--r--Source/cmGlobalVisualStudio10Generator.h2
-rw-r--r--Source/cmGlobalVisualStudio11Generator.cxx3
-rw-r--r--Source/cmGlobalVisualStudio11Generator.h11
-rw-r--r--Source/cmGlobalVisualStudio12Generator.cxx3
-rw-r--r--Source/cmGlobalVisualStudio12Generator.h9
-rw-r--r--Source/cmGlobalVisualStudio14Generator.cxx3
-rw-r--r--Source/cmGlobalVisualStudio14Generator.h9
-rw-r--r--Source/cmGlobalVisualStudio15Generator.cxx14
-rw-r--r--Source/cmGlobalVisualStudio15Generator.h8
-rw-r--r--Source/cmGlobalVisualStudio71Generator.cxx3
-rw-r--r--Source/cmGlobalVisualStudio7Generator.cxx43
-rw-r--r--Source/cmGlobalVisualStudio8Generator.cxx10
-rw-r--r--Source/cmGlobalVisualStudio8Generator.h3
-rw-r--r--Source/cmGlobalVisualStudio9Generator.cxx3
-rw-r--r--Source/cmGlobalVisualStudioGenerator.cxx4
-rw-r--r--Source/cmGlobalVisualStudioGenerator.h15
-rw-r--r--Source/cmGlobalWatcomWMakeGenerator.cxx1
-rw-r--r--Source/cmGlobalXCodeGenerator.cxx63
-rw-r--r--Source/cmGlobalXCodeGenerator.h70
-rw-r--r--Source/cmGraphAdjacencyList.h4
-rw-r--r--Source/cmGraphVizWriter.cxx11
-rw-r--r--Source/cmHexFileConverter.cxx5
-rw-r--r--Source/cmHexFileConverter.h4
-rw-r--r--Source/cmIDEOptions.cxx7
-rw-r--r--Source/cmIDEOptions.h6
-rw-r--r--Source/cmIncludeCommand.cxx4
-rw-r--r--Source/cmInstallCommand.cxx3
-rw-r--r--Source/cmInstallCommandArguments.cxx2
-rw-r--r--Source/cmInstallCommandArguments.h5
-rw-r--r--Source/cmInstallTargetGenerator.cxx13
-rw-r--r--Source/cmLinkItem.h8
-rw-r--r--Source/cmLinkLineComputer.cxx5
-rw-r--r--Source/cmLinkLineComputer.h10
-rw-r--r--Source/cmLinkLineDeviceComputer.cxx74
-rw-r--r--Source/cmLinkLineDeviceComputer.h36
-rw-r--r--Source/cmLinkedTree.h4
-rw-r--r--Source/cmLoadCommandCommand.cxx8
-rw-r--r--Source/cmLocalCommonGenerator.cxx5
-rw-r--r--Source/cmLocalCommonGenerator.h5
-rw-r--r--Source/cmLocalGenerator.cxx35
-rw-r--r--Source/cmLocalGenerator.h19
-rw-r--r--Source/cmLocalNinjaGenerator.cxx23
-rw-r--r--Source/cmLocalNinjaGenerator.h10
-rw-r--r--Source/cmLocalUnixMakefileGenerator3.cxx26
-rw-r--r--Source/cmLocalVisualStudio10Generator.h7
-rw-r--r--Source/cmLocalVisualStudio7Generator.h17
-rw-r--r--Source/cmLocalVisualStudioGenerator.h16
-rw-r--r--Source/cmLocalXCodeGenerator.cxx5
-rw-r--r--Source/cmLocalXCodeGenerator.h9
-rw-r--r--Source/cmLocale.h2
-rw-r--r--Source/cmMSVC60LinkLineComputer.cxx6
-rw-r--r--Source/cmMSVC60LinkLineComputer.h7
-rw-r--r--Source/cmMachO.cxx6
-rw-r--r--Source/cmMachO.h5
-rw-r--r--Source/cmMacroCommand.cxx1
-rw-r--r--Source/cmMakefile.cxx31
-rw-r--r--Source/cmMakefile.h20
-rw-r--r--Source/cmMakefileExecutableTargetGenerator.cxx238
-rw-r--r--Source/cmMakefileExecutableTargetGenerator.h4
-rw-r--r--Source/cmMakefileLibraryTargetGenerator.cxx233
-rw-r--r--Source/cmMakefileLibraryTargetGenerator.h6
-rw-r--r--Source/cmMakefileTargetGenerator.cxx48
-rw-r--r--Source/cmMakefileTargetGenerator.h12
-rw-r--r--Source/cmMakefileUtilityTargetGenerator.cxx10
-rw-r--r--Source/cmMessageCommand.cxx2
-rw-r--r--Source/cmNinjaLinkLineComputer.cxx4
-rw-r--r--Source/cmNinjaLinkLineComputer.h7
-rw-r--r--Source/cmNinjaNormalTargetGenerator.cxx384
-rw-r--r--Source/cmNinjaNormalTargetGenerator.h10
-rw-r--r--Source/cmNinjaTargetGenerator.cxx44
-rw-r--r--Source/cmNinjaTypes.h6
-rw-r--r--Source/cmOptionCommand.cxx2
-rw-r--r--Source/cmOutputConverter.cxx11
-rw-r--r--Source/cmOutputConverter.h6
-rw-r--r--Source/cmOutputRequiredFilesCommand.cxx19
-rw-r--r--Source/cmParseArgumentsCommand.cxx1
-rw-r--r--Source/cmPathLabel.cxx2
-rw-r--r--Source/cmPathLabel.h4
-rw-r--r--Source/cmProcessOutput.cxx170
-rw-r--r--Source/cmProcessOutput.h88
-rw-r--r--Source/cmProcessTools.cxx23
-rw-r--r--Source/cmProcessTools.h5
-rw-r--r--Source/cmQtAutoGeneratorInitializer.cxx2
-rw-r--r--Source/cmQtAutoGenerators.cxx27
-rw-r--r--Source/cmRulePlaceholderExpander.cxx6
-rw-r--r--Source/cmRulePlaceholderExpander.h1
-rw-r--r--Source/cmSearchPath.cxx2
-rw-r--r--Source/cmSearchPath.h4
-rw-r--r--Source/cmServer.cxx1
-rw-r--r--Source/cmServerConnection.cxx1
-rw-r--r--Source/cmServerProtocol.cxx89
-rw-r--r--Source/cmServerProtocol.h24
-rw-r--r--Source/cmSetCommand.cxx1
-rw-r--r--Source/cmSetPropertyCommand.cxx2
-rw-r--r--Source/cmSourceFile.cxx5
-rw-r--r--Source/cmSourceGroupCommand.cxx2
-rw-r--r--Source/cmState.cxx16
-rw-r--r--Source/cmState.h15
-rw-r--r--Source/cmStateDirectory.cxx10
-rw-r--r--Source/cmStateDirectory.h3
-rw-r--r--Source/cmStatePrivate.h7
-rw-r--r--Source/cmStateSnapshot.cxx14
-rw-r--r--Source/cmStateSnapshot.h2
-rw-r--r--Source/cmStateTypes.h4
-rw-r--r--Source/cmStringCommand.cxx5
-rw-r--r--Source/cmSubdirCommand.cxx6
-rw-r--r--Source/cmSystemTools.cxx51
-rw-r--r--Source/cmSystemTools.h11
-rw-r--r--Source/cmTarget.cxx98
-rw-r--r--Source/cmTarget.h20
-rw-r--r--Source/cmTargetCompileFeaturesCommand.cxx1
-rw-r--r--Source/cmTargetCompileOptionsCommand.cxx1
-rw-r--r--Source/cmTargetDepend.h4
-rw-r--r--Source/cmTargetExport.h6
-rw-r--r--Source/cmTargetPropCommandBase.cxx3
-rw-r--r--Source/cmTargetPropCommandBase.h5
-rw-r--r--Source/cmTargetPropertyComputer.cxx16
-rw-r--r--Source/cmTargetPropertyComputer.h7
-rw-r--r--Source/cmTargetSourcesCommand.cxx1
-rw-r--r--Source/cmTest.cxx1
-rw-r--r--Source/cmTestGenerator.cxx9
-rw-r--r--Source/cmTimestamp.cxx8
-rw-r--r--Source/cmTimestamp.h4
-rw-r--r--Source/cmTryRunCommand.cxx5
-rw-r--r--Source/cmUnexpectedCommand.cxx22
-rw-r--r--Source/cmUnexpectedCommand.h40
-rw-r--r--Source/cmUseMangledMesaCommand.cxx2
-rw-r--r--Source/cmUuid.cxx31
-rw-r--r--Source/cmVS10CSharpFlagTable.h120
-rw-r--r--Source/cmVS11CSharpFlagTable.h120
-rw-r--r--Source/cmVS12CSharpFlagTable.h120
-rw-r--r--Source/cmVS140CLFlagTable.h2
-rw-r--r--Source/cmVS140CSharpFlagTable.h120
-rw-r--r--Source/cmVS141CLFlagTable.h1
-rw-r--r--Source/cmVS141CSharpFlagTable.h120
-rw-r--r--Source/cmVisualStudio10TargetGenerator.cxx220
-rw-r--r--Source/cmVisualStudio10TargetGenerator.h44
-rw-r--r--Source/cmVisualStudio10ToolsetOptions.cxx25
-rw-r--r--Source/cmVisualStudio10ToolsetOptions.h6
-rw-r--r--Source/cmVisualStudioGeneratorOptions.cxx6
-rw-r--r--Source/cmVisualStudioGeneratorOptions.h10
-rw-r--r--Source/cmVisualStudioSlnData.h4
-rw-r--r--Source/cmVisualStudioSlnParser.h6
-rw-r--r--Source/cmVisualStudioWCEPlatformParser.h5
-rw-r--r--Source/cmWriteFileCommand.cxx2
-rw-r--r--Source/cmXCode21Object.cxx3
-rw-r--r--Source/cmXCode21Object.h5
-rw-r--r--Source/cmXCodeObject.cxx5
-rw-r--r--Source/cmXCodeObject.h9
-rw-r--r--Source/cm_codecvt.hxx3
-rw-r--r--Source/cm_sha2.c1613
-rw-r--r--Source/cm_sha2.h140
-rw-r--r--Source/cm_sha2_mangle.h42
-rw-r--r--Source/cmake.cxx71
-rw-r--r--Source/cmake.h18
-rw-r--r--Source/cmakemain.cxx5
-rw-r--r--Source/cmakexbuild.cxx9
-rw-r--r--Source/cmcmd.cxx25
-rw-r--r--Source/ctest.cxx2
-rw-r--r--Source/kwsys/Base64.c218
-rw-r--r--Source/kwsys/Base64.h.in82
-rw-r--r--Source/kwsys/CMakeLists.txt28
-rw-r--r--Source/kwsys/CONTRIBUTING.rst13
-rw-r--r--Source/kwsys/CTestConfig.cmake14
-rw-r--r--Source/kwsys/CommandLineArguments.cxx786
-rw-r--r--Source/kwsys/CommandLineArguments.hxx.in133
-rw-r--r--Source/kwsys/Configure.h.in167
-rw-r--r--Source/kwsys/Configure.hxx.in29
-rw-r--r--Source/kwsys/ConsoleBuf.hxx.in659
-rw-r--r--Source/kwsys/Copyright.txt17
-rw-r--r--Source/kwsys/Directory.cxx140
-rw-r--r--Source/kwsys/Directory.hxx.in23
-rw-r--r--Source/kwsys/DynamicLoader.cxx229
-rw-r--r--Source/kwsys/DynamicLoader.hxx.in43
-rw-r--r--Source/kwsys/Encoding.h.in58
-rw-r--r--Source/kwsys/Encoding.hxx.in72
-rw-r--r--Source/kwsys/EncodingC.c53
-rw-r--r--Source/kwsys/EncodingCXX.cxx110
-rw-r--r--Source/kwsys/FStream.cxx67
-rw-r--r--Source/kwsys/FStream.hxx.in428
-rw-r--r--Source/kwsys/Glob.cxx416
-rw-r--r--Source/kwsys/Glob.hxx.in64
-rw-r--r--Source/kwsys/IOStream.cxx245
-rw-r--r--Source/kwsys/IOStream.hxx.in136
-rw-r--r--Source/kwsys/MD5.c523
-rw-r--r--Source/kwsys/MD5.h.in64
-rw-r--r--Source/kwsys/Process.h.in260
-rw-r--r--Source/kwsys/ProcessUNIX.c2078
-rw-r--r--Source/kwsys/ProcessWin32.c1837
-rw-r--r--Source/kwsys/RegularExpression.cxx1666
-rw-r--r--Source/kwsys/RegularExpression.hxx.in148
-rw-r--r--Source/kwsys/SharedForward.h.in604
-rw-r--r--Source/kwsys/String.c97
-rw-r--r--Source/kwsys/String.h.in36
-rw-r--r--Source/kwsys/String.hxx.in62
-rw-r--r--Source/kwsys/System.c221
-rw-r--r--Source/kwsys/System.h.in32
-rw-r--r--Source/kwsys/SystemInformation.cxx4306
-rw-r--r--Source/kwsys/SystemInformation.hxx.in61
-rw-r--r--Source/kwsys/SystemTools.cxx3905
-rw-r--r--Source/kwsys/SystemTools.hxx.in294
-rw-r--r--Source/kwsys/Terminal.c317
-rw-r--r--Source/kwsys/Terminal.h.in191
-rw-r--r--Source/kwsys/hash_fun.hxx.in89
-rw-r--r--Source/kwsys/hash_map.hxx.in246
-rw-r--r--Source/kwsys/hash_set.hxx.in217
-rw-r--r--Source/kwsys/hashtable.hxx.in486
-rwxr-xr-xSource/kwsys/kwsysHeaderDump.pl13
-rw-r--r--Source/kwsys/kwsysPlatformTests.cmake14
-rw-r--r--Source/kwsys/kwsysPlatformTestsC.c52
-rw-r--r--Source/kwsys/kwsysPlatformTestsCXX.cxx147
-rw-r--r--Source/kwsys/kwsysPrivate.h19
-rw-r--r--Source/kwsys/testCommandLineArguments.cxx201
-rw-r--r--Source/kwsys/testCommandLineArguments1.cxx83
-rw-r--r--Source/kwsys/testConsoleBuf.cxx412
-rw-r--r--Source/kwsys/testConsoleBuf.hxx20
-rw-r--r--Source/kwsys/testConsoleBufChild.cxx18
-rw-r--r--Source/kwsys/testDynamicLoader.cxx89
-rw-r--r--Source/kwsys/testDynload.c15
-rw-r--r--Source/kwsys/testEncode.c31
-rw-r--r--Source/kwsys/testEncoding.cxx130
-rw-r--r--Source/kwsys/testFStream.cxx114
-rw-r--r--Source/kwsys/testFail.c31
-rw-r--r--Source/kwsys/testHashSTL.cxx37
-rw-r--r--Source/kwsys/testIOS.cxx153
-rw-r--r--Source/kwsys/testProcess.c454
-rw-r--r--Source/kwsys/testSharedForward.c.in27
-rw-r--r--Source/kwsys/testSystemInformation.cxx67
-rw-r--r--Source/kwsys/testSystemTools.cxx1128
-rw-r--r--Source/kwsys/testSystemTools.h.in13
-rw-r--r--Source/kwsys/testTerminal.c19
-rw-r--r--Tests/CMakeLib/CMakeLists.txt3
-rw-r--r--Tests/CMakeLib/run_compile_commands.cxx4
-rw-r--r--Tests/CMakeLib/testEncoding.cxx49
-rw-r--r--Tests/CMakeLib/testFindPackageCommand.cxx6
-rw-r--r--Tests/CMakeLib/testSystemTools.cxx7
-rw-r--r--Tests/CMakeLib/testXMLSafe.cxx5
-rw-r--r--Tests/CMakeLists.txt27
-rw-r--r--Tests/CMakeTests/File-SHA3_224-Works.cmake2
-rw-r--r--Tests/CMakeTests/File-SHA3_256-Works.cmake2
-rw-r--r--Tests/CMakeTests/File-SHA3_384-Works.cmake2
-rw-r--r--Tests/CMakeTests/File-SHA3_512-Works.cmake2
-rw-r--r--Tests/CMakeTests/FileTest.cmake.in12
-rw-r--r--Tests/CMakeTests/String-SHA3_224-Works.cmake2
-rw-r--r--Tests/CMakeTests/String-SHA3_256-Works.cmake2
-rw-r--r--Tests/CMakeTests/String-SHA3_384-Works.cmake2
-rw-r--r--Tests/CMakeTests/String-SHA3_512-Works.cmake2
-rw-r--r--Tests/CMakeTests/StringTest.cmake.in12
-rw-r--r--Tests/CompileFeatures/CMakeLists.txt19
-rw-r--r--Tests/Cuda/CMakeLists.txt4
-rw-r--r--Tests/Cuda/Complex/CMakeLists.txt40
-rw-r--r--Tests/Cuda/Complex/dynamic.cpp5
-rw-r--r--Tests/Cuda/Complex/dynamic.cu29
-rw-r--r--Tests/Cuda/Complex/file1.cu10
-rw-r--r--Tests/Cuda/Complex/file1.h7
-rw-r--r--Tests/Cuda/Complex/file2.cu20
-rw-r--r--Tests/Cuda/Complex/file2.h10
-rw-r--r--Tests/Cuda/Complex/file3.cu25
-rw-r--r--Tests/Cuda/Complex/main.cpp14
-rw-r--r--Tests/Cuda/Complex/mixed.cpp14
-rw-r--r--Tests/Cuda/Complex/mixed.cu25
-rw-r--r--Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt17
-rw-r--r--Tests/Cuda/ConsumeCompileFeatures/main.cu18
-rw-r--r--Tests/Cuda/ConsumeCompileFeatures/static.cpp10
-rw-r--r--Tests/Cuda/ConsumeCompileFeatures/static.cu9
-rw-r--r--Tests/Cuda/ObjectLibrary/CMakeLists.txt12
-rw-r--r--Tests/Cuda/ObjectLibrary/main.cpp20
-rw-r--r--Tests/Cuda/ObjectLibrary/static.cpp6
-rw-r--r--Tests/Cuda/ObjectLibrary/static.cu21
-rw-r--r--Tests/CudaOnly/CMakeLists.txt4
-rw-r--r--Tests/CudaOnly/EnableStandard/CMakeLists.txt15
-rw-r--r--Tests/CudaOnly/EnableStandard/main.cu17
-rw-r--r--Tests/CudaOnly/EnableStandard/shared.cu9
-rw-r--r--Tests/CudaOnly/EnableStandard/static.cu9
-rw-r--r--Tests/CudaOnly/SeparateCompilation/CMakeLists.txt33
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file1.cu10
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file1.h7
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file2.cu20
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file2.h10
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file3.cu25
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file4.cu25
-rw-r--r--Tests/CudaOnly/SeparateCompilation/file5.cu25
-rw-r--r--Tests/CudaOnly/SeparateCompilation/main.cu15
-rw-r--r--Tests/CudaOnly/WithDefs/CMakeLists.txt31
-rw-r--r--Tests/CudaOnly/WithDefs/main.notcu46
-rw-r--r--Tests/ExternalProject/CMakeLists.txt17
-rw-r--r--Tests/ExternalProjectLocal/CMakeLists.txt1
-rw-r--r--Tests/FindLibRHash/CMakeLists.txt10
-rw-r--r--Tests/FindLibRHash/Test/CMakeLists.txt17
-rw-r--r--Tests/FindLibRHash/Test/main.c7
-rw-r--r--Tests/IncludeDirectories/CMakeLists.txt4
-rw-r--r--Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt15
-rw-r--r--Tests/InterfaceLibrary/CMakeLists.txt20
-rw-r--r--Tests/InterfaceLibrary/definetestexe.cpp3
-rw-r--r--Tests/InterfaceLibrary/item.cpp4
-rw-r--r--Tests/InterfaceLibrary/item_fake.cpp5
-rw-r--r--Tests/Module/ExternalData/SHA3_256/.gitattributes1
-rw-r--r--Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e2311
-rw-r--r--Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-2561
-rw-r--r--Tests/QtAutogen/CMakeLists.txt132
-rw-r--r--Tests/QtAutogen/complex/Adir/CMakeLists.txt (renamed from Tests/QtAutogen/Adir/CMakeLists.txt)0
-rw-r--r--Tests/QtAutogen/complex/Adir/libA.cpp (renamed from Tests/QtAutogen/Adir/libA.cpp)0
-rw-r--r--Tests/QtAutogen/complex/Adir/libA.h (renamed from Tests/QtAutogen/Adir/libA.h)0
-rw-r--r--Tests/QtAutogen/complex/Bdir/CMakeLists.txt (renamed from Tests/QtAutogen/Bdir/CMakeLists.txt)0
-rw-r--r--Tests/QtAutogen/complex/Bdir/libB.cpp (renamed from Tests/QtAutogen/Bdir/libB.cpp)0
-rw-r--r--Tests/QtAutogen/complex/Bdir/libB.h (renamed from Tests/QtAutogen/Bdir/libB.h)0
-rw-r--r--Tests/QtAutogen/complex/CMakeLists.txt81
-rw-r--r--Tests/QtAutogen/complex/abc.cpp (renamed from Tests/QtAutogen/abc.cpp)0
-rw-r--r--Tests/QtAutogen/complex/abc.h (renamed from Tests/QtAutogen/abc.h)0
-rw-r--r--Tests/QtAutogen/complex/abc_p.h (renamed from Tests/QtAutogen/abc_p.h)0
-rw-r--r--Tests/QtAutogen/complex/bar.cpp (renamed from Tests/QtAutogen/bar.cpp)0
-rw-r--r--Tests/QtAutogen/complex/blub.cpp (renamed from Tests/QtAutogen/blub.cpp)0
-rw-r--r--Tests/QtAutogen/complex/blub.h (renamed from Tests/QtAutogen/blub.h)0
-rw-r--r--Tests/QtAutogen/complex/calwidget.cpp (renamed from Tests/QtAutogen/calwidget.cpp)0
-rw-r--r--Tests/QtAutogen/complex/calwidget.h (renamed from Tests/QtAutogen/calwidget.h)0
-rw-r--r--Tests/QtAutogen/complex/calwidget.ui (renamed from Tests/QtAutogen/calwidget.ui)0
-rw-r--r--Tests/QtAutogen/complex/codeeditor.cpp (renamed from Tests/QtAutogen/codeeditor.cpp)0
-rw-r--r--Tests/QtAutogen/complex/codeeditor.h (renamed from Tests/QtAutogen/codeeditor.h)0
-rw-r--r--Tests/QtAutogen/complex/debug_class.cpp (renamed from Tests/QtAutogen/debug_class.cpp)0
-rw-r--r--Tests/QtAutogen/complex/debug_class.h (renamed from Tests/QtAutogen/debug_class.h)0
-rw-r--r--Tests/QtAutogen/complex/debug_class.ui (renamed from Tests/QtAutogen/debug_class.ui)0
-rw-r--r--Tests/QtAutogen/complex/debug_resource.qrc (renamed from Tests/QtAutogen/debug_resource.qrc)0
-rw-r--r--Tests/QtAutogen/complex/foo.cpp (renamed from Tests/QtAutogen/foo.cpp)0
-rw-r--r--Tests/QtAutogen/complex/foo.h (renamed from Tests/QtAutogen/foo.h)0
-rw-r--r--Tests/QtAutogen/complex/gadget.cpp (renamed from Tests/QtAutogen/gadget.cpp)0
-rw-r--r--Tests/QtAutogen/complex/gadget.h (renamed from Tests/QtAutogen/gadget.h)0
-rw-r--r--Tests/QtAutogen/complex/generated.cpp (renamed from Tests/QtAutogen/generated.cpp)0
-rw-r--r--Tests/QtAutogen/complex/generated.h (renamed from Tests/QtAutogen/generated.h)0
-rw-r--r--Tests/QtAutogen/complex/generated.txt.in (renamed from Tests/QtAutogen/generated.txt.in)0
-rw-r--r--Tests/QtAutogen/complex/generated_resource.qrc.in (renamed from Tests/QtAutogen/generated_resource.qrc.in)0
-rw-r--r--Tests/QtAutogen/complex/libC.cpp (renamed from Tests/QtAutogen/libC.cpp)0
-rw-r--r--Tests/QtAutogen/complex/libC.h (renamed from Tests/QtAutogen/libC.h)0
-rw-r--r--Tests/QtAutogen/complex/main.cpp (renamed from Tests/QtAutogen/main.cpp)0
-rw-r--r--Tests/QtAutogen/complex/multiplewidgets.cpp (renamed from Tests/QtAutogen/multiplewidgets.cpp)0
-rw-r--r--Tests/QtAutogen/complex/multiplewidgets.h (renamed from Tests/QtAutogen/multiplewidgets.h)0
-rw-r--r--Tests/QtAutogen/complex/myinterface.h.in (renamed from Tests/QtAutogen/myinterface.h.in)0
-rw-r--r--Tests/QtAutogen/complex/myotherinterface.h.in (renamed from Tests/QtAutogen/myotherinterface.h.in)0
-rw-r--r--Tests/QtAutogen/complex/private_slot.cpp (renamed from Tests/QtAutogen/private_slot.cpp)0
-rw-r--r--Tests/QtAutogen/complex/private_slot.h (renamed from Tests/QtAutogen/private_slot.h)0
-rw-r--r--Tests/QtAutogen/complex/resourcetester.cpp (renamed from Tests/QtAutogen/resourcetester.cpp)0
-rw-r--r--Tests/QtAutogen/complex/resourcetester.h (renamed from Tests/QtAutogen/resourcetester.h)0
-rw-r--r--Tests/QtAutogen/complex/second_resource.qrc (renamed from Tests/QtAutogen/second_resource.qrc)0
-rw-r--r--Tests/QtAutogen/complex/second_widget.cpp (renamed from Tests/QtAutogen/second_widget.cpp)0
-rw-r--r--Tests/QtAutogen/complex/second_widget.h (renamed from Tests/QtAutogen/second_widget.h)0
-rw-r--r--Tests/QtAutogen/complex/second_widget.ui (renamed from Tests/QtAutogen/second_widget.ui)0
-rw-r--r--Tests/QtAutogen/complex/sub/bar.h (renamed from Tests/QtAutogen/sub/bar.h)0
-rw-r--r--Tests/QtAutogen/complex/targetObjectsTest.cpp (renamed from Tests/QtAutogen/targetObjectsTest.cpp)0
-rw-r--r--Tests/QtAutogen/complex/test.qrc (renamed from Tests/QtAutogen/test.qrc)0
-rw-r--r--Tests/QtAutogen/complex/widget1.ui (renamed from Tests/QtAutogen/widget1.ui)0
-rw-r--r--Tests/QtAutogen/complex/widget2.ui (renamed from Tests/QtAutogen/widget2.ui)0
-rw-r--r--Tests/QtAutogen/complex/xyz.cpp (renamed from Tests/QtAutogen/xyz.cpp)0
-rw-r--r--Tests/QtAutogen/complex/xyz.h (renamed from Tests/QtAutogen/xyz.h)0
-rw-r--r--Tests/QtAutogen/complex/yaf.cpp (renamed from Tests/QtAutogen/yaf.cpp)0
-rw-r--r--Tests/QtAutogen/complex/yaf.h (renamed from Tests/QtAutogen/yaf.h)0
-rw-r--r--Tests/QtAutogen/complex/yaf_p.h (renamed from Tests/QtAutogen/yaf_p.h)0
-rw-r--r--Tests/QtAutogen/rccEmpty.cpp (renamed from Tests/QtAutogen/rcconly.cpp)4
-rw-r--r--Tests/QtAutogen/rccEmptyRes.qrc (renamed from Tests/QtAutogen/rcc_empty_resource.qrc)0
-rw-r--r--Tests/QtAutogen/rccOnly.cpp (renamed from Tests/QtAutogen/rcc_empty.cpp)4
-rw-r--r--Tests/QtAutogen/rccOnlyRes.qrc5
-rw-r--r--Tests/QtAutogen/uicOnlySource/uiconly.cpp (renamed from Tests/QtAutogen/sub/uiconly.cpp)0
-rw-r--r--Tests/QtAutogen/uicOnlySource/uiconly.h (renamed from Tests/QtAutogen/sub/uiconly.h)0
-rw-r--r--Tests/QtAutogen/uicOnlySource/uiconly.ui (renamed from Tests/QtAutogen/sub/uiconly.ui)0
-rw-r--r--Tests/RunCMake/Android/common.cmake34
-rw-r--r--Tests/RunCMake/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/CPack/CMakeLists.txt13
-rw-r--r--Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake5
-rw-r--r--Tests/RunCMake/CPack/CPackTestHelpers.cmake47
-rw-r--r--Tests/RunCMake/CPack/CUSTOM_NAMES.cmake7
-rw-r--r--Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake9
-rw-r--r--Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake6
-rw-r--r--Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake9
-rw-r--r--Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake14
-rw-r--r--Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake34
-rw-r--r--Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake23
-rw-r--r--Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake2
-rw-r--r--Tests/RunCMake/CPack/DEB/Helpers.cmake43
-rw-r--r--Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake3
-rw-r--r--Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake2
-rw-r--r--Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake9
-rw-r--r--Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake18
-rw-r--r--Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake7
-rw-r--r--Tests/RunCMake/CPack/DEB/Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/DEB/packaging_COMPONENT_default.cmake (renamed from Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake)3
-rw-r--r--Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake1
-rw-r--r--Tests/RunCMake/CPack/DEPENDENCIES.cmake20
-rw-r--r--Tests/RunCMake/CPack/EMPTY_DIR.cmake4
-rw-r--r--Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake5
-rw-r--r--Tests/RunCMake/CPack/README.txt168
-rw-r--r--Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake9
-rw-r--r--Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt3
-rw-r--r--Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake14
-rw-r--r--Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt3
-rw-r--r--Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake13
-rw-r--r--Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake45
-rw-r--r--Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake22
-rw-r--r--Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/Helpers.cmake53
-rw-r--r--Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake7
-rw-r--r--Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake19
-rw-r--r--Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-ExpectedFiles.cmake13
-rw-r--r--Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-found-stderr.txt3
-rw-r--r--Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake9
-rw-r--r--Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake18
-rw-r--r--Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_components-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_debuginfo-stderr.txt3
-rw-r--r--Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_main-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_no_debuginfo-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-valid-stderr.txt3
-rw-r--r--Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/RPM/default_expected_stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake1
-rw-r--r--Tests/RunCMake/CPack/RunCMakeTest.cmake38
-rw-r--r--Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake3
-rw-r--r--Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake3
-rw-r--r--Tests/RunCMake/CPack/TGZ/Helpers.cmake52
-rw-r--r--Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake9
-rw-r--r--Tests/RunCMake/CPack/TGZ/packaging_COMPONENT_default.cmake (renamed from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake)0
-rw-r--r--Tests/RunCMake/CPack/VerifyResult.cmake65
-rw-r--r--Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake12
-rw-r--r--Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake14
-rw-r--r--Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake16
-rw-r--r--Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake (renamed from Tests/RunCMake/CPack/DEBUGINFO.cmake)4
-rw-r--r--Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake18
-rw-r--r--Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake82
-rw-r--r--Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake60
-rw-r--r--Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/RPM/RPM_DIST-VerifyResult.cmake)0
-rw-r--r--Tests/RunCMake/CPack/tests/DIST/test.cmake (renamed from Tests/RunCMake/CPack/RPM_DIST.cmake)1
-rw-r--r--Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake7
-rw-r--r--Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake14
-rw-r--r--Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake8
-rw-r--r--Tests/RunCMake/CPack/tests/EXTRA/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/DEB/DEB_EXTRA-VerifyResult.cmake)0
-rw-r--r--Tests/RunCMake/CPack/tests/EXTRA/test.cmake (renamed from Tests/RunCMake/CPack/DEB_EXTRA.cmake)4
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/ExpectedFiles.cmake (renamed from Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-VerifyResult.cmake)0
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/test.cmake (renamed from Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake)4
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake (renamed from Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-VerifyResult.cmake)0
-rw-r--r--Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/test.cmake (renamed from Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake)4
-rw-r--r--Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake5
-rw-r--r--Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-VerifyResult.cmake)0
-rw-r--r--Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/test.cmake (renamed from Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake)22
-rw-r--r--Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake7
-rw-r--r--Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake3
-rw-r--r--Tests/RunCMake/CPack/tests/LONG_FILENAMES/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake)0
-rw-r--r--Tests/RunCMake/CPack/tests/LONG_FILENAMES/test.cmake (renamed from Tests/RunCMake/CPack/LONG_FILENAMES.cmake)7
-rw-r--r--Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake11
-rw-r--r--Tests/RunCMake/CPack/tests/MAIN_COMPONENT/RPM-invalid-stderr.txt (renamed from Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-invalid-stderr.txt)0
-rw-r--r--Tests/RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake (renamed from Tests/RunCMake/CPack/MAIN_COMPONENT.cmake)4
-rw-r--r--Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/MINIMAL/test.cmake (renamed from Tests/RunCMake/CPack/MINIMAL.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake6
-rw-r--r--Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/TGZ-invalid-stderr.txt (renamed from Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt)0
-rw-r--r--Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/test.cmake (renamed from Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake)1
-rw-r--r--Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/RPM-stderr.txt (renamed from Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-stderr.txt)0
-rw-r--r--Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake (renamed from Tests/RunCMake/CPack/PARTIALLY_RELOCATABLE_WARNING.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake8
-rw-r--r--Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake26
-rw-r--r--Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake18
-rw-r--r--Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake (renamed from Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-ExpectedFiles.cmake)14
-rw-r--r--Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/RPM-no_main_component-stderr.txt (renamed from Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_main_component-stderr.txt)0
-rw-r--r--Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/test.cmake (renamed from Tests/RunCMake/CPack/SINGLE_DEBUGINFO.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake (renamed from Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake (renamed from Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake)2
-rw-r--r--Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake31
-rw-r--r--Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake3
-rw-r--r--Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/ClangTidy/C-bad-Build-result.txt1
-rw-r--r--Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt2
-rw-r--r--Tests/RunCMake/ClangTidy/C-bad.cmake3
-rw-r--r--Tests/RunCMake/ClangTidy/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake4
-rw-r--r--Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake2
-rw-r--r--Tests/RunCMake/Configure/RemoveCache-stdout.txt1
-rw-r--r--Tests/RunCMake/Configure/RemoveCache.cmake17
-rw-r--r--Tests/RunCMake/Configure/RunCMakeTest.cmake9
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake17
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake16
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx9
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx4
-rw-r--r--Tests/RunCMake/RunCMake.cmake2
-rw-r--r--Tests/RunCMake/RunCTest.cmake1
-rw-r--r--Tests/RunCMake/VS10Project/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/VS10Project/VsCustomProps-check.cmake25
-rw-r--r--Tests/RunCMake/VS10Project/VsCustomProps.cmake7
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake22
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake5
-rw-r--r--Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake45
-rw-r--r--Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake9
-rw-r--r--Tests/RunCMake/VS10Project/bar.cpp3
-rw-r--r--Tests/RunCMake/VS10Project/baz.cpp3
-rw-r--r--Tests/RunCMake/VS10Project/my.props5
-rw-r--r--Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake29
-rw-r--r--Tests/RunCMake/VSSolution/AddPackageToDefault.cmake2
-rw-r--r--Tests/RunCMake/VSSolution/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-result.txt1
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt3
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt4
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt4
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt4
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt4
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt4
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt1
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt8
-rw-r--r--Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt4
-rw-r--r--Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake31
-rw-r--r--Tests/RunCMake/ctest_memcheck/test.cmake.in4
-rw-r--r--Tests/RunCMake/execute_process/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/execute_process/Encoding.cmake6
-rw-r--r--Tests/RunCMake/execute_process/EncodingMissing-result.txt1
-rw-r--r--Tests/RunCMake/execute_process/EncodingMissing-stderr.txt4
-rw-r--r--Tests/RunCMake/execute_process/EncodingMissing.cmake1
-rw-r--r--Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt1
-rw-r--r--Tests/RunCMake/execute_process/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt1
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt44
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake6
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt1
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt45
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake17
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt1
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt21
-rw-r--r--Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake5
-rw-r--r--Tests/RunCMake/interface_library/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/pseudo_emulator_custom_command.c3
-rw-r--r--Tests/RunCMake/pseudo_iwyu.c3
-rw-r--r--Tests/RunCMake/pseudo_tidy.c6
-rw-r--r--Tests/RunCMake/try_compile/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/try_compile/WarnDeprecated.cmake19
-rw-r--r--Tests/RunCMake/while/EndAlone-stderr.txt2
-rw-r--r--Tests/SwigTest/CMakeLists.txt13
-rw-r--r--Utilities/CMakeLists.txt2
-rw-r--r--Utilities/KWStyle/CMake.kws.xml.in11
-rw-r--r--Utilities/KWStyle/CMakeFiles.txt.in15
-rw-r--r--Utilities/KWStyle/CMakeLists.txt69
-rw-r--r--Utilities/KWStyle/CMakeMoreChecks.kws.xml.in30
-rw-r--r--Utilities/KWStyle/CMakeOverwrite.txt0
-rw-r--r--Utilities/Release/linux64_release.cmake6
-rwxr-xr-xUtilities/Scripts/clang-format.bash2
-rwxr-xr-xUtilities/Scripts/update-librhash.bash45
-rw-r--r--Utilities/cmThirdParty.h.in1
-rw-r--r--Utilities/cm_rhash.h14
-rw-r--r--Utilities/cmlibarchive/libarchive/CMakeLists.txt2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_cryptor.c9
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_cryptor_private.h4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_digest.c74
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_digest_private.h14
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_hmac.c14
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_hmac_private.h4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_openssl_evp_private.h51
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h52
-rw-r--r--Utilities/cmlibrhash/.gitattributes1
-rw-r--r--Utilities/cmlibrhash/CMakeLists.txt40
-rw-r--r--Utilities/cmlibrhash/COPYING15
-rw-r--r--Utilities/cmlibrhash/README7
-rw-r--r--Utilities/cmlibrhash/librhash/algorithms.c220
-rw-r--r--Utilities/cmlibrhash/librhash/algorithms.h120
-rw-r--r--Utilities/cmlibrhash/librhash/byte_order.c150
-rw-r--r--Utilities/cmlibrhash/librhash/byte_order.h156
-rw-r--r--Utilities/cmlibrhash/librhash/hex.c188
-rw-r--r--Utilities/cmlibrhash/librhash/hex.h25
-rw-r--r--Utilities/cmlibrhash/librhash/md5.c236
-rw-r--r--Utilities/cmlibrhash/librhash/md5.h31
-rw-r--r--Utilities/cmlibrhash/librhash/rhash.c872
-rw-r--r--Utilities/cmlibrhash/librhash/rhash.h288
-rw-r--r--Utilities/cmlibrhash/librhash/sha1.c196
-rw-r--r--Utilities/cmlibrhash/librhash/sha1.h31
-rw-r--r--Utilities/cmlibrhash/librhash/sha256.c241
-rw-r--r--Utilities/cmlibrhash/librhash/sha256.h32
-rw-r--r--Utilities/cmlibrhash/librhash/sha3.c356
-rw-r--r--Utilities/cmlibrhash/librhash/sha3.h54
-rw-r--r--Utilities/cmlibrhash/librhash/sha512.c255
-rw-r--r--Utilities/cmlibrhash/librhash/sha512.h32
-rw-r--r--Utilities/cmlibrhash/librhash/ustd.h39
-rw-r--r--Utilities/cmlibrhash/librhash/util.h31
-rwxr-xr-xbootstrap18
922 files changed, 24001 insertions, 18758 deletions
diff --git a/Auxiliary/CMakeLists.txt b/Auxiliary/CMakeLists.txt
index 8eb74b7..53cf2c5 100644
--- a/Auxiliary/CMakeLists.txt
+++ b/Auxiliary/CMakeLists.txt
@@ -1,4 +1,4 @@
install(DIRECTORY vim/indent vim/syntax DESTINATION ${CMAKE_DATA_DIR}/editors/vim)
install(FILES cmake-mode.el DESTINATION ${CMAKE_DATA_DIR}/editors/emacs)
-install(FILES cmake.m4 DESTINATION share/aclocal)
+install(FILES cmake.m4 DESTINATION ${CMAKE_XDGDATA_DIR}/aclocal)
add_subdirectory (bash-completion)
diff --git a/Auxiliary/vim/syntax/cmake.vim b/Auxiliary/vim/syntax/cmake.vim
index 11b0fcb..fabf9c1 100644
--- a/Auxiliary/vim/syntax/cmake.vim
+++ b/Auxiliary/vim/syntax/cmake.vim
@@ -128,7 +128,7 @@ syn keyword cmakeKWctest_coverage
\ contained
syn keyword cmakeKWctest_memcheck
- \ APPEND BUILD END EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
+ \ APPEND BUILD DEFECT_COUNT END EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
\ contained
syn keyword cmakeKWctest_run_script
diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake
index fc042bc..ba858bd 100644
--- a/CMakeCPack.cmake
+++ b/CMakeCPack.cmake
@@ -54,6 +54,47 @@ if(${CPACK_SYSTEM_NAME} MATCHES Windows)
endif()
endif()
+# Advanced IFW configuration
+set(_cpifwrc CPACK_IFW_COMPONENT_GROUP_CMAKE_)
+set(_cpifwrcconf _CPACK_IFW_COMPONENT_GROUP_CMAKE)
+set(${_cpifwrcconf} "# CMake IFW configuration\n")
+macro(_cmifwarg DESCRIPTION TYPE NAME DEFAULT)
+ set(_var CMake_IFW_ROOT_COMPONENT_${NAME})
+ if(DEFINED ${_var})
+ set(${_var} ${${_var}} CACHE ${TYPE} ${DESCRIPTION})
+ mark_as_advanced(${_var})
+ elseif(NOT "${DEFAULT}" STREQUAL "")
+ set(${_var} ${DEFAULT})
+ endif()
+ if(DEFINED ${_var})
+ set(${_cpifwrcconf}
+ "${${_cpifwrcconf}} set(${_cpifwrc}${NAME}\n \"${${_var}}\")\n")
+ endif()
+endmacro()
+
+_cmifwarg("Package <Name> tag (domen-like)"
+ STRING NAME "")
+_cmifwarg("Package <DisplayName> tag"
+ STRING DISPLAY_NAME "")
+_cmifwarg("Package <Description> tag"
+ STRING DESCRIPTION "")
+_cmifwarg("Package <ReleaseDate> tag (keep empty to auto generate)"
+ STRING RELEASE_DATE "")
+_cmifwarg("Package <Default> tag (values: TRUE, FALSE, SCRIPT)"
+ STRING DEFAULT "")
+_cmifwarg("Package <Version> tag"
+ STRING VERSION
+ "${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATCH}")
+_cmifwarg("Package <Script> tag"
+ FILEPATH SCRIPT "${CMake_BINARY_DIR}/installscript.qs")
+_cmifwarg("Package <SortingPriority> tag"
+ STRING PRIORITY "100")
+_cmifwarg("Package <ForsedInstallation> tag"
+ STRING FORCED_INSTALLATION "")
+
+set(${_cpifwrc}LICENSES_DEFAULT
+ "${CPACK_PACKAGE_NAME} Copyright;${CPACK_RESOURCE_FILE_LICENSE}")
+
# Components
if(CMake_INSTALL_COMPONENTS)
set(_CPACK_IFW_COMPONENTS_ALL cmake ctest cpack)
@@ -103,20 +144,31 @@ if(CMake_INSTALL_COMPONENTS)
endif()
endif()
set(_CPACK_IFW_COMPONENTS_CONFIGURATION "
-# Components
-set(CPACK_COMPONENTS_ALL \"${_CPACK_IFW_COMPONENTS_ALL}\")
-set(CPACK_COMPONENTS_GROUPING IGNORE)
-")
+ # Components
+ set(CPACK_COMPONENTS_ALL \"${_CPACK_IFW_COMPONENTS_ALL}\")
+ set(CPACK_COMPONENTS_GROUPING IGNORE)
+ ")
else()
if(BUILD_QtDialog AND USE_LGPL)
- set(_CPACK_IFW_ADDITIONAL_LICENSES
- "\"LGPLv${USE_LGPL}\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt\"")
+ set(${_cpifwrc}LICENSES_DEFAULT
+ "${${_cpifwrc}LICENSES_DEFAULT};LGPLv${USE_LGPL};${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt")
endif()
endif()
+_cmifwarg("Package <Licenses> tag (pairs of <display_name> <file_path>)"
+ STRING LICENSES "${${_cpifwrc}LICENSES_DEFAULT}")
+
# Components scripts configuration
+if(CMake_INSTALL_COMPONENTS)
+ configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/CMake.qs.in"
+ "${CMake_BINARY_DIR}/installscript.qs" @ONLY
+ )
+else()
+ configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/installscript.qs.in"
+ "${CMake_BINARY_DIR}/installscript.qs" @ONLY
+ )
+endif()
foreach(_script
- CMake
CMake.Documentation.SphinxHTML
CMake.DeveloperReference.HTML)
configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/${_script}.qs.in"
@@ -137,17 +189,9 @@ if(${CMAKE_SYSTEM_NAME} MATCHES Windows)
set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/developer-reference/html/index.html\", \"@StartMenuDir@/CMake Developer Reference.lnk\");\n")
endif()
endif()
- configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/installscript.qs.in"
- "${CMake_BINARY_DIR}/installscript.qs" @ONLY
- )
install(FILES "${CMake_SOURCE_DIR}/Source/QtIFW/cmake.org.html"
DESTINATION "${CMAKE_DOC_DIR}"
)
- if(CMake_INSTALL_COMPONENTS)
- set(_CPACK_IFW_PACKAGE_SCRIPT "${CMake_BINARY_DIR}/CMake.qs")
- else()
- set(_CPACK_IFW_PACKAGE_SCRIPT "${CMake_BINARY_DIR}/installscript.qs")
- endif()
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES Linux)
@@ -155,8 +199,6 @@ if(${CMAKE_SYSTEM_NAME} MATCHES Linux)
set(CPACK_IFW_ADMIN_TARGET_DIRECTORY "@ApplicationsDir@/${CMAKE_PROJECT_NAME}")
endif()
-set(_CPACK_IFW_PACKAGE_VERSION ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATCH})
-
if(NOT DEFINED CPACK_PACKAGE_FILE_NAME)
# if the CPACK_PACKAGE_FILE_NAME is not defined by the cache
# default to source package - system, on cygwin system is not
diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in
index d7a33bc..99746b0 100644
--- a/CMakeCPackOptions.cmake.in
+++ b/CMakeCPackOptions.cmake.in
@@ -47,7 +47,7 @@ if(CPACK_GENERATOR MATCHES "IFW")
@_CPACK_IFW_COMPONENTS_CONFIGURATION@
# Unspecified
set(CPACK_IFW_COMPONENT_@_CPACK_IFW_COMPONENT_UNSPECIFIED_UNAME@_VERSION
- "@_CPACK_IFW_PACKAGE_VERSION@")
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
# Package configuration group
set(CPACK_IFW_PACKAGE_GROUP CMake)
@@ -59,13 +59,7 @@ if(CPACK_GENERATOR MATCHES "IFW")
"@CPACK_PACKAGE_NAME@")
set(CPACK_COMPONENT_GROUP_CMAKE_DESCRIPTION
"@CPACK_PACKAGE_DESCRIPTION_SUMMARY@")
- set(CPACK_IFW_COMPONENT_GROUP_CMAKE_VERSION
- "@_CPACK_IFW_PACKAGE_VERSION@")
- set(CPACK_IFW_COMPONENT_GROUP_CMAKE_LICENSES
- "@CPACK_PACKAGE_NAME@ Copyright" "@CPACK_RESOURCE_FILE_LICENSE@"
- @_CPACK_IFW_ADDITIONAL_LICENSES@)
- set(CPACK_IFW_COMPONENT_GROUP_CMAKE_SCRIPT "@_CPACK_IFW_PACKAGE_SCRIPT@")
- set(CPACK_IFW_COMPONENT_GROUP_CMAKE_PRIORITY 100)
+ @_CPACK_IFW_COMPONENT_GROUP_CMAKE@
# Tools
set(CPACK_COMPONENT_GROUP_TOOLS_DISPLAY_NAME "Command-Line Tools")
@@ -73,7 +67,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
"Command-Line Tools: cmake, ctest and cpack")
set(CPACK_COMPONENT_GROUP_TOOLS_PARENT_GROUP CMake)
set(CPACK_IFW_COMPONENT_GROUP_TOOLS_PRIORITY 90)
- set(CPACK_IFW_COMPONENT_GROUP_TOOLS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_GROUP_TOOLS_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CMAKE_DISPLAY_NAME "cmake")
set(CPACK_COMPONENT_CMAKE_DESCRIPTION
@@ -82,7 +77,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_CMAKE_GROUP Tools)
set(CPACK_IFW_COMPONENT_CMAKE_NAME "CMake")
set(CPACK_IFW_COMPONENT_CMAKE_PRIORITY 89)
- set(CPACK_IFW_COMPONENT_CMAKE_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CMAKE_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CTEST_DISPLAY_NAME "ctest")
set(CPACK_COMPONENT_CTEST_DESCRIPTION
@@ -91,7 +87,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_CTEST_GROUP Tools)
set(CPACK_IFW_COMPONENT_CTEST_NAME "CTest")
set(CPACK_IFW_COMPONENT_CTEST_PRIORITY 88)
- set(CPACK_IFW_COMPONENT_CTEST_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CTEST_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CPACK_DISPLAY_NAME "cpack")
set(CPACK_COMPONENT_CPACK_DESCRIPTION
@@ -100,7 +97,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_CPACK_GROUP Tools)
set(CPACK_IFW_COMPONENT_CPACK_NAME "CPack")
set(CPACK_IFW_COMPONENT_CPACK_PRIORITY 87)
- set(CPACK_IFW_COMPONENT_CPACK_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CPACK_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CMCLDEPS_DISPLAY_NAME "cmcldeps")
set(CPACK_COMPONENT_CMCLDEPS_DESCRIPTION
@@ -108,7 +106,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_CMCLDEPS_GROUP Tools)
set(CPACK_IFW_COMPONENT_CMCLDEPS_NAME "CMClDeps")
set(CPACK_IFW_COMPONENT_CMCLDEPS_PRIORITY 86)
- set(CPACK_IFW_COMPONENT_CMCLDEPS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CMCLDEPS_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CMAKEXBUILD_DISPLAY_NAME "cmakexbuild")
set(CPACK_COMPONENT_CMAKEXBUILD_DESCRIPTION
@@ -117,7 +116,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_CMAKEXBUILD_GROUP Tools)
set(CPACK_IFW_COMPONENT_CMAKEXBUILD_NAME "CMakeXBuild")
set(CPACK_IFW_COMPONENT_CMAKEXBUILD_PRIORITY 85)
- set(CPACK_IFW_COMPONENT_CMAKEXBUILD_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CMAKEXBUILD_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
# Dialogs
set(CPACK_COMPONENT_GROUP_DIALOGS_DISPLAY_NAME "Interactive Dialogs")
@@ -125,20 +125,23 @@ if(CPACK_GENERATOR MATCHES "IFW")
"Interactive Dialogs with Console and GUI interfaces")
set(CPACK_COMPONENT_GROUP_DIALOGS_PARENT_GROUP CMake)
set(CPACK_IFW_COMPONENT_GROUP_DIALOGS_PRIORITY 80)
- set(CPACK_IFW_COMPONENT_GROUP_DIALOGS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_GROUP_DIALOGS_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CMAKE-GUI_DISPLAY_NAME "cmake-gui")
set(CPACK_COMPONENT_CMAKE-GUI_GROUP Dialogs)
set(CPACK_IFW_COMPONENT_CMAKE-GUI_NAME "QtGUI")
set(CPACK_IFW_COMPONENT_CMAKE-GUI_SCRIPT
"@CMake_SOURCE_DIR@/Source/QtIFW/CMake.Dialogs.QtGUI.qs")
- set(CPACK_IFW_COMPONENT_CMAKE-GUI_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CMAKE-GUI_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
@_CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES@
set(CPACK_COMPONENT_CCMAKE_DISPLAY_NAME "ccmake")
set(CPACK_COMPONENT_CCMAKE_GROUP Dialogs)
set(CPACK_IFW_COMPONENT_CCMAKE_NAME "CursesGUI")
- set(CPACK_IFW_COMPONENT_CCMAKE_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CCMAKE_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
# Documentation
set(CPACK_COMPONENT_GROUP_DOCUMENTATION_DISPLAY_NAME "Documentation")
@@ -147,33 +150,36 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_GROUP_DOCUMENTATION_PARENT_GROUP CMake)
set(CPACK_IFW_COMPONENT_GROUP_DOCUMENTATION_PRIORITY 60)
set(CPACK_IFW_COMPONENT_GROUP_DOCUMENTATION_VERSION
- "@_CPACK_IFW_PACKAGE_VERSION@")
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_SPHINX-MAN_DISPLAY_NAME "man")
set(CPACK_COMPONENT_SPHINX-MAN_GROUP Documentation)
set(CPACK_COMPONENT_SPHINX-MAN_DISABLED TRUE)
set(CPACK_IFW_COMPONENT_SPHINX-MAN_NAME "SphinxMan")
- set(CPACK_IFW_COMPONENT_SPHINX-MAN_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_SPHINX-MAN_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_SPHINX-HTML_DISPLAY_NAME "HTML")
set(CPACK_COMPONENT_SPHINX-HTML_GROUP Documentation)
set(CPACK_IFW_COMPONENT_SPHINX-HTML_NAME "SphinxHTML")
set(CPACK_IFW_COMPONENT_SPHINX-HTML_SCRIPT
"@CMake_BINARY_DIR@/CMake.Documentation.SphinxHTML.qs")
- set(CPACK_IFW_COMPONENT_SPHINX-HTML_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_SPHINX-HTML_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_SPHINX-SINGLEHTML_DISPLAY_NAME "Single HTML")
set(CPACK_COMPONENT_SPHINX-SINGLEHTML_GROUP Documentation)
set(CPACK_COMPONENT_SPHINX-SINGLEHTML_DISABLED TRUE)
set(CPACK_IFW_COMPONENT_SPHINX-SINGLEHTML_NAME "SphinxSingleHTML")
set(CPACK_IFW_COMPONENT_SPHINX-SINGLEHTML_VERSION
- "@_CPACK_IFW_PACKAGE_VERSION@")
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_SPHINX-QTHELP_DISPLAY_NAME "Qt Compressed Help")
set(CPACK_COMPONENT_SPHINX-QTHELP_GROUP Documentation)
set(CPACK_COMPONENT_SPHINX-QTHELP_DISABLED TRUE)
set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_NAME "SphinxQtHelp")
- set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
# Developer Reference
set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_DISPLAY_NAME "Developer Reference")
@@ -182,7 +188,7 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_PARENT_GROUP CMake)
set(CPACK_IFW_COMPONENT_GROUP_DEVELOPERREFERENCE_PRIORITY 50)
set(CPACK_IFW_COMPONENT_GROUP_DEVELOPERREFERENCE_VERSION
- "@_CPACK_IFW_PACKAGE_VERSION@")
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_DISPLAY_NAME "HTML")
set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_GROUP DeveloperReference)
@@ -190,13 +196,15 @@ if(CPACK_GENERATOR MATCHES "IFW")
set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_NAME "HTML")
set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_SCRIPT
"@CMake_BINARY_DIR@/CMake.DeveloperReference.HTML.qs")
- set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_DISPLAY_NAME "Qt Compressed Help")
set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_GROUP DeveloperReference)
set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_DISABLED TRUE)
set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_NAME "QtHelp")
- set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+ set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_VERSION
+ "@CMake_IFW_ROOT_COMPONENT_VERSION@")
endif()
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1bc4b4e..7aa8010 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -66,12 +66,8 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
include(${CMake_SOURCE_DIR}/Source/Checks/cm_cxx_features.cmake)
endif()
-# option to set the internal encoding of CMake to UTF-8
-option(CMAKE_ENCODING_UTF8 "Use UTF-8 encoding internally." ON)
-mark_as_advanced(CMAKE_ENCODING_UTF8)
-if(CMAKE_ENCODING_UTF8)
- set(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_UTF8)
-endif()
+# set the internal encoding of CMake to UTF-8
+set(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_UTF8)
# option to use COMPONENT with install command
option(CMake_INSTALL_COMPONENTS "Using components when installing" OFF)
@@ -108,7 +104,7 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
# Allow the user to enable/disable all system utility library options by
# defining CMAKE_USE_SYSTEM_LIBRARIES or CMAKE_USE_SYSTEM_LIBRARY_${util}.
- set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA LIBUV ZLIB)
+ set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA LIBRHASH LIBUV ZLIB)
foreach(util ${UTILITIES})
if(NOT DEFINED CMAKE_USE_SYSTEM_LIBRARY_${util}
AND DEFINED CMAKE_USE_SYSTEM_LIBRARIES)
@@ -148,6 +144,7 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
"${CMAKE_USE_SYSTEM_LIBRARY_LIBLZMA}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
option(CMAKE_USE_SYSTEM_FORM "Use system-installed libform" "${CMAKE_USE_SYSTEM_LIBRARY_FORM}")
option(CMAKE_USE_SYSTEM_JSONCPP "Use system-installed jsoncpp" "${CMAKE_USE_SYSTEM_LIBRARY_JSONCPP}")
+ option(CMAKE_USE_SYSTEM_LIBRHASH "Use system-installed librhash" "${CMAKE_USE_SYSTEM_LIBRARY_LIBRHASH}")
option(CMAKE_USE_SYSTEM_LIBUV "Use system-installed libuv" "${CMAKE_USE_SYSTEM_LIBRARY_LIBUV}")
# For now use system KWIML only if explicitly requested rather
@@ -302,6 +299,23 @@ macro (CMAKE_BUILD_UTILITIES)
add_subdirectory(Utilities/KWIML)
endif()
+ if(CMAKE_USE_SYSTEM_LIBRHASH)
+ if(NOT CMAKE_VERSION VERSION_LESS 3.0)
+ find_package(LibRHash)
+ else()
+ message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBRHASH requires CMake >= 3.0")
+ endif()
+ if(NOT LibRHash_FOUND)
+ message(FATAL_ERROR
+ "CMAKE_USE_SYSTEM_LIBRHASH is ON but LibRHash is not found!")
+ endif()
+ set(CMAKE_LIBRHASH_LIBRARIES LibRHash::LibRHash)
+ else()
+ set(CMAKE_LIBRHASH_LIBRARIES cmlibrhash)
+ add_subdirectory(Utilities/cmlibrhash)
+ CMAKE_SET_TARGET_FOLDER(cmlibrhash "Utilities/3rdParty")
+ endif()
+
#---------------------------------------------------------------------
# Build zlib library for Curl, CMake, and CTest.
set(CMAKE_ZLIB_HEADER "cm_zlib.h")
diff --git a/CTestCustom.cmake.in b/CTestCustom.cmake.in
index 48dd3de..07a9fdb 100644
--- a/CTestCustom.cmake.in
+++ b/CTestCustom.cmake.in
@@ -17,7 +17,6 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"Utilities.cmbzip2."
"Source.CTest.Curl"
"Source.CursesDialog.form"
- "Source.cm_sha2.*warning.*cast increases required alignment of target type"
"Utilities.cmcurl"
"Utilities.cmexpat."
"Utilities.cmlibarchive"
@@ -84,7 +83,6 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"warning: Value stored to 'yytoken' is never read"
"index_encoder.c.241.2. warning: Value stored to .out_start. is never read"
"index.c.*warning: Access to field.*results in a dereference of a null pointer.*loaded from variable.*"
- "cm_sha2.*warning: Value stored to.*is never read"
"cmFortranLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
"testProcess.*warning: Dereference of null pointer .loaded from variable .invalidAddress.."
"liblzma/simple/x86.c:[0-9]+:[0-9]+: warning: The result of the '<<' expression is undefined"
diff --git a/Help/command/ctest_memcheck.rst b/Help/command/ctest_memcheck.rst
index 29bdf7d..a983d68 100644
--- a/Help/command/ctest_memcheck.rst
+++ b/Help/command/ctest_memcheck.rst
@@ -18,6 +18,7 @@ Perform the :ref:`CTest MemCheck Step` as a :ref:`Dashboard Client`.
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
+ [DEFECT_COUNT <defect-count-var>]
[QUIET]
)
@@ -26,4 +27,9 @@ Run tests with a dynamic analysis tool and store results in
``MemCheck.xml`` for submission with the :command:`ctest_submit`
command.
-The options are the same as those for the :command:`ctest_test` command.
+Most options are the same as those for the :command:`ctest_test` command.
+
+The options unique to this command are:
+
+``DEFECT_COUNT <defect-count-var>``
+ Store in the ``<defect-count-var>`` the number of defects found.
diff --git a/Help/command/execute_process.rst b/Help/command/execute_process.rst
index ca44b53..71233d9 100644
--- a/Help/command/execute_process.rst
+++ b/Help/command/execute_process.rst
@@ -18,9 +18,10 @@ Execute one or more child processes.
[OUTPUT_QUIET]
[ERROR_QUIET]
[OUTPUT_STRIP_TRAILING_WHITESPACE]
- [ERROR_STRIP_TRAILING_WHITESPACE])
+ [ERROR_STRIP_TRAILING_WHITESPACE]
+ [ENCODING <name>])
-Runs the given sequence of one or more commands with the standard
+Runs the given sequence of one or more commands in parallel with the standard
output of each process piped to the standard input of the next.
A single standard error pipe is used for all processes.
@@ -36,6 +37,9 @@ Options:
(Use the ``INPUT_*``, ``OUTPUT_*``, and ``ERROR_*`` options to
redirect stdin, stdout, and stderr.)
+ If a sequential execution of multiple commands is required, use multiple
+ :command:`execute_process` calls with a single ``COMMAND`` argument.
+
``WORKING_DIRECTORY``
The named directory will be set as the current working directory of
the child processes.
@@ -63,6 +67,14 @@ Options:
``OUTPUT_QUIET``, ``ERROR_QUIET``
The standard output or standard error results will be quietly ignored.
+``ENCODING <name>``
+ On Windows, the encoding that is used to decode output from the process.
+ Ignored on other platforms.
+ Valid encoding names are: ``AUTO`` (the default), ``NONE``, ``UTF8``,
+ ``ANSI`` and ``OEM``.
+ ``AUTO`` encoding means current active console's codepage will be used
+ or if that isn't available then ``ANSI`` codepage will be used.
+
If more than one ``OUTPUT_*`` or ``ERROR_*`` option is given for the
same pipe the precedence is not specified.
If no ``OUTPUT_*`` or ``ERROR_*`` options are given the output will
diff --git a/Help/command/file.rst b/Help/command/file.rst
index 77e9f62..3e669c2 100644
--- a/Help/command/file.rst
+++ b/Help/command/file.rst
@@ -83,10 +83,12 @@ from the input file.
::
- file(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512> <filename> <variable>)
+ file(<HASH> <filename> <variable>)
Compute a cryptographic hash of the content of ``<filename>`` and
-store it in a ``<variable>``.
+store it in a ``<variable>``. The supported ``<HASH>`` algorithm names
+are those listed by the :ref:`string(\<HASH\>) <Supported Hash Algorithms>`
+command.
------------------------------------------------------------------------------
@@ -153,7 +155,8 @@ Move a file or directory within a filesystem from ``<oldname>`` to
file(REMOVE_RECURSE [<files>...])
Remove the given files. The ``REMOVE_RECURSE`` mode will remove the given
-files and directories, also non-empty directories
+files and directories, also non-empty directories. No error is emitted if a
+given file does not exist.
------------------------------------------------------------------------------
@@ -233,8 +236,8 @@ Additional options to ``DOWNLOAD`` are:
``EXPECTED_HASH ALGO=<value>``
Verify that the downloaded content hash matches the expected value, where
- ``ALGO`` is one of ``MD5``, ``SHA1``, ``SHA224``, ``SHA256``, ``SHA384``, or
- ``SHA512``. If it does not match, the operation fails with an error.
+ ``ALGO`` is one of the algorithms supported by ``file(<HASH>)``.
+ If it does not match, the operation fails with an error.
``EXPECTED_MD5 <value>``
Historical short-hand for ``EXPECTED_HASH MD5=<value>``.
diff --git a/Help/command/string.rst b/Help/command/string.rst
index 8028333..77538f6 100644
--- a/Help/command/string.rst
+++ b/Help/command/string.rst
@@ -206,15 +206,38 @@ Comparison
Compare the strings and store true or false in the output variable.
+.. _`Supported Hash Algorithms`:
+
Hashing
^^^^^^^
::
- string(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512>
- <output variable> <input>)
+ string(<HASH> <output variable> <input>)
Compute a cryptographic hash of the input string.
+The supported ``<HASH>`` algorithm names are:
+
+``MD5``
+ Message-Digest Algorithm 5, RFC 1321.
+``SHA1``
+ US Secure Hash Algorithm 1, RFC 3174.
+``SHA224``
+ US Secure Hash Algorithms, RFC 4634.
+``SHA256``
+ US Secure Hash Algorithms, RFC 4634.
+``SHA384``
+ US Secure Hash Algorithms, RFC 4634.
+``SHA512``
+ US Secure Hash Algorithms, RFC 4634.
+``SHA3_224``
+ Keccak SHA-3.
+``SHA3_256``
+ Keccak SHA-3.
+``SHA3_384``
+ Keccak SHA-3.
+``SHA3_512``
+ Keccak SHA-3.
Generation
^^^^^^^^^^
diff --git a/Help/command/target_link_libraries.rst b/Help/command/target_link_libraries.rst
index 90b6575..30d69f2 100644
--- a/Help/command/target_link_libraries.rst
+++ b/Help/command/target_link_libraries.rst
@@ -53,6 +53,11 @@ Each ``<item>`` may be:
:ref:`usage requirement <Target Usage Requirements>`. This has the same
effect as passing the framework directory as an include directory.
+ On :ref:`Visual Studio Generators` for VS 2010 and above, library files
+ ending in ``.targets`` will be treated as MSBuild targets files and
+ imported into generated project files. This is not supported by other
+ generators.
+
* **A plain library name**: The generated link line will ask the linker
to search for the library (e.g. ``foo`` becomes ``-lfoo`` or ``foo.lib``).
diff --git a/Help/generator/Visual Studio 15.rst b/Help/generator/Visual Studio 15 2017.rst
index 2eb9052..a88f8bc 100644
--- a/Help/generator/Visual Studio 15.rst
+++ b/Help/generator/Visual Studio 15 2017.rst
@@ -1,7 +1,7 @@
-Visual Studio 15
-----------------
+Visual Studio 15 2017
+---------------------
-Generates Visual Studio 15 project files.
+Generates Visual Studio 15 (VS 2017) project files.
The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
to specify a target platform name (architecture).
@@ -9,16 +9,16 @@ to specify a target platform name (architecture).
For compatibility with CMake versions prior to 3.1, one may specify
a target platform name optionally at the end of this generator name:
-``Visual Studio 15 Win64``
+``Visual Studio 15 2017 Win64``
Specify target platform ``x64``.
-``Visual Studio 15 ARM``
+``Visual Studio 15 2017 ARM``
Specify target platform ``ARM``.
Toolset Selection
^^^^^^^^^^^^^^^^^
-The ``v141`` toolset that comes with Visual Studio 15 is selected by
+The ``v141`` toolset that comes with Visual Studio 15 2017 is selected by
default. The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
diff --git a/Help/manual/cmake-buildsystem.7.rst b/Help/manual/cmake-buildsystem.7.rst
index 4950fee..2e6a803 100644
--- a/Help/manual/cmake-buildsystem.7.rst
+++ b/Help/manual/cmake-buildsystem.7.rst
@@ -964,6 +964,8 @@ are:
* ``EXPORT_NAME``
* ``IMPORTED``
* ``NAME``
+* ``NO_SYSTEM_FROM_IMPORTED``
+* Properties matching ``IMPORTED_LIBNAME_*``
* Properties matching ``MAP_IMPORTED_CONFIG_*``
``INTERFACE`` libraries may be installed and exported. Any content they refer
diff --git a/Help/manual/cmake-compile-features.7.rst b/Help/manual/cmake-compile-features.7.rst
index 7289e61..13f7d16 100644
--- a/Help/manual/cmake-compile-features.7.rst
+++ b/Help/manual/cmake-compile-features.7.rst
@@ -84,6 +84,33 @@ Feature requirements are evaluated transitively by consuming the link
implementation. See :manual:`cmake-buildsystem(7)` for more on
transitive behavior of build properties and usage requirements.
+Requiring Language Standards
+----------------------------
+
+In projects that use a large number of commonly available features from
+a particular language standard (e.g. C++ 11) one may specify a
+meta-feature (e.g. ``cxx_std_11``) that requires use of a compiler mode
+aware of that standard. This is simpler than specifying all the
+features individually, but does not guarantee the existence of any
+particular feature. Diagnosis of use of unsupported features will be
+delayed until compile time.
+
+For example, if C++ 11 features are used extensively in a project's
+header files, then clients must use a compiler mode aware of C++ 11
+or above. This can be requested with the code:
+
+.. code-block:: cmake
+
+ target_compile_features(mylib PUBLIC cxx_std_11)
+
+In this example, CMake will ensure the compiler is invoked in a mode
+that is aware of C++ 11 (or above), adding flags such as
+``-std=gnu++11`` if necessary. This applies to sources within ``mylib``
+as well as any dependents (that may include headers from ``mylib``).
+
+Availability of Compiler Extensions
+-----------------------------------
+
Because the :prop_tgt:`CXX_EXTENSIONS` target property is ``ON`` by default,
CMake uses extended variants of language dialects by default, such as
``-std=gnu++11`` instead of ``-std=c++11``. That target property may be
@@ -309,4 +336,4 @@ versions specified for each:
* ``GNU``: GNU compiler versions 4.4 through 5.0.
* ``MSVC``: Microsoft Visual Studio versions 2010 through 2015.
* ``SunPro``: Oracle SolarisStudio version 12.4.
-* ``Intel``: Intel compiler versions 12.1 through 16.0 on UNIX platforms.
+* ``Intel``: Intel compiler versions 12.1 through 17.0.
diff --git a/Help/manual/cmake-generators.7.rst b/Help/manual/cmake-generators.7.rst
index 3df3a81..a37c65b 100644
--- a/Help/manual/cmake-generators.7.rst
+++ b/Help/manual/cmake-generators.7.rst
@@ -82,7 +82,7 @@ Visual Studio Generators
/generator/Visual Studio 11 2012
/generator/Visual Studio 12 2013
/generator/Visual Studio 14 2015
- /generator/Visual Studio 15
+ /generator/Visual Studio 15 2017
Other Generators
^^^^^^^^^^^^^^^^
diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst
index fa21a1f..e55524c 100644
--- a/Help/manual/cmake-properties.7.rst
+++ b/Help/manual/cmake-properties.7.rst
@@ -143,6 +143,7 @@ Properties on Targets
/prop_tgt/CONFIG_OUTPUT_NAME
/prop_tgt/CONFIG_POSTFIX
/prop_tgt/CROSSCOMPILING_EMULATOR
+ /prop_tgt/CUDA_SEPARABLE_COMPILATION
/prop_tgt/CXX_EXTENSIONS
/prop_tgt/CXX_STANDARD
/prop_tgt/CXX_STANDARD_REQUIRED
@@ -167,6 +168,8 @@ Properties on Targets
/prop_tgt/IMPORTED_CONFIGURATIONS
/prop_tgt/IMPORTED_IMPLIB_CONFIG
/prop_tgt/IMPORTED_IMPLIB
+ /prop_tgt/IMPORTED_LIBNAME_CONFIG
+ /prop_tgt/IMPORTED_LIBNAME
/prop_tgt/IMPORTED_LINK_DEPENDENT_LIBRARIES_CONFIG
/prop_tgt/IMPORTED_LINK_DEPENDENT_LIBRARIES
/prop_tgt/IMPORTED_LINK_INTERFACE_LANGUAGES_CONFIG
@@ -266,6 +269,7 @@ Properties on Targets
/prop_tgt/VERSION
/prop_tgt/VISIBILITY_INLINES_HIDDEN
/prop_tgt/VS_CONFIGURATION_TYPE
+ /prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY
/prop_tgt/VS_DESKTOP_EXTENSIONS_VERSION
/prop_tgt/VS_DOTNET_REFERENCES
/prop_tgt/VS_DOTNET_TARGET_FRAMEWORK_VERSION
@@ -282,6 +286,7 @@ Properties on Targets
/prop_tgt/VS_SCC_PROJECTNAME
/prop_tgt/VS_SCC_PROVIDER
/prop_tgt/VS_SDK_REFERENCES
+ /prop_tgt/VS_USER_PROPS_CXX
/prop_tgt/VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION
/prop_tgt/VS_WINRT_COMPONENT
/prop_tgt/VS_WINRT_EXTENSIONS
diff --git a/Help/manual/cmake-qt.7.rst b/Help/manual/cmake-qt.7.rst
index e8a2c1e..7827065 100644
--- a/Help/manual/cmake-qt.7.rst
+++ b/Help/manual/cmake-qt.7.rst
@@ -29,7 +29,7 @@ Qt 4 and Qt 5 may be used together in the same
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
- find_package(Qt5Widgets REQUIRED)
+ find_package(Qt5 COMPONENTS Widgets DBus REQUIRED)
add_executable(publisher publisher.cpp)
target_link_libraries(publisher Qt5::Widgets Qt5::DBus)
diff --git a/Help/manual/cmake-toolchains.7.rst b/Help/manual/cmake-toolchains.7.rst
index 74eab2d..64abe9a 100644
--- a/Help/manual/cmake-toolchains.7.rst
+++ b/Help/manual/cmake-toolchains.7.rst
@@ -387,7 +387,7 @@ Configure use of an Android NDK with the following variables:
:variable:`CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION`
Set to the version of the NDK toolchain to be selected as the compiler.
- If not specified, the latest available GCC toolchain will be used.
+ If not specified, the default will be the latest available GCC toolchain.
:variable:`CMAKE_ANDROID_STL_TYPE`
Set to specify which C++ standard library to use. If not specified,
diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst
index a5b1daa..8533f36 100644
--- a/Help/manual/cmake-variables.7.rst
+++ b/Help/manual/cmake-variables.7.rst
@@ -149,6 +149,7 @@ Variables that Change Behavior
/variable/CMAKE_INSTALL_DEFAULT_COMPONENT_NAME
/variable/CMAKE_INSTALL_MESSAGE
/variable/CMAKE_INSTALL_PREFIX
+ /variable/CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT
/variable/CMAKE_LIBRARY_PATH
/variable/CMAKE_MFC_FLAG
/variable/CMAKE_MODULE_PATH
@@ -160,6 +161,7 @@ Variables that Change Behavior
/variable/CMAKE_PROJECT_PROJECT-NAME_INCLUDE
/variable/CMAKE_SKIP_INSTALL_ALL_DEPENDENCY
/variable/CMAKE_STAGING_PREFIX
+ /variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
/variable/CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE
/variable/CMAKE_SYSTEM_APPBUNDLE_PATH
/variable/CMAKE_SYSTEM_FRAMEWORK_PATH
@@ -243,6 +245,7 @@ Variables that Control the Build
/variable/CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES
/variable/CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES
/variable/CMAKE_ANDROID_NDK
+ /variable/CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG
/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION
/variable/CMAKE_ANDROID_PROCESS_MAX
/variable/CMAKE_ANDROID_PROGUARD
@@ -326,6 +329,7 @@ Variables that Control the Build
/variable/CMAKE_USE_RELATIVE_PATHS
/variable/CMAKE_VISIBILITY_INLINES_HIDDEN
/variable/CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD
+ /variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD
/variable/CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS
/variable/CMAKE_WIN32_EXECUTABLE
/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute
@@ -353,6 +357,7 @@ Variables for Languages
/variable/CMAKE_Fortran_MODDIR_FLAG
/variable/CMAKE_Fortran_MODOUT_FLAG
/variable/CMAKE_INTERNAL_PLATFORM_ABI
+ /variable/CMAKE_LANG_ANDROID_TOOLCHAIN_MACHINE
/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX
/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX
/variable/CMAKE_LANG_ARCHIVE_APPEND
diff --git a/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst b/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst
index e8f4d2a..00a5104 100644
--- a/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst
+++ b/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst
@@ -14,6 +14,15 @@ compile features and a list of supported compilers.
The features known to this version of CMake are:
+``cxx_std_98``
+ Compiler mode is aware of C++ 98.
+
+``cxx_std_11``
+ Compiler mode is aware of C++ 11.
+
+``cxx_std_14``
+ Compiler mode is aware of C++ 14.
+
``cxx_aggregate_default_initializers``
Aggregate default initializers, as defined in N3605_.
diff --git a/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst b/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst
index a08af00..3707fef 100644
--- a/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst
+++ b/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst
@@ -13,6 +13,15 @@ compile features and a list of supported compilers.
The features known to this version of CMake are:
+``c_std_90``
+ Compiler mode is aware of C 90.
+
+``c_std_99``
+ Compiler mode is aware of C 99.
+
+``c_std_11``
+ Compiler mode is aware of C 11.
+
``c_function_prototypes``
Function prototypes, as defined in ``ISO/IEC 9899:1990``.
diff --git a/Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst b/Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst
new file mode 100644
index 0000000..1c7dd80
--- /dev/null
+++ b/Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst
@@ -0,0 +1,13 @@
+CUDA_SEPARABLE_COMPILATION
+--------------------------
+
+CUDA only: Enables separate compilation of device code
+
+If set this will enable separable compilation for all CUDA files for
+the given target.
+
+For instance:
+
+.. code-block:: cmake
+
+ set_property(TARGET myexe PROPERTY CUDA_SEPARABLE_COMPILATION ON)
diff --git a/Help/prop_tgt/IMPORTED_LIBNAME.rst b/Help/prop_tgt/IMPORTED_LIBNAME.rst
new file mode 100644
index 0000000..1943dba
--- /dev/null
+++ b/Help/prop_tgt/IMPORTED_LIBNAME.rst
@@ -0,0 +1,23 @@
+IMPORTED_LIBNAME
+----------------
+
+Specify the link library name for an :ref:`imported <Imported Targets>`
+:ref:`Interface Library <Interface Libraries>`.
+
+An interface library builds no library file itself but does specify
+usage requirements for its consumers. The ``IMPORTED_LIBNAME``
+property may be set to specify a single library name to be placed
+on the link line in place of the interface library target name as
+a requirement for using the interface.
+
+This property is intended for use in naming libraries provided by
+a platform SDK for which the full path to a library file may not
+be known. The value may be a plain library name such as ``foo``
+but may *not* be a path (e.g. ``/usr/lib/libfoo.so``) or a flag
+(e.g. ``-Wl,...``). The name is never treated as a library target
+name even if it happens to name one.
+
+The ``IMPORTED_LIBNAME`` property is allowed only on
+:ref:`imported <Imported Targets>` :ref:`Interface Libraries`
+and is rejected on targets of other types (for which
+the :prop_tgt:`IMPORTED_LOCATION` target property may be used).
diff --git a/Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst b/Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst
new file mode 100644
index 0000000..a28b838
--- /dev/null
+++ b/Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst
@@ -0,0 +1,7 @@
+IMPORTED_LIBNAME_<CONFIG>
+-------------------------
+
+<CONFIG>-specific version of :prop_tgt:`IMPORTED_LIBNAME` property.
+
+Configuration names correspond to those provided by the project from
+which the target is imported.
diff --git a/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst b/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst
new file mode 100644
index 0000000..0af85cb
--- /dev/null
+++ b/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst
@@ -0,0 +1,6 @@
+VS_DEBUGGER_WORKING_DIRECTORY
+-----------------------------
+
+Sets the local debugger working directory for Visual Studio C++ targets.
+This is defined in ``<LocalDebuggerWorkingDirectory>`` in the Visual Studio
+project file.
diff --git a/Help/prop_tgt/VS_USER_PROPS_CXX.rst b/Help/prop_tgt/VS_USER_PROPS_CXX.rst
new file mode 100644
index 0000000..083ce03
--- /dev/null
+++ b/Help/prop_tgt/VS_USER_PROPS_CXX.rst
@@ -0,0 +1,12 @@
+VS_USER_PROPS_CXX
+-----------------
+
+Sets the user props file to be included in the visual studio
+C++ project file. The standard path is
+``$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props``, which is
+in most cases the same as
+``%LOCALAPPDATA%\\Microsoft\\MSBuild\\v4.0\\Microsoft.Cpp.Win32.user.props``
+or ``%LOCALAPPDATA%\\Microsoft\\MSBuild\\v4.0\\Microsoft.Cpp.x64.user.props``.
+
+The ``*.user.props`` files can be used for Visual Studio wide
+configuration which is independent from cmake.
diff --git a/Help/release/3.7.rst b/Help/release/3.7.rst
index 3b8ade6..4c51af4 100644
--- a/Help/release/3.7.rst
+++ b/Help/release/3.7.rst
@@ -31,9 +31,9 @@ Generators
This is equivalent to ``cd sub/dir; make {test,install,package}``
with :ref:`Makefile Generators`.
-* The :generator:`Visual Studio 15` generator was added. This is
- experimental and based on Preview 5 because this version of VS
- has not been released.
+* The :generator:`Visual Studio 15 2017` generator was added. This is
+ experimental and based on "Visual Studio 2017 RC" because this version
+ of VS has not been released.
* :ref:`Visual Studio Generators` for VS 2010 and above learned to
place ``.natvis`` source files into VS project files properly.
diff --git a/Help/release/dev/CUDA-language-support.rst b/Help/release/dev/CUDA-language-support.rst
new file mode 100644
index 0000000..7df45bf
--- /dev/null
+++ b/Help/release/dev/CUDA-language-support.rst
@@ -0,0 +1,6 @@
+CUDA-language-support
+---------------------
+
+* CMake learned to support CUDA as a first-class language.
+ It is supported by the :ref:`Makefile Generators` and the
+ :generator:`Ninja` generator.
diff --git a/Help/release/dev/ExternalProject-GIT_CONFIG.rst b/Help/release/dev/ExternalProject-GIT_CONFIG.rst
new file mode 100644
index 0000000..2ab15e5
--- /dev/null
+++ b/Help/release/dev/ExternalProject-GIT_CONFIG.rst
@@ -0,0 +1,5 @@
+ExternalProject-GIT_CONFIG
+--------------------------
+
+* The :module:`ExternalProject` module gained a ``GIT_CONFIG`` option
+ to pass ``--config`` options to Git when cloning repositories.
diff --git a/Help/release/dev/UseSWIG-SWIG_OUTFILE_DIR.rst b/Help/release/dev/UseSWIG-SWIG_OUTFILE_DIR.rst
new file mode 100644
index 0000000..c001a88
--- /dev/null
+++ b/Help/release/dev/UseSWIG-SWIG_OUTFILE_DIR.rst
@@ -0,0 +1,6 @@
+UseSWIG-SWIG_OUTFILE_DIR
+------------------------
+
+* The :module:`UseSWIG` module ``swig_add_source_to_module`` command
+ learned a new ``SWIG_OUTFILE_DIR`` option to control the output
+ file location (``swig -o``).
diff --git a/Help/release/dev/add-SHA-3.rst b/Help/release/dev/add-SHA-3.rst
new file mode 100644
index 0000000..5743f10
--- /dev/null
+++ b/Help/release/dev/add-SHA-3.rst
@@ -0,0 +1,4 @@
+add-SHA-3
+---------
+
+* CMake functionality using cryptographic hashes now supports SHA-3 algorithms.
diff --git a/Help/release/dev/capture-clang-tidy-errors.rst b/Help/release/dev/capture-clang-tidy-errors.rst
new file mode 100644
index 0000000..14c32e6
--- /dev/null
+++ b/Help/release/dev/capture-clang-tidy-errors.rst
@@ -0,0 +1,6 @@
+capture-clang-tidy-errors
+-------------------------
+
+* If a command specified by the :prop_tgt:`<LANG>_CLANG_TIDY` target property
+ returns non-zero at build time this is now treated as an error instead of
+ silently ignored.
diff --git a/Help/release/dev/compile-features-for-language-standards.rst b/Help/release/dev/compile-features-for-language-standards.rst
new file mode 100644
index 0000000..20473b7
--- /dev/null
+++ b/Help/release/dev/compile-features-for-language-standards.rst
@@ -0,0 +1,7 @@
+compile-features-for-language-standards
+---------------------------------------
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+ now offers meta-features that request compiler modes for specific language
+ standard levels. See :prop_gbl:`CMAKE_C_KNOWN_FEATURES` and
+ :prop_gbl:`CMAKE_CXX_KNOWN_FEATURES`.
diff --git a/Help/release/dev/cpack-ifw-options.rst b/Help/release/dev/cpack-ifw-options.rst
new file mode 100644
index 0000000..cbe0f63
--- /dev/null
+++ b/Help/release/dev/cpack-ifw-options.rst
@@ -0,0 +1,7 @@
+cpack-ifw-options
+-----------------
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component` and
+ :command:`cpack_ifw_configure_component_group` commands gained a new
+ ``DEFAULT``, ``VIRTUAL``, ``FORCED_INSTALLATION``, ``DISPLAY_NAME``,
+ ``DESCRIPTION`` and ``RELEASE_DATE`` options to more specific configuration.
diff --git a/Help/release/dev/cpack-rpm-omit-unsupported-tags.rst b/Help/release/dev/cpack-rpm-omit-unsupported-tags.rst
new file mode 100644
index 0000000..abcb7a6
--- /dev/null
+++ b/Help/release/dev/cpack-rpm-omit-unsupported-tags.rst
@@ -0,0 +1,8 @@
+cpack-rpm-omit-unsupported-tags
+-------------------------------
+
+* The :module:`CPackRPM` module learned to omit
+ tags that are not supported by provided
+ rpmbuild tool. If unsupported tags are set
+ they are ignored and a developer warning is
+ printed out.
diff --git a/Help/release/dev/ctest_memcheck_defect_count.rst b/Help/release/dev/ctest_memcheck_defect_count.rst
new file mode 100644
index 0000000..70061c1
--- /dev/null
+++ b/Help/release/dev/ctest_memcheck_defect_count.rst
@@ -0,0 +1,5 @@
+ctest_memcheck_defect_count
+---------------------------
+
+* The :command:`ctest_memcheck` command gained a ``DEFECT_COUNT <var>``
+ option to capture the number of memory defects detected.
diff --git a/Help/release/dev/execute_process-encoding.rst b/Help/release/dev/execute_process-encoding.rst
new file mode 100644
index 0000000..1c7cd8c
--- /dev/null
+++ b/Help/release/dev/execute_process-encoding.rst
@@ -0,0 +1,5 @@
+execute_process-encoding
+------------------------
+
+* The :command:`execute_process` command gained an ``ENCODING`` option to
+ specify on Windows which encoding is used for output from child process.
diff --git a/Help/release/dev/fuchsia-platform.rst b/Help/release/dev/fuchsia-platform.rst
new file mode 100644
index 0000000..9d5f3e8
--- /dev/null
+++ b/Help/release/dev/fuchsia-platform.rst
@@ -0,0 +1,4 @@
+fuchsia-platform
+----------------
+
+* A new minimal platform file for Fuchsia was added.
diff --git a/Help/release/dev/imported-interface-libname.rst b/Help/release/dev/imported-interface-libname.rst
new file mode 100644
index 0000000..fdbae78
--- /dev/null
+++ b/Help/release/dev/imported-interface-libname.rst
@@ -0,0 +1,7 @@
+imported-interface-libname
+--------------------------
+
+* :ref:`Imported <Imported Targets>` :ref:`Interface Libraries` learned new
+ :prop_tgt:`IMPORTED_LIBNAME` and :prop_tgt:`IMPORTED_LIBNAME_<CONFIG>`
+ target properties to specify a link library name since interface libraries
+ do not build their own library files.
diff --git a/Help/release/dev/imported-interface-no-system.rst b/Help/release/dev/imported-interface-no-system.rst
new file mode 100644
index 0000000..3a727cc
--- /dev/null
+++ b/Help/release/dev/imported-interface-no-system.rst
@@ -0,0 +1,5 @@
+imported-interface-no-system
+----------------------------
+
+* The :prop_tgt:`NO_SYSTEM_FROM_IMPORTED` target property is now supported
+ on :ref:`Imported <Imported Targets>` :ref:`Interface Libraries`.
diff --git a/Help/release/dev/intel-compile-features-windows.rst b/Help/release/dev/intel-compile-features-windows.rst
new file mode 100644
index 0000000..6a2cdfe
--- /dev/null
+++ b/Help/release/dev/intel-compile-features-windows.rst
@@ -0,0 +1,6 @@
+intel-compile-features-windows
+------------------------------
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+ is now aware of features supported by Intel C++ compilers versions 12.1
+ through 17.0 on UNIX and Windows platforms.
diff --git a/Help/release/dev/st2-env-settings.rst b/Help/release/dev/st2-env-settings.rst
new file mode 100644
index 0000000..7b36347
--- /dev/null
+++ b/Help/release/dev/st2-env-settings.rst
@@ -0,0 +1,6 @@
+st2-env-settings
+----------------
+
+* The :generator:`Sublime Text 2` extra generator learned to place
+ environment variables in the generated ``.sublime-project``.
+ See the :variable:`CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS` variable.
diff --git a/Help/release/dev/swig_add_library.rst b/Help/release/dev/swig_add_library.rst
new file mode 100644
index 0000000..4b7723b
--- /dev/null
+++ b/Help/release/dev/swig_add_library.rst
@@ -0,0 +1,8 @@
+swig_add_library
+----------------
+
+* The :module:`UseSWIG` module gained a ``swig_add_library`` command
+ to give more flexibility over the old ``swig_add_module`` command.
+
+* The :module:`UseSWIG` module ``swig_add_module`` command is now
+ deprecated in favor of ``swig_add_library``.
diff --git a/Help/release/dev/try_compile-honor-CMAKE_WARN_DEPRECATED.rst b/Help/release/dev/try_compile-honor-CMAKE_WARN_DEPRECATED.rst
new file mode 100644
index 0000000..9e13575
--- /dev/null
+++ b/Help/release/dev/try_compile-honor-CMAKE_WARN_DEPRECATED.rst
@@ -0,0 +1,6 @@
+try_compile-honor-CMAKE_WARN_DEPRECATED
+---------------------------------------
+
+* The :command:`try_compile` command source file signature now
+ honors the :variable:`CMAKE_WARN_DEPRECATED` variable value
+ in the generated test project.
diff --git a/Help/release/dev/vs-custom-msbuild-props.rst b/Help/release/dev/vs-custom-msbuild-props.rst
new file mode 100644
index 0000000..15a5b0a
--- /dev/null
+++ b/Help/release/dev/vs-custom-msbuild-props.rst
@@ -0,0 +1,9 @@
+vs-custom-msbuild-props
+-----------------------
+
+* The :ref:`Visual Studio Generators` for VS 2010 and above can
+ now be fine tuned using custom msbuild .props files.
+ :prop_tgt:`VS_USER_PROPS_CXX` can be
+ used to change the default path of the user .props file from
+ ``$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props`` to
+ an arbitrary filename.
diff --git a/Help/release/dev/vs-debugger-config.rst b/Help/release/dev/vs-debugger-config.rst
new file mode 100644
index 0000000..58873a5
--- /dev/null
+++ b/Help/release/dev/vs-debugger-config.rst
@@ -0,0 +1,6 @@
+vs-debugger-configuration
+-------------------------
+
+* For the :ref:`Visual Studio Generators` for VS 2010 and above
+ the working directory for debugging can be set using a new
+ :prop_tgt:`VS_DEBUGGER_WORKING_DIRECTORY` target property.
diff --git a/Help/release/dev/vs-default-build-package.rst b/Help/release/dev/vs-default-build-package.rst
new file mode 100644
index 0000000..62c66e0
--- /dev/null
+++ b/Help/release/dev/vs-default-build-package.rst
@@ -0,0 +1,7 @@
+vs-default-build-package
+------------------------
+
+* The :ref:`Visual Studio Generators` for VS 2010 and above now support
+ adding the PACKAGE target to the targets which are built by default.
+ The behavior is similar to :variable:`CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD`
+ and can be toggled using :variable:`CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD`.
diff --git a/Help/release/dev/vs-flag-order.rst b/Help/release/dev/vs-flag-order.rst
new file mode 100644
index 0000000..21cea37
--- /dev/null
+++ b/Help/release/dev/vs-flag-order.rst
@@ -0,0 +1,9 @@
+vs-flag-order
+-------------
+
+* The :ref:`Visual Studio Generators` for VS 2010 and above now place
+ per-source file flags after target-wide flags when they are classified
+ as raw flags with no project file setting (``AdditionalOptions``).
+ This behavior is more consistent with the ordering of flags produced
+ by other generators, and allows flags on more-specific properties
+ (per-source) to override those on more general ones (per-target).
diff --git a/Help/release/dev/vs_targets_file_as_library.rst b/Help/release/dev/vs_targets_file_as_library.rst
new file mode 100644
index 0000000..9c923fa
--- /dev/null
+++ b/Help/release/dev/vs_targets_file_as_library.rst
@@ -0,0 +1,6 @@
+vs_targets_file_as_library
+--------------------------
+
+* :ref:`Visual Studio Generators` learned to treat files passed to
+ :command:`target_link_libraries` whose names end in ``.targets``
+ as MSBuild targets files to be imported into generated project files.
diff --git a/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG.rst b/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG.rst
new file mode 100644
index 0000000..207019a
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG.rst
@@ -0,0 +1,6 @@
+CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG
+------------------------------------
+
+When :ref:`Cross Compiling for Android with the NDK`, this variable
+provides the NDK's "host tag" used to construct the path to prebuilt
+toolchains that run on the host.
diff --git a/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst b/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst
index dff7d64..5ae55d1 100644
--- a/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst
+++ b/Help/variable/CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION.rst
@@ -11,3 +11,6 @@ as the compiler. The variable must be set to one of these forms:
A toolchain of the requested version will be selected automatically to
match the ABI named in the :variable:`CMAKE_ANDROID_ARCH_ABI` variable.
+
+If not specified, the default will be a value that selects the latest
+available GCC toolchain.
diff --git a/Help/variable/CMAKE_INSTALL_PREFIX.rst b/Help/variable/CMAKE_INSTALL_PREFIX.rst
index 86f1944..7bd87d6 100644
--- a/Help/variable/CMAKE_INSTALL_PREFIX.rst
+++ b/Help/variable/CMAKE_INSTALL_PREFIX.rst
@@ -6,6 +6,8 @@ Install directory used by :command:`install`.
If ``make install`` is invoked or ``INSTALL`` is built, this directory is
prepended onto all install directories. This variable defaults to
``/usr/local`` on UNIX and ``c:/Program Files/${PROJECT_NAME}`` on Windows.
+See :variable:`CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT` for how a
+project might choose its own default.
On UNIX one can use the ``DESTDIR`` mechanism in order to relocate the
whole installation. ``DESTDIR`` means DESTination DIRectory. It is
diff --git a/Help/variable/CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT.rst b/Help/variable/CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT.rst
new file mode 100644
index 0000000..2a5842d
--- /dev/null
+++ b/Help/variable/CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT.rst
@@ -0,0 +1,14 @@
+CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT
+-------------------------------------------
+
+CMake sets this variable to a ``TRUE`` value when the
+:variable:`CMAKE_INSTALL_PREFIX` has just been initialized to
+its default value, typically on the first run of CMake within
+a new build tree. This can be used by project code to change
+the default without overriding a user-provided value:
+
+.. code-block:: cmake
+
+ if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+ set(CMAKE_INSTALL_PREFIX "/my/default" CACHE PATH "..." FORCE)
+ endif()
diff --git a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_MACHINE.rst b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_MACHINE.rst
new file mode 100644
index 0000000..d336364
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_MACHINE.rst
@@ -0,0 +1,9 @@
+CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE
+--------------------------------------
+
+When :ref:`Cross Compiling for Android` this variable contains the
+toolchain binutils machine name (e.g. ``gcc -dumpmachine``). The
+binutils typically have a ``<machine>-`` prefix on their name.
+
+See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`
+and :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`.
diff --git a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst
index b51422f..db04af3 100644
--- a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst
+++ b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_PREFIX.rst
@@ -4,7 +4,8 @@ CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX
When :ref:`Cross Compiling for Android` this variable contains the absolute
path prefixing the toolchain GNU compiler and its binutils.
-See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`.
+See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX`
+and :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE`.
For example, the path to the linker is::
diff --git a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst
index a4af640..159eb22 100644
--- a/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst
+++ b/Help/variable/CMAKE_LANG_ANDROID_TOOLCHAIN_SUFFIX.rst
@@ -4,4 +4,5 @@ CMAKE_<LANG>_ANDROID_TOOLCHAIN_SUFFIX
When :ref:`Cross Compiling for Android` this variable contains the
host platform suffix of the toolchain GNU compiler and its binutils.
-See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`.
+See also :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_PREFIX`
+and :variable:`CMAKE_<LANG>_ANDROID_TOOLCHAIN_MACHINE`.
diff --git a/Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst b/Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst
new file mode 100644
index 0000000..02c8663
--- /dev/null
+++ b/Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst
@@ -0,0 +1,25 @@
+CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+---------------------------------
+
+This variable contains a list of env vars as a list of tokens with the
+syntax ``var=value``.
+
+Example:
+
+.. code-block:: cmake
+
+ set(CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+ "FOO=FOO1\;FOO2\;FOON"
+ "BAR=BAR1\;BAR2\;BARN"
+ "BAZ=BAZ1\;BAZ2\;BAZN"
+ "FOOBAR=FOOBAR1\;FOOBAR2\;FOOBARN"
+ "VALID="
+ )
+
+In case of malformed variables CMake will fail:
+
+.. code-block:: cmake
+
+ set(CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+ "THIS_IS_NOT_VALID"
+ )
diff --git a/Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst b/Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst
new file mode 100644
index 0000000..693ba45
--- /dev/null
+++ b/Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst
@@ -0,0 +1,8 @@
+CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD
+-----------------------------------------
+
+Include ``PACKAGE`` target to default build.
+
+In Visual Studio solution, by default the ``PACKAGE`` target will not be part
+of the default build. Setting this variable will enable the ``PACKAGE`` target
+to be part of the default build.
diff --git a/Modules/CMakeCUDACompiler.cmake.in b/Modules/CMakeCUDACompiler.cmake.in
new file mode 100644
index 0000000..8a6c0bc
--- /dev/null
+++ b/Modules/CMakeCUDACompiler.cmake.in
@@ -0,0 +1,20 @@
+set(CMAKE_CUDA_COMPILER "@CMAKE_CUDA_COMPILER@")
+set(CMAKE_CUDA_HOST_COMPILER "@CMAKE_CUDA_HOST_COMPILER@")
+set(CMAKE_CUDA_HOST_LINK_LAUNCHER "@CMAKE_CUDA_HOST_LINK_LAUNCHER@")
+set(CMAKE_CUDA_COMPILER_ID "@CMAKE_CUDA_COMPILER_ID@")
+set(CMAKE_CUDA_COMPILER_VERSION "@CMAKE_CUDA_COMPILER_VERSION@")
+set(CMAKE_CUDA_STANDARD_COMPUTED_DEFAULT "@CMAKE_CUDA_STANDARD_COMPUTED_DEFAULT@")
+
+set(CMAKE_CUDA_COMPILER_ENV_VAR "CUDACXX")
+set(CMAKE_CUDA_HOST_COMPILER_ENV_VAR "CUDAHOSTCXX")
+
+set(CMAKE_CUDA_COMPILER_ID_RUN 1)
+set(CMAKE_CUDA_SOURCE_FILE_EXTENSIONS cu)
+
+set(CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES "@CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES@")
+set(CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES "@CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES@")
+set(CMAKE_CUDA_HOST_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "@CMAKE_CUDA_HOST_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES@")
+
+set(CMAKE_CUDA_IMPLICIT_LINK_LIBRARIES "@CMAKE_CUDA_IMPLICIT_LINK_LIBRARIES@")
+set(CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES "@CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES@")
+set(CMAKE_CUDA_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "@CMAKE_CUDA_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES@")
diff --git a/Modules/CMakeCUDACompilerABI.cu b/Modules/CMakeCUDACompilerABI.cu
new file mode 100644
index 0000000..5aa1b8a
--- /dev/null
+++ b/Modules/CMakeCUDACompilerABI.cu
@@ -0,0 +1,16 @@
+#ifndef __CUDACC__
+# error "A C or C++ compiler has been selected for CUDA"
+#endif
+
+#include "CMakeCompilerABI.h"
+
+int main(int argc, char* argv[])
+{
+ int require = 0;
+ require += info_sizeof_dptr[argc];
+#if defined(ABI_ID)
+ require += info_abi[argc];
+#endif
+ (void)argv;
+ return require;
+}
diff --git a/Modules/CMakeCUDACompilerId.cu.in b/Modules/CMakeCUDACompilerId.cu.in
new file mode 100644
index 0000000..5fa85da
--- /dev/null
+++ b/Modules/CMakeCUDACompilerId.cu.in
@@ -0,0 +1,39 @@
+#ifndef __CUDACC__
+# error "A C or C++ compiler has been selected for CUDA"
+#endif
+
+@CMAKE_CUDA_COMPILER_ID_CONTENT@
+
+/* Construct the string literal in pieces to prevent the source from
+ getting matched. Store it in a pointer rather than an array
+ because some compilers will just produce instructions to fill the
+ array rather than assigning a pointer to a static array. */
+char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]";
+
+@CMAKE_CUDA_COMPILER_ID_PLATFORM_CONTENT@
+@CMAKE_CUDA_COMPILER_ID_ERROR_FOR_TEST@
+
+const char* info_language_dialect_default = "INFO" ":" "dialect_default["
+#if __cplusplus >= 201402L
+ "14"
+#elif __cplusplus >= 201103L
+ "11"
+#else
+ "98"
+#endif
+"]";
+
+/*--------------------------------------------------------------------------*/
+
+int main(int argc, char* argv[])
+{
+ int require = 0;
+ require += info_compiler[argc];
+ require += info_platform[argc];
+#ifdef COMPILER_VERSION_MAJOR
+ require += info_version[argc];
+#endif
+ require += info_language_dialect_default[argc];
+ (void)argv;
+ return require;
+}
diff --git a/Modules/CMakeCUDAInformation.cmake b/Modules/CMakeCUDAInformation.cmake
new file mode 100644
index 0000000..202a7a6
--- /dev/null
+++ b/Modules/CMakeCUDAInformation.cmake
@@ -0,0 +1,193 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+set(CMAKE_CUDA_OUTPUT_EXTENSION .o)
+set(CMAKE_INCLUDE_FLAG_CUDA "-I")
+
+# Load compiler-specific information.
+if(CMAKE_CUDA_COMPILER_ID)
+ include(Compiler/${CMAKE_CUDA_COMPILER_ID}-CUDA OPTIONAL)
+endif()
+
+# load the system- and compiler specific files
+if(CMAKE_CUDA_COMPILER_ID)
+ # load a hardware specific file, mostly useful for embedded compilers
+ if(CMAKE_SYSTEM_PROCESSOR)
+ include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL)
+ endif()
+ include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA OPTIONAL)
+endif()
+
+
+if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG)
+ set(CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG})
+endif()
+
+if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG_SEP)
+ set(CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP})
+endif()
+
+if(NOT CMAKE_SHARED_LIBRARY_RPATH_LINK_CUDA_FLAG)
+ set(CMAKE_SHARED_LIBRARY_RPATH_LINK_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG})
+endif()
+
+if(NOT DEFINED CMAKE_EXE_EXPORTS_CUDA_FLAG)
+ set(CMAKE_EXE_EXPORTS_CUDA_FLAG ${CMAKE_EXE_EXPORTS_C_FLAG})
+endif()
+
+if(NOT DEFINED CMAKE_SHARED_LIBRARY_SONAME_CUDA_FLAG)
+ set(CMAKE_SHARED_LIBRARY_SONAME_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_SONAME_C_FLAG})
+endif()
+
+if(NOT CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG)
+ set(CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG})
+endif()
+
+if(NOT CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG_SEP)
+ set(CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG_SEP})
+endif()
+
+if(NOT CMAKE_EXECUTABLE_RPATH_LINK_CUDA_FLAG)
+ set(CMAKE_EXECUTABLE_RPATH_LINK_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_CUDA_FLAG})
+endif()
+
+if(NOT DEFINED CMAKE_SHARED_LIBRARY_LINK_CUDA_WITH_RUNTIME_PATH)
+ set(CMAKE_SHARED_LIBRARY_LINK_CUDA_WITH_RUNTIME_PATH ${CMAKE_SHARED_LIBRARY_LINK_C_WITH_RUNTIME_PATH})
+endif()
+
+
+# for most systems a module is the same as a shared library
+# so unless the variable CMAKE_MODULE_EXISTS is set just
+# copy the values from the LIBRARY variables
+if(NOT CMAKE_MODULE_EXISTS)
+ set(CMAKE_SHARED_MODULE_CUDA_FLAGS ${CMAKE_SHARED_LIBRARY_CUDA_FLAGS})
+ set(CMAKE_SHARED_MODULE_CREATE_CUDA_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS})
+endif()
+
+# add the flags to the cache based
+# on the initial values computed in the platform/*.cmake files
+# use _INIT variables so that this only happens the first time
+# and you can set these flags in the cmake cache
+set(CMAKE_CUDA_FLAGS_INIT "$ENV{CUDAFLAGS} ${CMAKE_CUDA_FLAGS_INIT}")
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+ string(STRIP "${CMAKE_CUDA_FLAGS${c}_INIT}" CMAKE_CUDA_FLAGS${c}_INIT)
+endforeach()
+
+set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS_INIT}" CACHE STRING
+ "Flags used by the compiler during all build types.")
+
+if(NOT CMAKE_NOT_USING_CONFIG_FLAGS)
+ set (CMAKE_CUDA_FLAGS_DEBUG "${CMAKE_CUDA_FLAGS_DEBUG_INIT}" CACHE STRING
+ "Flags used by the compiler during debug builds.")
+ set (CMAKE_CUDA_FLAGS_MINSIZEREL "${CMAKE_CUDA_FLAGS_MINSIZEREL_INIT}" CACHE STRING
+ "Flags used by the compiler during release builds for minimum size.")
+ set (CMAKE_CUDA_FLAGS_RELEASE "${CMAKE_CUDA_FLAGS_RELEASE_INIT}" CACHE STRING
+ "Flags used by the compiler during release builds.")
+ set (CMAKE_CUDA_FLAGS_RELWITHDEBINFO "${CMAKE_CUDA_FLAGS_RELWITHDEBINFO_INIT}" CACHE STRING
+ "Flags used by the compiler during release builds with debug info.")
+
+endif()
+
+include(CMakeCommonLanguageInclude)
+
+# now define the following rules:
+# CMAKE_CUDA_CREATE_SHARED_LIBRARY
+# CMAKE_CUDA_CREATE_SHARED_MODULE
+# CMAKE_CUDA_COMPILE_OBJECT
+# CMAKE_CUDA_LINK_EXECUTABLE
+
+if(CMAKE_CUDA_HOST_COMPILER)
+ set(CMAKE_CUDA_HOST_FLAGS "-ccbin=<CMAKE_CUDA_HOST_COMPILER>")
+else()
+ set(CMAKE_CUDA_HOST_FLAGS "")
+endif()
+
+set(__IMPLICT_LINKS )
+foreach(dir ${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES})
+ string(APPEND __IMPLICT_LINKS " -L\"${dir}\"")
+endforeach()
+foreach(lib ${CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES})
+ if(${lib} MATCHES "/")
+ string(APPEND __IMPLICT_LINKS " \"${lib}\"")
+ else()
+ string(APPEND __IMPLICT_LINKS " -l${lib}")
+ endif()
+endforeach()
+
+# create a shared library
+if(NOT CMAKE_CUDA_CREATE_SHARED_LIBRARY)
+ set(CMAKE_CUDA_CREATE_SHARED_LIBRARY
+ "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_SHARED_LIBRARY_CUDA_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
+endif()
+
+# create a shared module copy the shared library rule by default
+if(NOT CMAKE_CUDA_CREATE_SHARED_MODULE)
+ set(CMAKE_CUDA_CREATE_SHARED_MODULE ${CMAKE_CUDA_CREATE_SHARED_LIBRARY})
+endif()
+
+# Create a static archive incrementally for large object file counts.
+if(NOT DEFINED CMAKE_CUDA_ARCHIVE_CREATE)
+ set(CMAKE_CUDA_ARCHIVE_CREATE "<CMAKE_AR> qc <TARGET> <LINK_FLAGS> <OBJECTS>")
+endif()
+if(NOT DEFINED CMAKE_CUDA_ARCHIVE_APPEND)
+ set(CMAKE_CUDA_ARCHIVE_APPEND "<CMAKE_AR> q <TARGET> <LINK_FLAGS> <OBJECTS>")
+endif()
+if(NOT DEFINED CMAKE_CUDA_ARCHIVE_FINISH)
+ set(CMAKE_CUDA_ARCHIVE_FINISH "<CMAKE_RANLIB> <TARGET>")
+endif()
+
+#Specify how to compile when ptx has been requested
+if(NOT CMAKE_CUDA_COMPILE_PTX_COMPILATION)
+ set(CMAKE_CUDA_COMPILE_PTX_COMPILATION
+ "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -ptx <SOURCE> -o <OBJECT>")
+endif()
+
+#Specify how to compile when separable compilation has been requested
+if(NOT CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION)
+ set(CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION
+ "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -dc <SOURCE> -o <OBJECT>")
+endif()
+
+#Specify how to compile when whole compilation has been requested
+if(NOT CMAKE_CUDA_COMPILE_WHOLE_COMPILATION)
+ set(CMAKE_CUDA_COMPILE_WHOLE_COMPILATION
+ "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -c <SOURCE> -o <OBJECT>")
+endif()
+
+if(CMAKE_GENERATOR STREQUAL "Ninja")
+ set(CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION
+ "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -M <SOURCE> -MT <OBJECT> -o $DEP_FILE")
+ #The Ninja generator uses the make file dependency files to determine what
+ #files need to be recompiled. Unfortunately, nvcc doesn't support building
+ #a source file and generating the dependencies of said file in a single
+ #invocation. Instead we have to state that you need to chain two commands.
+ #
+ #The makefile generators uses the custom CMake dependency scanner, and thus
+ #it is exempt from this logic.
+ list(APPEND CMAKE_CUDA_COMPILE_PTX_COMPILATION "${CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION}")
+ list(APPEND CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION "${CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION}")
+ list(APPEND CMAKE_CUDA_COMPILE_WHOLE_COMPILATION "${CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION}")
+endif()
+
+# compile a cu file into an executable
+if(NOT CMAKE_CUDA_LINK_EXECUTABLE)
+ set(CMAKE_CUDA_LINK_EXECUTABLE
+ "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_CUDA_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
+endif()
+
+#These are used when linking relocatable (dc) cuda code
+set(CMAKE_CUDA_DEVICE_LINK_LIBRARY
+ "<CMAKE_CUDA_COMPILER> <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>")
+set(CMAKE_CUDA_DEVICE_LINK_EXECUTABLE
+ "<CMAKE_CUDA_COMPILER> <CMAKE_CUDA_LINK_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>")
+
+
+mark_as_advanced(
+CMAKE_CUDA_FLAGS
+CMAKE_CUDA_FLAGS_RELEASE
+CMAKE_CUDA_FLAGS_RELWITHDEBINFO
+CMAKE_CUDA_FLAGS_MINSIZEREL
+CMAKE_CUDA_FLAGS_DEBUG)
+
+set(CMAKE_CUDA_INFORMATION_LOADED 1)
diff --git a/Modules/CMakeCompilerIdDetection.cmake b/Modules/CMakeCompilerIdDetection.cmake
index 4732250..2881cb1 100644
--- a/Modules/CMakeCompilerIdDetection.cmake
+++ b/Modules/CMakeCompilerIdDetection.cmake
@@ -90,6 +90,11 @@ function(compiler_id_detection outvar lang)
list(APPEND ordered_compilers
MIPSpro)
+ #Currently the only CUDA compilers are NVIDIA
+ if(lang STREQUAL CUDA)
+ set(ordered_compilers NVIDIA)
+ endif()
+
if(CID_ID_DEFINE)
foreach(Id ${ordered_compilers})
set(CMAKE_${lang}_COMPILER_ID_CONTENT "${CMAKE_${lang}_COMPILER_ID_CONTENT}# define ${CID_PREFIX}COMPILER_IS_${Id} 0\n")
diff --git a/Modules/CMakeDetermineASMCompiler.cmake b/Modules/CMakeDetermineASMCompiler.cmake
index deb10fb..4162726 100644
--- a/Modules/CMakeDetermineASMCompiler.cmake
+++ b/Modules/CMakeDetermineASMCompiler.cmake
@@ -9,7 +9,13 @@ include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER)
# prefer the environment variable ASM
if(NOT $ENV{ASM${ASM_DIALECT}} STREQUAL "")
- set(CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT "$ENV{ASM${ASM_DIALECT}}")
+ get_filename_component(CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT $ENV{ASM${ASM_DIALECT}} PROGRAM PROGRAM_ARGS CMAKE_ASM${ASM_DIALECT}_FLAGS_ENV_INIT)
+ if(CMAKE_ASM${ASM_DIALECT}_FLAGS_ENV_INIT)
+ set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARG1 "${CMAKE_ASM${ASM_DIALECT}_FLAGS_ENV_INIT}" CACHE STRING "First argument to ASM${ASM_DIALECT} compiler")
+ endif()
+ if(NOT EXISTS ${CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT})
+ message(FATAL_ERROR "Could not find compiler set in environment variable ASM${ASM_DIALECT}:\n$ENV{ASM${ASM_DIALECT}}.")
+ endif()
endif()
# finally list compilers to try
diff --git a/Modules/CMakeDetermineCUDACompiler.cmake b/Modules/CMakeDetermineCUDACompiler.cmake
new file mode 100644
index 0000000..419f3a5
--- /dev/null
+++ b/Modules/CMakeDetermineCUDACompiler.cmake
@@ -0,0 +1,115 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
+include(${CMAKE_ROOT}/Modules//CMakeParseImplicitLinkInfo.cmake)
+
+if( NOT ( ("${CMAKE_GENERATOR}" MATCHES "Make") OR
+ ("${CMAKE_GENERATOR}" MATCHES "Ninja") ) )
+ message(FATAL_ERROR "CUDA language not currently supported by \"${CMAKE_GENERATOR}\" generator")
+endif()
+
+if(NOT CMAKE_CUDA_COMPILER)
+ set(CMAKE_CUDA_COMPILER_INIT NOTFOUND)
+
+ # prefer the environment variable CUDACXX
+ if(NOT $ENV{CUDACXX} STREQUAL "")
+ get_filename_component(CMAKE_CUDA_COMPILER_INIT $ENV{CUDACXX} PROGRAM PROGRAM_ARGS CMAKE_CUDA_FLAGS_ENV_INIT)
+ if(CMAKE_CUDA_FLAGS_ENV_INIT)
+ set(CMAKE_CUDA_COMPILER_ARG1 "${CMAKE_CUDA_FLAGS_ENV_INIT}" CACHE STRING "First argument to CXX compiler")
+ endif()
+ if(NOT EXISTS ${CMAKE_CUDA_COMPILER_INIT})
+ message(FATAL_ERROR "Could not find compiler set in environment variable CUDACXX:\n$ENV{CUDACXX}.\n${CMAKE_CUDA_COMPILER_INIT}")
+ endif()
+ endif()
+
+ # finally list compilers to try
+ if(NOT CMAKE_CUDA_COMPILER_INIT)
+ set(CMAKE_CUDA_COMPILER_LIST nvcc)
+ endif()
+
+ _cmake_find_compiler(CUDA)
+else()
+ _cmake_find_compiler_path(CUDA)
+endif()
+
+mark_as_advanced(CMAKE_CUDA_COMPILER)
+
+#Allow the user to specify a host compiler
+set(CMAKE_CUDA_HOST_COMPILER "" CACHE FILEPATH "Host compiler to be used by nvcc")
+if(NOT $ENV{CUDAHOSTCXX} STREQUAL "")
+ get_filename_component(CMAKE_CUDA_HOST_COMPILER $ENV{CUDAHOSTCXX} PROGRAM)
+ if(NOT EXISTS ${CMAKE_CUDA_HOST_COMPILER})
+ message(FATAL_ERROR "Could not find compiler set in environment variable CUDAHOSTCXX:\n$ENV{CUDAHOSTCXX}.\n${CMAKE_CUDA_HOST_COMPILER}")
+ endif()
+endif()
+
+# Build a small source file to identify the compiler.
+if(NOT CMAKE_CUDA_COMPILER_ID_RUN)
+ set(CMAKE_CUDA_COMPILER_ID_RUN 1)
+
+ # Try to identify the compiler.
+ set(CMAKE_CUDA_COMPILER_ID)
+ set(CMAKE_CUDA_PLATFORM_ID)
+ file(READ ${CMAKE_ROOT}/Modules/CMakePlatformId.h.in
+ CMAKE_CUDA_COMPILER_ID_PLATFORM_CONTENT)
+
+ list(APPEND CMAKE_CUDA_COMPILER_ID_MATCH_VENDORS NVIDIA)
+ set(CMAKE_CUDA_COMPILER_ID_MATCH_VENDOR_REGEX_NVIDIA "nvcc: NVIDIA \(R\) Cuda compiler driver")
+
+ set(CMAKE_CXX_COMPILER_ID_TOOL_MATCH_REGEX "\nLd[^\n]*(\n[ \t]+[^\n]*)*\n[ \t]+([^ \t\r\n]+)[^\r\n]*-o[^\r\n]*CompilerIdCUDA/(\\./)?(CompilerIdCUDA.xctest/)?CompilerIdCUDA[ \t\n\\\"]")
+ set(CMAKE_CXX_COMPILER_ID_TOOL_MATCH_INDEX 2)
+
+ set(CMAKE_CUDA_COMPILER_ID_FLAGS_ALWAYS "-v")
+ if(CMAKE_CUDA_HOST_COMPILER)
+ list(APPEND CMAKE_CUDA_COMPILER_ID_FLAGS_ALWAYS "-ccbin=${CMAKE_CUDA_HOST_COMPILER}")
+ endif()
+
+ include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake)
+ CMAKE_DETERMINE_COMPILER_ID(CUDA CUDAFLAGS CMakeCUDACompilerId.cu)
+endif()
+
+include(CMakeFindBinUtils)
+
+#if this compiler vendor is matches NVIDIA we can determine
+#what the host compiler is. This only needs to be done if the CMAKE_CUDA_HOST_COMPILER
+#has NOT been explicitly set
+#
+#Find the line from compiler ID that contains a.out ( or last line )
+#We also need to find the implicit link lines. Which can be done by replacing
+#the compiler with cuda-fake-ld and pass too CMAKE_PARSE_IMPLICIT_LINK_INFO
+if(CMAKE_CUDA_COMPILER_ID STREQUAL NVIDIA)
+ #grab the last line of the output which holds the link line
+ string(REPLACE "#\$ " ";" nvcc_output "${CMAKE_CUDA_COMPILER_PRODUCED_OUTPUT}")
+ list(GET nvcc_output -1 nvcc_output)
+
+ #extract the compiler that is being used for linking
+ string(REPLACE " " ";" nvcc_output_to_find_launcher "${nvcc_output}")
+ list(GET nvcc_output_to_find_launcher 0 CMAKE_CUDA_HOST_LINK_LAUNCHER)
+ #we need to remove the quotes that nvcc adds around the directory section
+ #of the path
+ string(REPLACE "\"" "" CMAKE_CUDA_HOST_LINK_LAUNCHER "${CMAKE_CUDA_HOST_LINK_LAUNCHER}")
+
+ #prefix the line with cuda-fake-ld so that implicit link info believes it is
+ #a link line
+ set(nvcc_output "cuda-fake-ld ${nvcc_output}")
+ CMAKE_PARSE_IMPLICIT_LINK_INFO("${nvcc_output}"
+ CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES
+ CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES
+ CMAKE_CUDA_HOST_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES
+ log
+ "${CMAKE_CUDA_IMPLICIT_OBJECT_REGEX}")
+
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Parsed CUDA nvcc implicit link information from above output:\n${log}\n\n")
+
+endif()
+
+# configure all variables set in this file
+configure_file(${CMAKE_ROOT}/Modules/CMakeCUDACompiler.cmake.in
+ ${CMAKE_PLATFORM_INFO_DIR}/CMakeCUDACompiler.cmake
+ @ONLY
+ )
+
+set(CMAKE_CUDA_COMPILER_ENV_VAR "CUDACXX")
+set(CMAKE_CUDA_HOST_COMPILER_ENV_VAR "CUDAHOSTCXX")
diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake
index 59d8ab6..c5a2bcb 100644
--- a/Modules/CMakeDetermineCompilerId.cmake
+++ b/Modules/CMakeDetermineCompilerId.cmake
@@ -101,6 +101,8 @@ function(CMAKE_DETERMINE_COMPILER_ID lang flagvar src)
set(CMAKE_${lang}_SIMULATE_ID "${CMAKE_${lang}_SIMULATE_ID}" PARENT_SCOPE)
set(CMAKE_${lang}_SIMULATE_VERSION "${CMAKE_${lang}_SIMULATE_VERSION}" PARENT_SCOPE)
set(CMAKE_${lang}_STANDARD_COMPUTED_DEFAULT "${CMAKE_${lang}_STANDARD_COMPUTED_DEFAULT}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_PRODUCED_OUTPUT "${COMPILER_${lang}_PRODUCED_OUTPUT}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_PRODUCED_FILES "${COMPILER_${lang}_PRODUCED_FILES}" PARENT_SCOPE)
endfunction()
include(CMakeCompilerIdDetection)
@@ -135,7 +137,7 @@ function(CMAKE_DETERMINE_COMPILER_ID_BUILD lang testflags src)
set(COMPILER_DESCRIPTION
"Compiler: ${CMAKE_${lang}_COMPILER} ${CMAKE_${lang}_COMPILER_ID_ARG1}
Build flags: ${CMAKE_${lang}_COMPILER_ID_FLAGS_LIST}
-Id flags: ${testflags}
+Id flags: ${testflags} ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS}
")
# Compile the compiler identification source.
@@ -322,6 +324,7 @@ Id flags: ${testflags}
${CMAKE_${lang}_COMPILER_ID_ARG1}
${CMAKE_${lang}_COMPILER_ID_FLAGS_LIST}
${testflags}
+ ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS}
"${src}"
WORKING_DIRECTORY ${CMAKE_${lang}_COMPILER_ID_DIR}
OUTPUT_VARIABLE CMAKE_${lang}_COMPILER_ID_OUTPUT
@@ -400,6 +403,7 @@ ${CMAKE_${lang}_COMPILER_ID_OUTPUT}
# Return the files produced by the compilation.
set(COMPILER_${lang}_PRODUCED_FILES "${COMPILER_${lang}_PRODUCED_FILES}" PARENT_SCOPE)
set(COMPILER_${lang}_PRODUCED_OUTPUT "${COMPILER_${lang}_PRODUCED_OUTPUT}" PARENT_SCOPE)
+
endfunction()
#-----------------------------------------------------------------------------
diff --git a/Modules/CMakeGraphVizOptions.cmake b/Modules/CMakeGraphVizOptions.cmake
index e7c4de6..420e3a9 100644
--- a/Modules/CMakeGraphVizOptions.cmake
+++ b/Modules/CMakeGraphVizOptions.cmake
@@ -13,8 +13,8 @@
# CMake
# can generate graphviz files, showing the dependencies between the
# targets in a project and also external libraries which are linked
-# against. When CMake is run with the --graphviz=foo option, it will
-# produce
+# against. When CMake is run with the --graphviz=foo.dot option, it will
+# produce:
#
# * a foo.dot file showing all dependencies in the project
# * a foo.dot.<target> file for each target, file showing on which other targets the respective target depends
@@ -29,11 +29,18 @@
#
# .. variable:: GRAPHVIZ_GRAPH_TYPE
#
-# The graph type
+# The graph type.
#
# * Mandatory : NO
# * Default : "digraph"
#
+# Valid graph types are:
+#
+# * "graph" : Nodes are joined with lines
+# * "digraph" : Nodes are joined with arrows showing direction
+# * "strict graph" : Like "graph" but max one line between each node
+# * "strict digraph" : Like "graph" but max one line between each node in each direction
+#
# .. variable:: GRAPHVIZ_GRAPH_NAME
#
# The graph name.
diff --git a/Modules/CMakeTestCUDACompiler.cmake b/Modules/CMakeTestCUDACompiler.cmake
new file mode 100644
index 0000000..670b31d
--- /dev/null
+++ b/Modules/CMakeTestCUDACompiler.cmake
@@ -0,0 +1,71 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(CMAKE_CUDA_COMPILER_FORCED)
+ # The compiler configuration was forced by the user.
+ # Assume the user has configured all compiler information.
+ set(CMAKE_CUDA_COMPILER_WORKS TRUE)
+ return()
+endif()
+
+include(CMakeTestCompilerCommon)
+
+# Remove any cached result from an older CMake version.
+# We now store this in CMakeCUDACompiler.cmake.
+unset(CMAKE_CUDA_COMPILER_WORKS CACHE)
+
+# This file is used by EnableLanguage in cmGlobalGenerator to
+# determine that that selected cuda compiler can actually compile
+# and link the most basic of programs. If not, a fatal error
+# is set and cmake stops processing commands and will not generate
+# any makefiles or projects.
+if(NOT CMAKE_CUDA_COMPILER_WORKS)
+ PrintTestCompilerStatus("CUDA" "")
+ file(WRITE ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/main.cu
+ "#ifndef __CUDACC__\n"
+ "# error \"The CMAKE_CUDA_COMPILER is set to an invalid CUDA compiler\"\n"
+ "#endif\n"
+ "int main(){return 0;}\n")
+
+ try_compile(CMAKE_CUDA_COMPILER_WORKS ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/main.cu
+ OUTPUT_VARIABLE __CMAKE_CUDA_COMPILER_OUTPUT)
+
+ # Move result from cache to normal variable.
+ set(CMAKE_CUDA_COMPILER_WORKS ${CMAKE_CUDA_COMPILER_WORKS})
+ unset(CMAKE_CUDA_COMPILER_WORKS CACHE)
+ set(CUDA_TEST_WAS_RUN 1)
+endif()
+
+if(NOT CMAKE_CUDA_COMPILER_WORKS)
+ PrintTestCompilerStatus("CUDA" " -- broken")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Determining if the CUDA compiler works failed with "
+ "the following output:\n${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n")
+ message(FATAL_ERROR "The CUDA compiler \"${CMAKE_CUDA_COMPILER}\" "
+ "is not able to compile a simple test program.\nIt fails "
+ "with the following output:\n ${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n"
+ "CMake will not be able to correctly generate this project.")
+else()
+ if(CUDA_TEST_WAS_RUN)
+ PrintTestCompilerStatus("CUDA" " -- works")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Determining if the CUDA compiler works passed with "
+ "the following output:\n${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n")
+ endif()
+
+ # Try to identify the ABI and configure it into CMakeCUDACompiler.cmake
+ include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerABI.cmake)
+ CMAKE_DETERMINE_COMPILER_ABI(CUDA ${CMAKE_ROOT}/Modules/CMakeCUDACompilerABI.cu)
+
+ # Re-configure to save learned information.
+ configure_file(
+ ${CMAKE_ROOT}/Modules/CMakeCUDACompiler.cmake.in
+ ${CMAKE_PLATFORM_INFO_DIR}/CMakeCUDACompiler.cmake
+ @ONLY
+ )
+ include(${CMAKE_PLATFORM_INFO_DIR}/CMakeCUDACompiler.cmake)
+endif()
+
+
+unset(__CMAKE_CUDA_COMPILER_OUTPUT)
diff --git a/Modules/CPack.cmake b/Modules/CPack.cmake
index cee1914..4e7546b 100644
--- a/Modules/CPack.cmake
+++ b/Modules/CPack.cmake
@@ -126,7 +126,9 @@
#
# ${CPACK_PACKAGE_FILE_NAME}.${CPACK_PACKAGE_CHECKSUM}
#
-# Current supported alogorithms: MD5|SHA1|SHA224|SHA256|SHA384|SHA512.
+# Supported algorithms are those listed by the
+# :ref:`string(\<HASH\>) <Supported Hash Algorithms>`
+# command.
#
# .. variable:: CPACK_PROJECT_CONFIG_FILE
#
diff --git a/Modules/CPackDeb.cmake b/Modules/CPackDeb.cmake
index 653283c..909a12b 100644
--- a/Modules/CPackDeb.cmake
+++ b/Modules/CPackDeb.cmake
@@ -32,11 +32,11 @@
# - https://cmake.org/Wiki/CMake:CPackConfiguration
# - https://cmake.org/Wiki/CMake:CPackPackageGenerators#DEB_.28UNIX_only.29
#
-# List of CPackRPM specific variables:
+# List of CPackDEB specific variables:
#
-# .. variable:: CPACK_DEB_PACKAGE_COMPONENT
+# .. variable:: CPACK_DEB_COMPONENT_INSTALL
#
-# Enable component packaging for CPackRPM
+# Enable component packaging for CPackDEB
#
# * Mandatory : NO
# * Default : OFF
@@ -616,7 +616,7 @@ function(cpack_deb_prepare_package_vars)
find_program(SHLIBDEPS_EXECUTABLE dpkg-shlibdeps)
if(SHLIBDEPS_EXECUTABLE)
- # Check version of the dpkg-shlibdeps tool using CPackRPM method
+ # Check version of the dpkg-shlibdeps tool using CPackDEB method
execute_process(COMMAND env LC_ALL=C ${SHLIBDEPS_EXECUTABLE} --version
OUTPUT_VARIABLE _TMP_VERSION
ERROR_QUIET
diff --git a/Modules/CPackIFW.cmake b/Modules/CPackIFW.cmake
index 6c93ddb..d0d24ba 100644
--- a/Modules/CPackIFW.cmake
+++ b/Modules/CPackIFW.cmake
@@ -198,13 +198,18 @@
#
# ::
#
-# cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL]
+# cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL] [VIRTUAL]
+# [FORCED_INSTALLATION]
# [NAME <name>]
+# [DISPLAY_NAME <display_name>]
+# [DESCRIPTION <description>]
# [VERSION <version>]
+# [RELEASE_DATE <release_date>]
# [SCRIPT <script>]
# [PRIORITY <priority>]
# [DEPENDS <com_id> ...]
# [LICENSES <display_name> <file_path> ...]
+# [DEFAULT <value>]
# [USER_INTERFACES <file_path> <file_path> ...])
#
# This command should be called after :command:`cpack_add_component` command.
@@ -217,14 +222,35 @@
# if set, then the package manager stays disabled until that
# component is updated.
#
+# ``VIRTUAL``
+# if set, then the component will be hidden from the installer.
+# It is a equivalent of the ``HIDDEN`` option from the
+# :command:`cpack_add_component` command.
+#
+# ``FORCED_INSTALLATION``
+# if set, then the component must always be installed.
+# It is a equivalent of the ``REQUARED`` option from the
+# :command:`cpack_add_component` command.
+#
# ``NAME``
# is used to create domain-like identification for this component.
# By default used origin component name.
#
+# ``DISPLAY_NAME``
+# set to rewrite original name configured by
+# :command:`cpack_add_component` command.
+#
+# ``DESCRIPTION``
+# set to rewrite original description configured by
+# :command:`cpack_add_component` command.
+#
# ``VERSION``
# is version of component.
# By default used :variable:`CPACK_PACKAGE_VERSION`.
#
+# ``RELEASE_DATE``
+# keep empty to auto generate.
+#
# ``SCRIPT``
# is a relative or absolute path to operations script
# for this component.
@@ -239,6 +265,12 @@
# pair of <display_name> and <file_path> of license text for this
# component. You can specify more then one license.
#
+# ``DEFAULT``
+# Possible values are: TRUE, FALSE, and SCRIPT.
+# Set to FALSE to disable the component in the installer or to SCRIPT
+# to resolved during runtime (don't forget add the file of the script
+# as a value of the ``SCRIPT`` option).
+#
# ``USER_INTERFACES``
# a list of <file_path> representing pages to load
#
@@ -249,25 +281,48 @@
#
# ::
#
-# cpack_ifw_configure_component_group(<groupname>
+# cpack_ifw_configure_component_group(<groupname> [VIRTUAL]
+# [FORCED_INSTALLATION]
# [NAME <name>]
+# [DISPLAY_NAME <display_name>]
+# [DESCRIPTION <description>]
# [VERSION <version>]
+# [RELEASE_DATE <release_date>]
# [SCRIPT <script>]
# [PRIORITY <priority>]
# [LICENSES <display_name> <file_path> ...]
+# [DEFAULT <value>]
# [USER_INTERFACES <file_path> <file_path> ...])
#
# This command should be called after :command:`cpack_add_component_group`
# command.
#
+# ``VIRTUAL``
+# if set, then the group will be hidden from the installer.
+# Note that setting this on a root component does not work.
+#
+# ``FORCED_INSTALLATION``
+# if set, then the group must always be installed.
+#
# ``NAME``
# is used to create domain-like identification for this component group.
# By default used origin component group name.
#
+# ``DISPLAY_NAME``
+# set to rewrite original name configured by
+# :command:`cpack_add_component_group` command.
+#
+# ``DESCRIPTION``
+# set to rewrite original description configured by
+# :command:`cpack_add_component_group` command.
+#
# ``VERSION``
# is version of component group.
# By default used :variable:`CPACK_PACKAGE_VERSION`.
#
+# ``RELEASE_DATE``
+# keep empty to auto generate.
+#
# ``SCRIPT``
# is a relative or absolute path to operations script
# for this component group.
@@ -279,6 +334,13 @@
# pair of <display_name> and <file_path> of license text for this
# component group. You can specify more then one license.
#
+# ``DEFAULT``
+# Possible values are: TRUE, FALSE, and SCRIPT.
+# Set to TRUE to preselect the group in the installer
+# (this takes effect only on groups that have no visible child components)
+# or to SCRIPT to resolved during runtime (don't forget add the file of
+# the script as a value of the ``SCRIPT`` option).
+#
# ``USER_INTERFACES``
# a list of <file_path> representing pages to load
#
@@ -433,11 +495,15 @@
# Default path
-set(_CPACK_IFW_PATHS
- "${QTIFWDIR}"
- "$ENV{QTIFWDIR}"
- "${QTDIR}"
- "$ENV{QTIFWDIR}")
+foreach(_CPACK_IFW_PATH_VAR "QTIFWDIR" "QTDIR")
+ if(DEFINED ${_CPACK_IFW_PATH_VAR}
+ AND NOT "${${_CPACK_IFW_PATH_VAR}}" STREQUAL "")
+ list(APPEND _CPACK_IFW_PATHS "${${_CPACK_IFW_PATH_VAR}}")
+ endif()
+ if(NOT "$ENV{${_CPACK_IFW_PATH_VAR}}" STREQUAL "")
+ list(APPEND _CPACK_IFW_PATHS "$ENV{${_CPACK_IFW_PATH_VAR}}")
+ endif()
+endforeach()
if(WIN32)
list(APPEND _CPACK_IFW_PATHS
"$ENV{HOMEDRIVE}/Qt"
@@ -447,22 +513,44 @@ else()
"$ENV{HOME}/Qt"
"/opt/Qt")
endif()
-
-set(_CPACK_IFW_SUFFIXES
-# Common
- "bin"
-# Second branch
- "QtIFW2.3.0/bin"
- "QtIFW2.2.0/bin"
- "QtIFW2.1.0/bin"
- "QtIFW2.0.3/bin"
- "QtIFW2.0.1/bin"
- "QtIFW2.0.0/bin"
-# First branch
- "QtIFW-1.6.0/bin"
- "QtIFW-1.5.0/bin"
- "QtIFW-1.4.0/bin"
- "QtIFW-1.3.0/bin")
+list(REMOVE_DUPLICATES _CPACK_IFW_PATHS)
+
+set(_CPACK_IFW_PREFIXES
+ # QtSDK
+ "Tools/QtInstallerFramework/"
+ # Second branch
+ "QtIFW"
+ # First branch
+ "QtIFW-")
+
+set(_CPACK_IFW_VERSIONS
+ "2.3"
+ "2.3.0"
+ "2.2"
+ "2.2.0"
+ "2.1"
+ "2.1.0"
+ "2.0"
+ "2.0.3"
+ "2.0.2"
+ "2.0.1"
+ "2.0.0"
+ "1.6"
+ "1.6.0"
+ "1.5"
+ "1.5.0"
+ "1.4"
+ "1.4.0"
+ "1.3"
+ "1.3.0")
+
+set(_CPACK_IFW_SUFFIXES "bin")
+foreach(_CPACK_IFW_PREFIX ${_CPACK_IFW_PREFIXES})
+ foreach(_CPACK_IFW_VERSION ${_CPACK_IFW_VERSIONS})
+ list(APPEND
+ _CPACK_IFW_SUFFIXES "${_CPACK_IFW_PREFIX}${_CPACK_IFW_VERSION}/bin")
+ endforeach()
+endforeach()
# Look for 'binarycreator'
@@ -599,8 +687,8 @@ macro(cpack_ifw_configure_component compname)
string(TOUPPER ${compname} _CPACK_IFWCOMP_UNAME)
- set(_IFW_OPT COMMON ESSENTIAL)
- set(_IFW_ARGS NAME VERSION SCRIPT PRIORITY)
+ set(_IFW_OPT COMMON ESSENTIAL VIRTUAL FORCED_INSTALLATION)
+ set(_IFW_ARGS NAME DISPLAY_NAME DESCRIPTION VERSION RELEASE_DATE SCRIPT PRIORITY DEFAULT)
set(_IFW_MULTI_ARGS DEPENDS LICENSES USER_INTERFACES)
cmake_parse_arguments(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
@@ -639,8 +727,8 @@ macro(cpack_ifw_configure_component_group grpname)
string(TOUPPER ${grpname} _CPACK_IFWGRP_UNAME)
- set(_IFW_OPT)
- set(_IFW_ARGS NAME VERSION SCRIPT PRIORITY)
+ set(_IFW_OPT VIRTUAL FORCED_INSTALLATION)
+ set(_IFW_ARGS NAME DISPLAY_NAME DESCRIPTION VERSION RELEASE_DATE SCRIPT PRIORITY DEFAULT)
set(_IFW_MULTI_ARGS LICENSES USER_INTERFACES)
cmake_parse_arguments(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
diff --git a/Modules/CPackRPM.cmake b/Modules/CPackRPM.cmake
index 6017ce3..39697f0 100644
--- a/Modules/CPackRPM.cmake
+++ b/Modules/CPackRPM.cmake
@@ -45,7 +45,7 @@
#
# List of CPackRPM specific variables:
#
-# .. variable:: CPACK_RPM_PACKAGE_COMPONENT
+# .. variable:: CPACK_RPM_COMPONENT_INSTALL
#
# Enable component packaging for CPackRPM
#
@@ -472,7 +472,7 @@
# May be used to embed a pre (un)installation script in the spec file.
# The referred script file (or both) will be read and directly
# put after the ``%pre`` or ``%preun`` section
-# If :variable:`CPACK_RPM_PACKAGE_COMPONENT` is set to ON the (un)install
+# If :variable:`CPACK_RPM_COMPONENT_INSTALL` is set to ON the (un)install
# script for each component can be overridden with
# ``CPACK_RPM_<COMPONENT>_PRE_INSTALL_SCRIPT_FILE`` and
# ``CPACK_RPM_<COMPONENT>_PRE_UNINSTALL_SCRIPT_FILE``.
@@ -491,7 +491,7 @@
# May be used to embed a post (un)installation script in the spec file.
# The referred script file (or both) will be read and directly
# put after the ``%post`` or ``%postun`` section.
-# If :variable:`CPACK_RPM_PACKAGE_COMPONENT` is set to ON the (un)install
+# If :variable:`CPACK_RPM_COMPONENT_INSTALL` is set to ON the (un)install
# script for each component can be overridden with
# ``CPACK_RPM_<COMPONENT>_POST_INSTALL_SCRIPT_FILE`` and
# ``CPACK_RPM_<COMPONENT>_POST_UNINSTALL_SCRIPT_FILE``.
@@ -1844,6 +1844,12 @@ function(cpack_rpm_generate_package)
set(CPACK_RPM_PACKAGE_RELOCATABLE FALSE) # disable relocatable option if building source RPM
endif()
+ execute_process(
+ COMMAND "${RPMBUILD_EXECUTABLE}" --querytags
+ OUTPUT_VARIABLE RPMBUILD_TAG_LIST
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REPLACE "\n" ";" RPMBUILD_TAG_LIST "${RPMBUILD_TAG_LIST}")
+
# Check if additional fields for RPM spec header are given
# There may be some COMPONENT specific variables as well
# If component specific var is not provided we use the global one
@@ -1852,6 +1858,7 @@ function(cpack_rpm_generate_package)
if(CPACK_RPM_PACKAGE_DEBUG)
message("CPackRPM:Debug: processing ${_RPM_SPEC_HEADER}")
endif()
+
if(CPACK_RPM_PACKAGE_COMPONENT)
cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}"
"CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_${_RPM_SPEC_HEADER}"
@@ -1859,9 +1866,24 @@ function(cpack_rpm_generate_package)
endif()
if(DEFINED CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER})
+ cmake_policy(PUSH)
+ cmake_policy(SET CMP0057 NEW)
+ # Prefix can be replaced by Prefixes but the old version stil works so we'll ignore it for now
+ # Requires* is a special case because it gets transformed to Requires(pre/post/preun/postun)
+ # Auto* is a special case because the tags can not be queried by querytags rpmbuild flag
+ set(special_case_tags_ PREFIX REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN AUTOPROV AUTOREQ AUTOREQPROV)
+ if(NOT _RPM_SPEC_HEADER IN_LIST RPMBUILD_TAG_LIST AND NOT _RPM_SPEC_HEADER IN_LIST special_case_tags_)
+ cmake_policy(POP)
+ message(AUTHOR_WARNING "CPackRPM:Warning: ${_RPM_SPEC_HEADER} not "
+ "supported in provided rpmbuild. Tag will not be used.")
+ continue()
+ endif()
+ cmake_policy(POP)
+
if(CPACK_RPM_PACKAGE_DEBUG)
message("CPackRPM:Debug: using CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}")
endif()
+
set(CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP ${CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}})
endif()
@@ -2416,6 +2438,7 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
\@TMP_RPM_PROVIDES\@
\@TMP_RPM_OBSOLETES\@
\@TMP_RPM_CONFLICTS\@
+\@TMP_RPM_SUGGESTS\@
\@TMP_RPM_AUTOPROV\@
\@TMP_RPM_AUTOREQ\@
\@TMP_RPM_AUTOREQPROV\@
@@ -2470,6 +2493,7 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
\@TMP_RPM_PROVIDES\@
\@TMP_RPM_OBSOLETES\@
\@TMP_RPM_CONFLICTS\@
+\@TMP_RPM_SUGGESTS\@
\@TMP_RPM_AUTOPROV\@
\@TMP_RPM_AUTOREQ\@
\@TMP_RPM_AUTOREQPROV\@
diff --git a/Modules/Compiler/ARMCC.cmake b/Modules/Compiler/ARMCC.cmake
index 2ec75c3..250a8f4 100644
--- a/Modules/Compiler/ARMCC.cmake
+++ b/Modules/Compiler/ARMCC.cmake
@@ -28,6 +28,7 @@ macro(__compiler_armcc lang)
set(CMAKE_${lang}_OUTPUT_EXTENSION ".o")
set(CMAKE_${lang}_OUTPUT_EXTENSION_REPLACE 1)
+ set(CMAKE_${lang}_RESPONSE_FILE_LINK_FLAG "--via=")
set(CMAKE_${lang}_LINK_EXECUTABLE "<CMAKE_LINKER> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> <OBJECTS> -o <TARGET> --list <TARGET_BASE>.map")
set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "<CMAKE_AR> --create -cr <TARGET> <LINK_FLAGS> <OBJECTS>")
diff --git a/Modules/Compiler/AppleClang-C.cmake b/Modules/Compiler/AppleClang-C.cmake
index 1cc72c0..fe39b3b 100644
--- a/Modules/Compiler/AppleClang-C.cmake
+++ b/Modules/Compiler/AppleClang-C.cmake
@@ -25,18 +25,14 @@ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.0)
endif()
macro(cmake_record_c_compile_features)
- macro(_get_appleclang_features std_version list)
- record_compiler_features(C "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.0)
- _get_appleclang_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
+ _record_compiler_features_c(11)
if (_result EQUAL 0)
- _get_appleclang_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+ _record_compiler_features_c(99)
endif()
if (_result EQUAL 0)
- _get_appleclang_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+ _record_compiler_features_c(90)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/AppleClang-CXX.cmake b/Modules/Compiler/AppleClang-CXX.cmake
index 95bc79a..8dd6278 100644
--- a/Modules/Compiler/AppleClang-CXX.cmake
+++ b/Modules/Compiler/AppleClang-CXX.cmake
@@ -36,21 +36,17 @@ endif()
macro(cmake_record_cxx_compile_features)
- macro(_get_appleclang_features std_version list)
- record_compiler_features(CXX "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.0)
set(_result 0)
if(CMAKE_CXX14_STANDARD_COMPILE_OPTION)
- _get_appleclang_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
+ _record_compiler_features_cxx(14)
endif()
if (_result EQUAL 0)
- _get_appleclang_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+ _record_compiler_features_cxx(11)
endif()
if (_result EQUAL 0)
- _get_appleclang_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+ _record_compiler_features_cxx(98)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/Clang-C.cmake b/Modules/Compiler/Clang-C.cmake
index d8b7743..b3f3805 100644
--- a/Modules/Compiler/Clang-C.cmake
+++ b/Modules/Compiler/Clang-C.cmake
@@ -34,18 +34,14 @@ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
endif()
macro(cmake_record_c_compile_features)
- macro(_get_clang_features std_version list)
- record_compiler_features(C "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (UNIX AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
- _get_clang_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
+ _record_compiler_features_c(11)
if (_result EQUAL 0)
- _get_clang_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+ _record_compiler_features_c(99)
endif()
if (_result EQUAL 0)
- _get_clang_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+ _record_compiler_features_c(90)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/Clang-CXX.cmake b/Modules/Compiler/Clang-CXX.cmake
index dc62711..dfe0628 100644
--- a/Modules/Compiler/Clang-CXX.cmake
+++ b/Modules/Compiler/Clang-CXX.cmake
@@ -44,18 +44,14 @@ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
endif()
macro(cmake_record_cxx_compile_features)
- macro(_get_clang_features std_version list)
- record_compiler_features(CXX "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
- _get_clang_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
+ _record_compiler_features_cxx(14)
if (_result EQUAL 0)
- _get_clang_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+ _record_compiler_features_cxx(11)
endif()
if (_result EQUAL 0)
- _get_clang_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+ _record_compiler_features_cxx(98)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/GNU-C.cmake b/Modules/Compiler/GNU-C.cmake
index 2c478da..4dbf6ef 100644
--- a/Modules/Compiler/GNU-C.cmake
+++ b/Modules/Compiler/GNU-C.cmake
@@ -40,20 +40,16 @@ endif()
macro(cmake_record_c_compile_features)
- macro(_get_gcc_features std_version list)
- record_compiler_features(C "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.6)
- _get_gcc_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
+ _record_compiler_features_c(11)
endif()
if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
if (_result EQUAL 0)
- _get_gcc_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+ _record_compiler_features_c(99)
endif()
if (_result EQUAL 0)
- _get_gcc_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+ _record_compiler_features_c(90)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/GNU-CXX.cmake b/Modules/Compiler/GNU-CXX.cmake
index e1c555b..936f62b 100644
--- a/Modules/Compiler/GNU-CXX.cmake
+++ b/Modules/Compiler/GNU-CXX.cmake
@@ -47,20 +47,16 @@ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
endif()
macro(cmake_record_cxx_compile_features)
- macro(_get_gcc_features std_version list)
- record_compiler_features(CXX "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8)
- _get_gcc_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
+ _record_compiler_features_cxx(14)
endif()
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
if (_result EQUAL 0)
- _get_gcc_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+ _record_compiler_features_cxx(11)
endif()
if (_result EQUAL 0)
- _get_gcc_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+ _record_compiler_features_cxx(98)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/Intel-C-FeatureTests.cmake b/Modules/Compiler/Intel-C-FeatureTests.cmake
index 34175c8..5d09767 100644
--- a/Modules/Compiler/Intel-C-FeatureTests.cmake
+++ b/Modules/Compiler/Intel-C-FeatureTests.cmake
@@ -3,15 +3,11 @@
# - https://software.intel.com/en-us/articles/c99-support-in-intel-c-compiler
# - https://software.intel.com/en-us/articles/c11-support-in-intel-c-compiler
-# FIXME: Intel C feature detection works only when simulating the GNU compiler.
-if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC")
- return()
-endif()
-
set(DETECT_C99 "defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L")
+set(DETECT_C11 "defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L")
#static assert is only around in version 1500 update 2 and above
-set(_cmake_feature_test_c_static_assert "(__INTEL_COMPILER > 1500 || (__INTEL_COMPILER == 1500 && __INTEL_COMPILER_UPDATE > 1) ) && ${DETECT_C99}")
+set(_cmake_feature_test_c_static_assert "(__INTEL_COMPILER > 1500 || (__INTEL_COMPILER == 1500 && __INTEL_COMPILER_UPDATE > 1) ) && (${DETECT_C11} || ${DETECT_C99} && !defined(_MSC_VER))")
set(_cmake_oldestSupported "__INTEL_COMPILER >= 1110")
set(Intel_C99 "${_cmake_oldestSupported} && ${DETECT_C99}")
@@ -21,3 +17,4 @@ set(_cmake_feature_test_c_function_prototypes "${_cmake_oldestSupported}")
unset(Intel_C99)
unset(DETECT_C99)
+unset(DETECT_C11)
diff --git a/Modules/Compiler/Intel-C.cmake b/Modules/Compiler/Intel-C.cmake
index 61adf40..5a79452 100644
--- a/Modules/Compiler/Intel-C.cmake
+++ b/Modules/Compiler/Intel-C.cmake
@@ -47,21 +47,16 @@ unset(_std)
unset(_ext)
macro(cmake_record_c_compile_features)
- macro(_get_intel_c_features std_version list)
- record_compiler_features(C "${std_version}" ${list})
- endmacro()
-
set(_result 0)
- if (NOT "x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC" AND
- NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.1)
+ if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.1)
if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.0)
- _get_intel_c_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
+ _record_compiler_features_C(11)
endif()
if (_result EQUAL 0)
- _get_intel_c_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+ _record_compiler_features_C(99)
endif()
if (_result EQUAL 0)
- _get_intel_c_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+ _record_compiler_features_C(90)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/Intel-CXX-FeatureTests.cmake b/Modules/Compiler/Intel-CXX-FeatureTests.cmake
index 57a05c8..e370647 100644
--- a/Modules/Compiler/Intel-CXX-FeatureTests.cmake
+++ b/Modules/Compiler/Intel-CXX-FeatureTests.cmake
@@ -3,11 +3,14 @@
# - https://software.intel.com/en-us/articles/c14-features-supported-by-intel-c-compiler
# - http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0096r3.html
-# FIXME: Intel C++ feature detection works only when simulating the GNU compiler.
-# When simulating MSVC, Intel always sets __cplusplus to 199711L.
-if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
- return()
-endif()
+# Notes:
+# [1] Some Intel versions define some feature macros under -std=gnu++98
+# that do not work in that mode (or work with warnings):
+# - __cpp_attributes 200809
+# - __cpp_init_captures 201304
+# - __cpp_lambdas 200907
+# - __cpp_rvalue_references 200610
+# - __cpp_variadic_templates 200704
set(_cmake_feature_test_cxx_variable_templates "__cpp_variable_templates >= 201304")
set(_cmake_feature_test_cxx_relaxed_constexpr "__cpp_constexpr >= 201304")
@@ -18,44 +21,50 @@ set(DETECT_CXX11 "((__cplusplus >= 201103L) || defined(__INTEL_CXX11_MODE__) ||
#if you are compiling as 98/11/14. So to properly detect C++14 with this version
#we look for the existence of __GXX_EXPERIMENTAL_CXX0X__ but not __INTEL_CXX11_MODE__
set(DETECT_BUGGY_ICC15 "((__INTEL_COMPILER == 1500) && (__INTEL_COMPILER_UPDATE == 1))")
-set(DETECT_CXX14 "((__cplusplus >= 201300L) || ((__cplusplus == 201103L) && !defined(__INTEL_CXX11_MODE__)) || ((${DETECT_BUGGY_ICC15}) && defined(__GXX_EXPERIMENTAL_CXX0X__) && !defined(__INTEL_CXX11_MODE__) ) )")
+set(DETECT_CXX14 "((__cplusplus >= 201300L) || ((__cplusplus == 201103L) && !defined(__INTEL_CXX11_MODE__)) || ((${DETECT_BUGGY_ICC15}) && defined(__GXX_EXPERIMENTAL_CXX0X__) && !defined(__INTEL_CXX11_MODE__) ) || (defined(__INTEL_CXX11_MODE__) && defined(__cpp_aggregate_nsdmi)) )")
+unset(DETECT_BUGGY_ICC15)
set(Intel16_CXX14 "__INTEL_COMPILER >= 1600 && ${DETECT_CXX14}")
set(_cmake_feature_test_cxx_aggregate_default_initializers "${Intel16_CXX14}")
set(_cmake_feature_test_cxx_contextual_conversions "${Intel16_CXX14}")
-set(_cmake_feature_test_cxx_generic_lambdas "${Intel16_CXX14}")
+set(_cmake_feature_test_cxx_generic_lambdas "__cpp_generic_lambdas >= 201304")
set(_cmake_feature_test_cxx_digit_separators "${Intel16_CXX14}")
# This test is supposed to work in Intel 14 but the compiler has a bug
# in versions 14 and 15::
# https://software.intel.com/en-us/forums/intel-c-compiler/topic/600514
-# It also appears to fail with an internal compiler error on Intel 16.
+# It also appears to fail with an internal compiler error on Intel 16 and 17.
#set(_cmake_feature_test_cxx_generalized_initializers "${Intel16_CXX14}")
+unset(Intel16_CXX14)
-set(Intel15_CXX14 "__INTEL_COMPILER >= 1500 && ${DETECT_CXX14}")
-set(_cmake_feature_test_cxx_decltype_auto "${Intel15_CXX14}")
-set(_cmake_feature_test_cxx_lambda_init_captures "${Intel15_CXX14}")
+set(Intel15 "__INTEL_COMPILER >= 1500")
+set(Intel15_CXX14 "${Intel15} && ${DETECT_CXX14}")
+set(_cmake_feature_test_cxx_decltype_auto "__cpp_decltype_auto >= 201304 || ${Intel15_CXX14}")
+set(_cmake_feature_test_cxx_lambda_init_captures "(__cpp_init_captures >= 201304 || ${Intel15}) && ${DETECT_CXX14}") # [1]
set(_cmake_feature_test_cxx_attribute_deprecated "${Intel15_CXX14}")
-set(_cmake_feature_test_cxx_return_type_deduction "${Intel15_CXX14}")
+set(_cmake_feature_test_cxx_return_type_deduction "__cpp_return_type_deduction >= 201304 || ${Intel15_CXX14}")
+unset(Intel15_CXX14)
+unset(Intel15)
set(Intel15_CXX11 "__INTEL_COMPILER >= 1500 && ${DETECT_CXX11}")
set(_cmake_feature_test_cxx_alignas "${Intel15_CXX11}")
set(_cmake_feature_test_cxx_alignof "${Intel15_CXX11}")
set(_cmake_feature_test_cxx_inheriting_constructors "${Intel15_CXX11}")
-set(_cmake_feature_test_cxx_user_literals "${Intel15_CXX11}")
+set(_cmake_feature_test_cxx_user_literals "__cpp_user_defined_literals >= 200809 || (${Intel15_CXX11} && (!defined(_MSC_VER) || __INTEL_COMPILER >= 1600))")
set(_cmake_feature_test_cxx_thread_local "${Intel15_CXX11}")
+unset(Intel15_CXX11)
set(Intel14_CXX11 "${DETECT_CXX11} && (__INTEL_COMPILER > 1400 || (__INTEL_COMPILER == 1400 && __INTEL_COMPILER_UPDATE >= 2))")
# Documented as 12.0+ but in testing it only works on 14.0.2+
-set(_cmake_feature_test_cxx_decltype_incomplete_return_types "${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_decltype_incomplete_return_types "${Intel14_CXX11} && !defined(_MSC_VER)")
set(Intel14_CXX11 "__INTEL_COMPILER >= 1400 && ${DETECT_CXX11}")
set(_cmake_feature_test_cxx_delegating_constructors "${Intel14_CXX11}")
-set(_cmake_feature_test_cxx_constexpr "${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_constexpr "__cpp_constexpr >= 200704 || ${Intel14_CXX11}")
set(_cmake_feature_test_cxx_sizeof_member "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_strong_enums "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_reference_qualified_functions "${Intel14_CXX11}")
-set(_cmake_feature_test_cxx_raw_string_literals "${Intel14_CXX11}")
-set(_cmake_feature_test_cxx_unicode_literals "${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_raw_string_literals "__cpp_raw_strings >= 200710 || ${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_unicode_literals "__cpp_unicode_literals >= 200710 || (${Intel14_CXX11} && (!defined(_MSC_VER) || __INTEL_COMPILER >= 1600))")
set(_cmake_feature_test_cxx_inline_namespaces "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_unrestricted_unions "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_nonstatic_member_init "${Intel14_CXX11}")
@@ -64,29 +73,32 @@ set(_cmake_feature_test_cxx_override "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_final "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_noexcept "${Intel14_CXX11}")
set(_cmake_feature_test_cxx_defaulted_move_initializers "${Intel14_CXX11}")
+unset(Intel14_CXX11)
set(Intel13_CXX11 "__INTEL_COMPILER >= 1300 && ${DETECT_CXX11}")
set(_cmake_feature_test_cxx_explicit_conversions "${Intel13_CXX11}")
set(_cmake_feature_test_cxx_range_for "${Intel13_CXX11}")
# Cannot find Intel documentation for N2640: cxx_uniform_initialization
set(_cmake_feature_test_cxx_uniform_initialization "${Intel13_CXX11}")
+unset(Intel13_CXX11)
-set(Intel121_CXX11 "${_cmake_oldestSupported} && ${DETECT_CXX11}")
-set(_cmake_feature_test_cxx_variadic_templates "${Intel121_CXX11}")
+set(Intel121 "${_cmake_oldestSupported}")
+set(Intel121_CXX11 "${Intel121} && ${DETECT_CXX11}")
+set(_cmake_feature_test_cxx_variadic_templates "(__cpp_variadic_templates >= 200704 || ${Intel121}) && ${DETECT_CXX11}") # [1]
set(_cmake_feature_test_cxx_alias_templates "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_nullptr "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_trailing_return_types "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_attributes "${Intel121_CXX11}")
+set(_cmake_feature_test_cxx_attributes "(__cpp_attributes >= 200809 || ${Intel121}) && ${DETECT_CXX11}") # [1]
set(_cmake_feature_test_cxx_default_function_template_args "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_extended_friend_declarations "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_rvalue_references "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_decltype "${Intel121_CXX11}")
+set(_cmake_feature_test_cxx_rvalue_references "(__cpp_rvalue_references >= 200610 || ${Intel121}) && ${DETECT_CXX11}") # [1]
+set(_cmake_feature_test_cxx_decltype "__cpp_decltype >= 200707 || ${Intel121_CXX11}")
set(_cmake_feature_test_cxx_defaulted_functions "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_deleted_functions "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_local_type_template_args "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_lambdas "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_binary_literals "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_static_assert "${Intel121_CXX11}")
+set(_cmake_feature_test_cxx_lambdas "(__cpp_lambdas >= 200907 || ${Intel121}) && ${DETECT_CXX11}") # [1]
+set(_cmake_feature_test_cxx_binary_literals "__cpp_binary_literals >= 201304 || ${Intel121}")
+set(_cmake_feature_test_cxx_static_assert "(__cpp_static_assert >= 200410 || ${Intel121}) && ${DETECT_CXX11}")
set(_cmake_feature_test_cxx_right_angle_brackets "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_auto_type "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_extern_templates "${Intel121_CXX11}")
@@ -94,3 +106,8 @@ set(_cmake_feature_test_cxx_variadic_macros "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_long_long_type "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_func_identifier "${Intel121_CXX11}")
set(_cmake_feature_test_cxx_template_template_parameters "${Intel121_CXX11}")
+unset(Intel121_CXX11)
+unset(Intel121)
+
+unset(DETECT_CXX11)
+unset(DETECT_CXX14)
diff --git a/Modules/Compiler/Intel-CXX.cmake b/Modules/Compiler/Intel-CXX.cmake
index 29e02d3..d01d38d 100644
--- a/Modules/Compiler/Intel-CXX.cmake
+++ b/Modules/Compiler/Intel-CXX.cmake
@@ -10,19 +10,23 @@ set(CMAKE_DEPFILE_FLAGS_CXX "-MD -MT <OBJECT> -MF <DEPFILE>")
if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
set(_std -Qstd)
set(_ext c++)
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-Qstd=c++14")
+ # todo: there is no gnu++14 value supported; figure out what to do
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-Qstd=c++14")
+ endif()
else()
set(_std -std)
set(_ext gnu++)
-endif()
-
-if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.2)
- set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "${_std}=c++14")
- # todo: there is no gnu++14 value supported; figure out what to do
- set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "${_std}=c++14")
-elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.0)
- set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "${_std}=c++1y")
- # todo: there is no gnu++14 value supported; figure out what to do
- set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "${_std}=c++1y")
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.2)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
+ # todo: there is no gnu++14 value supported; figure out what to do
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=c++14")
+ elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.0)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++1y")
+ # todo: there is no gnu++14 value supported; figure out what to do
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=c++1y")
+ endif()
endif()
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.0)
@@ -35,11 +39,12 @@ endif()
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
- set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "${_std}=gnu++98")
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
else()
set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "${_std}=c++98")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "${_std}=gnu++98")
endif()
- set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "${_std}=${_ext}98")
endif()
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
@@ -59,21 +64,18 @@ unset(_std)
unset(_ext)
macro(cmake_record_cxx_compile_features)
- macro(_get_intel_features std_version list)
- record_compiler_features(CXX "${std_version}" ${list})
- endmacro()
-
set(_result 0)
- if(NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC" AND
- NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
- if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0)
- _get_intel_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0
+ OR (NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC" AND
+ NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0))
+ _record_compiler_features_cxx(14)
endif()
if (_result EQUAL 0)
- _get_intel_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+ _record_compiler_features_cxx(11)
endif()
if (_result EQUAL 0)
- _get_intel_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+ _record_compiler_features_cxx(98)
endif()
endif()
endmacro()
diff --git a/Modules/Compiler/MSVC-CXX.cmake b/Modules/Compiler/MSVC-CXX.cmake
index 82ce069..f103832 100644
--- a/Modules/Compiler/MSVC-CXX.cmake
+++ b/Modules/Compiler/MSVC-CXX.cmake
@@ -5,5 +5,12 @@ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0)
endif()
macro(cmake_record_cxx_compile_features)
- record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES)
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0)
+ list(APPEND CMAKE_CXX_COMPILE_FEATURES
+ cxx_std_98
+ cxx_std_11
+ cxx_std_14
+ )
+ _record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES)
+ endif()
endmacro()
diff --git a/Modules/Compiler/NVIDIA-CUDA.cmake b/Modules/Compiler/NVIDIA-CUDA.cmake
new file mode 100644
index 0000000..e3ff5e3
--- /dev/null
+++ b/Modules/Compiler/NVIDIA-CUDA.cmake
@@ -0,0 +1,24 @@
+set(CMAKE_CUDA_VERBOSE_FLAG "-v")
+
+
+set(CMAKE_CUDA_COMPILE_OPTIONS_PIE -Xcompiler=-fPIE)
+set(CMAKE_CUDA_COMPILE_OPTIONS_PIC -Xcompiler=-fPIC)
+#CMAKE_SHARED_LIBRARY_CUDA_FLAGS is sent to the host linker so we don' need
+#to forward it through nvcc
+set(CMAKE_SHARED_LIBRARY_CUDA_FLAGS -fPIC)
+set(CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS -shared)
+set(CMAKE_INCLUDE_SYSTEM_FLAG_CUDA -isystem=)
+set(CMAKE_CUDA_COMPILE_OPTIONS_VISIBILITY -Xcompiler=-fvisibility=)
+
+set(CMAKE_CUDA_FLAGS_INIT " ")
+set(CMAKE_CUDA_FLAGS_DEBUG_INIT " -g")
+set(CMAKE_CUDA_FLAGS_MINSIZEREL_INIT " -Os -DNDEBUG")
+set(CMAKE_CUDA_FLAGS_RELEASE_INIT " -O3 -DNDEBUG")
+set(CMAKE_CUDA_FLAGS_RELWITHDEBINFO_INIT " -O2 -g -DNDEBUG")
+
+set(CMAKE_CUDA98_STANDARD_COMPILE_OPTION "")
+set(CMAKE_CUDA98_EXTENSION_COMPILE_OPTION "")
+set(CMAKE_CUDA11_STANDARD_COMPILE_OPTION "-std=c++11")
+set(CMAKE_CUDA11_EXTENSION_COMPILE_OPTION "-std=c++11")
+
+set(CMAKE_CUDA_STANDARD_DEFAULT 98)
diff --git a/Modules/Compiler/NVIDIA-DetermineCompiler.cmake b/Modules/Compiler/NVIDIA-DetermineCompiler.cmake
new file mode 100644
index 0000000..32ccf8a
--- /dev/null
+++ b/Modules/Compiler/NVIDIA-DetermineCompiler.cmake
@@ -0,0 +1,7 @@
+
+set(_compiler_id_pp_test "defined(__NVCC__)")
+
+set(_compiler_id_version_compute "
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__CUDACC_VER_MAJOR__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__CUDACC_VER_MINOR__)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__CUDACC_VER_BUILD__)")
diff --git a/Modules/Compiler/SunPro-CXX.cmake b/Modules/Compiler/SunPro-CXX.cmake
index ce01cdd..e83c896 100644
--- a/Modules/Compiler/SunPro-CXX.cmake
+++ b/Modules/Compiler/SunPro-CXX.cmake
@@ -32,6 +32,8 @@ set(CMAKE_CXX_CREATE_STATIC_LIBRARY
"<CMAKE_RANLIB> <TARGET> ")
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13)
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++11")
set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=c++11")
endif()
@@ -49,15 +51,11 @@ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13)
endif()
macro(cmake_record_cxx_compile_features)
- macro(_get_solaris_studio_features std_version list)
- record_compiler_features(CXX "${std_version}" ${list})
- endmacro()
-
set(_result 0)
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13)
- _get_solaris_studio_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+ _record_compiler_features_cxx(11)
if (_result EQUAL 0)
- _get_solaris_studio_features("" CMAKE_CXX98_COMPILE_FEATURES)
+ _record_compiler_features_cxx(98)
endif()
endif()
endmacro()
diff --git a/Modules/ExternalData.cmake b/Modules/ExternalData.cmake
index 07cd114..873f88d 100644
--- a/Modules/ExternalData.cmake
+++ b/Modules/ExternalData.cmake
@@ -279,6 +279,10 @@ The following hash algorithms are supported::
SHA256 .sha256 US Secure Hash Algorithms, RFC 4634
SHA384 .sha384 US Secure Hash Algorithms, RFC 4634
SHA512 .sha512 US Secure Hash Algorithms, RFC 4634
+ SHA3_224 .sha3-224 Keccak SHA-3
+ SHA3_256 .sha3-256 Keccak SHA-3
+ SHA3_384 .sha3-384 Keccak SHA-3
+ SHA3_512 .sha3-512 Keccak SHA-3
Note that the hashes are used only for unique data identification and
download verification.
@@ -508,8 +512,8 @@ endfunction()
#-----------------------------------------------------------------------------
# Private helper interface
-set(_ExternalData_REGEX_ALGO "MD5|SHA1|SHA224|SHA256|SHA384|SHA512")
-set(_ExternalData_REGEX_EXT "md5|sha1|sha224|sha256|sha384|sha512")
+set(_ExternalData_REGEX_ALGO "MD5|SHA1|SHA224|SHA256|SHA384|SHA512|SHA3_224|SHA3_256|SHA3_384|SHA3_512")
+set(_ExternalData_REGEX_EXT "md5|sha1|sha224|sha256|sha384|sha512|sha3-224|sha3-256|sha3-384|sha3-512")
set(_ExternalData_SELF "${CMAKE_CURRENT_LIST_FILE}")
get_filename_component(_ExternalData_SELF_DIR "${_ExternalData_SELF}" PATH)
@@ -1082,6 +1086,7 @@ if("${ExternalData_ACTION}" STREQUAL "fetch")
if("${ext}" MATCHES "^\\.(${_ExternalData_REGEX_EXT})$")
string(TOUPPER "${CMAKE_MATCH_1}" algo)
+ string(REPLACE "-" "_" algo "${algo}")
else()
message(FATAL_ERROR "Unknown hash algorithm extension \"${ext}\"")
endif()
diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake
index 1e0be09..a0f731c 100644
--- a/Modules/ExternalProject.cmake
+++ b/Modules/ExternalProject.cmake
@@ -73,6 +73,10 @@ Create custom targets to build projects in external trees
does not output anything which can make the build appear to have stalled.
This option forces Git to output progress information during the clone step
so that forward progress is indicated.
+ ``GIT_CONFIG <option>...``
+ Tell Git to clone with ``--config <option>``. Use additional configuration
+ parameters when cloning the project (``key=value`` as expected by ``git
+ config``).
``HG_REPOSITORY <url>``
URL of mercurial repo
``HG_TAG <tag>``
@@ -423,7 +427,7 @@ if(_ep_func)
endif()
# Save regex matching supported hash algorithm names.
-set(_ep_hash_algos "MD5|SHA1|SHA224|SHA256|SHA384|SHA512")
+set(_ep_hash_algos "MD5|SHA1|SHA224|SHA256|SHA384|SHA512|SHA3_224|SHA3_256|SHA3_384|SHA3_512")
set(_ep_hash_regex "^(${_ep_hash_algos})=([0-9A-Fa-f]+)$")
set(_ExternalProject_SELF "${CMAKE_CURRENT_LIST_FILE}")
@@ -514,7 +518,7 @@ define_property(DIRECTORY PROPERTY "EP_UPDATE_DISCONNECTED" INHERITED
"ExternalProject module."
)
-function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_remote_name git_submodules git_shallow git_progress src_name work_dir gitclone_infofile gitclone_stampfile tls_verify)
+function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_remote_name git_submodules git_shallow git_progress git_config src_name work_dir gitclone_infofile gitclone_stampfile tls_verify)
if(NOT GIT_VERSION_STRING VERSION_LESS 1.7.10)
set(git_clone_shallow_options "--depth 1 --no-single-branch")
else()
@@ -565,6 +569,11 @@ if(git_progress)
list(APPEND git_clone_options --progress)
endif()
+set(git_config \"${git_config}\")
+foreach(config IN LISTS git_config)
+ list(APPEND git_clone_options --config \${config})
+endforeach()
+
# try the clone 3 times incase there is an odd git clone issue
set(error_code 1)
set(number_of_tries 0)
@@ -1236,87 +1245,84 @@ endfunction()
function(_ep_get_build_command name step cmd_var)
- set(cmd "${${cmd_var}}")
- if(NOT cmd)
- set(args)
- _ep_get_configure_command_id(${name} cfg_cmd_id)
- if(cfg_cmd_id STREQUAL "cmake")
- # CMake project. Select build command based on generator.
- get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
- if("${CMAKE_GENERATOR}" MATCHES "Make" AND
- ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
- # The project uses the same Makefile generator. Use recursive make.
- set(cmd "$(MAKE)")
- if(step STREQUAL "INSTALL")
- set(args install)
- endif()
- if("x${step}x" STREQUAL "xTESTx")
- set(args test)
- endif()
- else()
- # Drive the project with "cmake --build".
- get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
- if(cmake_command)
- set(cmd "${cmake_command}")
- else()
- set(cmd "${CMAKE_COMMAND}")
- endif()
- set(args --build ".")
- if(CMAKE_CONFIGURATION_TYPES)
- if (CMAKE_CFG_INTDIR AND
- NOT CMAKE_CFG_INTDIR STREQUAL "." AND
- NOT CMAKE_CFG_INTDIR MATCHES "\\$")
- # CMake 3.4 and below used the CMAKE_CFG_INTDIR placeholder value
- # provided by multi-configuration generators. Some projects were
- # taking advantage of that undocumented implementation detail to
- # specify a specific configuration here. They should use
- # BUILD_COMMAND to change the default command instead, but for
- # compatibility honor the value.
- set(config ${CMAKE_CFG_INTDIR})
- message(AUTHOR_WARNING "CMAKE_CFG_INTDIR should not be set by project code.\n"
- "To get a non-default build command, use the BUILD_COMMAND option.")
- else()
- set(config $<CONFIG>)
- endif()
- list(APPEND args --config ${config})
- endif()
- if(step STREQUAL "INSTALL")
- list(APPEND args --target install)
- endif()
- # But for "TEST" drive the project with corresponding "ctest".
- if("x${step}x" STREQUAL "xTESTx")
- string(REGEX REPLACE "^(.*/)cmake([^/]*)$" "\\1ctest\\2" cmd "${cmd}")
- set(args "")
- if(CMAKE_CONFIGURATION_TYPES)
- list(APPEND args -C ${config})
- endif()
- endif()
+ set(cmd "")
+ set(args)
+ _ep_get_configure_command_id(${name} cfg_cmd_id)
+ if(cfg_cmd_id STREQUAL "cmake")
+ # CMake project. Select build command based on generator.
+ get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
+ if("${CMAKE_GENERATOR}" MATCHES "Make" AND
+ ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
+ # The project uses the same Makefile generator. Use recursive make.
+ set(cmd "$(MAKE)")
+ if(step STREQUAL "INSTALL")
+ set(args install)
+ endif()
+ if("x${step}x" STREQUAL "xTESTx")
+ set(args test)
endif()
else()
- # Non-CMake project. Guess "make" and "make install" and "make test".
- if("${CMAKE_GENERATOR}" MATCHES "Makefiles")
- # Try to get the parallel arguments
- set(cmd "$(MAKE)")
+ # Drive the project with "cmake --build".
+ get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
+ if(cmake_command)
+ set(cmd "${cmake_command}")
else()
- set(cmd "make")
+ set(cmd "${CMAKE_COMMAND}")
+ endif()
+ set(args --build ".")
+ if(CMAKE_CONFIGURATION_TYPES)
+ if (CMAKE_CFG_INTDIR AND
+ NOT CMAKE_CFG_INTDIR STREQUAL "." AND
+ NOT CMAKE_CFG_INTDIR MATCHES "\\$")
+ # CMake 3.4 and below used the CMAKE_CFG_INTDIR placeholder value
+ # provided by multi-configuration generators. Some projects were
+ # taking advantage of that undocumented implementation detail to
+ # specify a specific configuration here. They should use
+ # BUILD_COMMAND to change the default command instead, but for
+ # compatibility honor the value.
+ set(config ${CMAKE_CFG_INTDIR})
+ message(AUTHOR_WARNING "CMAKE_CFG_INTDIR should not be set by project code.\n"
+ "To get a non-default build command, use the BUILD_COMMAND option.")
+ else()
+ set(config $<CONFIG>)
+ endif()
+ list(APPEND args --config ${config})
endif()
if(step STREQUAL "INSTALL")
- set(args install)
+ list(APPEND args --target install)
endif()
+ # But for "TEST" drive the project with corresponding "ctest".
if("x${step}x" STREQUAL "xTESTx")
- set(args test)
+ string(REGEX REPLACE "^(.*/)cmake([^/]*)$" "\\1ctest\\2" cmd "${cmd}")
+ set(args "")
+ if(CMAKE_CONFIGURATION_TYPES)
+ list(APPEND args -C ${config})
+ endif()
endif()
endif()
-
- # Use user-specified arguments instead of default arguments, if any.
- get_property(have_args TARGET ${name} PROPERTY _EP_${step}_ARGS SET)
- if(have_args)
- get_target_property(args ${name} _EP_${step}_ARGS)
+ else()
+ # Non-CMake project. Guess "make" and "make install" and "make test".
+ if("${CMAKE_GENERATOR}" MATCHES "Makefiles")
+ # Try to get the parallel arguments
+ set(cmd "$(MAKE)")
+ else()
+ set(cmd "make")
endif()
+ if(step STREQUAL "INSTALL")
+ set(args install)
+ endif()
+ if("x${step}x" STREQUAL "xTESTx")
+ set(args test)
+ endif()
+ endif()
- list(APPEND cmd ${args})
+ # Use user-specified arguments instead of default arguments, if any.
+ get_property(have_args TARGET ${name} PROPERTY _EP_${step}_ARGS SET)
+ if(have_args)
+ get_target_property(args ${name} _EP_${step}_ARGS)
endif()
+ list(APPEND cmd ${args})
set(${cmd_var} "${cmd}" PARENT_SCOPE)
endfunction()
@@ -1812,6 +1818,7 @@ function(_ep_add_download_command name)
endif()
get_property(git_shallow TARGET ${name} PROPERTY _EP_GIT_SHALLOW)
get_property(git_progress TARGET ${name} PROPERTY _EP_GIT_PROGRESS)
+ get_property(git_config TARGET ${name} PROPERTY _EP_GIT_CONFIG)
# For the download step, and the git clone operation, only the repository
# should be recorded in a configured RepositoryInfo file. If the repo
@@ -1836,7 +1843,7 @@ function(_ep_add_download_command name)
# The script will delete the source directory and then call git clone.
#
_ep_write_gitclone_script(${tmp_dir}/${name}-gitclone.cmake ${source_dir}
- ${GIT_EXECUTABLE} ${git_repository} ${git_tag} ${git_remote_name} "${git_submodules}" "${git_shallow}" "${git_progress}" ${src_name} ${work_dir}
+ ${GIT_EXECUTABLE} ${git_repository} ${git_tag} ${git_remote_name} "${git_submodules}" "${git_shallow}" "${git_progress}" "${git_config}" ${src_name} ${work_dir}
${stamp_dir}/${name}-gitinfo.txt ${stamp_dir}/${name}-gitclone-lastrun.txt "${tls_verify}"
)
set(comment "Performing download step (git clone) for '${name}'")
@@ -2155,12 +2162,12 @@ Update to Mercurial >= 2.1.1.
${uses_terminal}
)
- if(always AND update_disconnected)
+ if(update_disconnected)
_ep_get_step_stampfile(${name} skip-update skip-update_stamp_file)
string(REPLACE "Performing" "Skipping" comment "${comment}")
ExternalProject_Add_Step(${name} skip-update
COMMENT ${comment}
- ALWAYS 1
+ ALWAYS ${always}
EXCLUDE_FROM_MAIN 1
WORKING_DIRECTORY ${work_dir}
DEPENDEES download
diff --git a/Modules/FindALSA.cmake b/Modules/FindALSA.cmake
index d0ffa03..fa9a434 100644
--- a/Modules/FindALSA.cmake
+++ b/Modules/FindALSA.cmake
@@ -39,8 +39,6 @@ if(ALSA_INCLUDE_DIR AND EXISTS "${ALSA_INCLUDE_DIR}/alsa/version.h")
unset(alsa_version_str)
endif()
-# handle the QUIETLY and REQUIRED arguments and set ALSA_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(ALSA
REQUIRED_VARS ALSA_LIBRARY ALSA_INCLUDE_DIR
diff --git a/Modules/FindASPELL.cmake b/Modules/FindASPELL.cmake
index 8f2b007..6944ac1 100644
--- a/Modules/FindASPELL.cmake
+++ b/Modules/FindASPELL.cmake
@@ -25,8 +25,6 @@ find_program(ASPELL_EXECUTABLE
find_library(ASPELL_LIBRARIES NAMES aspell aspell-15 libaspell-15 libaspell)
-# handle the QUIETLY and REQUIRED arguments and set ASPELL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(ASPELL DEFAULT_MSG ASPELL_LIBRARIES ASPELL_INCLUDE_DIR ASPELL_EXECUTABLE)
diff --git a/Modules/FindAVIFile.cmake b/Modules/FindAVIFile.cmake
index 38701be..88a2a25 100644
--- a/Modules/FindAVIFile.cmake
+++ b/Modules/FindAVIFile.cmake
@@ -32,8 +32,6 @@ if (UNIX)
endif ()
-# handle the QUIETLY and REQUIRED arguments and set AVIFILE_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(AVIFile DEFAULT_MSG AVIFILE_INCLUDE_DIR AVIFILE_AVIPLAY_LIBRARY)
diff --git a/Modules/FindArmadillo.cmake b/Modules/FindArmadillo.cmake
index fab04c2..95f0c56 100644
--- a/Modules/FindArmadillo.cmake
+++ b/Modules/FindArmadillo.cmake
@@ -73,10 +73,6 @@ if(ARMADILLO_INCLUDE_DIR)
set(ARMADILLO_VERSION_STRING "${ARMADILLO_VERSION_MAJOR}.${ARMADILLO_VERSION_MINOR}.${ARMADILLO_VERSION_PATCH}")
endif ()
-#======================
-
-
-# Checks 'REQUIRED', 'QUIET' and versions.
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(Armadillo
REQUIRED_VARS ARMADILLO_LIBRARY ARMADILLO_INCLUDE_DIR
@@ -88,10 +84,7 @@ if (ARMADILLO_FOUND)
set(ARMADILLO_LIBRARIES ${ARMADILLO_LIBRARY})
endif ()
-
# Hide internal variables
mark_as_advanced(
ARMADILLO_INCLUDE_DIR
ARMADILLO_LIBRARY)
-
-#======================
diff --git a/Modules/FindBISON.cmake b/Modules/FindBISON.cmake
index 5de7a39..0ebd465 100644
--- a/Modules/FindBISON.cmake
+++ b/Modules/FindBISON.cmake
@@ -228,7 +228,7 @@ if(BISON_EXECUTABLE)
list(APPEND BISON_TARGET_outputs "${BISON_TARGET_output_header}")
add_custom_command(OUTPUT ${BISON_TARGET_outputs}
- ${BISON_TARGET_verbose_file}
+ ${BISON_TARGET_extraoutputs}
COMMAND ${BISON_EXECUTABLE} ${BISON_TARGET_cmdopt} -o ${BisonOutput} ${BisonInput}
VERBATIM
DEPENDS ${BisonInput}
@@ -253,5 +253,3 @@ endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(BISON REQUIRED_VARS BISON_EXECUTABLE
VERSION_VAR BISON_VERSION)
-
-# FindBISON.cmake ends here
diff --git a/Modules/FindBZip2.cmake b/Modules/FindBZip2.cmake
index 2d93eba..d2307f1 100644
--- a/Modules/FindBZip2.cmake
+++ b/Modules/FindBZip2.cmake
@@ -45,8 +45,6 @@ if (BZIP2_INCLUDE_DIR AND EXISTS "${BZIP2_INCLUDE_DIR}/bzlib.h")
string(REGEX REPLACE ".* bzip2/libbzip2 version ([0-9]+\\.[^ ]+) of [0-9]+ .*" "\\1" BZIP2_VERSION_STRING "${BZLIB_H}")
endif ()
-# handle the QUIETLY and REQUIRED arguments and set BZip2_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(BZip2
REQUIRED_VARS BZIP2_LIBRARIES BZIP2_INCLUDE_DIR
diff --git a/Modules/FindBullet.cmake b/Modules/FindBullet.cmake
index d000f79..fc6695c 100644
--- a/Modules/FindBullet.cmake
+++ b/Modules/FindBullet.cmake
@@ -78,8 +78,6 @@ _FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY BulletSoftBody)
_FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY_DEBUG BulletSoftBody_Debug BulletSoftBody_d)
-# handle the QUIETLY and REQUIRED arguments and set BULLET_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Bullet DEFAULT_MSG
BULLET_DYNAMICS_LIBRARY BULLET_COLLISION_LIBRARY BULLET_MATH_LIBRARY
diff --git a/Modules/FindCURL.cmake b/Modules/FindCURL.cmake
index 200f8c3..f4bcc36 100644
--- a/Modules/FindCURL.cmake
+++ b/Modules/FindCURL.cmake
@@ -44,8 +44,6 @@ if(CURL_INCLUDE_DIR)
endforeach()
endif()
-# handle the QUIETLY and REQUIRED arguments and set CURL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(CURL
REQUIRED_VARS CURL_LIBRARY CURL_INCLUDE_DIR
diff --git a/Modules/FindCoin3D.cmake b/Modules/FindCoin3D.cmake
index fea644d..f11903d 100644
--- a/Modules/FindCoin3D.cmake
+++ b/Modules/FindCoin3D.cmake
@@ -70,11 +70,7 @@ else ()
endif ()
-# handle the QUIETLY and REQUIRED arguments and set COIN3D_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Coin3D DEFAULT_MSG COIN3D_LIBRARIES COIN3D_INCLUDE_DIRS)
mark_as_advanced(COIN3D_INCLUDE_DIRS COIN3D_LIBRARIES )
-
-
diff --git a/Modules/FindCurses.cmake b/Modules/FindCurses.cmake
index a0929ce..4365e99 100644
--- a/Modules/FindCurses.cmake
+++ b/Modules/FindCurses.cmake
@@ -190,8 +190,6 @@ endif()
set(CURSES_INCLUDE_DIRS ${CURSES_INCLUDE_PATH})
set(CURSES_INCLUDE_DIR ${CURSES_INCLUDE_PATH}) # compatibility
-# handle the QUIETLY and REQUIRED arguments and set CURSES_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Curses DEFAULT_MSG
CURSES_LIBRARY CURSES_INCLUDE_PATH)
diff --git a/Modules/FindDart.cmake b/Modules/FindDart.cmake
index 37164e6..acd4ef6 100644
--- a/Modules/FindDart.cmake
+++ b/Modules/FindDart.cmake
@@ -26,8 +26,6 @@ find_path(DART_ROOT README.INSTALL
DOC "If you have Dart installed, where is it located?"
)
-# handle the QUIETLY and REQUIRED arguments and set DART_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Dart DEFAULT_MSG DART_ROOT)
diff --git a/Modules/FindDevIL.cmake b/Modules/FindDevIL.cmake
index dc8e38a..45fab82 100644
--- a/Modules/FindDevIL.cmake
+++ b/Modules/FindDevIL.cmake
@@ -67,6 +67,6 @@ find_library(ILU_LIBRARIES
#message("ILU_LIBRARIES is ${ILU_LIBRARIES}")
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(IL DEFAULT_MSG
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(DevIL DEFAULT_MSG
IL_LIBRARIES ILU_LIBRARIES
- ILUT_LIBRARIES IL_INCLUDE_DIR)
+ IL_INCLUDE_DIR)
diff --git a/Modules/FindEXPAT.cmake b/Modules/FindEXPAT.cmake
index cc89203..09963fc 100644
--- a/Modules/FindEXPAT.cmake
+++ b/Modules/FindEXPAT.cmake
@@ -44,8 +44,6 @@ if (EXPAT_INCLUDE_DIR AND EXISTS "${EXPAT_INCLUDE_DIR}/expat.h")
endforeach()
endif ()
-# handle the QUIETLY and REQUIRED arguments and set EXPAT_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(EXPAT
REQUIRED_VARS EXPAT_LIBRARY EXPAT_INCLUDE_DIR
diff --git a/Modules/FindFLEX.cmake b/Modules/FindFLEX.cmake
index 69cf513..214873c 100644
--- a/Modules/FindFLEX.cmake
+++ b/Modules/FindFLEX.cmake
@@ -218,5 +218,3 @@ endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(FLEX REQUIRED_VARS FLEX_EXECUTABLE
VERSION_VAR FLEX_VERSION)
-
-# FindFLEX.cmake ends here
diff --git a/Modules/FindFreetype.cmake b/Modules/FindFreetype.cmake
index 21a5d89..9ea77df 100644
--- a/Modules/FindFreetype.cmake
+++ b/Modules/FindFreetype.cmake
@@ -135,9 +135,6 @@ if(FREETYPE_INCLUDE_DIR_freetype2 AND FREETYPE_H)
endforeach()
endif()
-
-# handle the QUIETLY and REQUIRED arguments and set FREETYPE_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
diff --git a/Modules/FindGIF.cmake b/Modules/FindGIF.cmake
index 88c4180..0843d5f 100644
--- a/Modules/FindGIF.cmake
+++ b/Modules/FindGIF.cmake
@@ -91,8 +91,6 @@ if(GIF_INCLUDE_DIR)
CMAKE_POP_CHECK_STATE()
endif()
-# handle the QUIETLY and REQUIRED arguments and set GIF_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(GIF REQUIRED_VARS GIF_LIBRARY GIF_INCLUDE_DIR
VERSION_VAR GIF_VERSION )
diff --git a/Modules/FindGSL.cmake b/Modules/FindGSL.cmake
index 98377a2..446c3a8 100644
--- a/Modules/FindGSL.cmake
+++ b/Modules/FindGSL.cmake
@@ -55,7 +55,6 @@
# GSL_LIBRARY_DEBUG - Location of the debug GSL library (if any).
#
-# Include these modules to handle the QUIETLY and REQUIRED arguments.
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
#=============================================================================
diff --git a/Modules/FindGTK2.cmake b/Modules/FindGTK2.cmake
index 78dc6ba..1f447f1 100644
--- a/Modules/FindGTK2.cmake
+++ b/Modules/FindGTK2.cmake
@@ -957,4 +957,3 @@ endif()
if(GTK2_INCLUDE_DIRS)
list(REMOVE_DUPLICATES GTK2_INCLUDE_DIRS)
endif()
-
diff --git a/Modules/FindGit.cmake b/Modules/FindGit.cmake
index 5d38193..769c6c3 100644
--- a/Modules/FindGit.cmake
+++ b/Modules/FindGit.cmake
@@ -65,9 +65,6 @@ if(GIT_EXECUTABLE)
unset(git_version)
endif()
-# Handle the QUIETLY and REQUIRED arguments and set Git_FOUND to TRUE if
-# all listed variables are TRUE
-
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(Git
REQUIRED_VARS GIT_EXECUTABLE
diff --git a/Modules/FindGnuTLS.cmake b/Modules/FindGnuTLS.cmake
index a6ab092..1a97d99 100644
--- a/Modules/FindGnuTLS.cmake
+++ b/Modules/FindGnuTLS.cmake
@@ -50,8 +50,6 @@ find_library(GNUTLS_LIBRARY NAMES gnutls libgnutls
mark_as_advanced(GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY)
-# handle the QUIETLY and REQUIRED arguments and set GNUTLS_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(GnuTLS
REQUIRED_VARS GNUTLS_LIBRARY GNUTLS_INCLUDE_DIR
@@ -61,4 +59,3 @@ if(GNUTLS_FOUND)
set(GNUTLS_LIBRARIES ${GNUTLS_LIBRARY})
set(GNUTLS_INCLUDE_DIRS ${GNUTLS_INCLUDE_DIR})
endif()
-
diff --git a/Modules/FindGnuplot.cmake b/Modules/FindGnuplot.cmake
index 9ace651..aa4cd6c 100644
--- a/Modules/FindGnuplot.cmake
+++ b/Modules/FindGnuplot.cmake
@@ -46,12 +46,9 @@ endif()
# for compatibility
set(GNUPLOT ${GNUPLOT_EXECUTABLE})
-# handle the QUIETLY and REQUIRED arguments and set GNUPLOT_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Gnuplot
REQUIRED_VARS GNUPLOT_EXECUTABLE
VERSION_VAR GNUPLOT_VERSION_STRING)
mark_as_advanced( GNUPLOT_EXECUTABLE )
-
diff --git a/Modules/FindHDF5.cmake b/Modules/FindHDF5.cmake
index 1c2c443..16764e0 100644
--- a/Modules/FindHDF5.cmake
+++ b/Modules/FindHDF5.cmake
@@ -100,18 +100,10 @@ include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
set(HDF5_VALID_LANGUAGE_BINDINGS C CXX Fortran)
# Validate the list of find components.
-set(HDF5_LANGUAGE_BINDINGS)
if(NOT HDF5_FIND_COMPONENTS)
- get_property(__langs GLOBAL PROPERTY ENABLED_LANGUAGES)
- foreach(__lang IN LISTS __langs)
- if(__lang MATCHES "^(C|CXX|Fortran)$")
- list(APPEND HDF5_LANGUAGE_BINDINGS ${__lang})
- set(HDF5_FIND_REQUIRED_${__lang} True)
- endif()
- endforeach()
- set(FIND_HL ON)
- set(HDF5_FIND_REQUIRED_HL True)
+ set(HDF5_LANGUAGE_BINDINGS "C")
else()
+ set(HDF5_LANGUAGE_BINDINGS)
# add the extra specified components, ensuring that they are valid.
set(FIND_HL OFF)
foreach(component IN LISTS HDF5_FIND_COMPONENTS)
diff --git a/Modules/FindHSPELL.cmake b/Modules/FindHSPELL.cmake
index 72d70ad..bb0e2f0 100644
--- a/Modules/FindHSPELL.cmake
+++ b/Modules/FindHSPELL.cmake
@@ -36,12 +36,9 @@ if (HSPELL_INCLUDE_DIR)
unset(HSPELL_H)
endif()
-# handle the QUIETLY and REQUIRED arguments and set HSPELL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(HSPELL
REQUIRED_VARS HSPELL_LIBRARIES HSPELL_INCLUDE_DIR
VERSION_VAR HSPELL_VERSION_STRING)
mark_as_advanced(HSPELL_INCLUDE_DIR HSPELL_LIBRARIES)
-
diff --git a/Modules/FindHg.cmake b/Modules/FindHg.cmake
index ef85abc..8aa553e 100644
--- a/Modules/FindHg.cmake
+++ b/Modules/FindHg.cmake
@@ -90,8 +90,6 @@ if(HG_EXECUTABLE)
endmacro(HG_WC_INFO)
endif()
-# Handle the QUIETLY and REQUIRED arguments and set HG_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(Hg
REQUIRED_VARS HG_EXECUTABLE
diff --git a/Modules/FindIcotool.cmake b/Modules/FindIcotool.cmake
index bd3e327..26e95a0 100644
--- a/Modules/FindIcotool.cmake
+++ b/Modules/FindIcotool.cmake
@@ -39,8 +39,6 @@ if(ICOTOOL_EXECUTABLE)
unset(_icotool_version)
endif()
-# handle the QUIETLY and REQUIRED arguments and set ICOTOOL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(
Icotool
diff --git a/Modules/FindJPEG.cmake b/Modules/FindJPEG.cmake
index b644181..e233714 100644
--- a/Modules/FindJPEG.cmake
+++ b/Modules/FindJPEG.cmake
@@ -26,8 +26,6 @@ find_path(JPEG_INCLUDE_DIR jpeglib.h)
set(JPEG_NAMES ${JPEG_NAMES} jpeg libjpeg)
find_library(JPEG_LIBRARY NAMES ${JPEG_NAMES} )
-# handle the QUIETLY and REQUIRED arguments and set JPEG_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(JPEG DEFAULT_MSG JPEG_LIBRARY JPEG_INCLUDE_DIR)
diff --git a/Modules/FindJasper.cmake b/Modules/FindJasper.cmake
index 748510e..db76657 100644
--- a/Modules/FindJasper.cmake
+++ b/Modules/FindJasper.cmake
@@ -34,8 +34,6 @@ if (JASPER_INCLUDE_DIR AND EXISTS "${JASPER_INCLUDE_DIR}/jasper/jas_config.h")
string(REGEX REPLACE "^#define[\t ]+JAS_VERSION[\t ]+\"([^\"]+)\".*" "\\1" JASPER_VERSION_STRING "${jasper_version_str}")
endif ()
-# handle the QUIETLY and REQUIRED arguments and set JASPER_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Jasper
REQUIRED_VARS JASPER_LIBRARIES JASPER_INCLUDE_DIR JPEG_LIBRARIES
diff --git a/Modules/FindJava.cmake b/Modules/FindJava.cmake
index e30917d..5c0abb0 100644
--- a/Modules/FindJava.cmake
+++ b/Modules/FindJava.cmake
@@ -262,4 +262,3 @@ mark_as_advanced(
set(JAVA_RUNTIME ${Java_JAVA_EXECUTABLE})
set(JAVA_ARCHIVE ${Java_JAR_EXECUTABLE})
set(JAVA_COMPILE ${Java_JAVAC_EXECUTABLE})
-
diff --git a/Modules/FindLATEX.cmake b/Modules/FindLATEX.cmake
index 1d8f6ce..d1f4fa4 100644
--- a/Modules/FindLATEX.cmake
+++ b/Modules/FindLATEX.cmake
@@ -271,7 +271,6 @@ mark_as_advanced(
HTLATEX_COMPILER
)
-# handle variables for found Latex and its components
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(LATEX
REQUIRED_VARS LATEX_COMPILER
diff --git a/Modules/FindLTTngUST.cmake b/Modules/FindLTTngUST.cmake
index 8781bae..00d5e7a 100644
--- a/Modules/FindLTTngUST.cmake
+++ b/Modules/FindLTTngUST.cmake
@@ -90,8 +90,6 @@ if(LTTNGUST_INCLUDE_DIRS AND LTTNGUST_LIBRARIES)
set(LTTNGUST_LIBRARIES ${LTTNGUST_LIBRARIES} ${CMAKE_DL_LIBS})
endif()
-# handle the QUIETLY and REQUIRED arguments and set LTTNGUST_FOUND to
-# TRUE if all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(LTTngUST FOUND_VAR LTTNGUST_FOUND
REQUIRED_VARS LTTNGUST_LIBRARIES
diff --git a/Modules/FindLibArchive.cmake b/Modules/FindLibArchive.cmake
index 1a26bbb..38e512f 100644
--- a/Modules/FindLibArchive.cmake
+++ b/Modules/FindLibArchive.cmake
@@ -46,17 +46,11 @@ if(LibArchive_INCLUDE_DIR AND EXISTS "${LibArchive_INCLUDE_DIR}/archive.h")
unset(_LibArchive_VERSION_STRING)
endif()
-# Handle the QUIETLY and REQUIRED arguments and set LIBARCHIVE_FOUND
-# to TRUE if all listed variables are TRUE.
-# (Use ${CMAKE_ROOT}/Modules instead of ${CMAKE_CURRENT_LIST_DIR} because CMake
-# itself includes this FindLibArchive when built with an older CMake that does
-# not provide it. The older CMake also does not have CMAKE_CURRENT_LIST_DIR.)
-include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(LibArchive
REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
VERSION_VAR LibArchive_VERSION
)
-set(LibArchive_FOUND ${LIBARCHIVE_FOUND})
unset(LIBARCHIVE_FOUND)
if(LibArchive_FOUND)
diff --git a/Modules/FindLibXml2.cmake b/Modules/FindLibXml2.cmake
index 9580981..613f927 100644
--- a/Modules/FindLibXml2.cmake
+++ b/Modules/FindLibXml2.cmake
@@ -52,8 +52,6 @@ elseif(LIBXML2_INCLUDE_DIR AND EXISTS "${LIBXML2_INCLUDE_DIR}/libxml/xmlversion.
unset(libxml2_version_str)
endif()
-# handle the QUIETLY and REQUIRED arguments and set LIBXML2_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXml2
REQUIRED_VARS LIBXML2_LIBRARIES LIBXML2_INCLUDE_DIR
diff --git a/Modules/FindMPEG.cmake b/Modules/FindMPEG.cmake
index aff464e..cd1b021 100644
--- a/Modules/FindMPEG.cmake
+++ b/Modules/FindMPEG.cmake
@@ -34,8 +34,6 @@ find_library( MPEG_vo_LIBRARY vo
/usr/local/livid/mpeg2dec/libvo/.libs
)
-# handle the QUIETLY and REQUIRED arguments and set MPEG2_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(MPEG DEFAULT_MSG MPEG_INCLUDE_DIR MPEG_mpeg2_LIBRARY MPEG_vo_LIBRARY)
diff --git a/Modules/FindMPEG2.cmake b/Modules/FindMPEG2.cmake
index e28054d..2c75d7b 100644
--- a/Modules/FindMPEG2.cmake
+++ b/Modules/FindMPEG2.cmake
@@ -35,9 +35,6 @@ find_library( MPEG2_vo_LIBRARY vo
/usr/local/livid/mpeg2dec/libvo/.libs
)
-
-# handle the QUIETLY and REQUIRED arguments and set MPEG2_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(MPEG2 DEFAULT_MSG MPEG2_mpeg2_LIBRARY MPEG2_INCLUDE_DIR)
diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake
index 676e1bc..842acef 100644
--- a/Modules/FindMPI.cmake
+++ b/Modules/FindMPI.cmake
@@ -91,7 +91,6 @@
#
# In new projects, please use the ``MPI_<lang>_XXX`` equivalents.
-# include this to handle the QUIETLY and REQUIRED arguments
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
#
diff --git a/Modules/FindMatlab.cmake b/Modules/FindMatlab.cmake
index b7f2db5..eae1585 100644
--- a/Modules/FindMatlab.cmake
+++ b/Modules/FindMatlab.cmake
@@ -225,6 +225,7 @@ if(NOT MATLAB_ADDITIONAL_VERSIONS)
endif()
set(MATLAB_VERSIONS_MAPPING
+ "R2016b=9.1"
"R2016a=9.0"
"R2015b=8.6"
"R2015a=8.5"
@@ -793,7 +794,7 @@ function(matlab_add_unit_test)
"-Dworking_directory=${${prefix}_WORKING_DIRECTORY}"
"-DMatlab_PROGRAM=${Matlab_MAIN_PROGRAM}"
"-Dno_unittest_framework=${${prefix}_NO_UNITTEST_FRAMEWORK}"
- "-DMatlab_ADDITIONNAL_STARTUP_OPTIONS=${${prefix}_MATLAB_ADDITIONAL_STARTUP_OPTIONS}"
+ "-DMatlab_ADDITIONAL_STARTUP_OPTIONS=${${prefix}_MATLAB_ADDITIONAL_STARTUP_OPTIONS}"
"-Dunittest_file_to_run=${${prefix}_UNITTEST_FILE}"
"-Dcustom_Matlab_test_command=${${prefix}_CUSTOM_TEST_COMMAND}"
"-Dcmd_to_run_before_test=${${prefix}_UNITTEST_PRECOMMAND}"
diff --git a/Modules/FindMotif.cmake b/Modules/FindMotif.cmake
index 3923238..7304d95 100644
--- a/Modules/FindMotif.cmake
+++ b/Modules/FindMotif.cmake
@@ -30,12 +30,9 @@ if(UNIX)
endif()
-# handle the QUIETLY and REQUIRED arguments and set MOTIF_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Motif DEFAULT_MSG MOTIF_LIBRARIES MOTIF_INCLUDE_DIR)
-
mark_as_advanced(
MOTIF_INCLUDE_DIR
MOTIF_LIBRARIES
diff --git a/Modules/FindOpenAL.cmake b/Modules/FindOpenAL.cmake
index 1abb0d6..8622b4c 100644
--- a/Modules/FindOpenAL.cmake
+++ b/Modules/FindOpenAL.cmake
@@ -92,8 +92,6 @@ find_library(OPENAL_LIBRARY
unset(_OpenAL_ARCH_DIR)
-# handle the QUIETLY and REQUIRED arguments and set OPENAL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenAL DEFAULT_MSG OPENAL_LIBRARY OPENAL_INCLUDE_DIR)
diff --git a/Modules/FindOpenGL.cmake b/Modules/FindOpenGL.cmake
index e487726..295de65 100644
--- a/Modules/FindOpenGL.cmake
+++ b/Modules/FindOpenGL.cmake
@@ -156,8 +156,6 @@ endif()
# This deprecated setting is for backward compatibility with CMake1.4
set(OPENGL_INCLUDE_PATH ${OPENGL_INCLUDE_DIR})
-# handle the QUIETLY and REQUIRED arguments and set OPENGL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenGL REQUIRED_VARS ${_OpenGL_REQUIRED_VARS})
unset(_OpenGL_REQUIRED_VARS)
diff --git a/Modules/FindOpenSceneGraph.cmake b/Modules/FindOpenSceneGraph.cmake
index af873fa..425aa45 100644
--- a/Modules/FindOpenSceneGraph.cmake
+++ b/Modules/FindOpenSceneGraph.cmake
@@ -227,4 +227,3 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenSceneGraph
unset(_osg_component_founds)
set(OPENSCENEGRAPH_INCLUDE_DIRS ${OPENSCENEGRAPH_INCLUDE_DIR})
-
diff --git a/Modules/FindPNG.cmake b/Modules/FindPNG.cmake
index 6f94d50..1d5d553 100644
--- a/Modules/FindPNG.cmake
+++ b/Modules/FindPNG.cmake
@@ -140,8 +140,6 @@ if(ZLIB_FOUND)
endif ()
endif()
-# handle the QUIETLY and REQUIRED arguments and set PNG_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(PNG
REQUIRED_VARS PNG_LIBRARY PNG_PNG_INCLUDE_DIR
diff --git a/Modules/FindPerl.cmake b/Modules/FindPerl.cmake
index a0c8a33..423fc69 100644
--- a/Modules/FindPerl.cmake
+++ b/Modules/FindPerl.cmake
@@ -70,8 +70,6 @@ endif()
# Deprecated settings for compatibility with CMake1.4
set(PERL ${PERL_EXECUTABLE})
-# handle the QUIETLY and REQUIRED arguments and set PERL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Perl
REQUIRED_VARS PERL_EXECUTABLE
diff --git a/Modules/FindPerlLibs.cmake b/Modules/FindPerlLibs.cmake
index 42729d7..e01e75e 100644
--- a/Modules/FindPerlLibs.cmake
+++ b/Modules/FindPerlLibs.cmake
@@ -239,8 +239,6 @@ if (PERL_EXECUTABLE)
endif ()
-# handle the QUIETLY and REQUIRED arguments and set PERLLIBS_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(PerlLibs REQUIRED_VARS PERL_LIBRARY PERL_INCLUDE_PATH
VERSION_VAR PERL_VERSION_STRING)
diff --git a/Modules/FindPhysFS.cmake b/Modules/FindPhysFS.cmake
index fe5b397..cfe9b0f 100644
--- a/Modules/FindPhysFS.cmake
+++ b/Modules/FindPhysFS.cmake
@@ -43,8 +43,5 @@ find_library(PHYSFS_LIBRARY
/opt
)
-# handle the QUIETLY and REQUIRED arguments and set PHYSFS_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(PhysFS DEFAULT_MSG PHYSFS_LIBRARY PHYSFS_INCLUDE_DIR)
-
diff --git a/Modules/FindPkgConfig.cmake b/Modules/FindPkgConfig.cmake
index 072a27a..8b7131b 100644
--- a/Modules/FindPkgConfig.cmake
+++ b/Modules/FindPkgConfig.cmake
@@ -193,7 +193,7 @@ function(_pkg_create_imp_target _prefix _no_cmake_path _no_cmake_environment_pat
foreach (flag IN LISTS ${_prefix}_LDFLAGS)
if (flag MATCHES "^-L(.*)")
# only look into the given paths from now on
- set(_find_opts "HINTS ${${CMAKE_MATCH_1}} NO_DEFAULT_PATH")
+ set(_find_opts HINTS ${CMAKE_MATCH_1} NO_DEFAULT_PATH)
continue()
endif()
if (flag MATCHES "^-l(.*)")
@@ -381,8 +381,9 @@ macro(_pkg_check_modules_internal _is_required _is_silent _no_cmake_path _no_cma
if (_pkg_check_modules_pkg_op)
list(APPEND _pkg_check_modules_exist_query "${_pkg_check_modules_pkg_ver}")
else()
- list(APPEND _pkg_check_modules_exist_query --exists --print-errors --short-errors)
+ list(APPEND _pkg_check_modules_exist_query --exists)
endif()
+ list(APPEND _pkg_check_modules_exist_query --print-errors --short-errors)
_pkgconfig_unset(${_prefix}_${_pkg_check_modules_pkg_name}_VERSION)
_pkgconfig_unset(${_prefix}_${_pkg_check_modules_pkg_name}_PREFIX)
diff --git a/Modules/FindPythonInterp.cmake b/Modules/FindPythonInterp.cmake
index 103e820..f255246 100644
--- a/Modules/FindPythonInterp.cmake
+++ b/Modules/FindPythonInterp.cmake
@@ -145,8 +145,6 @@ if(PYTHON_EXECUTABLE)
unset(_VERSION)
endif()
-# handle the QUIETLY and REQUIRED arguments and set PYTHONINTERP_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(PythonInterp REQUIRED_VARS PYTHON_EXECUTABLE VERSION_VAR PYTHON_VERSION_STRING)
diff --git a/Modules/FindPythonLibs.cmake b/Modules/FindPythonLibs.cmake
index 1ebbf29..cd623cf 100644
--- a/Modules/FindPythonLibs.cmake
+++ b/Modules/FindPythonLibs.cmake
@@ -42,16 +42,16 @@
# Use the executable's path as a hint
set(_Python_LIBRARY_PATH_HINT)
-if(PYTHON_EXECUTABLE)
+if(IS_ABSOLUTE "${PYTHON_EXECUTABLE}")
if(WIN32)
- get_filename_component(_Python_PREFIX ${PYTHON_EXECUTABLE} PATH)
+ get_filename_component(_Python_PREFIX "${PYTHON_EXECUTABLE}" PATH)
if(_Python_PREFIX)
set(_Python_LIBRARY_PATH_HINT ${_Python_PREFIX}/libs)
endif()
unset(_Python_PREFIX)
else()
- get_filename_component(_Python_PREFIX ${PYTHON_EXECUTABLE} PATH)
- get_filename_component(_Python_PREFIX ${_Python_PREFIX} PATH)
+ get_filename_component(_Python_PREFIX "${PYTHON_EXECUTABLE}" PATH)
+ get_filename_component(_Python_PREFIX "${_Python_PREFIX}" PATH)
if(_Python_PREFIX)
set(_Python_LIBRARY_PATH_HINT ${_Python_PREFIX}/lib)
endif()
diff --git a/Modules/FindQuickTime.cmake b/Modules/FindQuickTime.cmake
index 2ee1899..995d882 100644
--- a/Modules/FindQuickTime.cmake
+++ b/Modules/FindQuickTime.cmake
@@ -29,7 +29,5 @@ find_library(QUICKTIME_LIBRARY QuickTime
lib
)
-# handle the QUIETLY and REQUIRED arguments and set QUICKTIME_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(QuickTime DEFAULT_MSG QUICKTIME_LIBRARY QUICKTIME_INCLUDE_DIR)
diff --git a/Modules/FindSDL.cmake b/Modules/FindSDL.cmake
index 4e4411f..3410018 100644
--- a/Modules/FindSDL.cmake
+++ b/Modules/FindSDL.cmake
@@ -94,6 +94,11 @@ find_library(SDL_LIBRARY_TEMP
PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX}
)
+# Hide this cache variable from the user, it's an internal implementation
+# detail. The documented library variable for the user is SDL_LIBRARY
+# which is derived from SDL_LIBRARY_TEMP further below.
+set_property(CACHE SDL_LIBRARY_TEMP PROPERTY TYPE INTERNAL)
+
if(NOT SDL_BUILDING_LIBRARY)
if(NOT SDL_INCLUDE_DIR MATCHES ".framework")
# Non-OS X framework versions expect you to also dynamically link to
@@ -162,8 +167,6 @@ if(SDL_LIBRARY_TEMP)
# Set the final string here so the GUI reflects the final state.
set(SDL_LIBRARY ${SDL_LIBRARY_TEMP} CACHE STRING "Where the SDL Library can be found")
- # Set the temp variable to INTERNAL so it is not seen in the CMake GUI
- set(SDL_LIBRARY_TEMP "${SDL_LIBRARY_TEMP}" CACHE INTERNAL "")
endif()
if(SDL_INCLUDE_DIR AND EXISTS "${SDL_INCLUDE_DIR}/SDL_version.h")
diff --git a/Modules/FindSDL_sound.cmake b/Modules/FindSDL_sound.cmake
index 3198088..cf33a4c 100644
--- a/Modules/FindSDL_sound.cmake
+++ b/Modules/FindSDL_sound.cmake
@@ -19,7 +19,7 @@
# SDL_SOUND_INCLUDE_DIR, where to find SDL_sound.h
# SDL_SOUND_FOUND, if false, do not try to link to SDL_sound
# SDL_SOUND_LIBRARIES, this contains the list of libraries that you need
-# to link against. This is a read-only variable and is marked INTERNAL.
+# to link against.
# SDL_SOUND_EXTRAS, this is an optional variable for you to add your own
# flags to SDL_SOUND_LIBRARIES. This is prepended to SDL_SOUND_LIBRARIES.
# This is available mostly for cases this module failed to anticipate for
@@ -367,11 +367,10 @@ if(SDL_FOUND AND SDL_SOUND_INCLUDE_DIR AND SDL_SOUND_LIBRARY)
endif()
endif()
+ set(SDL_SOUND_LIBRARIES ${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARIES_TMP})
else()
- set(SDL_SOUND_LIBRARIES "${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARY}" CACHE INTERNAL "SDL_sound and dependent libraries")
+ set(SDL_SOUND_LIBRARIES ${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARY})
endif()
-
- set(SDL_SOUND_LIBRARIES "${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARIES_TMP}" CACHE INTERNAL "SDL_sound and dependent libraries")
endif()
if(SDL_SOUND_INCLUDE_DIR AND EXISTS "${SDL_SOUND_INCLUDE_DIR}/SDL_sound.h")
diff --git a/Modules/FindTCL.cmake b/Modules/FindTCL.cmake
index 12d6616..b6e24a3 100644
--- a/Modules/FindTCL.cmake
+++ b/Modules/FindTCL.cmake
@@ -205,8 +205,6 @@ find_path(TK_INCLUDE_PATH
HINTS ${TCLTK_POSSIBLE_INCLUDE_PATHS}
)
-# handle the QUIETLY and REQUIRED arguments and set TCL_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(TCL DEFAULT_MSG TCL_LIBRARY TCL_INCLUDE_PATH)
diff --git a/Modules/FindTIFF.cmake b/Modules/FindTIFF.cmake
index 23ae308..b622ca6 100644
--- a/Modules/FindTIFF.cmake
+++ b/Modules/FindTIFF.cmake
@@ -65,8 +65,6 @@ if(TIFF_INCLUDE_DIR AND EXISTS "${TIFF_INCLUDE_DIR}/tiffvers.h")
unset(tiff_version_str)
endif()
-# handle the QUIETLY and REQUIRED arguments and set TIFF_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(TIFF
REQUIRED_VARS TIFF_LIBRARY TIFF_INCLUDE_DIR
diff --git a/Modules/FindTclsh.cmake b/Modules/FindTclsh.cmake
index c8a87ec..9fcb41c 100644
--- a/Modules/FindTclsh.cmake
+++ b/Modules/FindTclsh.cmake
@@ -89,8 +89,6 @@ if(TCL_TCLSH)
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
-# handle the QUIETLY and REQUIRED arguments and set TIFF_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Tclsh
REQUIRED_VARS TCL_TCLSH
diff --git a/Modules/FindWget.cmake b/Modules/FindWget.cmake
index 68419e2..4fcb2fa 100644
--- a/Modules/FindWget.cmake
+++ b/Modules/FindWget.cmake
@@ -21,8 +21,6 @@ find_program(WGET_EXECUTABLE
${CYGWIN_INSTALL_PATH}/bin
)
-# handle the QUIETLY and REQUIRED arguments and set WGET_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Wget DEFAULT_MSG WGET_EXECUTABLE)
@@ -30,4 +28,4 @@ mark_as_advanced( WGET_EXECUTABLE )
# WGET option is deprecated.
# use WGET_EXECUTABLE instead.
-set (WGET ${WGET_EXECUTABLE} )
+set (WGET ${WGET_EXECUTABLE})
diff --git a/Modules/FindZLIB.cmake b/Modules/FindZLIB.cmake
index 5ee55b3..4065999 100644
--- a/Modules/FindZLIB.cmake
+++ b/Modules/FindZLIB.cmake
@@ -108,8 +108,6 @@ if(ZLIB_INCLUDE_DIR AND EXISTS "${ZLIB_INCLUDE_DIR}/zlib.h")
set(ZLIB_PATCH_VERSION "${ZLIB_VERSION_PATCH}")
endif()
-# handle the QUIETLY and REQUIRED arguments and set ZLIB_FOUND to TRUE if
-# all listed variables are TRUE
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(ZLIB REQUIRED_VARS ZLIB_LIBRARY ZLIB_INCLUDE_DIR
VERSION_VAR ZLIB_VERSION_STRING)
diff --git a/Modules/FortranCInterface/CMakeLists.txt b/Modules/FortranCInterface/CMakeLists.txt
index dee57b5..3a66f68 100644
--- a/Modules/FortranCInterface/CMakeLists.txt
+++ b/Modules/FortranCInterface/CMakeLists.txt
@@ -94,6 +94,9 @@ add_library(myfort STATIC mysub.f my_sub.f ${myfort_modules})
# Provide symbols through C but fall back to Fortran.
add_library(symbols STATIC ${symbol_sources})
target_link_libraries(symbols myfort)
+# In case the Fortran compiler produces PIC by default make sure
+# the C compiler produces PIC even if it is not its default.
+set_property(TARGET symbols PROPERTY POSITION_INDEPENDENT_CODE 1)
# Require symbols through Fortran.
add_executable(FortranCInterface main.F call_sub.f ${call_mod})
diff --git a/Modules/Internal/FeatureTesting.cmake b/Modules/Internal/FeatureTesting.cmake
index 86b89b2..50b8526 100644
--- a/Modules/Internal/FeatureTesting.cmake
+++ b/Modules/Internal/FeatureTesting.cmake
@@ -1,5 +1,5 @@
-macro(record_compiler_features lang compile_flags feature_list)
+macro(_record_compiler_features lang compile_flags feature_list)
include("${CMAKE_ROOT}/Modules/Compiler/${CMAKE_${lang}_COMPILER_ID}-${lang}-FeatureTests.cmake" OPTIONAL)
string(TOLOWER ${lang} lang_lc)
@@ -58,3 +58,13 @@ macro(record_compiler_features lang compile_flags feature_list)
"Detecting ${lang} [${compile_flags}] compiler features failed to compile with the following output:\n${_output}\n${_copy_error}\n\n")
endif()
endmacro()
+
+macro(_record_compiler_features_c std)
+ list(APPEND CMAKE_C${std}_COMPILE_FEATURES c_std_${std})
+ _record_compiler_features(C "${CMAKE_C${std}_STANDARD_COMPILE_OPTION}" CMAKE_C${std}_COMPILE_FEATURES)
+endmacro()
+
+macro(_record_compiler_features_cxx std)
+ list(APPEND CMAKE_CXX${std}_COMPILE_FEATURES cxx_std_${std})
+ _record_compiler_features(CXX "${CMAKE_CXX${std}_STANDARD_COMPILE_OPTION}" CMAKE_CXX${std}_COMPILE_FEATURES)
+endmacro()
diff --git a/Modules/MatlabTestsRedirect.cmake b/Modules/MatlabTestsRedirect.cmake
index a0c6621..64d580d 100644
--- a/Modules/MatlabTestsRedirect.cmake
+++ b/Modules/MatlabTestsRedirect.cmake
@@ -10,14 +10,14 @@
# -Dadditional_paths=""
# -Dno_unittest_framework=""
# -DMatlab_PROGRAM=matlab_exe_location
-# -DMatlab_ADDITIONNAL_STARTUP_OPTIONS=""
+# -DMatlab_ADDITIONAL_STARTUP_OPTIONS=""
# -Dtest_name=name_of_the_test
# -Dcustom_Matlab_test_command=""
# -Dcmd_to_run_before_test=""
# -Dunittest_file_to_run
# -P FindMatlab_TestsRedirect.cmake
-set(Matlab_UNIT_TESTS_CMD -nosplash -nodesktop -nodisplay ${Matlab_ADDITIONNAL_STARTUP_OPTIONS})
+set(Matlab_UNIT_TESTS_CMD -nosplash -nodesktop -nodisplay ${Matlab_ADDITIONAL_STARTUP_OPTIONS})
if(WIN32)
set(Matlab_UNIT_TESTS_CMD ${Matlab_UNIT_TESTS_CMD} -wait)
endif()
diff --git a/Modules/Platform/Android/Determine-Compiler-NDK.cmake b/Modules/Platform/Android/Determine-Compiler-NDK.cmake
index 953bc85..d983dd6 100644
--- a/Modules/Platform/Android/Determine-Compiler-NDK.cmake
+++ b/Modules/Platform/Android/Determine-Compiler-NDK.cmake
@@ -52,6 +52,7 @@ unset(_ANDROID_CONFIG_MK_PATTERNS)
# Find the newest toolchain version matching the ABI.
set(_ANDROID_TOOL_NAME "")
set(_ANDROID_TOOL_VERS 0)
+set(_ANDROID_TOOL_VERS_NDK "")
set(_ANDROID_TOOL_SETUP_MK "")
foreach(config_mk IN LISTS _ANDROID_CONFIG_MKS)
# Check that the toolchain matches the ABI.
@@ -62,18 +63,21 @@ foreach(config_mk IN LISTS _ANDROID_CONFIG_MKS)
unset(_ANDROID_TOOL_ABIS)
# Check the version.
- if("${config_mk}" MATCHES [[/([^/]+-(clang)?([0-9]\.[0-9]|))/config.mk$]])
+ if("${config_mk}" MATCHES [[/([^/]+-((clang)?([0-9]\.[0-9]|)))/config.mk$]])
set(_ANDROID_CUR_NAME "${CMAKE_MATCH_1}")
- set(_ANDROID_CUR_VERS "${CMAKE_MATCH_3}")
+ set(_ANDROID_CUR_VERS "${CMAKE_MATCH_4}")
+ set(_ANDROID_CUR_VERS_NDK "${CMAKE_MATCH_2}")
if(_ANDROID_TOOL_VERS STREQUAL "")
# already the latest possible
elseif(_ANDROID_CUR_VERS STREQUAL "" OR _ANDROID_CUR_VERS VERSION_GREATER _ANDROID_TOOL_VERS)
set(_ANDROID_TOOL_NAME "${_ANDROID_CUR_NAME}")
set(_ANDROID_TOOL_VERS "${_ANDROID_CUR_VERS}")
+ set(_ANDROID_TOOL_VERS_NDK "${_ANDROID_CUR_VERS_NDK}")
string(REPLACE "/config.mk" "/setup.mk" _ANDROID_TOOL_SETUP_MK "${config_mk}")
endif()
unset(_ANDROID_CUR_TOOL)
unset(_ANDROID_CUR_VERS)
+ unset(_ANDROID_CUR_VERS_NDK)
endif()
endforeach()
@@ -206,10 +210,17 @@ endif()
# Help CMakeFindBinUtils locate things.
set(_CMAKE_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_PREFIX}")
+set(_ANDROID_TOOL_NDK_TOOLCHAIN_HOST_TAG "${_ANDROID_HOST_DIR}")
+set(_ANDROID_TOOL_NDK_TOOLCHAIN_VERSION "${_ANDROID_TOOL_VERS_NDK}")
+
+# _ANDROID_TOOL_PREFIX should now match `gcc -dumpmachine`.
+string(REGEX REPLACE "-$" "" _ANDROID_TOOL_C_TOOLCHAIN_MACHINE "${_ANDROID_TOOL_PREFIX}")
+
set(_ANDROID_TOOL_C_TOOLCHAIN_VERSION "${_ANDROID_TOOL_VERS}")
set(_ANDROID_TOOL_C_TOOLCHAIN_PREFIX "${CMAKE_ANDROID_NDK}/toolchains/${_ANDROID_TOOL_NAME}/prebuilt/${_ANDROID_HOST_DIR}/bin/${_ANDROID_TOOL_PREFIX}")
set(_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX "${_ANDROID_HOST_EXT}")
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_MACHINE "${_ANDROID_TOOL_C_TOOLCHAIN_MACHINE}")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_VERSION "${_ANDROID_TOOL_C_TOOLCHAIN_VERSION}")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_C_TOOLCHAIN_PREFIX}")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX "${_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX}")
@@ -231,6 +242,7 @@ endif()
if(CMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG)
message(STATUS "_ANDROID_TOOL_NAME=${_ANDROID_TOOL_NAME}")
message(STATUS "_ANDROID_TOOL_VERS=${_ANDROID_TOOL_VERS}")
+ message(STATUS "_ANDROID_TOOL_VERS_NDK=${_ANDROID_TOOL_VERS_NDK}")
message(STATUS "_ANDROID_TOOL_PREFIX=${_ANDROID_TOOL_PREFIX}")
message(STATUS "_ANDROID_TOOL_CLANG_NAME=${_ANDROID_TOOL_CLANG_NAME}")
message(STATUS "_ANDROID_TOOL_CLANG_VERS=${_ANDROID_TOOL_CLANG_VERS}")
@@ -239,6 +251,7 @@ endif()
unset(_ANDROID_TOOL_NAME)
unset(_ANDROID_TOOL_VERS)
+unset(_ANDROID_TOOL_VERS_NDK)
unset(_ANDROID_TOOL_PREFIX)
unset(_ANDROID_TOOL_CLANG_NAME)
unset(_ANDROID_TOOL_CLANG_VERS)
diff --git a/Modules/Platform/Android/Determine-Compiler-Standalone.cmake b/Modules/Platform/Android/Determine-Compiler-Standalone.cmake
index 6393105..4c1ac1f 100644
--- a/Modules/Platform/Android/Determine-Compiler-Standalone.cmake
+++ b/Modules/Platform/Android/Determine-Compiler-Standalone.cmake
@@ -22,6 +22,9 @@ endif()
# Help CMakeFindBinUtils locate things.
set(_CMAKE_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_PREFIX}")
+# _ANDROID_TOOL_PREFIX should now match `gcc -dumpmachine`.
+string(REGEX REPLACE "-$" "" _ANDROID_TOOL_C_TOOLCHAIN_MACHINE "${_ANDROID_TOOL_PREFIX}")
+
execute_process(
COMMAND "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/${_ANDROID_TOOL_PREFIX}gcc${_ANDROID_HOST_EXT}" -dumpversion
OUTPUT_VARIABLE _gcc_version
@@ -42,6 +45,7 @@ endif()
set(_ANDROID_TOOL_C_TOOLCHAIN_PREFIX "${CMAKE_ANDROID_STANDALONE_TOOLCHAIN}/bin/${_ANDROID_TOOL_PREFIX}")
set(_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX "${_ANDROID_HOST_EXT}")
+set(_ANDROID_TOOL_CXX_TOOLCHAIN_MACHINE "${_ANDROID_TOOL_C_TOOLCHAIN_MACHINE}")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_VERSION "${_ANDROID_TOOL_C_TOOLCHAIN_VERSION}")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX "${_ANDROID_TOOL_C_TOOLCHAIN_PREFIX}")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX "${_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX}")
@@ -57,3 +61,6 @@ else()
set(_ANDROID_TOOL_CXX_COMPILER "${_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX}g++${_ANDROID_TOOL_CXX_TOOLCHAIN_SUFFIX}")
set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "")
endif()
+
+set(_ANDROID_TOOL_NDK_TOOLCHAIN_HOST_TAG "")
+set(_ANDROID_TOOL_NDK_TOOLCHAIN_VERSION "")
diff --git a/Modules/Platform/Android/Determine-Compiler.cmake b/Modules/Platform/Android/Determine-Compiler.cmake
index 2fd2c4a..a03ebcc 100644
--- a/Modules/Platform/Android/Determine-Compiler.cmake
+++ b/Modules/Platform/Android/Determine-Compiler.cmake
@@ -40,12 +40,16 @@ if(CMAKE_ANDROID_NDK)
elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
include(Platform/Android/Determine-Compiler-Standalone)
else()
+ set(_ANDROID_TOOL_NDK_TOOLCHAIN_HOST_TAG "")
+ set(_ANDROID_TOOL_NDK_TOOLCHAIN_VERSION "")
set(_ANDROID_TOOL_C_COMPILER "")
+ set(_ANDROID_TOOL_C_TOOLCHAIN_MACHINE "")
set(_ANDROID_TOOL_C_TOOLCHAIN_VERSION "")
set(_ANDROID_TOOL_C_COMPILER_EXTERNAL_TOOLCHAIN "")
set(_ANDROID_TOOL_C_TOOLCHAIN_PREFIX "")
set(_ANDROID_TOOL_C_TOOLCHAIN_SUFFIX "")
set(_ANDROID_TOOL_CXX_COMPILER "")
+ set(_ANDROID_TOOL_CXX_TOOLCHAIN_MACHINE "")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_VERSION "")
set(_ANDROID_TOOL_CXX_COMPILER_EXTERNAL_TOOLCHAIN "")
set(_ANDROID_TOOL_CXX_TOOLCHAIN_PREFIX "")
@@ -61,6 +65,9 @@ macro(__android_determine_compiler lang)
# Save the Android-specific information in CMake${lang}Compiler.cmake.
set(CMAKE_${lang}_COMPILER_CUSTOM_CODE "
+set(CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG \"${_ANDROID_TOOL_NDK_TOOLCHAIN_HOST_TAG}\")
+set(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION \"${_ANDROID_TOOL_NDK_TOOLCHAIN_VERSION}\")
+set(CMAKE_${lang}_ANDROID_TOOLCHAIN_MACHINE \"${_ANDROID_TOOL_${lang}_TOOLCHAIN_MACHINE}\")
set(CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION \"${_ANDROID_TOOL_${lang}_TOOLCHAIN_VERSION}\")
set(CMAKE_${lang}_COMPILER_EXTERNAL_TOOLCHAIN \"${_ANDROID_TOOL_${lang}_COMPILER_EXTERNAL_TOOLCHAIN}\")
set(CMAKE_${lang}_ANDROID_TOOLCHAIN_PREFIX \"${_ANDROID_TOOL_${lang}_TOOLCHAIN_PREFIX}\")
diff --git a/Modules/Platform/Darwin-Initialize.cmake b/Modules/Platform/Darwin-Initialize.cmake
index 39374e1..b539e45 100644
--- a/Modules/Platform/Darwin-Initialize.cmake
+++ b/Modules/Platform/Darwin-Initialize.cmake
@@ -113,7 +113,6 @@ set(CMAKE_OSX_SYSROOT "${_CMAKE_OSX_SYSROOT_DEFAULT}" CACHE ${_CMAKE_OSX_SYSROOT
"The product will be built against the headers and libraries located inside the indicated SDK.")
# Transform the cached value to something we can use.
-set(_CMAKE_OSX_SYSROOT_ORIG "${CMAKE_OSX_SYSROOT}")
set(_CMAKE_OSX_SYSROOT_PATH "")
if(CMAKE_OSX_SYSROOT)
if("x${CMAKE_OSX_SYSROOT}" MATCHES "/")
@@ -122,13 +121,10 @@ if(CMAKE_OSX_SYSROOT)
message(WARNING "Ignoring CMAKE_OSX_SYSROOT value:\n ${CMAKE_OSX_SYSROOT}\n"
"because the directory does not exist.")
set(CMAKE_OSX_SYSROOT "")
- set(_CMAKE_OSX_SYSROOT_ORIG "")
endif()
set(_CMAKE_OSX_SYSROOT_PATH "${CMAKE_OSX_SYSROOT}")
- endif()
-
- if(CMAKE_OSX_SYSROOT)
- # Transform the (maybe unversioned) sysroot into a versioned path.
+ else()
+ # Transform the sdk name into a path.
execute_process(
COMMAND xcodebuild -sdk ${CMAKE_OSX_SYSROOT} -version Path
OUTPUT_VARIABLE _stdout
diff --git a/Modules/Platform/Darwin-PGI-C.cmake b/Modules/Platform/Darwin-PGI-C.cmake
new file mode 100644
index 0000000..790919b
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Darwin-PGI)
+__darwin_compiler_pgi(C)
diff --git a/Modules/Platform/Darwin-PGI-CXX.cmake b/Modules/Platform/Darwin-PGI-CXX.cmake
new file mode 100644
index 0000000..ceaed71
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Darwin-PGI)
+__darwin_compiler_pgi(CXX)
diff --git a/Modules/Platform/Darwin-PGI-Fortran.cmake b/Modules/Platform/Darwin-PGI-Fortran.cmake
new file mode 100644
index 0000000..146807b
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI-Fortran.cmake
@@ -0,0 +1,2 @@
+include(Platform/Darwin-PGI)
+__darwin_compiler_pgi(Fortran)
diff --git a/Modules/Platform/Darwin-PGI.cmake b/Modules/Platform/Darwin-PGI.cmake
new file mode 100644
index 0000000..04479a8
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI.cmake
@@ -0,0 +1,14 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# This module is shared by multiple languages; use include blocker.
+if(__DARWIN_COMPILER_PGI)
+ return()
+endif()
+set(__DARWIN_COMPILER_PGI 1)
+
+macro(__darwin_compiler_pgi lang)
+ set(CMAKE_${lang}_OSX_COMPATIBILITY_VERSION_FLAG "-Wl,-compatibility_version,")
+ set(CMAKE_${lang}_OSX_CURRENT_VERSION_FLAG "-Wl,-current_version,")
+ set(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG "-Wl,-install_name")
+endmacro()
diff --git a/Modules/Platform/Darwin.cmake b/Modules/Platform/Darwin.cmake
index c09bac4..727baa6 100644
--- a/Modules/Platform/Darwin.cmake
+++ b/Modules/Platform/Darwin.cmake
@@ -64,30 +64,6 @@ if(NOT DEFINED CMAKE_INSTALL_NAME_TOOL)
mark_as_advanced(CMAKE_INSTALL_NAME_TOOL)
endif()
-# Make sure the combination of SDK and Deployment Target are allowed
-if(CMAKE_OSX_DEPLOYMENT_TARGET)
- if("${_CMAKE_OSX_SYSROOT_PATH}" MATCHES "/MacOSX([0-9]+\\.[0-9]+)[^/]*\\.sdk")
- set(_sdk_ver "${CMAKE_MATCH_1}")
- elseif("${_CMAKE_OSX_SYSROOT_ORIG}" MATCHES "^macosx([0-9]+\\.[0-9]+)$")
- set(_sdk_ver "${CMAKE_MATCH_1}")
- elseif("${_CMAKE_OSX_SYSROOT_ORIG}" STREQUAL "/")
- set(_sdk_ver "${_CURRENT_OSX_VERSION}")
- else()
- message(FATAL_ERROR
- "CMAKE_OSX_DEPLOYMENT_TARGET is '${CMAKE_OSX_DEPLOYMENT_TARGET}' "
- "but CMAKE_OSX_SYSROOT:\n \"${_CMAKE_OSX_SYSROOT_ORIG}\"\n"
- "is not set to a MacOSX SDK with a recognized version. "
- "Either set CMAKE_OSX_SYSROOT to a valid SDK or set "
- "CMAKE_OSX_DEPLOYMENT_TARGET to empty.")
- endif()
- if(CMAKE_OSX_DEPLOYMENT_TARGET VERSION_GREATER "${_sdk_ver}")
- message(FATAL_ERROR
- "CMAKE_OSX_DEPLOYMENT_TARGET (${CMAKE_OSX_DEPLOYMENT_TARGET}) "
- "is greater than CMAKE_OSX_SYSROOT SDK:\n ${_CMAKE_OSX_SYSROOT_ORIG}\n"
- "Please set CMAKE_OSX_DEPLOYMENT_TARGET to ${_sdk_ver} or lower.")
- endif()
-endif()
-
# Enable shared library versioning.
set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-install_name")
diff --git a/Modules/Platform/Fuchsia.cmake b/Modules/Platform/Fuchsia.cmake
new file mode 100644
index 0000000..896da7b
--- /dev/null
+++ b/Modules/Platform/Fuchsia.cmake
@@ -0,0 +1,25 @@
+set(FUCHSIA 1)
+
+set(CMAKE_DL_LIBS "")
+set(CMAKE_C_COMPILE_OPTIONS_PIC "-fPIC")
+set(CMAKE_C_COMPILE_OPTIONS_PIE "-fPIE")
+set(CMAKE_SHARED_LIBRARY_C_FLAGS "-fPIC")
+set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-shared")
+set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG "-Wl,-rpath,")
+set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP ":")
+set(CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG "-Wl,-rpath-link,")
+set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-Wl,-soname,")
+set(CMAKE_EXE_EXPORTS_C_FLAG "-Wl,--export-dynamic")
+
+# Shared libraries with no builtin soname may not be linked safely by
+# specifying the file path.
+set(CMAKE_PLATFORM_USES_PATH_WHEN_NO_SONAME 1)
+
+# Initialize C link type selection flags. These flags are used when
+# building a shared library, shared module, or executable that links
+# to other libraries to select whether to use the static or shared
+# versions of the libraries.
+foreach(type SHARED_LIBRARY SHARED_MODULE EXE)
+ set(CMAKE_${type}_LINK_STATIC_C_FLAGS "-Wl,-Bstatic")
+ set(CMAKE_${type}_LINK_DYNAMIC_C_FLAGS "-Wl,-Bdynamic")
+endforeach()
diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake
index d72ec66..f506500 100644
--- a/Modules/Platform/Windows-MSVC.cmake
+++ b/Modules/Platform/Windows-MSVC.cmake
@@ -285,13 +285,13 @@ macro(__windows_compiler_msvc lang)
# note: MSVC 14 2015 Update 1 sets -fno-ms-compatibility by default, but this does not allow one to compile many projects
# that include MS's own headers. CMake itself is affected project too.
string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} -fms-extensions -fms-compatibility -D_WINDOWS -Wall${_FLAGS_${lang}}")
- string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -D_DEBUG /MDd -gline-tables-only -fno-inline -O0 ${_RTC1}")
+ string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /MDd -gline-tables-only -fno-inline -O0 ${_RTC1}")
string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " /MD -O2 -DNDEBUG")
string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " /MD -gline-tables-only -O2 -fno-inline -DNDEBUG")
string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " /MD -DNDEBUG") # TODO: Add '-Os' once VS generator maps it properly for Clang
else()
string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} /D_WINDOWS /W3${_FLAGS_${lang}}")
- string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /D_DEBUG /MDd /Zi /Ob0 /Od ${_RTC1}")
+ string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /MDd /Zi /Ob0 /Od ${_RTC1}")
string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " /MD /O2 /Ob2 /DNDEBUG")
string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " /MD /Zi /O2 /Ob1 /DNDEBUG")
string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " /MD /O1 /Ob1 /DNDEBUG")
diff --git a/Modules/Platform/Windows.cmake b/Modules/Platform/Windows.cmake
index 9a937a7..d8b3957 100644
--- a/Modules/Platform/Windows.cmake
+++ b/Modules/Platform/Windows.cmake
@@ -17,6 +17,7 @@ set(CMAKE_IMPORT_LIBRARY_SUFFIX ".lib")
set(CMAKE_EXECUTABLE_SUFFIX ".exe") # .exe
set(CMAKE_LINK_LIBRARY_SUFFIX ".lib")
set(CMAKE_DL_LIBS "")
+set(CMAKE_EXTRA_LINK_EXTENSIONS ".targets")
set(CMAKE_FIND_LIBRARY_PREFIXES "")
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib")
diff --git a/Modules/UseSWIG.cmake b/Modules/UseSWIG.cmake
index d242f87..651f9f1 100644
--- a/Modules/UseSWIG.cmake
+++ b/Modules/UseSWIG.cmake
@@ -9,18 +9,22 @@
#
# ::
#
-# SWIG_ADD_MODULE(name language [ files ])
+# SWIG_ADD_LIBRARY(<name>
+# [TYPE <SHARED|MODULE|STATIC|USE_BUILD_SHARED_LIBS>]
+# LANGUAGE <language>
+# SOURCES <file>...
+# )
# - Define swig module with given name and specified language
# SWIG_LINK_LIBRARIES(name [ libraries ])
# - Link libraries to swig module
#
# Source files properties on module files can be set before the invocation
-# of the SWIG_ADD_MODULE macro to specify special behavior of SWIG.
+# of the SWIG_ADD_LIBRARY macro to specify special behavior of SWIG.
#
# The source file property CPLUSPLUS calls SWIG in c++ mode, e.g.::
#
# set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON)
-# swig_add_module(mymod python mymod.i)
+# swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
#
# The source file property SWIG_FLAGS adds custom flags to the SWIG executable.
#
@@ -36,8 +40,11 @@
#
# CMAKE_SWIG_FLAGS can be used to add special flags to all swig calls.
#
-# Another special variable is CMAKE_SWIG_OUTDIR, it allows one to specify
-# where to write all the swig generated module (swig -outdir option)
+# CMAKE_SWIG_OUTDIR allows one to specify where to write
+# the language specific files (swig -outdir option).
+#
+# SWIG_OUTFILE_DIR allows one to specify where to write the output file
+# (swig -o option). If not specified, CMAKE_SWIG_OUTDIR is used.
#
# The name-specific variable SWIG_MODULE_<name>_EXTRA_DEPS may be used to specify extra
# dependencies for the generated modules.
@@ -50,7 +57,8 @@
set(SWIG_CXX_EXTENSION "cxx")
set(SWIG_EXTRA_LIBRARIES "")
-set(SWIG_PYTHON_EXTRA_FILE_EXTENSION "py")
+set(SWIG_PYTHON_EXTRA_FILE_EXTENSIONS ".py")
+set(SWIG_JAVA_EXTRA_FILE_EXTENSIONS ".java" "JNI.java")
#
# For given swig module initialize variables associated with it
@@ -116,9 +124,9 @@ macro(SWIG_GET_EXTRA_OUTPUT_FILES language outfiles generatedpath infile)
endif ()
endif()
- foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSION})
+ foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSIONS})
set(${outfiles} ${${outfiles}}
- "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}.${it}")
+ "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}${it}")
endforeach()
endmacro()
@@ -142,6 +150,13 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
else()
set(swig_outdir ${CMAKE_CURRENT_BINARY_DIR})
endif()
+
+ if(SWIG_OUTFILE_DIR)
+ set(swig_outfile_dir ${SWIG_OUTFILE_DIR})
+ else()
+ set(swig_outfile_dir ${swig_outdir})
+ endif()
+
if (NOT SWIG_MODULE_${name}_NOPROXY)
SWIG_GET_EXTRA_OUTPUT_FILES(${SWIG_MODULE_${name}_LANGUAGE}
swig_extra_generated_files
@@ -149,7 +164,7 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
"${swig_source_file_fullname}")
endif()
set(swig_generated_file_fullname
- "${swig_outdir}/${swig_source_file_name_we}")
+ "${swig_outfile_dir}/${swig_source_file_name_we}")
# add the language into the name of the file (i.e. TCL_wrap)
# this allows for the same .i file to be wrapped into different languages
string(APPEND swig_generated_file_fullname
@@ -207,10 +222,42 @@ endmacro()
# Create Swig module
#
macro(SWIG_ADD_MODULE name language)
- SWIG_MODULE_INITIALIZE(${name} ${language})
+ message(DEPRECATION "SWIG_ADD_MODULE is deprecated. Use SWIG_ADD_LIBRARY instead.")
+ swig_add_library(${name}
+ LANGUAGE ${language}
+ TYPE MODULE
+ SOURCES ${ARGN})
+endmacro()
+
+
+macro(SWIG_ADD_LIBRARY name)
+
+ include(CMakeParseArguments)
+ set(options "")
+ set(oneValueArgs LANGUAGE
+ TYPE)
+ set(multiValueArgs SOURCES)
+ cmake_parse_arguments(_SAM "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT DEFINED _SAM_LANGUAGE)
+ message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing LANGUAGE argument")
+ endif()
+
+ if(NOT DEFINED _SAM_SOURCES)
+ message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing SOURCES argument")
+ endif()
+
+ if(NOT DEFINED _SAM_TYPE)
+ set(_SAM_TYPE MODULE)
+ elseif("${_SAM_TYPE}" STREQUAL "USE_BUILD_SHARED_LIBS")
+ unset(_SAM_TYPE)
+ endif()
+
+ swig_module_initialize(${name} ${_SAM_LANGUAGE})
+
set(swig_dot_i_sources)
set(swig_other_sources)
- foreach(it ${ARGN})
+ foreach(it ${_SAM_SOURCES})
if(${it} MATCHES "\\.i$")
set(swig_dot_i_sources ${swig_dot_i_sources} "${it}")
else()
@@ -227,11 +274,13 @@ macro(SWIG_ADD_MODULE name language)
set_directory_properties(PROPERTIES
ADDITIONAL_MAKE_CLEAN_FILES "${swig_extra_clean_files};${swig_generated_sources}")
add_library(${SWIG_MODULE_${name}_REAL_NAME}
- MODULE
+ ${_SAM_TYPE}
${swig_generated_sources}
${swig_other_sources})
- set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES NO_SONAME ON)
- string(TOLOWER "${language}" swig_lowercase_language)
+ if("${_SAM_TYPE}" STREQUAL "MODULE")
+ set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES NO_SONAME ON)
+ endif()
+ string(TOLOWER "${_SAM_LANGUAGE}" swig_lowercase_language)
if ("${swig_lowercase_language}" STREQUAL "octave")
set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".oct")
@@ -248,7 +297,9 @@ macro(SWIG_ADD_MODULE name language)
set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".jnilib")
endif ()
elseif ("${swig_lowercase_language}" STREQUAL "lua")
- set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
+ if("${_SAM_TYPE}" STREQUAL "MODULE")
+ set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
+ endif()
elseif ("${swig_lowercase_language}" STREQUAL "python")
# this is only needed for the python case where a _modulename.so is generated
set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
diff --git a/Modules/WriteCompilerDetectionHeader.cmake b/Modules/WriteCompilerDetectionHeader.cmake
index 82e8fba..a390f4b 100644
--- a/Modules/WriteCompilerDetectionHeader.cmake
+++ b/Modules/WriteCompilerDetectionHeader.cmake
@@ -76,6 +76,7 @@
# Available features in this version of CMake are listed in the
# :prop_gbl:`CMAKE_C_KNOWN_FEATURES` and
# :prop_gbl:`CMAKE_CXX_KNOWN_FEATURES` global properties.
+# The ``{c,cxx}_std_*`` meta-features are ignored if requested.
#
# See the :manual:`cmake-compile-features(7)` manual for information on
# compile features.
@@ -358,7 +359,11 @@ function(write_compiler_detection_header
endif()
foreach(feature ${_WCD_FEATURES})
- if (feature MATCHES "^cxx_")
+ if (feature MATCHES "^c_std_")
+ # ignored
+ elseif (feature MATCHES "^cxx_std_")
+ # ignored
+ elseif (feature MATCHES "^cxx_")
list(APPEND _langs CXX)
list(APPEND CXX_features ${feature})
elseif (feature MATCHES "^c_")
diff --git a/Packaging/QtSDK/ToolsCMakeXX.cmake b/Packaging/QtSDK/ToolsCMakeXX.cmake
new file mode 100644
index 0000000..e227b73
--- /dev/null
+++ b/Packaging/QtSDK/ToolsCMakeXX.cmake
@@ -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.
+
+# CMake version
+include("${CMAKE_CURRENT_LIST_DIR}/../../Source/CMakeVersion.cmake")
+set(CM_VER_XY ${CMake_VERSION_MAJOR}${CMake_VERSION_MINOR})
+set(CM_VER_X_Y ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR})
+set(CM_VER_X_Y_Z ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATH})
+
+# Destiantion
+set(CM_INST_PREF "Tools/CMake/${CM_VER_X_Y}")
+set(CMAKE_BIN_DIR "${CM_INST_PREF}/bin"
+ CACHE STRING "Location under install bin")
+set(CMAKE_DATA_DIR "${CM_INST_PREF}/share/cmake-${CM_VER_X_Y}"
+ CACHE STRING "Location under install data")
+set(CMAKE_DOC_DIR "${CM_INST_PREF}/doc/cmake-${CM_VER_X_Y}"
+ CACHE STRING "Location under install docs")
+set(CMAKE_MAN_DIR "${CM_INST_PREF}/man"
+ CACHE STRING "Location under install man pages")
+set(CMAKE_XDGDATA_DIR "${CM_INST_PREF}/share"
+ CACHE STRING "Location under install XDG specific files")
+
+# Package
+set(CMake_IFW_ROOT_COMPONENT_NAME
+ "qt.tools.cmake.${CM_VER_XY}"
+ CACHE STRING "QtSDK CMake tools component name")
+set(CMake_IFW_ROOT_COMPONENT_DISPLAY_NAME
+ "CMake ${CM_VER_X_Y}"
+ CACHE STRING "QtSDK CMake tools component display name")
+set(CMake_IFW_ROOT_COMPONENT_DESCRIPTION
+ "CMake Build Tools ${CM_VER_X_Y_Z}"
+ CACHE STRING "QtSDK CMake tools component description")
+set(CMake_IFW_ROOT_COMPONENT_SCRIPT
+ "${CMAKE_CURRENT_BINARY_DIR}/qt.tools.cmake.${CM_VER_XY}.qs"
+ CACHE STRING "QtSDK CMake tools component display name")
+set(CMake_IFW_ROOT_COMPONENT_PRIORITY
+ "${CM_VER_XY}"
+ CACHE STRING "QtSDK CMake tools component sorting priority")
+set(CMake_IFW_ROOT_COMPONENT_DEFAULT ""
+ CACHE STRING "QtSDK CMake tools component default")
+set(CMake_IFW_ROOT_COMPONENT_FORCED_INSTALLATION ""
+ CACHE STRING "QtSDK CMake tools component forsed installation")
+
+# CPack
+set(CPACK_GENERATOR "IFW"
+ CACHE STRING "Generator to build QtSDK CMake package")
+set(CPACK_PACKAGE_FILE_NAME "CMake"
+ CACHE STRING "Short package name")
+set(CPACK_TOPLEVEL_TAG "../QtSDK"
+ CACHE STRING "QtSDK packages dir")
+set(CPACK_IFW_DOWNLOAD_ALL "TRUE"
+ CACHE STRING "All QtSDK components is downloaded")
+set(CPACK_DOWNLOAD_SITE "file:///${CMAKE_CURRENT_BINARY_DIR}/QtSDK/IFW/CMake/repository"
+ CACHE STRING "Local repository for testing")
+
+# Script
+set(SDKToolBinary "@SDKToolBinary@")
+set(CM_VER_XY_DIR "@CMAKE${CM_VER_XY}_DIR@")
+configure_file("${CMAKE_CURRENT_LIST_DIR}/qt.tools.cmake.xx.qs.in"
+ "${CMAKE_CURRENT_BINARY_DIR}/qt.tools.cmake.${CM_VER_XY}.qs"
+ @ONLY)
+
+# Unset temporary variables
+unset(CM_VER_XY)
+unset(CM_VER_X_Y)
+unset(CM_VER_X_Y_Z)
+unset(CM_INST_PREF)
+unset(SDKToolBinary)
diff --git a/Packaging/QtSDK/qt.tools.cmake.xx.qs.in b/Packaging/QtSDK/qt.tools.cmake.xx.qs.in
new file mode 100644
index 0000000..cb42a71
--- /dev/null
+++ b/Packaging/QtSDK/qt.tools.cmake.xx.qs.in
@@ -0,0 +1,48 @@
+/****************************************************************************
+**
+** Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+** file Copyright.txt or https://cmake.org/licensing for details.
+**
+****************************************************************************/
+
+// constructor
+function Component()
+{
+ installer.valueChanged.connect( this, Component.prototype.reactOnTargetDirChange );
+ // set the default values to CMAKE@CM_VER_XY@_DIR
+ Component.prototype.reactOnTargetDirChange("TargetDir", installer.value("TargetDir"));
+}
+
+Component.prototype.reactOnTargetDirChange = function(key, value)
+{
+ if (key == "TargetDir") {
+ var path = value + "/@CM_INST_PREF@";
+ installer.setValue("CMAKE@CM_VER_XY@_DIR", path.replace(/\\/g, "/"));
+ }
+}
+
+Component.prototype.createOperations = function()
+{
+ component.createOperations();
+
+ if (installer.value("os") == "win") {
+ try {
+ if (installer.value("SDKToolBinary") == "")
+ return;
+
+ var cmId = component.name;
+ installer.setValue("CMAKE@CM_VER_XY@_ID", cmId);
+
+ component.addOperation("Execute",
+ ["{0,2}", "@SDKToolBinary@", "addCMake",
+ "--id", cmId,
+ "--name", "@CMake_IFW_ROOT_COMPONENT_DISPLAY_NAME@",
+ "--path", "@CM_VER_XY_DIR@/bin/cmake.exe",
+ "UNDOEXECUTE",
+ "@SDKToolBinary@", "rmCMake", "--id", cmId]);
+
+ } catch( e ) {
+ print( e );
+ }
+ }
+}
diff --git a/Source/.gitattributes b/Source/.gitattributes
index 5002b2a..e9e35bd 100644
--- a/Source/.gitattributes
+++ b/Source/.gitattributes
@@ -1,6 +1,3 @@
-# Preserve upstream indentation style.
-cm_sha2.* whitespace=indent-with-non-tab
-
# Preserve indentation style in generated code.
cmListFileLexer.c whitespace=-tab-in-indent,-indent-with-non-tab
cmFortranLexer.cxx whitespace=-tab-in-indent,-indent-with-non-tab
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt
index cf9dbb8..5b381b4 100644
--- a/Source/CMakeLists.txt
+++ b/Source/CMakeLists.txt
@@ -298,6 +298,8 @@ set(SRCS
cmLinkItem.h
cmLinkLineComputer.cxx
cmLinkLineComputer.h
+ cmLinkLineDeviceComputer.cxx
+ cmLinkLineDeviceComputer.h
cmListFileCache.cxx
cmListFileCache.h
cmListFileLexer.c
@@ -330,6 +332,8 @@ set(SRCS
cmOrderDirectories.h
cmPolicies.h
cmPolicies.cxx
+ cmProcessOutput.cxx
+ cmProcessOutput.h
cmProcessTools.cxx
cmProcessTools.h
cmProperty.cxx
@@ -436,24 +440,10 @@ set(SRCS
cmCreateTestSourceList.h
cmDefinePropertyCommand.cxx
cmDefinePropertyCommand.h
- cmElseCommand.cxx
- cmElseCommand.h
- cmElseIfCommand.cxx
- cmElseIfCommand.h
cmEnableLanguageCommand.cxx
cmEnableLanguageCommand.h
cmEnableTestingCommand.cxx
cmEnableTestingCommand.h
- cmEndForEachCommand.cxx
- cmEndForEachCommand.h
- cmEndFunctionCommand.cxx
- cmEndFunctionCommand.h
- cmEndIfCommand.cxx
- cmEndIfCommand.h
- cmEndMacroCommand.cxx
- cmEndMacroCommand.h
- cmEndWhileCommand.cxx
- cmEndWhileCommand.h
cmExecProgramCommand.cxx
cmExecProgramCommand.h
cmExecuteProcessCommand.cxx
@@ -608,6 +598,8 @@ set(SRCS
cmTryCompileCommand.h
cmTryRunCommand.cxx
cmTryRunCommand.h
+ cmUnexpectedCommand.cxx
+ cmUnexpectedCommand.h
cmUnsetCommand.cxx
cmUnsetCommand.h
cmUseMangledMesaCommand.cxx
@@ -626,14 +618,15 @@ set(SRCS
cm_auto_ptr.hxx
cm_get_date.h
cm_get_date.c
- cm_sha2.h
- cm_sha2.c
cm_utf8.h
cm_utf8.c
cm_codecvt.hxx
cm_codecvt.cxx
)
+SET_PROPERTY(SOURCE cmProcessOutput.cxx APPEND PROPERTY COMPILE_DEFINITIONS
+ KWSYS_ENCODING_DEFAULT_CODEPAGE=${KWSYS_ENCODING_DEFAULT_CODEPAGE})
+
# Kdevelop only works on UNIX and not windows
if(UNIX)
set(SRCS ${SRCS} cmGlobalKdevelopGenerator.cxx)
@@ -788,6 +781,7 @@ target_link_libraries(CMakeLib cmsys
${CMAKE_CURL_LIBRARIES}
${CMAKE_JSONCPP_LIBRARIES}
${CMAKE_LIBUV_LIBRARIES}
+ ${CMAKE_LIBRHASH_LIBRARIES}
${CMake_KWIML_LIBRARIES}
)
diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake
index e3c01fe..d7f27be 100644
--- a/Source/CMakeVersion.cmake
+++ b/Source/CMakeVersion.cmake
@@ -1,5 +1,5 @@
# CMake version number components.
set(CMake_VERSION_MAJOR 3)
set(CMake_VERSION_MINOR 7)
-set(CMake_VERSION_PATCH 20161028)
+set(CMake_VERSION_PATCH 20161205)
#set(CMake_VERSION_RC 1)
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
index 0098a4b..a6d443b 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
@@ -2,6 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackIFWInstaller.h"
+#include <cmConfigure.h>
+#include <sstream>
+#include <stddef.h>
+#include <utility>
+
#include "CPack/cmCPackGenerator.h"
#include "CPack/cmCPackLog.h"
#include "cmCPackIFWGenerator.h"
@@ -12,9 +17,6 @@
#include "cmXMLParser.h"
#include "cmXMLWriter.h"
-#include <cmConfigure.h>
-#include <utility>
-
#ifdef cmCPackLogger
#undef cmCPackLogger
#endif
@@ -403,7 +405,11 @@ void cmCPackIFWInstaller::GeneratePackageFiles()
// Check package group
if (const char* option = GetOption("CPACK_IFW_PACKAGE_GROUP")) {
package.ConfigureFromGroup(option);
- package.ForcedInstallation = "true";
+ std::string forcedOption = "CPACK_IFW_COMPONENT_GROUP_" +
+ cmsys::SystemTools::UpperCase(option) + "_FORCED_INSTALLATION";
+ if (!GetOption(forcedOption)) {
+ package.ForcedInstallation = "true";
+ }
} else {
package.ConfigureFromOptions();
}
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx
index 4d46120..902c85d 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.cxx
+++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx
@@ -109,6 +109,16 @@ bool cmCPackIFWPackage::IsOn(const std::string& op) const
return Generator ? Generator->IsOn(op) : false;
}
+bool cmCPackIFWPackage::IsSetToOff(const std::string& op) const
+{
+ return Generator ? Generator->IsSetToOff(op) : false;
+}
+
+bool cmCPackIFWPackage::IsSetToEmpty(const std::string& op) const
+{
+ return Generator ? Generator->IsSetToEmpty(op) : false;
+}
+
bool cmCPackIFWPackage::IsVersionLess(const char* version)
{
return Generator ? Generator->IsVersionLess(version) : false;
@@ -286,7 +296,7 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
// ForcedInstallation
ForcedInstallation = component->IsRequired ? "true" : "false";
- return 1;
+ return ConfigureFromPrefix(prefix);
}
int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
@@ -344,7 +354,7 @@ int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
SortingPriority = option;
}
- return 1;
+ return ConfigureFromPrefix(prefix);
}
int cmCPackIFWPackage::ConfigureFromGroup(const std::string& groupName)
@@ -380,6 +390,74 @@ int cmCPackIFWPackage::ConfigureFromGroup(const std::string& groupName)
return ConfigureFromGroup(&group);
}
+// Common options for components and groups
+int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
+{
+ // Temporary variable for full option name
+ std::string option;
+
+ // Display name
+ option = prefix + "DISPLAY_NAME";
+ if (IsSetToEmpty(option)) {
+ DisplayName.clear();
+ } else if (const char* value = GetOption(option)) {
+ DisplayName = value;
+ }
+
+ // Description
+ option = prefix + "DESCRIPTION";
+ if (IsSetToEmpty(option)) {
+ Description.clear();
+ } else if (const char* value = GetOption(option)) {
+ Description = value;
+ }
+
+ // Release date
+ option = prefix + "RELEASE_DATE";
+ if (IsSetToEmpty(option)) {
+ ReleaseDate.clear();
+ } else if (const char* value = GetOption(option)) {
+ ReleaseDate = value;
+ }
+
+ // Visibility
+ option = prefix + "VIRTUAL";
+ if (IsSetToEmpty(option)) {
+ Virtual.clear();
+ } else if (IsOn(option)) {
+ Virtual = "true";
+ }
+
+ // Default selection
+ option = prefix + "DEFAULT";
+ if (IsSetToEmpty(option)) {
+ Default.clear();
+ } else if (const char* value = GetOption(option)) {
+ std::string lowerValue = cmsys::SystemTools::LowerCase(value);
+ if (lowerValue.compare("true") == 0) {
+ Default = "true";
+ } else if (lowerValue.compare("false") == 0) {
+ Default = "false";
+ } else if (lowerValue.compare("script") == 0) {
+ Default = "script";
+ } else {
+ Default = value;
+ }
+ }
+
+ // Forsed installation
+ option = prefix + "FORCED_INSTALLATION";
+ if (IsSetToEmpty(option)) {
+ ForcedInstallation.clear();
+ } else if (IsOn(option)) {
+ ForcedInstallation = "true";
+ } else if (IsSetToOff(option)) {
+ ForcedInstallation = "false";
+ }
+
+ return 1;
+}
+
void cmCPackIFWPackage::GeneratePackageFile()
{
// Lazy directory initialization
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.h b/Source/CPack/IFW/cmCPackIFWPackage.h
index d1af2bd..76ed540 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.h
+++ b/Source/CPack/IFW/cmCPackIFWPackage.h
@@ -112,6 +112,8 @@ public:
const char* GetOption(const std::string& op) const;
bool IsOn(const std::string& op) const;
+ bool IsSetToOff(const std::string& op) const;
+ bool IsSetToEmpty(const std::string& op) const;
bool IsVersionLess(const char* version);
bool IsVersionGreater(const char* version);
@@ -125,6 +127,7 @@ public:
int ConfigureFromComponent(cmCPackComponent* component);
int ConfigureFromGroup(cmCPackComponentGroup* group);
int ConfigureFromGroup(const std::string& groupName);
+ int ConfigureFromPrefix(const std::string& prefix);
void GeneratePackageFile();
diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx
index 6eb4a6c..b159e64 100644
--- a/Source/CPack/OSXScriptLauncher.cxx
+++ b/Source/CPack/OSXScriptLauncher.cxx
@@ -3,8 +3,10 @@
#include <cmsys/FStream.hxx>
#include <cmsys/Process.h>
#include <cmsys/SystemTools.hxx>
-
#include <iostream>
+#include <stddef.h>
+#include <string>
+#include <vector>
#include <CoreFoundation/CoreFoundation.h>
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
index 5320449..2bccf2e 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
@@ -4,6 +4,7 @@
#include <CPack/cmCPackComponentGroup.h>
#include <CPack/cmCPackLog.h>
+#include <algorithm>
#include <cmCryptoHash.h>
#include <cmGeneratedFileStream.h>
#include <cmInstalledFile.h>
@@ -410,8 +411,7 @@ void cmCPackWIXGenerator::AddDefinition(cmWIXSourceWriter& source,
std::ostringstream tmp;
tmp << name << "=\"" << value << '"';
- source.AddProcessingInstruction(
- "define", cmWIXSourceWriter::CMakeEncodingToUtf8(tmp.str()));
+ source.AddProcessingInstruction("define", tmp.str());
}
bool cmCPackWIXGenerator::CreateWiXSourceFiles()
@@ -1061,8 +1061,8 @@ std::string cmCPackWIXGenerator::CreateNewIdForPath(std::string const& path)
std::string cmCPackWIXGenerator::CreateHashedId(
std::string const& path, std::string const& normalizedFilename)
{
- CM_AUTO_PTR<cmCryptoHash> sha1 = cmCryptoHash::New("SHA1");
- std::string hash = sha1->HashString(path.c_str());
+ cmCryptoHash sha1(cmCryptoHash::AlgoSHA1);
+ std::string const hash = sha1.HashString(path);
std::string identifier;
identifier += hash.substr(0, 7) + "_";
diff --git a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
index b535979..a3c8394 100644
--- a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
+++ b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
@@ -5,9 +5,8 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
-
#include <cmsys/FStream.hxx>
+#include <string>
/** \class cmWIXRichtTextFormatWriter
* \brief Helper class to generate Rich Text Format (RTF) documents
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.cxx b/Source/CPack/WiX/cmWIXSourceWriter.cxx
index a8b0d7c..b434334 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXSourceWriter.cxx
@@ -117,9 +117,7 @@ void cmWIXSourceWriter::AddProcessingInstruction(std::string const& target,
void cmWIXSourceWriter::AddAttribute(std::string const& key,
std::string const& value)
{
- std::string utf8 = CMakeEncodingToUtf8(value);
-
- File << " " << key << "=\"" << EscapeAttributeValue(utf8) << '"';
+ File << " " << key << "=\"" << EscapeAttributeValue(value) << '"';
}
void cmWIXSourceWriter::AddAttributeUnlessEmpty(std::string const& key,
@@ -130,43 +128,6 @@ void cmWIXSourceWriter::AddAttributeUnlessEmpty(std::string const& key,
}
}
-std::string cmWIXSourceWriter::CMakeEncodingToUtf8(std::string const& value)
-{
-#ifdef CMAKE_ENCODING_UTF8
- return value;
-#else
- if (value.empty()) {
- return std::string();
- }
-
- int characterCount = MultiByteToWideChar(
- CP_ACP, 0, value.c_str(), static_cast<int>(value.size()), 0, 0);
-
- if (characterCount == 0) {
- return std::string();
- }
-
- std::vector<wchar_t> utf16(characterCount);
-
- MultiByteToWideChar(CP_ACP, 0, value.c_str(), static_cast<int>(value.size()),
- &utf16[0], static_cast<int>(utf16.size()));
-
- int utf8ByteCount = WideCharToMultiByte(
- CP_UTF8, 0, &utf16[0], static_cast<int>(utf16.size()), 0, 0, 0, 0);
-
- if (utf8ByteCount == 0) {
- return std::string();
- }
-
- std::vector<char> utf8(utf8ByteCount);
-
- WideCharToMultiByte(CP_UTF8, 0, &utf16[0], static_cast<int>(utf16.size()),
- &utf8[0], static_cast<int>(utf8.size()), 0, 0);
-
- return std::string(&utf8[0], utf8.size());
-#endif
-}
-
std::string cmWIXSourceWriter::CreateGuidFromComponentId(
std::string const& componentId)
{
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.h b/Source/CPack/WiX/cmWIXSourceWriter.h
index b5c06ab..45aefe5 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXSourceWriter.h
@@ -50,8 +50,6 @@ public:
std::string CreateGuidFromComponentId(std::string const& componentId);
- static std::string CMakeEncodingToUtf8(std::string const& value);
-
protected:
cmCPackLog* Logger;
diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx
index 61d0127..d538901 100644
--- a/Source/CPack/cmCPackBundleGenerator.cxx
+++ b/Source/CPack/cmCPackBundleGenerator.cxx
@@ -2,11 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackBundleGenerator.h"
+#include <sstream>
+#include <vector>
+
#include "cmCPackLog.h"
#include "cmSystemTools.h"
-#include <cmsys/RegularExpression.hxx>
-
cmCPackBundleGenerator::cmCPackBundleGenerator()
{
}
diff --git a/Source/CPack/cmCPackBundleGenerator.h b/Source/CPack/cmCPackBundleGenerator.h
index 9ea4304..c9200c1 100644
--- a/Source/CPack/cmCPackBundleGenerator.h
+++ b/Source/CPack/cmCPackBundleGenerator.h
@@ -3,7 +3,11 @@
#ifndef cmCPackBundleGenerator_h
#define cmCPackBundleGenerator_h
+#include <cmConfigure.h>
+#include <string>
+
#include "cmCPackDragNDropGenerator.h"
+#include "cmCPackGenerator.h"
/** \class cmCPackBundleGenerator
* \brief A generator for OSX bundles
diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx
index bdf4076..fd67df9 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.cxx
+++ b/Source/CPack/cmCPackDragNDropGenerator.cxx
@@ -2,14 +2,16 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackDragNDropGenerator.h"
+#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
#include "cmGeneratedFileStream.h"
#include "cmSystemTools.h"
#include <cmsys/FStream.hxx>
#include <cmsys/RegularExpression.hxx>
-
#include <iomanip>
+#include <map>
+#include <stdlib.h>
#include <CoreFoundation/CoreFoundation.h>
diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h
index f803ad9..876eab7 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.h
+++ b/Source/CPack/cmCPackDragNDropGenerator.h
@@ -3,6 +3,12 @@
#ifndef cmCPackDragNDropGenerator_h
#define cmCPackDragNDropGenerator_h
+#include <cmConfigure.h>
+#include <sstream>
+#include <stddef.h>
+#include <string>
+#include <vector>
+
#include "cmCPackGenerator.h"
class cmGeneratedFileStream;
diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx
index 09b9c0d..21eda79 100644
--- a/Source/CPack/cmCPackGenerator.cxx
+++ b/Source/CPack/cmCPackGenerator.cxx
@@ -2,24 +2,24 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackGenerator.h"
+#include <algorithm>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <list>
+#include <utility>
+
#include "cmCPackComponentGroup.h"
#include "cmCPackLog.h"
#include "cmCryptoHash.h"
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
-#include "cmStateTypes.h"
+#include "cmStateSnapshot.h"
#include "cmXMLSafe.h"
#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <algorithm>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
-#include <list>
-#include <utility>
-
#if defined(__HAIKU__)
#include <FindDirectory.h>
#include <StorageDefs.h>
@@ -1074,6 +1074,24 @@ bool cmCPackGenerator::IsOn(const std::string& name) const
return cmSystemTools::IsOn(GetOption(name));
}
+bool cmCPackGenerator::IsSetToOff(const std::string& op) const
+{
+ const char* ret = this->MakefileMap->GetDefinition(op);
+ if (ret && *ret) {
+ return cmSystemTools::IsOff(ret);
+ }
+ return false;
+}
+
+bool cmCPackGenerator::IsSetToEmpty(const std::string& op) const
+{
+ const char* ret = this->MakefileMap->GetDefinition(op);
+ if (ret) {
+ return !*ret;
+ }
+ return false;
+}
+
const char* cmCPackGenerator::GetOption(const std::string& op) const
{
const char* ret = this->MakefileMap->GetDefinition(op);
diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h
index f32dd70..10a5a36 100644
--- a/Source/CPack/cmCPackGenerator.h
+++ b/Source/CPack/cmCPackGenerator.h
@@ -5,14 +5,15 @@
#include <cmConfigure.h>
-#include "cmCPackComponentGroup.h"
-#include "cmSystemTools.h"
-
#include <map>
#include <sstream>
#include <string>
#include <vector>
+#include "cmCPackComponentGroup.h"
+#include "cmSystemTools.h"
+
+class cmCPackGenerator;
class cmCPackLog;
class cmInstalledFile;
class cmMakefile;
@@ -91,6 +92,8 @@ public:
std::vector<std::string> GetOptions() const;
bool IsSet(const std::string& name) const;
bool IsOn(const std::string& name) const;
+ bool IsSetToOff(const std::string& op) const;
+ bool IsSetToEmpty(const std::string& op) const;
//! Set the logger
void SetLogger(cmCPackLog* log) { this->Logger = log; }
diff --git a/Source/CPack/cmCPackGeneratorFactory.cxx b/Source/CPack/cmCPackGeneratorFactory.cxx
index 2a0e65b..b012f01 100644
--- a/Source/CPack/cmCPackGeneratorFactory.cxx
+++ b/Source/CPack/cmCPackGeneratorFactory.cxx
@@ -2,9 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackGeneratorFactory.h"
+#include <cmConfigure.h>
+#include <ostream>
+#include <utility>
+
#include "IFW/cmCPackIFWGenerator.h"
+#include "cmAlgorithms.h"
#include "cmCPack7zGenerator.h"
#include "cmCPackGenerator.h"
+#include "cmCPackLog.h"
#include "cmCPackNSISGenerator.h"
#include "cmCPackSTGZGenerator.h"
#include "cmCPackTGZGenerator.h"
@@ -36,12 +42,6 @@
#include "WiX/cmCPackWIXGenerator.h"
#endif
-#include "cmAlgorithms.h"
-#include "cmCPackLog.h"
-
-#include <ostream>
-#include <utility>
-
cmCPackGeneratorFactory::cmCPackGeneratorFactory()
{
if (cmCPackTGZGenerator::CanGenerate()) {
diff --git a/Source/CPack/cmCPackGeneratorFactory.h b/Source/CPack/cmCPackGeneratorFactory.h
index 0a98f91..4ee0bc1 100644
--- a/Source/CPack/cmCPackGeneratorFactory.h
+++ b/Source/CPack/cmCPackGeneratorFactory.h
@@ -3,7 +3,7 @@
#ifndef cmCPackGeneratorFactory_h
#define cmCPackGeneratorFactory_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
#include <map>
#include <string>
diff --git a/Source/CPack/cmCPackLog.cxx b/Source/CPack/cmCPackLog.cxx
index 317f613..7d5c192 100644
--- a/Source/CPack/cmCPackLog.cxx
+++ b/Source/CPack/cmCPackLog.cxx
@@ -2,11 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackLog.h"
+#include <cmConfigure.h>
+#include <iostream>
+
#include "cmGeneratedFileStream.h"
#include "cmSystemTools.h"
-#include <iostream>
-
cmCPackLog::cmCPackLog()
{
this->Verbose = false;
diff --git a/Source/CPack/cmCPackLog.h b/Source/CPack/cmCPackLog.h
index 9ffe5c4..419c932 100644
--- a/Source/CPack/cmCPackLog.h
+++ b/Source/CPack/cmCPackLog.h
@@ -3,7 +3,7 @@
#ifndef cmCPackLog_h
#define cmCPackLog_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
#include <ostream>
#include <string.h>
diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx
index 225c1fb..0d8dc48 100644
--- a/Source/CPack/cmCPackOSXX11Generator.cxx
+++ b/Source/CPack/cmCPackOSXX11Generator.cxx
@@ -2,16 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackOSXX11Generator.h"
+#include <sstream>
+#include <sys/stat.h>
+
+#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include "cmake.h"
-
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
-#include <sys/stat.h>
cmCPackOSXX11Generator::cmCPackOSXX11Generator()
{
diff --git a/Source/CPack/cmCPackOSXX11Generator.h b/Source/CPack/cmCPackOSXX11Generator.h
index eb1e5ff..1918e21 100644
--- a/Source/CPack/cmCPackOSXX11Generator.h
+++ b/Source/CPack/cmCPackOSXX11Generator.h
@@ -3,6 +3,9 @@
#ifndef cmCPackOSXX11Generator_h
#define cmCPackOSXX11Generator_h
+#include <cmConfigure.h>
+#include <string>
+
#include "cmCPackGenerator.h"
/** \class cmCPackOSXX11Generator
diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx
index 785ee01..70ae267 100644
--- a/Source/CPack/cmCPackPKGGenerator.cxx
+++ b/Source/CPack/cmCPackPKGGenerator.cxx
@@ -2,18 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackPKGGenerator.h"
+#include <vector>
+
#include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
-#include "cmake.h"
-
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
cmCPackPKGGenerator::cmCPackPKGGenerator()
{
diff --git a/Source/CPack/cmCPackPKGGenerator.h b/Source/CPack/cmCPackPKGGenerator.h
index bb3c1a7..1e96a62 100644
--- a/Source/CPack/cmCPackPKGGenerator.h
+++ b/Source/CPack/cmCPackPKGGenerator.h
@@ -5,10 +5,12 @@
#include <cmConfigure.h>
#include <set>
+#include <sstream>
+#include <string>
+#include "cmCPackComponentGroup.h"
#include "cmCPackGenerator.h"
-class cmCPackComponent;
class cmXMLWriter;
/** \class cmCPackPKGGenerator
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx
index 25e8a1c..8000d6e 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.cxx
+++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx
@@ -2,20 +2,20 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackPackageMakerGenerator.h"
+#include <assert.h>
+#include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+
#include "cmCPackComponentGroup.h"
#include "cmCPackLog.h"
#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
-#include "cmake.h"
-
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
-
-#include <assert.h>
static inline unsigned int getVersion(unsigned int major, unsigned int minor)
{
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.h b/Source/CPack/cmCPackPackageMakerGenerator.h
index d679bc1..d4c6744 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.h
+++ b/Source/CPack/cmCPackPackageMakerGenerator.h
@@ -3,6 +3,9 @@
#ifndef cmCPackPackageMakerGenerator_h
#define cmCPackPackageMakerGenerator_h
+#include <cmConfigure.h>
+
+#include "cmCPackGenerator.h"
#include "cmCPackPKGGenerator.h"
class cmCPackComponent;
diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx
index ff0ec79..a46e3a6 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.cxx
+++ b/Source/CPack/cmCPackProductBuildGenerator.cxx
@@ -2,17 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackProductBuildGenerator.h"
+#include <map>
+#include <sstream>
+#include <stddef.h>
+
#include "cmCPackComponentGroup.h"
#include "cmCPackLog.h"
#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include "cmake.h"
-
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
cmCPackProductBuildGenerator::cmCPackProductBuildGenerator()
{
diff --git a/Source/CPack/cmCPackProductBuildGenerator.h b/Source/CPack/cmCPackProductBuildGenerator.h
index 4145eb4..b6da470 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.h
+++ b/Source/CPack/cmCPackProductBuildGenerator.h
@@ -3,6 +3,10 @@
#ifndef cmCPackProductBuildGenerator_h
#define cmCPackProductBuildGenerator_h
+#include <cmConfigure.h>
+#include <string>
+
+#include "cmCPackGenerator.h"
#include "cmCPackPKGGenerator.h"
class cmCPackComponent;
diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx
index 9817327..8ec03c2 100644
--- a/Source/CPack/cmCPackRPMGenerator.cxx
+++ b/Source/CPack/cmCPackRPMGenerator.cxx
@@ -2,17 +2,18 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackRPMGenerator.h"
-#include "cmCPackComponentGroup.h"
-#include "cmCPackGenerator.h"
-#include "cmCPackLog.h"
-#include "cmSystemTools.h"
-
#include <algorithm>
+#include <ctype.h>
#include <map>
#include <ostream>
#include <utility>
#include <vector>
+#include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
+#include "cmCPackLog.h"
+#include "cmSystemTools.h"
+
cmCPackRPMGenerator::cmCPackRPMGenerator()
{
}
diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx
index 66ba9f6..682394e 100644
--- a/Source/CPack/cmCPackSTGZGenerator.cxx
+++ b/Source/CPack/cmCPackSTGZGenerator.cxx
@@ -2,10 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackSTGZGenerator.h"
-#include "cmCPackGenerator.h"
-#include "cmCPackLog.h"
-#include "cmSystemTools.h"
-
#include <cmsys/FStream.hxx>
#include <sstream>
#include <stdio.h>
@@ -16,6 +12,10 @@
// include sys/stat.h after sys/types.h
#include <sys/stat.h>
+#include "cmCPackGenerator.h"
+#include "cmCPackLog.h"
+#include "cmSystemTools.h"
+
cmCPackSTGZGenerator::cmCPackSTGZGenerator()
{
}
diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx
index 06472c6..af80cbf 100644
--- a/Source/CPack/cpack.cxx
+++ b/Source/CPack/cpack.cxx
@@ -2,6 +2,20 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include <cmConfigure.h>
+#include <cmsys/CommandLineArguments.hxx>
+#include <cmsys/Encoding.hxx>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <stddef.h>
+#include <string>
+#include <utility>
+#include <vector>
+
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/ConsoleBuf.hxx>
+#endif
+
#include "cmCPackGenerator.h"
#include "cmCPackGeneratorFactory.h"
#include "cmCPackLog.h"
@@ -10,24 +24,11 @@
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmState.h"
-#include "cmStateTypes.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <cmsys/CommandLineArguments.hxx>
-#include <cmsys/Encoding.hxx>
-#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
-#include <cmsys/ConsoleBuf.hxx>
-#endif
-#include <iostream>
-#include <map>
-#include <sstream>
-#include <stddef.h>
-#include <string>
-#include <utility>
-#include <vector>
-
static const char* cmDocumentationName[][2] = {
{ CM_NULLPTR, " cpack - Packaging driver provided by CMake." },
{ CM_NULLPTR, CM_NULLPTR }
@@ -90,7 +91,9 @@ int main(int argc, char const* const* argv)
#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
// Replace streambuf so we can output Unicode to console
cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+ consoleOut.SetUTF8Pipes();
cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
+ consoleErr.SetUTF8Pipes();
#endif
cmsys::Encoding::CommandLineArguments args =
cmsys::Encoding::CommandLineArguments::Main(argc, argv);
diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx
index 7b4d994..a455908 100644
--- a/Source/CTest/cmCTestBuildHandler.cxx
+++ b/Source/CTest/cmCTestBuildHandler.cxx
@@ -7,6 +7,7 @@
#include "cmFileTimeComparison.h"
#include "cmGeneratedFileStream.h"
#include "cmMakefile.h"
+#include "cmProcessOutput.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
@@ -765,7 +766,7 @@ void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers(
int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
const char* dir, int timeout,
- std::ostream& ofs)
+ std::ostream& ofs, Encoding encoding)
{
// First generate the command and arguments
std::vector<std::string> args = cmSystemTools::ParseArguments(command);
@@ -809,6 +810,8 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
char* data;
int length;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
cmCTestOptionalLog(
this->CTest, HANDLER_PROGRESS_OUTPUT, " Each symbol represents "
<< tick_len << " bytes of output." << std::endl
@@ -842,13 +845,25 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
// Process the chunk of data
if (res == cmsysProcess_Pipe_STDERR) {
- this->ProcessBuffer(data, length, tick, tick_len, ofs,
+ processOutput.DecodeText(data, length, strdata, 1);
+ this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
&this->BuildProcessingErrorQueue);
} else {
- this->ProcessBuffer(data, length, tick, tick_len, ofs,
+ processOutput.DecodeText(data, length, strdata, 2);
+ this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
&this->BuildProcessingQueue);
}
}
+ processOutput.DecodeText(std::string(), strdata, 1);
+ if (!strdata.empty()) {
+ this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
+ &this->BuildProcessingErrorQueue);
+ }
+ processOutput.DecodeText(std::string(), strdata, 2);
+ if (!strdata.empty()) {
+ this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
+ &this->BuildProcessingQueue);
+ }
this->ProcessBuffer(CM_NULLPTR, 0, tick, tick_len, ofs,
&this->BuildProcessingQueue);
@@ -920,7 +935,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
//######################################################################
//######################################################################
-void cmCTestBuildHandler::ProcessBuffer(const char* data, int length,
+void cmCTestBuildHandler::ProcessBuffer(const char* data, size_t length,
size_t& tick, size_t tick_len,
std::ostream& ofs,
t_BuildProcessingQueueType* queue)
diff --git a/Source/CTest/cmCTestBuildHandler.h b/Source/CTest/cmCTestBuildHandler.h
index 5bd1157..a2f6112 100644
--- a/Source/CTest/cmCTestBuildHandler.h
+++ b/Source/CTest/cmCTestBuildHandler.h
@@ -7,6 +7,7 @@
#include "cmCTestGenericHandler.h"
+#include <cmProcessOutput.h>
#include <cmsys/RegularExpression.hxx>
#include <deque>
#include <iosfwd>
@@ -25,6 +26,7 @@ class cmCTestBuildHandler : public cmCTestGenericHandler
{
public:
typedef cmCTestGenericHandler Superclass;
+ typedef cmProcessOutput::Encoding Encoding;
/*
* The main entry point for this class
@@ -49,7 +51,8 @@ private:
//! Run command specialized for make and configure. Returns process status
// and retVal is return value or exception.
int RunMakeCommand(const char* command, int* retVal, const char* dir,
- int timeout, std::ostream& ofs);
+ int timeout, std::ostream& ofs,
+ Encoding encoding = cmProcessOutput::Auto);
enum
{
@@ -107,7 +110,7 @@ private:
typedef std::deque<char> t_BuildProcessingQueueType;
- void ProcessBuffer(const char* data, int length, size_t& tick,
+ void ProcessBuffer(const char* data, size_t length, size_t& tick,
size_t tick_len, std::ostream& ofs,
t_BuildProcessingQueueType* queue);
int ProcessSingleLine(const char* data);
diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx
index 1bc1851..d30f6b3 100644
--- a/Source/CTest/cmCTestGIT.cxx
+++ b/Source/CTest/cmCTestGIT.cxx
@@ -2,12 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestGIT.h"
-#include "cmAlgorithms.h"
-#include "cmCTest.h"
-#include "cmCTestVC.h"
-#include "cmProcessTools.h"
-#include "cmSystemTools.h"
-
#include <cmsys/FStream.hxx>
#include <cmsys/Process.h>
#include <ctype.h>
@@ -16,6 +10,13 @@
#include <time.h>
#include <vector>
+#include "cmAlgorithms.h"
+#include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessOutput.h"
+#include "cmProcessTools.h"
+#include "cmSystemTools.h"
+
static unsigned int cmCTestGITVersion(unsigned int epic, unsigned int major,
unsigned int minor, unsigned int fix)
{
@@ -91,7 +92,8 @@ std::string cmCTestGIT::FindGitDir()
std::string git_dir_line;
OneLineParser rev_parse_out(this, "rev-parse-out> ", git_dir_line);
OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
- if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err)) {
+ if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, CM_NULLPTR,
+ cmProcessOutput::UTF8)) {
git_dir = git_dir_line;
}
if (git_dir.empty()) {
@@ -114,7 +116,8 @@ std::string cmCTestGIT::FindGitDir()
0 };
OneLineParser cygpath_out(this, "cygpath-out> ", git_dir_line);
OutputLogger cygpath_err(this->Log, "cygpath-err> ");
- if (this->RunChild(cygpath, &cygpath_out, &cygpath_err)) {
+ if (this->RunChild(cygpath, &cygpath_out, &cygpath_err, CM_NULLPTR,
+ cmProcessOutput::UTF8)) {
git_dir = git_dir_line;
}
}
@@ -134,7 +137,8 @@ std::string cmCTestGIT::FindTopDir()
std::string cdup;
OneLineParser rev_parse_out(this, "rev-parse-out> ", cdup);
OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
- if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err) &&
+ if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, CM_NULLPTR,
+ cmProcessOutput::UTF8) &&
!cdup.empty()) {
top_dir += "/";
top_dir += cdup;
@@ -624,7 +628,7 @@ void cmCTestGIT::LoadRevisions()
CommitParser out(this, "dt-out> ");
OutputLogger err(this->Log, "dt-err> ");
- this->RunProcess(cp, &out, &err);
+ this->RunProcess(cp, &out, &err, cmProcessOutput::UTF8);
// Send one extra zero-byte to terminate the last record.
out.Process("", 1);
@@ -641,14 +645,16 @@ void cmCTestGIT::LoadModifications()
CM_NULLPTR };
OutputLogger ui_out(this->Log, "ui-out> ");
OutputLogger ui_err(this->Log, "ui-err> ");
- this->RunChild(git_update_index, &ui_out, &ui_err);
+ this->RunChild(git_update_index, &ui_out, &ui_err, CM_NULLPTR,
+ cmProcessOutput::UTF8);
// Use 'git diff-index' to get modified files.
const char* git_diff_index[] = { git, "diff-index", "-z",
"HEAD", "--", CM_NULLPTR };
DiffParser out(this, "di-out> ");
OutputLogger err(this->Log, "di-err> ");
- this->RunChild(git_diff_index, &out, &err);
+ this->RunChild(git_diff_index, &out, &err, CM_NULLPTR,
+ cmProcessOutput::UTF8);
for (std::vector<Change>::const_iterator ci = out.Changes.begin();
ci != out.Changes.end(); ++ci) {
diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx
index c093cc6..7638f45 100644
--- a/Source/CTest/cmCTestGenericHandler.cxx
+++ b/Source/CTest/cmCTestGenericHandler.cxx
@@ -2,12 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestGenericHandler.h"
-#include "cmCTest.h"
-#include "cmSystemTools.h"
-
+#include <cmConfigure.h>
#include <sstream>
#include <utility>
+#include "cmCTest.h"
+#include "cmSystemTools.h"
+
cmCTestGenericHandler::cmCTestGenericHandler()
{
this->HandlerVerbose = cmSystemTools::OUTPUT_NONE;
diff --git a/Source/CTest/cmCTestGenericHandler.h b/Source/CTest/cmCTestGenericHandler.h
index 4176eb2..2ebbe70 100644
--- a/Source/CTest/cmCTestGenericHandler.h
+++ b/Source/CTest/cmCTestGenericHandler.h
@@ -3,16 +3,16 @@
#ifndef cmCTestGenericHandler_h
#define cmCTestGenericHandler_h
-#include <cmConfigure.h>
-
-#include "cmCTest.h"
-#include "cmSystemTools.h"
+#include <cmConfigure.h> // IWYU pragma: keep
#include <map>
#include <stddef.h>
#include <string>
#include <vector>
+#include "cmCTest.h"
+#include "cmSystemTools.h"
+
class cmCTestCommand;
class cmGeneratedFileStream;
class cmMakefile;
diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx
index 2e5b56a..a989b12 100644
--- a/Source/CTest/cmCTestHandlerCommand.cxx
+++ b/Source/CTest/cmCTestHandlerCommand.cxx
@@ -226,6 +226,7 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
this->Makefile->AddDefinition(this->Values[ct_RETURN_VALUE],
str.str().c_str());
}
+ this->ProcessAdditionalValues(handler);
// log the error message if there was an error
if (capureCMakeError) {
const char* returnString = "0";
@@ -246,6 +247,10 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
return true;
}
+void cmCTestHandlerCommand::ProcessAdditionalValues(cmCTestGenericHandler*)
+{
+}
+
bool cmCTestHandlerCommand::CheckArgumentKeyword(std::string const& arg)
{
// Look for non-value arguments common to all commands.
diff --git a/Source/CTest/cmCTestHandlerCommand.h b/Source/CTest/cmCTestHandlerCommand.h
index 92748af..c86841f 100644
--- a/Source/CTest/cmCTestHandlerCommand.h
+++ b/Source/CTest/cmCTestHandlerCommand.h
@@ -45,6 +45,8 @@ public:
protected:
virtual cmCTestGenericHandler* InitializeHandler() = 0;
+ virtual void ProcessAdditionalValues(cmCTestGenericHandler* handler);
+
// Command argument handling.
virtual bool CheckArgumentKeyword(std::string const& arg);
virtual bool CheckArgumentValue(std::string const& arg);
diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx
index 224681a..03e0319 100644
--- a/Source/CTest/cmCTestLaunch.cxx
+++ b/Source/CTest/cmCTestLaunch.cxx
@@ -4,23 +4,24 @@
#include <cmConfigure.h>
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmStateTypes.h"
-#include "cmSystemTools.h"
-#include "cmXMLWriter.h"
-#include "cmake.h"
-
-#include <cm_auto_ptr.hxx>
#include <cmsys/FStream.hxx>
-#include <cmsys/MD5.h>
#include <cmsys/Process.h>
#include <cmsys/RegularExpression.hxx>
#include <iostream>
#include <stdlib.h>
#include <string.h>
+#include "cmCryptoHash.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmProcessOutput.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
#ifdef _WIN32
#include <fcntl.h> // for _O_BINARY
#include <io.h> // for _setmode
@@ -167,17 +168,14 @@ void cmCTestLaunch::ComputeFileNames()
// We hash the input command working dir and command line to obtain
// a repeatable and (probably) unique name for log files.
- char hash[32];
- cmsysMD5* md5 = cmsysMD5_New();
- cmsysMD5_Initialize(md5);
- cmsysMD5_Append(md5, (unsigned char const*)(this->CWD.c_str()), -1);
+ cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+ md5.Initialize();
+ md5.Append(this->CWD);
for (std::vector<std::string>::const_iterator ai = this->RealArgs.begin();
ai != this->RealArgs.end(); ++ai) {
- cmsysMD5_Append(md5, (unsigned char const*)ai->c_str(), -1);
+ md5.Append(*ai);
}
- cmsysMD5_FinalizeHex(md5, hash);
- cmsysMD5_Delete(md5);
- this->LogHash.assign(hash, 32);
+ this->LogHash = md5.FinalizeHex();
// We store stdout and stderr in temporary log files.
this->LogOut = this->LogDir;
@@ -228,17 +226,31 @@ void cmCTestLaunch::RunChild()
if (!this->Passthru) {
char* data = CM_NULLPTR;
int length = 0;
+ cmProcessOutput processOutput;
+ std::string strdata;
while (int p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
if (p == cmsysProcess_Pipe_STDOUT) {
- fout.write(data, length);
- std::cout.write(data, length);
+ processOutput.DecodeText(data, length, strdata, 1);
+ fout.write(strdata.c_str(), strdata.size());
+ std::cout.write(strdata.c_str(), strdata.size());
this->HaveOut = true;
} else if (p == cmsysProcess_Pipe_STDERR) {
- ferr.write(data, length);
- std::cerr.write(data, length);
+ processOutput.DecodeText(data, length, strdata, 2);
+ ferr.write(strdata.c_str(), strdata.size());
+ std::cerr.write(strdata.c_str(), strdata.size());
this->HaveErr = true;
}
}
+ processOutput.DecodeText(std::string(), strdata, 1);
+ if (!strdata.empty()) {
+ fout.write(strdata.c_str(), strdata.size());
+ std::cout.write(strdata.c_str(), strdata.size());
+ }
+ processOutput.DecodeText(std::string(), strdata, 2);
+ if (!strdata.empty()) {
+ ferr.write(strdata.c_str(), strdata.size());
+ std::cerr.write(strdata.c_str(), strdata.size());
+ }
}
// Wait for the real command to finish.
diff --git a/Source/CTest/cmCTestMemCheckCommand.cxx b/Source/CTest/cmCTestMemCheckCommand.cxx
index 05d0a53..fd7c3a9 100644
--- a/Source/CTest/cmCTestMemCheckCommand.cxx
+++ b/Source/CTest/cmCTestMemCheckCommand.cxx
@@ -2,8 +2,20 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestMemCheckCommand.h"
+#include <sstream>
+#include <vector>
+
#include "cmCTest.h"
#include "cmCTestGenericHandler.h"
+#include "cmCTestMemCheckHandler.h"
+#include "cmMakefile.h"
+
+cmCTestMemCheckCommand::cmCTestMemCheckCommand()
+{
+ this->Arguments[ctm_DEFECT_COUNT] = "DEFECT_COUNT";
+ this->Arguments[ctm_LAST] = CM_NULLPTR;
+ this->Last = ctm_LAST;
+}
cmCTestGenericHandler* cmCTestMemCheckCommand::InitializeActualHandler()
{
@@ -28,3 +40,14 @@ cmCTestGenericHandler* cmCTestMemCheckCommand::InitializeActualHandler()
handler->SetQuiet(this->Quiet);
return handler;
}
+
+void cmCTestMemCheckCommand::ProcessAdditionalValues(
+ cmCTestGenericHandler* handler)
+{
+ if (this->Values[ctm_DEFECT_COUNT] && *this->Values[ctm_DEFECT_COUNT]) {
+ std::ostringstream str;
+ str << static_cast<cmCTestMemCheckHandler*>(handler)->GetDefectCount();
+ this->Makefile->AddDefinition(this->Values[ctm_DEFECT_COUNT],
+ str.str().c_str());
+ }
+}
diff --git a/Source/CTest/cmCTestMemCheckCommand.h b/Source/CTest/cmCTestMemCheckCommand.h
index 30d9e2b..458ebb0 100644
--- a/Source/CTest/cmCTestMemCheckCommand.h
+++ b/Source/CTest/cmCTestMemCheckCommand.h
@@ -20,7 +20,7 @@ class cmCommand;
class cmCTestMemCheckCommand : public cmCTestTestCommand
{
public:
- cmCTestMemCheckCommand() {}
+ cmCTestMemCheckCommand();
/**
* This is a virtual constructor for the command.
@@ -40,6 +40,14 @@ public:
protected:
cmCTestGenericHandler* InitializeActualHandler() CM_OVERRIDE;
+
+ void ProcessAdditionalValues(cmCTestGenericHandler* handler) CM_OVERRIDE;
+
+ enum
+ {
+ ctm_DEFECT_COUNT = ctt_LAST,
+ ctm_LAST
+ };
};
#endif
diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx
index 0052a16..2c31f60 100644
--- a/Source/CTest/cmCTestMemCheckHandler.cxx
+++ b/Source/CTest/cmCTestMemCheckHandler.cxx
@@ -127,6 +127,7 @@ void cmCTestMemCheckHandler::Initialize()
this->MemoryTesterOptions.clear();
this->MemoryTesterStyle = UNKNOWN;
this->MemoryTesterOutputFile = "";
+ this->DefectCount = 0;
}
int cmCTestMemCheckHandler::PreProcessHandler()
@@ -279,6 +280,11 @@ void cmCTestMemCheckHandler::PopulateCustomVectors(cmMakefile* mf)
this->Quiet);
}
+int cmCTestMemCheckHandler::GetDefectCount()
+{
+ return this->DefectCount;
+}
+
void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
{
if (!this->CTest->GetProduceXML()) {
@@ -323,10 +329,8 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
}
xml.EndElement(); // TestList
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
- "-- Processing memory checking output: ", this->Quiet);
+ "-- Processing memory checking output:\n", this->Quiet);
size_t total = this->TestResults.size();
- size_t step = total / 10;
- size_t current = 0;
for (cc = 0; cc < this->TestResults.size(); cc++) {
cmCTestTestResult* result = &this->TestResults[cc];
std::string memcheckstr;
@@ -341,20 +345,31 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
static_cast<size_t>(this->CustomMaximumFailedTestOutputSize));
this->WriteTestResultHeader(xml, result);
xml.StartElement("Results");
+ int memoryErrors = 0;
for (std::vector<int>::size_type kk = 0; kk < memcheckresults.size();
++kk) {
if (memcheckresults[kk]) {
xml.StartElement("Defect");
xml.Attribute("type", this->ResultStringsLong[kk]);
xml.Content(memcheckresults[kk]);
+ memoryErrors += memcheckresults[kk];
xml.EndElement(); // Defect
}
this->GlobalResults[kk] += memcheckresults[kk];
}
xml.EndElement(); // Results
-
+ if (memoryErrors > 0) {
+ const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
+ std::string outname = result->Name + " ";
+ outname.resize(maxTestNameWidth + 4, '.');
+ cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, cc + 1
+ << "/" << total << " MemCheck: #"
+ << result->TestCount << ": " << outname
+ << " Defects: " << memoryErrors << std::endl,
+ this->Quiet);
+ }
xml.StartElement("Log");
- if (this->CTest->ShouldCompressMemCheckOutput()) {
+ if (this->CTest->ShouldCompressTestOutput()) {
this->CTest->CompressString(memcheckstr);
xml.Attribute("compression", "gzip");
xml.Attribute("encoding", "base64");
@@ -363,13 +378,16 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
xml.EndElement(); // Log
this->WriteTestResultFooter(xml, result);
- if (current < cc) {
- cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "#" << std::flush,
- this->Quiet);
- current += step;
- }
}
- cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
+ cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+ "MemCheck log files can be found here: "
+ "( * corresponds to test number)"
+ << std::endl,
+ this->Quiet);
+ std::string output = this->MemoryTesterOutputFile;
+ cmSystemTools::ReplaceString(output, "??", "*");
+ cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, output << std::endl,
+ this->Quiet);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
"Memory checking results:" << std::endl, this->Quiet);
xml.StartElement("DefectList");
@@ -702,6 +720,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
ostr << *i << std::endl;
}
log = ostr.str();
+ this->DefectCount += defects;
return defects == 0;
}
bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
@@ -743,6 +762,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
}
log = ostr.str();
+ this->DefectCount += defects;
return defects == 0;
}
@@ -878,6 +898,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
<< (cmSystemTools::GetTime() - sttime) << std::endl,
this->Quiet);
log = ostr.str();
+ this->DefectCount += defects;
return defects == 0;
}
@@ -923,9 +944,9 @@ bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
// only put the output of Bounds Checker if there were
// errors or leaks detected
log = parser.Log;
- return false;
}
- return true;
+ this->DefectCount += defects;
+ return defects == 0;
}
// PostProcessTest memcheck results
diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h
index b12da28..5faace0 100644
--- a/Source/CTest/cmCTestMemCheckHandler.h
+++ b/Source/CTest/cmCTestMemCheckHandler.h
@@ -30,6 +30,8 @@ public:
void Initialize() CM_OVERRIDE;
+ int GetDefectCount();
+
protected:
int PreProcessHandler() CM_OVERRIDE;
int PostProcessHandler() CM_OVERRIDE;
@@ -105,6 +107,7 @@ private:
std::vector<std::string> ResultStringsLong;
std::vector<int> GlobalResults;
bool LogWithPID; // does log file add pid
+ int DefectCount;
std::vector<int>::size_type FindOrAddWarning(const std::string& warning);
// initialize the ResultStrings and ResultStringsLong for
diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx
index b30f6eb..fbc94cc 100644
--- a/Source/CTest/cmCTestRunTest.cxx
+++ b/Source/CTest/cmCTestRunTest.cxx
@@ -153,7 +153,7 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
if ((!this->TestHandler->MemCheck &&
this->CTest->ShouldCompressTestOutput()) ||
(this->TestHandler->MemCheck &&
- this->CTest->ShouldCompressMemCheckOutput())) {
+ this->CTest->ShouldCompressTestOutput())) {
this->CompressOutput();
}
diff --git a/Source/CTest/cmCTestRunTest.h b/Source/CTest/cmCTestRunTest.h
index a10e271..ee4630a 100644
--- a/Source/CTest/cmCTestRunTest.h
+++ b/Source/CTest/cmCTestRunTest.h
@@ -5,11 +5,13 @@
#include <cmConfigure.h> // IWYU pragma: keep
-#include <cmCTestTestHandler.h>
+#include <set>
#include <stddef.h>
#include <string>
#include <vector>
+#include "cmCTestTestHandler.h"
+
class cmCTest;
class cmProcess;
diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx
index 7ee0f75..b537242 100644
--- a/Source/CTest/cmCTestScriptHandler.cxx
+++ b/Source/CTest/cmCTestScriptHandler.cxx
@@ -2,6 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestScriptHandler.h"
+#include <cmsys/Directory.hxx>
+#include <cmsys/Process.h>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
+
#include "cmCTest.h"
#include "cmCTestBuildCommand.h"
#include "cmCTestCommand.h"
@@ -22,19 +31,11 @@
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmState.h"
-#include "cmStateTypes.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmake.h"
-#include <cmsys/Directory.hxx>
-#include <cmsys/Process.h>
-#include <map>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <utility>
-
#ifdef _WIN32
#include <windows.h>
#else
diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx
index d21471d..0f13c1e 100644
--- a/Source/CTest/cmCTestSubmitHandler.cxx
+++ b/Source/CTest/cmCTestSubmitHandler.cxx
@@ -2,25 +2,26 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestSubmitHandler.h"
+#include <cm_curl.h>
+#include <cm_jsoncpp_reader.h>
+#include <cm_jsoncpp_value.h>
+#include <cmsys/Process.h>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+
#include "cmCTest.h"
#include "cmCTestCurl.h"
#include "cmCTestScriptHandler.h"
#include "cmCurl.h"
#include "cmGeneratedFileStream.h"
+#include "cmProcessOutput.h"
#include "cmState.h"
-#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cmThirdParty.h"
#include "cmXMLParser.h"
#include "cmake.h"
-#include <cm_curl.h>
-#include <cm_jsoncpp_reader.h>
-#include <cm_jsoncpp_value.h>
-#include <cmsys/Process.h>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-
#if defined(CTEST_USE_XMLRPC)
#include "cmVersion.h"
#include <cm_xmlrpc.h>
@@ -46,7 +47,6 @@ public:
};
StatusType Status;
- std::string CDashVersion;
std::string Filename;
std::string MD5;
std::string Message;
@@ -63,12 +63,10 @@ private:
return val;
}
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& /*name*/,
+ const char** /*atts*/) CM_OVERRIDE
{
this->CurrentValue.clear();
- if (name == "cdash") {
- this->CDashVersion = this->FindAttribute(atts, "version");
- }
}
void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
@@ -470,20 +468,6 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
// Now run off and do what you've been told!
res = ::curl_easy_perform(curl);
- if (cmSystemTools::IsOn(this->GetOption("InternalTest")) &&
- cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
- this->CTest->GetCDashVersion().c_str(),
- "1.7")) {
- // mock failure output for internal test case
- std::string mock_output =
- "<cdash version=\"1.7.0\">\n"
- " <status>ERROR</status>\n"
- " <message>Checksum failed for file.</message>\n"
- "</cdash>\n";
- chunk.clear();
- chunk.assign(mock_output.begin(), mock_output.end());
- }
-
if (!chunk.empty()) {
cmCTestOptionalLog(this->CTest, DEBUG, "CURL output: ["
<< cmCTestLogWrite(&*chunk.begin(), chunk.size())
@@ -801,10 +785,20 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
cmsysProcess_Execute(cp);
char* data;
int length;
+ cmProcessOutput processOutput;
+ std::string strdata;
while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+ processOutput.DecodeText(data, length, strdata);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- cmCTestLogWrite(data, length), this->Quiet);
+ cmCTestLogWrite(strdata.c_str(), strdata.size()),
+ this->Quiet);
+ }
+ processOutput.DecodeText(std::string(), strdata);
+ if (!strdata.empty()) {
+ cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+ cmCTestLogWrite(strdata.c_str(), strdata.size()),
+ this->Quiet);
}
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
@@ -926,7 +920,7 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
return false;
}
size_t fileSize = static_cast<size_t>(st.st_size);
- FILE* fp = cmsys::SystemTools::Fopen(local_file.c_str(), "rb");
+ FILE* fp = cmsys::SystemTools::Fopen(local_file, "rb");
if (!fp) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
" Cannot open file: " << local_file << std::endl);
diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx
index 132d049..ab43dbc 100644
--- a/Source/CTest/cmCTestTestHandler.cxx
+++ b/Source/CTest/cmCTestTestHandler.cxx
@@ -2,21 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestTestHandler.h"
-#include "cmCTest.h"
-#include "cmCTestBatchTestHandler.h"
-#include "cmCTestMultiProcessHandler.h"
-#include "cmCommand.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmState.h"
-#include "cmStateTypes.h"
-#include "cmSystemTools.h"
-#include "cmXMLWriter.h"
-#include "cm_auto_ptr.hxx"
-#include "cm_utf8.h"
-#include "cmake.h"
-
#include <algorithm>
#include <cmsys/Base64.h>
#include <cmsys/Directory.hxx>
@@ -32,6 +17,21 @@
#include <string.h>
#include <time.h>
+#include "cmCTest.h"
+#include "cmCTestBatchTestHandler.h"
+#include "cmCTestMultiProcessHandler.h"
+#include "cmCommand.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
+#include "cm_utf8.h"
+#include "cmake.h"
+
class cmExecutionStatus;
class cmCTestSubdirCommand : public cmCommand
diff --git a/Source/CTest/cmCTestUploadCommand.cxx b/Source/CTest/cmCTestUploadCommand.cxx
index 9266bce..717117a 100644
--- a/Source/CTest/cmCTestUploadCommand.cxx
+++ b/Source/CTest/cmCTestUploadCommand.cxx
@@ -2,6 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestUploadCommand.h"
+#include <sstream>
+#include <vector>
+
#include "cmCTest.h"
#include "cmCTestGenericHandler.h"
#include "cmCTestUploadHandler.h"
@@ -9,8 +12,6 @@
#include "cmSystemTools.h"
#include "cmake.h"
-#include <sstream>
-
cmCTestGenericHandler* cmCTestUploadCommand::InitializeHandler()
{
cmCTestGenericHandler* handler =
diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx
index 7a2fa69..444c43d 100644
--- a/Source/CTest/cmCTestVC.cxx
+++ b/Source/CTest/cmCTestVC.cxx
@@ -76,7 +76,8 @@ bool cmCTestVC::InitialCheckout(const char* command)
}
bool cmCTestVC::RunChild(char const* const* cmd, OutputParser* out,
- OutputParser* err, const char* workDir)
+ OutputParser* err, const char* workDir,
+ Encoding encoding)
{
this->Log << this->ComputeCommandLine(cmd) << "\n";
@@ -84,7 +85,7 @@ bool cmCTestVC::RunChild(char const* const* cmd, OutputParser* out,
cmsysProcess_SetCommand(cp, cmd);
workDir = workDir ? workDir : this->SourceDirectory.c_str();
cmsysProcess_SetWorkingDirectory(cp, workDir);
- this->RunProcess(cp, out, err);
+ this->RunProcess(cp, out, err, encoding);
int result = cmsysProcess_GetExitValue(cp);
cmsysProcess_Delete(cp);
return result == 0;
@@ -102,7 +103,7 @@ std::string cmCTestVC::ComputeCommandLine(char const* const* cmd)
}
bool cmCTestVC::RunUpdateCommand(char const* const* cmd, OutputParser* out,
- OutputParser* err)
+ OutputParser* err, Encoding encoding)
{
// Report the command line.
this->UpdateCommandLine = this->ComputeCommandLine(cmd);
@@ -112,7 +113,7 @@ bool cmCTestVC::RunUpdateCommand(char const* const* cmd, OutputParser* out,
}
// Run the command.
- return this->RunChild(cmd, out, err);
+ return this->RunChild(cmd, out, err, CM_NULLPTR, encoding);
}
std::string cmCTestVC::GetNightlyTime()
diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h
index 4f2bba0..2681ba0 100644
--- a/Source/CTest/cmCTestVC.h
+++ b/Source/CTest/cmCTestVC.h
@@ -5,11 +5,12 @@
#include <cmConfigure.h>
-#include "cmProcessTools.h"
-
#include <iosfwd>
#include <string>
+#include "cmProcessOutput.h"
+#include "cmProcessTools.h"
+
class cmCTest;
class cmXMLWriter;
@@ -116,11 +117,13 @@ protected:
/** Run a command line and send output to given parsers. */
bool RunChild(char const* const* cmd, OutputParser* out, OutputParser* err,
- const char* workDir = CM_NULLPTR);
+ const char* workDir = CM_NULLPTR,
+ Encoding encoding = cmProcessOutput::Auto);
/** Run VC update command line and send output to given parsers. */
bool RunUpdateCommand(char const* const* cmd, OutputParser* out,
- OutputParser* err = CM_NULLPTR);
+ OutputParser* err = CM_NULLPTR,
+ Encoding encoding = cmProcessOutput::Auto);
/** Write xml element for one file. */
void WriteXMLEntry(cmXMLWriter& xml, std::string const& path,
diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx
index a24fe21..32ffa6b 100644
--- a/Source/CTest/cmProcess.cxx
+++ b/Source/CTest/cmProcess.cxx
@@ -3,6 +3,7 @@
#include "cmProcess.h"
#include <cmConfigure.h>
+#include <cmProcessOutput.h>
#include <cmSystemTools.h>
#include <iostream>
@@ -104,6 +105,8 @@ bool cmProcess::Buffer::GetLast(std::string& line)
int cmProcess::GetNextOutputLine(std::string& line, double timeout)
{
+ cmProcessOutput processOutput(cmProcessOutput::UTF8);
+ std::string strdata;
for (;;) {
// Look for lines already buffered.
if (this->Output.GetLine(line)) {
@@ -118,12 +121,17 @@ int cmProcess::GetNextOutputLine(std::string& line, double timeout)
return cmsysProcess_Pipe_Timeout;
}
if (p == cmsysProcess_Pipe_STDOUT) {
- this->Output.insert(this->Output.end(), data, data + length);
+ processOutput.DecodeText(data, length, strdata);
+ this->Output.insert(this->Output.end(), strdata.begin(), strdata.end());
} else { // p == cmsysProcess_Pipe_None
// The process will provide no more data.
break;
}
}
+ processOutput.DecodeText(std::string(), strdata);
+ if (!strdata.empty()) {
+ this->Output.insert(this->Output.end(), strdata.begin(), strdata.end());
+ }
// Look for partial last lines.
if (this->Output.GetLast(line)) {
diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx
index ebd35f3..4b5b4b1 100644
--- a/Source/CursesDialog/cmCursesMainForm.cxx
+++ b/Source/CursesDialog/cmCursesMainForm.cxx
@@ -347,61 +347,56 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
cw = reinterpret_cast<cmCursesWidget*>(field_userptr(currentField));
}
- if (cw) {
- cw->PrintKeys();
- }
-
- // {
- // }
- // else
- // {
- char firstLine[512] = "";
- char secondLine[512] = "";
- char thirdLine[512] = "";
- if (process) {
- const char* clearLine =
- " ";
- strcpy(firstLine, clearLine);
- strcpy(secondLine, clearLine);
- strcpy(thirdLine, clearLine);
- } else {
- if (this->OkToGenerate) {
- sprintf(firstLine,
- "Press [c] to configure Press [g] to generate and exit");
+ char fmt_s[] = "%s";
+ if (cw == CM_NULLPTR || !cw->PrintKeys()) {
+ char firstLine[512] = "";
+ char secondLine[512] = "";
+ char thirdLine[512] = "";
+ if (process) {
+ const char* clearLine =
+ " ";
+ strcpy(firstLine, clearLine);
+ strcpy(secondLine, clearLine);
+ strcpy(thirdLine, clearLine);
} else {
- sprintf(firstLine,
- "Press [c] to configure ");
- }
- {
- const char* toggleKeyInstruction =
- "Press [t] to toggle advanced mode (Currently %s)";
- sprintf(thirdLine, toggleKeyInstruction,
- this->AdvancedMode ? "On" : "Off");
+ if (this->OkToGenerate) {
+ sprintf(firstLine,
+ "Press [c] to configure Press [g] to generate and exit");
+ } else {
+ sprintf(firstLine,
+ "Press [c] to configure ");
+ }
+ {
+ const char* toggleKeyInstruction =
+ "Press [t] to toggle advanced mode (Currently %s)";
+ sprintf(thirdLine, toggleKeyInstruction,
+ this->AdvancedMode ? "On" : "Off");
+ }
+ sprintf(secondLine, "Press [h] for help "
+ "Press [q] to quit without generating");
}
- sprintf(secondLine, "Press [h] for help "
- "Press [q] to quit without generating");
- }
- curses_move(y - 4, 0);
- char fmt_s[] = "%s";
- char fmt[512] = "Press [enter] to edit option Press [d] to delete an entry";
- if (process) {
- strcpy(fmt, " ");
+ curses_move(y - 4, 0);
+ char fmt[512] =
+ "Press [enter] to edit option Press [d] to delete an entry";
+ if (process) {
+ strcpy(fmt, " ");
+ }
+ printw(fmt_s, fmt);
+ curses_move(y - 3, 0);
+ printw(fmt_s, firstLine);
+ curses_move(y - 2, 0);
+ printw(fmt_s, secondLine);
+ curses_move(y - 1, 0);
+ printw(fmt_s, thirdLine);
}
- printw(fmt_s, fmt);
- curses_move(y - 3, 0);
- printw(fmt_s, firstLine);
- curses_move(y - 2, 0);
- printw(fmt_s, secondLine);
- curses_move(y - 1, 0);
- printw(fmt_s, thirdLine);
if (cw) {
- sprintf(firstLine, "Page %d of %d", cw->GetPage(), this->NumberOfPages);
- curses_move(0, 65 - static_cast<unsigned int>(strlen(firstLine)) - 1);
- printw(fmt_s, firstLine);
+ char pageLine[512] = "";
+ sprintf(pageLine, "Page %d of %d", cw->GetPage(), this->NumberOfPages);
+ curses_move(0, 65 - static_cast<unsigned int>(strlen(pageLine)) - 1);
+ printw(fmt_s, pageLine);
}
- // }
pos_form_cursor(this->Form);
}
diff --git a/Source/CursesDialog/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx
index eabc642..ff189f0 100644
--- a/Source/CursesDialog/cmCursesStringWidget.cxx
+++ b/Source/CursesDialog/cmCursesStringWidget.cxx
@@ -202,7 +202,9 @@ bool cmCursesStringWidget::PrintKeys()
printw(fmt_s, firstLine);
curses_move(y - 3, 0);
- printw(fmt_s, "Editing option, press [enter] to leave edit.");
+ printw(fmt_s, "Editing option, press [enter] to confirm");
+ curses_move(y - 2, 0);
+ printw(fmt_s, " press [esc] to cancel");
return true;
}
return false;
diff --git a/Source/Modules/FindLibRHash.cmake b/Source/Modules/FindLibRHash.cmake
new file mode 100644
index 0000000..86c6189
--- /dev/null
+++ b/Source/Modules/FindLibRHash.cmake
@@ -0,0 +1,73 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindLibRHash
+------------
+
+Find LibRHash include directory and library.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+An :ref:`imported target <Imported targets>` named
+``LibRHash::LibRHash`` is provided if LibRHash has been found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module defines the following variables:
+
+``LibRHash_FOUND``
+ True if LibRHash was found, false otherwise.
+``LibRHash_INCLUDE_DIRS``
+ Include directories needed to include LibRHash headers.
+``LibRHash_LIBRARIES``
+ Libraries needed to link to LibRHash.
+
+Cache Variables
+^^^^^^^^^^^^^^^
+
+This module uses the following cache variables:
+
+``LibRHash_LIBRARY``
+ The location of the LibRHash library file.
+``LibRHash_INCLUDE_DIR``
+ The location of the LibRHash include directory containing ``rhash.h``.
+
+The cache variables should not be used by project code.
+They may be set by end users to point at LibRHash components.
+#]=======================================================================]
+
+#-----------------------------------------------------------------------------
+find_library(LibRHash_LIBRARY
+ NAMES rhash
+ )
+mark_as_advanced(LibRHash_LIBRARY)
+
+find_path(LibRHash_INCLUDE_DIR
+ NAMES rhash.h
+ )
+mark_as_advanced(LibRHash_INCLUDE_DIR)
+
+#-----------------------------------------------------------------------------
+include(${CMAKE_CURRENT_LIST_DIR}/../../Modules/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibRHash
+ FOUND_VAR LibRHash_FOUND
+ REQUIRED_VARS LibRHash_LIBRARY LibRHash_INCLUDE_DIR
+ )
+set(LIBRHASH_FOUND ${LibRHash_FOUND})
+
+#-----------------------------------------------------------------------------
+# Provide documented result variables and targets.
+if(LibRHash_FOUND)
+ set(LibRHash_INCLUDE_DIRS ${LibRHash_INCLUDE_DIR})
+ set(LibRHash_LIBRARIES ${LibRHash_LIBRARY})
+ if(NOT TARGET LibRHash::LibRHash)
+ add_library(LibRHash::LibRHash UNKNOWN IMPORTED)
+ set_target_properties(LibRHash::LibRHash PROPERTIES
+ IMPORTED_LOCATION "${LibRHash_LIBRARY}"
+ INTERFACE_INCLUDE_DIRECTORIES "${LibRHash_INCLUDE_DIRS}"
+ )
+ endif()
+endif()
diff --git a/Source/QtDialog/CMakeSetup.cxx b/Source/QtDialog/CMakeSetup.cxx
index fad8075..5e03c39 100644
--- a/Source/QtDialog/CMakeSetup.cxx
+++ b/Source/QtDialog/CMakeSetup.cxx
@@ -5,6 +5,7 @@
#include "CMakeSetupDialog.h"
#include "cmAlgorithms.h"
#include "cmDocumentation.h"
+#include "cmDocumentationEntry.h"
#include "cmVersion.h"
#include "cmake.h"
#include <QApplication>
@@ -17,6 +18,7 @@
#include <cmsys/CommandLineArguments.hxx>
#include <cmsys/Encoding.hxx>
#include <cmsys/SystemTools.hxx>
+#include <iostream>
#include "cmSystemTools.h" // IWYU pragma: keep
@@ -95,10 +97,8 @@ int main(int argc, char** argv)
setlocale(LC_NUMERIC, "C");
-#if defined(CMAKE_ENCODING_UTF8)
QTextCodec* utf8_codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(utf8_codec);
-#endif
#if QT_VERSION < 0x050000
// clean out standard Qt paths for plugins, which we don't use anyway
diff --git a/Source/QtDialog/FirstConfigure.cxx b/Source/QtDialog/FirstConfigure.cxx
index c34751a..2f1df4f 100644
--- a/Source/QtDialog/FirstConfigure.cxx
+++ b/Source/QtDialog/FirstConfigure.cxx
@@ -56,7 +56,7 @@ QFrame* StartCompilerSetup::CreateToolsetWidgets()
QVBoxLayout* l = new QVBoxLayout(frame);
l->setContentsMargins(0, 0, 0, 0);
- ToolsetLabel = new QLabel(tr("Optional toolset to use (-T parameter)"));
+ ToolsetLabel = new QLabel(tr("Optional toolset to use (argument to -T)"));
l->addWidget(ToolsetLabel);
Toolset = new QLineEdit(frame);
diff --git a/Source/bindexplib.cxx b/Source/bindexplib.cxx
index db97c47..eded883 100644
--- a/Source/bindexplib.cxx
+++ b/Source/bindexplib.cxx
@@ -62,11 +62,10 @@
*----------------------------------------------------------------------
*/
#include "bindexplib.h"
+
#include <cmsys/Encoding.hxx>
#include <fstream>
#include <iostream>
-#include <stdio.h>
-#include <string>
#include <windows.h>
typedef struct cmANON_OBJECT_HEADER_BIGOBJ {
diff --git a/Source/bindexplib.h b/Source/bindexplib.h
index 1a0c3a3..d6900ba 100644
--- a/Source/bindexplib.h
+++ b/Source/bindexplib.h
@@ -5,8 +5,9 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
-
+#include <set>
+#include <stdio.h>
+#include <string>
class bindexplib
{
diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h
index aa55379..22f69fa 100644
--- a/Source/cmAlgorithms.h
+++ b/Source/cmAlgorithms.h
@@ -3,9 +3,17 @@
#ifndef cmAlgorithms_h
#define cmAlgorithms_h
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <algorithm>
+#include <cm_kwiml.h>
+#include <functional>
+#include <iterator>
+#include <sstream>
+#include <string.h>
+#include <string>
+#include <utility>
+#include <vector>
inline bool cmHasLiteralPrefixImpl(const std::string& str1, const char* str2,
size_t N)
diff --git a/Source/cmAuxSourceDirectoryCommand.cxx b/Source/cmAuxSourceDirectoryCommand.cxx
index 04e1a0b..ecff0c3 100644
--- a/Source/cmAuxSourceDirectoryCommand.cxx
+++ b/Source/cmAuxSourceDirectoryCommand.cxx
@@ -44,7 +44,7 @@ bool cmAuxSourceDirectoryCommand::InitialPass(
// Load all the files in the directory
cmsys::Directory dir;
- if (dir.Load(tdir.c_str())) {
+ if (dir.Load(tdir)) {
size_t numfiles = dir.GetNumberOfFiles();
for (size_t i = 0; i < numfiles; ++i) {
std::string file = dir.GetFile(static_cast<unsigned long>(i));
diff --git a/Source/cmBuildCommand.cxx b/Source/cmBuildCommand.cxx
index d03b8c4..6836151 100644
--- a/Source/cmBuildCommand.cxx
+++ b/Source/cmBuildCommand.cxx
@@ -90,8 +90,7 @@ bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
std::string makecommand =
this->Makefile->GetGlobalGenerator()->GenerateCMakeBuildCommand(
- target, configuration.c_str(), "",
- this->Makefile->IgnoreErrorsCMP0061());
+ target, configuration, "", this->Makefile->IgnoreErrorsCMP0061());
this->Makefile->AddDefinition(variable, makecommand.c_str());
diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx
index 655c42a..942688c 100644
--- a/Source/cmCMakeMinimumRequired.cxx
+++ b/Source/cmCMakeMinimumRequired.cxx
@@ -2,9 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCMakeMinimumRequired.h"
+#include <sstream>
+#include <stdio.h>
+
#include "cmMakefile.h"
#include "cmSystemTools.h"
#include "cmVersion.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
// cmCMakeMinimumRequired
bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h
index 3acedd2..08a5c38 100644
--- a/Source/cmCMakeMinimumRequired.h
+++ b/Source/cmCMakeMinimumRequired.h
@@ -3,8 +3,14 @@
#ifndef cmCMakeMinimumRequired_h
#define cmCMakeMinimumRequired_h
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
#include "cmCommand.h"
+class cmExecutionStatus;
+
/** \class cmCMakeMinimumRequired
* \brief cmake_minimum_required command
*
diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx
index b70074e..d1f8446 100644
--- a/Source/cmCPluginAPI.cxx
+++ b/Source/cmCPluginAPI.cxx
@@ -408,7 +408,7 @@ char CCONV* cmExpandVariablesInString(void* arg, const char* source,
std::string result = mf->ExpandVariablesInString(
barf, (escapeQuotes ? true : false), (atOnly ? true : false));
char* res = static_cast<char*>(malloc(result.size() + 1));
- if (result.size()) {
+ if (!result.empty()) {
strcpy(res, result.c_str());
}
res[result.size()] = '\0';
@@ -570,7 +570,7 @@ void* CCONV cmAddSource(void* arg, void* arg2)
rsf->GetProperties() = osf->Properties;
for (std::vector<std::string>::iterator i = osf->Depends.begin();
i != osf->Depends.end(); ++i) {
- rsf->AddDepend(i->c_str());
+ rsf->AddDepend(*i);
}
// Create the proxy for the real source file.
@@ -676,7 +676,7 @@ void CCONV cmSourceFileSetName(void* arg, const char* name, const char* dir,
std::string hname = pathname;
if (cmSystemTools::FileExists(hname.c_str())) {
sf->SourceName = cmSystemTools::GetFilenamePath(name);
- if (sf->SourceName.size() > 0) {
+ if (!sf->SourceName.empty()) {
sf->SourceName += "/";
}
sf->SourceName += cmSystemTools::GetFilenameWithoutLastExtension(name);
@@ -756,7 +756,7 @@ void CCONV cmSourceFileSetName2(void* arg, const char* name, const char* dir,
fname += ".";
fname += ext;
}
- sf->FullPath = cmSystemTools::CollapseFullPath(fname.c_str(), dir);
+ sf->FullPath = cmSystemTools::CollapseFullPath(fname, dir);
cmSystemTools::ConvertToUnixSlashes(sf->FullPath);
sf->SourceExtension = ext;
}
diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx
index 024260c..1527b30 100644
--- a/Source/cmCTest.cxx
+++ b/Source/cmCTest.cxx
@@ -2,6 +2,27 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTest.h"
+#include <cm_curl.h>
+#include <cm_zlib.h>
+#include <cmsys/Base64.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/Process.h>
+#include <cmsys/String.hxx>
+#include <cmsys/SystemInformation.hxx>
+#include <ctype.h>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include <time.h>
+#include <utility>
+#include <vector>
+
#include "cmAlgorithms.h"
#include "cmCTestBuildAndTestHandler.h"
#include "cmCTestBuildHandler.h"
@@ -20,36 +41,17 @@
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
+#include "cmProcessOutput.h"
#include "cmState.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmVersion.h"
#include "cmVersionConfig.h"
#include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <cm_auto_ptr.hxx>
-#include <cm_curl.h>
-#include <cm_zlib.h>
-#include <cmsys/Base64.h>
-#include <cmsys/Directory.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/Process.h>
-#include <cmsys/String.hxx>
-#include <cmsys/SystemInformation.hxx>
-#include <ctype.h>
-#include <iostream>
-#include <map>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <string>
-#include <time.h>
-#include <utility>
-#include <vector>
-
#if defined(__BEOS__) || defined(__HAIKU__)
#include <be/kernel/OS.h> /* disable_debugger() API. */
#endif
@@ -270,7 +272,6 @@ cmCTest::cmCTest()
this->UseHTTP10 = false;
this->PrintLabels = false;
this->CompressTestOutput = true;
- this->CompressMemCheckOutput = true;
this->TestModel = cmCTest::EXPERIMENTAL;
this->MaxTestNameWidth = 30;
this->InteractiveDebugMode = true;
@@ -288,8 +289,6 @@ cmCTest::cmCTest()
this->DartVersion = 1;
this->DropSiteCDash = false;
this->OutputTestOutputOnTestFailure = false;
- this->ComputedCompressTestOutput = false;
- this->ComputedCompressMemCheckOutput = false;
this->RepeatTests = 1; // default to run each test once
this->RepeatUntilFail = false;
std::string outOnFail;
@@ -357,53 +356,9 @@ void cmCTest::SetTestLoad(unsigned long load)
bool cmCTest::ShouldCompressTestOutput()
{
- if (!this->ComputedCompressTestOutput) {
- std::string cdashVersion = this->GetCDashVersion();
- // version >= 1.6?
- bool cdashSupportsGzip = cmSystemTools::VersionCompare(
- cmSystemTools::OP_GREATER_EQUAL, cdashVersion.c_str(), "1.6");
- this->CompressTestOutput &= cdashSupportsGzip;
- this->ComputedCompressTestOutput = true;
- }
return this->CompressTestOutput;
}
-bool cmCTest::ShouldCompressMemCheckOutput()
-{
- if (!this->ComputedCompressMemCheckOutput) {
- std::string cdashVersion = this->GetCDashVersion();
-
- bool compressionSupported = cmSystemTools::VersionCompare(
- cmSystemTools::OP_GREATER, cdashVersion.c_str(), "1.9.0");
- this->CompressMemCheckOutput &= compressionSupported;
- this->ComputedCompressMemCheckOutput = true;
- }
- return this->CompressMemCheckOutput;
-}
-
-std::string cmCTest::GetCDashVersion()
-{
-#ifdef CMAKE_BUILD_WITH_CMAKE
- // First query the server. If that fails, fall back to the local setting
- std::string response;
- std::string url = "http://";
- url += this->GetCTestConfiguration("DropSite");
-
- std::string cdashUri = this->GetCTestConfiguration("DropLocation");
- cdashUri = cdashUri.substr(0, cdashUri.find("/submit.php"));
-
- int res = 1;
- if (!cdashUri.empty()) {
- url += cdashUri + "/api/getversion.php";
- res = cmCTest::HTTPRequest(url, cmCTest::HTTP_GET, response, "", "", 3);
- }
-
- return res ? this->GetCTestConfiguration("CDashVersion") : response;
-#else
- return this->GetCTestConfiguration("CDashVersion");
-#endif
-}
-
cmCTest::Part cmCTest::GetPartFromName(const char* name)
{
// Look up by lower-case to make names case-insensitive.
@@ -1006,7 +961,7 @@ int cmCTest::GetTestModelFromString(const char* str)
int cmCTest::RunMakeCommand(const char* command, std::string& output,
int* retVal, const char* dir, int timeout,
- std::ostream& ofs)
+ std::ostream& ofs, Encoding encoding)
{
// First generate the command and arguments
std::vector<std::string> args = cmSystemTools::ParseArguments(command);
@@ -1045,16 +1000,19 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
char* data;
int length;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Each . represents "
<< tick_len << " bytes of output" << std::endl
<< " " << std::flush);
while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
- for (int cc = 0; cc < length; ++cc) {
- if (data[cc] == 0) {
- data[cc] = '\n';
+ processOutput.DecodeText(data, length, strdata);
+ for (size_t cc = 0; cc < strdata.size(); ++cc) {
+ if (strdata[cc] == 0) {
+ strdata[cc] = '\n';
}
}
- output.append(data, length);
+ output.append(strdata);
while (output.size() > (tick * tick_len)) {
tick++;
cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
@@ -1065,9 +1023,19 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
<< " " << std::flush);
}
}
- cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, cmCTestLogWrite(data, length));
+ cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+ cmCTestLogWrite(strdata.c_str(), strdata.size()));
if (ofs) {
- ofs << cmCTestLogWrite(data, length);
+ ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
+ }
+ }
+ processOutput.DecodeText(std::string(), strdata);
+ if (!strdata.empty()) {
+ output.append(strdata);
+ cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+ cmCTestLogWrite(strdata.c_str(), strdata.size()));
+ if (ofs) {
+ ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
}
}
cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Size of output: "
@@ -1107,7 +1075,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
int* retVal, std::ostream* log, double testTimeOut,
- std::vector<std::string>* environment)
+ std::vector<std::string>* environment, Encoding encoding)
{
bool modifyEnv = (environment && !environment->empty());
@@ -1202,17 +1170,30 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
char* data;
int length;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+ processOutput.DecodeText(data, length, strdata);
if (output) {
tempOutput.insert(tempOutput.end(), data, data + length);
}
- cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, cmCTestLogWrite(data, length));
+ cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+ cmCTestLogWrite(strdata.c_str(), strdata.size()));
+ if (log) {
+ log->write(strdata.c_str(), strdata.size());
+ }
+ }
+ processOutput.DecodeText(std::string(), strdata);
+ if (!strdata.empty()) {
+ cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+ cmCTestLogWrite(strdata.c_str(), strdata.size()));
if (log) {
- log->write(data, length);
+ log->write(strdata.c_str(), strdata.size());
}
}
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ processOutput.DecodeText(tempOutput, tempOutput);
if (output && tempOutput.begin() != tempOutput.end()) {
output->append(&*tempOutput.begin(), tempOutput.size());
}
@@ -1745,7 +1726,6 @@ bool cmCTest::HandleCommandLineArguments(size_t& i,
if (this->CheckArgument(arg, "--no-compress-output")) {
this->CompressTestOutput = false;
- this->CompressMemCheckOutput = false;
}
if (this->CheckArgument(arg, "--print-labels")) {
@@ -2543,7 +2523,7 @@ bool cmCTest::SetCTestConfigurationFromCMakeVariable(
bool cmCTest::RunCommand(const char* command, std::string* stdOut,
std::string* stdErr, int* retVal, const char* dir,
- double timeout)
+ double timeout, Encoding encoding)
{
std::vector<std::string> args = cmSystemTools::ParseArguments(command);
@@ -2574,6 +2554,8 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
std::vector<char> tempError;
char* data;
int length;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
int res;
bool done = false;
while (!done) {
@@ -2590,15 +2572,24 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
}
if ((res == cmsysProcess_Pipe_STDOUT || res == cmsysProcess_Pipe_STDERR) &&
this->ExtraVerbose) {
- cmSystemTools::Stdout(data, length);
+ processOutput.DecodeText(data, length, strdata);
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+ }
+ }
+ if (this->ExtraVerbose) {
+ processOutput.DecodeText(std::string(), strdata);
+ if (!strdata.empty()) {
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
}
}
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
if (!tempOutput.empty()) {
+ processOutput.DecodeText(tempOutput, tempOutput);
stdOut->append(&*tempOutput.begin(), tempOutput.size());
}
if (!tempError.empty()) {
+ processOutput.DecodeText(tempError, tempError);
stdErr->append(&*tempError.begin(), tempError.size());
}
diff --git a/Source/cmCTest.h b/Source/cmCTest.h
index 8d3f8fb..8db2e5f 100644
--- a/Source/cmCTest.h
+++ b/Source/cmCTest.h
@@ -5,6 +5,7 @@
#include <cmConfigure.h>
+#include <cmProcessOutput.h>
#include <cmsys/String.hxx>
#include <map>
#include <set>
@@ -13,6 +14,7 @@
#include <time.h>
#include <vector>
+class cmCTest;
class cmCTestGenericHandler;
class cmCTestStartCommand;
class cmGeneratedFileStream;
@@ -48,6 +50,7 @@ class cmCTest
friend class cmCTestMultiProcessHandler;
public:
+ typedef cmProcessOutput::Encoding Encoding;
/** Enumerate parts of the testing and submission process. */
enum Part
{
@@ -232,11 +235,8 @@ public:
bool ShouldPrintLabels() { return this->PrintLabels; }
bool ShouldCompressTestOutput();
- bool ShouldCompressMemCheckOutput();
bool CompressString(std::string& str);
- std::string GetCDashVersion();
-
std::string GetStopTime() { return this->StopTime; }
void SetStopTime(std::string const& time);
@@ -270,7 +270,8 @@ public:
*/
bool RunCommand(const char* command, std::string* stdOut,
std::string* stdErr, int* retVal = CM_NULLPTR,
- const char* dir = CM_NULLPTR, double timeout = 0.0);
+ const char* dir = CM_NULLPTR, double timeout = 0.0,
+ Encoding encoding = cmProcessOutput::Auto);
/**
* Clean/make safe for xml the given value such that it may be used as
@@ -289,7 +290,8 @@ public:
* and retVal is return value or exception.
*/
int RunMakeCommand(const char* command, std::string& output, int* retVal,
- const char* dir, int timeout, std::ostream& ofs);
+ const char* dir, int timeout, std::ostream& ofs,
+ Encoding encoding = cmProcessOutput::Auto);
/** Return the current tag */
std::string GetCurrentTag();
@@ -336,7 +338,8 @@ public:
*/
int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
std::ostream* logfile, double testTimeOut,
- std::vector<std::string>* environment);
+ std::vector<std::string>* environment,
+ Encoding encoding = cmProcessOutput::Auto);
/**
* Execute handler and return its result. If the handler fails, it returns
@@ -487,10 +490,6 @@ private:
bool RunConfigurationScript;
- // flag for lazy getter (optimization)
- bool ComputedCompressTestOutput;
- bool ComputedCompressMemCheckOutput;
-
int GenerateNotesFile(const char* files);
void DetermineNextDayStop();
@@ -547,7 +546,6 @@ private:
bool CompressXMLFiles;
bool CompressTestOutput;
- bool CompressMemCheckOutput;
void InitStreams();
std::ostream* StreamOut;
diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx
index e84012c..cb0ba63 100644
--- a/Source/cmCacheManager.cxx
+++ b/Source/cmCacheManager.cxx
@@ -2,11 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCacheManager.h"
-#include "cmGeneratedFileStream.h"
-#include "cmSystemTools.h"
-#include "cmVersion.h"
-#include "cmake.h"
-
#include <algorithm>
#include <cmsys/FStream.hxx>
#include <cmsys/Glob.hxx>
@@ -14,6 +9,12 @@
#include <stdio.h>
#include <string.h>
+#include "cmGeneratedFileStream.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmVersion.h"
+#include "cmake.h"
+
cmCacheManager::cmCacheManager()
{
this->CacheMajorVersion = 0;
diff --git a/Source/cmCacheManager.h b/Source/cmCacheManager.h
index 90731f5..e82c9ef 100644
--- a/Source/cmCacheManager.h
+++ b/Source/cmCacheManager.h
@@ -5,9 +5,6 @@
#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmPropertyMap.h"
-#include "cmState.h"
-
#include <iosfwd>
#include <map>
#include <set>
@@ -15,6 +12,9 @@
#include <utility>
#include <vector>
+#include "cmPropertyMap.h"
+#include "cmStateTypes.h"
+
class cmake;
/** \class cmCacheManager
diff --git a/Source/cmCallVisualStudioMacro.cxx b/Source/cmCallVisualStudioMacro.cxx
index a21a7d2..99fe587 100644
--- a/Source/cmCallVisualStudioMacro.cxx
+++ b/Source/cmCallVisualStudioMacro.cxx
@@ -2,6 +2,8 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCallVisualStudioMacro.h"
+#include <sstream>
+
#include "cmSystemTools.h"
#if defined(_MSC_VER)
diff --git a/Source/cmCallVisualStudioMacro.h b/Source/cmCallVisualStudioMacro.h
index 7ff4513..e9d34e5 100644
--- a/Source/cmCallVisualStudioMacro.h
+++ b/Source/cmCallVisualStudioMacro.h
@@ -5,7 +5,7 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <string>
/** \class cmCallVisualStudioMacro
* \brief Control class for communicating with CMake's Visual Studio macros
diff --git a/Source/cmCommandArgumentsHelper.h b/Source/cmCommandArgumentsHelper.h
index 50af2e2..b19b0f9 100644
--- a/Source/cmCommandArgumentsHelper.h
+++ b/Source/cmCommandArgumentsHelper.h
@@ -5,10 +5,12 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <set>
+#include <string>
+#include <vector>
-class cmCommandArgumentsHelper;
class cmCommandArgumentGroup;
+class cmCommandArgumentsHelper;
/* cmCommandArgumentsHelper, cmCommandArgumentGroup and cmCommandArgument (i.e.
its derived classes cmCAXXX can be used to simplify the processing of
diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx
index 103e72c..4c5b093 100644
--- a/Source/cmCommands.cxx
+++ b/Source/cmCommands.cxx
@@ -18,14 +18,8 @@
#include "cmContinueCommand.h"
#include "cmCreateTestSourceList.h"
#include "cmDefinePropertyCommand.h"
-#include "cmElseCommand.h"
#include "cmEnableLanguageCommand.h"
#include "cmEnableTestingCommand.h"
-#include "cmEndForEachCommand.h"
-#include "cmEndFunctionCommand.h"
-#include "cmEndIfCommand.h"
-#include "cmEndMacroCommand.h"
-#include "cmEndWhileCommand.h"
#include "cmExecProgramCommand.h"
#include "cmExecuteProcessCommand.h"
#include "cmFileCommand.h"
@@ -74,6 +68,7 @@
#include "cmTargetLinkLibrariesCommand.h"
#include "cmTryCompileCommand.h"
#include "cmTryRunCommand.h"
+#include "cmUnexpectedCommand.h"
#include "cmUnsetCommand.h"
#include "cmWhileCommand.h"
@@ -82,7 +77,6 @@
#include "cmAuxSourceDirectoryCommand.h"
#include "cmBuildNameCommand.h"
#include "cmCMakeHostSystemInformationCommand.h"
-#include "cmElseIfCommand.h"
#include "cmExportCommand.h"
#include "cmExportLibraryDependenciesCommand.h"
#include "cmFLTKWrapUICommand.h"
@@ -130,14 +124,8 @@ std::vector<cmCommand*> GetPredefinedCommands()
commands.push_back(new cmContinueCommand);
commands.push_back(new cmCreateTestSourceList);
commands.push_back(new cmDefinePropertyCommand);
- commands.push_back(new cmElseCommand);
commands.push_back(new cmEnableLanguageCommand);
commands.push_back(new cmEnableTestingCommand);
- commands.push_back(new cmEndForEachCommand);
- commands.push_back(new cmEndFunctionCommand);
- commands.push_back(new cmEndIfCommand);
- commands.push_back(new cmEndMacroCommand);
- commands.push_back(new cmEndWhileCommand);
commands.push_back(new cmExecProgramCommand);
commands.push_back(new cmExecuteProcessCommand);
commands.push_back(new cmFileCommand);
@@ -189,12 +177,39 @@ std::vector<cmCommand*> GetPredefinedCommands()
commands.push_back(new cmUnsetCommand);
commands.push_back(new cmWhileCommand);
+ commands.push_back(new cmUnexpectedCommand(
+ "else", "An ELSE command was found outside of a proper "
+ "IF ENDIF structure. Or its arguments did not match "
+ "the opening IF command."));
+ commands.push_back(new cmUnexpectedCommand(
+ "elseif", "An ELSEIF command was found outside of a proper "
+ "IF ENDIF structure."));
+ commands.push_back(new cmUnexpectedCommand(
+ "endforeach", "An ENDFOREACH command was found outside of a proper "
+ "FOREACH ENDFOREACH structure. Or its arguments did "
+ "not match the opening FOREACH command."));
+ commands.push_back(new cmUnexpectedCommand(
+ "endfunction", "An ENDFUNCTION command was found outside of a proper "
+ "FUNCTION ENDFUNCTION structure. Or its arguments did not "
+ "match the opening FUNCTION command."));
+ commands.push_back(new cmUnexpectedCommand(
+ "endif", "An ENDIF command was found outside of a proper "
+ "IF ENDIF structure. Or its arguments did not match "
+ "the opening IF command."));
+ commands.push_back(new cmUnexpectedCommand(
+ "endmacro", "An ENDMACRO command was found outside of a proper "
+ "MACRO ENDMACRO structure. Or its arguments did not "
+ "match the opening MACRO command."));
+ commands.push_back(new cmUnexpectedCommand(
+ "endwhile", "An ENDWHILE command was found outside of a proper "
+ "WHILE ENDWHILE structure. Or its arguments did not "
+ "match the opening WHILE command."));
+
#if defined(CMAKE_BUILD_WITH_CMAKE)
commands.push_back(new cmAddCompileOptionsCommand);
commands.push_back(new cmAuxSourceDirectoryCommand);
commands.push_back(new cmBuildNameCommand);
commands.push_back(new cmCMakeHostSystemInformationCommand);
- commands.push_back(new cmElseIfCommand);
commands.push_back(new cmExportCommand);
commands.push_back(new cmExportLibraryDependenciesCommand);
commands.push_back(new cmFLTKWrapUICommand);
diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx
index 95b95c1..c3a925f 100644
--- a/Source/cmCommonTargetGenerator.cxx
+++ b/Source/cmCommonTargetGenerator.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCommonTargetGenerator.h"
-#include <algorithm>
#include <cmConfigure.h>
#include <set>
#include <sstream>
@@ -16,8 +15,8 @@
#include "cmLocalCommonGenerator.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
+#include "cmOutputConverter.h"
#include "cmSourceFile.h"
-#include "cmStateDirectory.h"
#include "cmStateTypes.h"
cmCommonTargetGenerator::cmCommonTargetGenerator(cmGeneratorTarget* gt)
diff --git a/Source/cmCommonTargetGenerator.h b/Source/cmCommonTargetGenerator.h
index fe27038..bdd6645 100644
--- a/Source/cmCommonTargetGenerator.h
+++ b/Source/cmCommonTargetGenerator.h
@@ -4,19 +4,16 @@
#define cmCommonTargetGenerator_h
#include <cmConfigure.h> // IWYU pragma: keep
-
-#include "cmOutputConverter.h"
-
#include <map>
#include <string>
#include <vector>
class cmGeneratorTarget;
class cmGlobalCommonGenerator;
+class cmLinkLineComputer;
class cmLocalCommonGenerator;
class cmMakefile;
class cmSourceFile;
-class cmLinkLineComputer;
/** \class cmCommonTargetGenerator
* \brief Common infrastructure for Makefile and Ninja per-target generators
diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx
index 28aa533..80e7e7d 100644
--- a/Source/cmComputeLinkInformation.cxx
+++ b/Source/cmComputeLinkInformation.cxx
@@ -606,6 +606,12 @@ void cmComputeLinkInformation::AddItem(std::string const& item,
// of COMPATIBLE_INTERFACE_ enforcement. The generators will ignore
// this for the actual link line.
this->Items.push_back(Item(std::string(), false, tgt));
+
+ // Also add the item the interface specifies to be used in its place.
+ std::string const& libName = tgt->GetImportedLibName(config);
+ if (!libName.empty()) {
+ this->AddItem(libName, CM_NULLPTR);
+ }
} else {
// Decide whether to use an import library.
bool implib =
diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h
index 1d29c26..3d26ea7 100644
--- a/Source/cmComputeLinkInformation.h
+++ b/Source/cmComputeLinkInformation.h
@@ -70,6 +70,7 @@ public:
std::string const& GetRPathLinkFlag() const { return this->RPathLinkFlag; }
std::string GetRPathLinkString();
+ std::string GetConfig() const { return this->Config; }
private:
void AddItem(std::string const& item, const cmGeneratorTarget* tgt);
void AddSharedDepItem(std::string const& item, cmGeneratorTarget const* tgt);
diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx
index 71d6c4e..f2eb601 100644
--- a/Source/cmConditionEvaluator.cxx
+++ b/Source/cmConditionEvaluator.cxx
@@ -2,12 +2,22 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmConditionEvaluator.h"
+#include <algorithm>
+#include <cmConfigure.h>
+#include <cmsys/RegularExpression.hxx>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#include "cmAlgorithms.h"
#include "cmMakefile.h"
-#include "cmOutputConverter.h"
#include "cmState.h"
#include "cmSystemTools.h"
+class cmCommand;
+class cmTest;
+
static std::string const keyAND = "AND";
static std::string const keyCOMMAND = "COMMAND";
static std::string const keyDEFINED = "DEFINED";
diff --git a/Source/cmConditionEvaluator.h b/Source/cmConditionEvaluator.h
index 3c9d2cd..5815177 100644
--- a/Source/cmConditionEvaluator.h
+++ b/Source/cmConditionEvaluator.h
@@ -3,12 +3,18 @@
#ifndef cmConditionEvaluator_h
#define cmConditionEvaluator_h
-#include "cmCommand.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <list>
+#include <string>
+#include <vector>
+
#include "cmExpandedCommandArgument.h"
#include "cmListFileCache.h"
+#include "cmPolicies.h"
#include "cmake.h"
-#include <list>
+class cmMakefile;
class cmConditionEvaluator
{
diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in
index 057c6c0..26f1df2 100644
--- a/Source/cmConfigure.cmake.h.in
+++ b/Source/cmConfigure.cmake.h.in
@@ -20,7 +20,6 @@
#cmakedefine CMAKE_USE_ELF_PARSER
#cmakedefine CMAKE_USE_MACH_PARSER
#cmakedefine CMAKE_USE_LIBUV
-#cmakedefine CMAKE_ENCODING_UTF8
#cmakedefine CMake_HAVE_CXX_AUTO_PTR
#cmakedefine CMake_HAVE_CXX_MAKE_UNIQUE
#cmakedefine CMake_HAVE_CXX_NULLPTR
diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx
index a1de074..fbad778 100644
--- a/Source/cmCoreTryCompile.cxx
+++ b/Source/cmCoreTryCompile.cxx
@@ -2,16 +2,24 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCoreTryCompile.h"
+#include <cmConfigure.h>
+#include <cmsys/Directory.hxx>
+#include <set>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+
#include "cmAlgorithms.h"
#include "cmExportTryCompileFileGenerator.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmOutputConverter.h"
+#include "cmPolicies.h"
#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmVersion.h"
#include "cmake.h"
-#include <cmsys/Directory.hxx>
-
-#include <assert.h>
static std::string const kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN =
"CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN";
@@ -36,11 +44,12 @@ static std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
"CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
static std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
"CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
+static std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
bool isTryRun)
{
- this->BinaryDirectory = argv[1].c_str();
+ this->BinaryDirectory = argv[1];
this->OutputFile = "";
// which signature were we called with ?
this->SrcFileSignature = true;
@@ -149,13 +158,13 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
}
}
} else if (doing == DoingOutputVariable) {
- outputVariable = argv[i].c_str();
+ outputVariable = argv[i];
doing = DoingNone;
} else if (doing == DoingCopyFile) {
- copyFile = argv[i].c_str();
+ copyFile = argv[i];
doing = DoingNone;
} else if (doing == DoingCopyFileError) {
- copyFileError = argv[i].c_str();
+ copyFileError = argv[i];
doing = DoingNone;
} else if (doing == DoingSources) {
sources.push_back(argv[i]);
@@ -163,7 +172,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
this->SrcFileSignature = false;
projectName = argv[i].c_str();
} else if (i == 4 && !this->SrcFileSignature) {
- targetName = argv[i].c_str();
+ targetName = argv[i];
} else {
std::ostringstream m;
m << "try_compile given unknown argument \"" << argv[i] << "\".";
@@ -445,6 +454,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
vars.insert(kCMAKE_OSX_SYSROOT);
vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
vars.insert(kCMAKE_SYSROOT);
+ vars.insert(kCMAKE_WARN_DEPRECATED);
if (const char* varListStr = this->Makefile->GetDefinition(
kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
diff --git a/Source/cmCoreTryCompile.h b/Source/cmCoreTryCompile.h
index 0d9bb79..1c94f09 100644
--- a/Source/cmCoreTryCompile.h
+++ b/Source/cmCoreTryCompile.h
@@ -3,6 +3,11 @@
#ifndef cmCoreTryCompile_h
#define cmCoreTryCompile_h
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
#include "cmCommand.h"
#include "cmStateTypes.h"
diff --git a/Source/cmCreateTestSourceList.cxx b/Source/cmCreateTestSourceList.cxx
index 14a6c88..69532e6 100644
--- a/Source/cmCreateTestSourceList.cxx
+++ b/Source/cmCreateTestSourceList.cxx
@@ -2,10 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCreateTestSourceList.h"
+#include <algorithm>
+
#include "cmMakefile.h"
#include "cmSourceFile.h"
#include "cmSystemTools.h"
+class cmExecutionStatus;
+
// cmCreateTestSourceList
bool cmCreateTestSourceList::InitialPass(std::vector<std::string> const& args,
cmExecutionStatus&)
diff --git a/Source/cmCreateTestSourceList.h b/Source/cmCreateTestSourceList.h
index 2f71a00..5e003cf 100644
--- a/Source/cmCreateTestSourceList.h
+++ b/Source/cmCreateTestSourceList.h
@@ -3,8 +3,15 @@
#ifndef cmCreateTestSourceList_h
#define cmCreateTestSourceList_h
+#include <cmConfigure.h>
+
+#include <string>
+#include <vector>
+
#include "cmCommand.h"
+class cmExecutionStatus;
+
/** \class cmCreateTestSourceList
* \brief Test driver generation command
*
diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx
index 9b3f84a..d5807b1 100644
--- a/Source/cmCryptoHash.cxx
+++ b/Source/cmCryptoHash.cxx
@@ -2,31 +2,78 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCryptoHash.h"
-#include "cm_sha2.h"
-
+#include <cm_kwiml.h>
+#include <cm_rhash.h>
#include <cmsys/FStream.hxx>
-#include <cmsys/MD5.h>
#include <string.h>
+static unsigned int const cmCryptoHashAlgoToId[] = {
+ /* clang-format needs this comment to break after the opening brace */
+ RHASH_MD5, //
+ RHASH_SHA1, //
+ RHASH_SHA224, //
+ RHASH_SHA256, //
+ RHASH_SHA384, //
+ RHASH_SHA512, //
+ RHASH_SHA3_224, //
+ RHASH_SHA3_256, //
+ RHASH_SHA3_384, //
+ RHASH_SHA3_512
+};
+
+static int cmCryptoHash_rhash_library_initialized;
+
+static rhash cmCryptoHash_rhash_init(unsigned int id)
+{
+ if (!cmCryptoHash_rhash_library_initialized) {
+ cmCryptoHash_rhash_library_initialized = 1;
+ rhash_library_init();
+ }
+ return rhash_init(id);
+}
+
+cmCryptoHash::cmCryptoHash(Algo algo)
+ : Id(cmCryptoHashAlgoToId[algo])
+ , CTX(cmCryptoHash_rhash_init(Id))
+{
+}
+
+cmCryptoHash::~cmCryptoHash()
+{
+ rhash_free(this->CTX);
+}
+
CM_AUTO_PTR<cmCryptoHash> cmCryptoHash::New(const char* algo)
{
if (strcmp(algo, "MD5") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashMD5);
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoMD5));
}
if (strcmp(algo, "SHA1") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA1);
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA1));
}
if (strcmp(algo, "SHA224") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA224);
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA224));
}
if (strcmp(algo, "SHA256") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA256);
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA256));
}
if (strcmp(algo, "SHA384") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA384);
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA384));
}
if (strcmp(algo, "SHA512") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA512);
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA512));
+ }
+ if (strcmp(algo, "SHA3_224") == 0) {
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_224));
+ }
+ if (strcmp(algo, "SHA3_256") == 0) {
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_256));
+ }
+ if (strcmp(algo, "SHA3_384") == 0) {
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_384));
+ }
+ if (strcmp(algo, "SHA3_512") == 0) {
+ return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_512));
}
return CM_AUTO_PTR<cmCryptoHash>(CM_NULLPTR);
}
@@ -80,7 +127,7 @@ std::vector<unsigned char> cmCryptoHash::ByteHashFile(const std::string& file)
this->Initialize();
{
// Should be efficient enough on most system:
- cm_sha2_uint64_t buffer[512];
+ KWIML_INT_uint64_t buffer[512];
char* buffer_c = reinterpret_cast<char*>(buffer);
unsigned char const* buffer_uc =
reinterpret_cast<unsigned char const*>(buffer);
@@ -117,51 +164,29 @@ std::string cmCryptoHash::HashFile(const std::string& file)
return ByteHashToString(this->ByteHashFile(file));
}
-cmCryptoHashMD5::cmCryptoHashMD5()
- : MD5(cmsysMD5_New())
+void cmCryptoHash::Initialize()
{
+ rhash_reset(this->CTX);
}
-cmCryptoHashMD5::~cmCryptoHashMD5()
+void cmCryptoHash::Append(void const* buf, size_t sz)
{
- cmsysMD5_Delete(this->MD5);
+ rhash_update(this->CTX, buf, sz);
}
-void cmCryptoHashMD5::Initialize()
+void cmCryptoHash::Append(std::string const& str)
{
- cmsysMD5_Initialize(this->MD5);
+ this->Append(str.c_str(), str.size());
}
-void cmCryptoHashMD5::Append(unsigned char const* buf, int sz)
+std::vector<unsigned char> cmCryptoHash::Finalize()
{
- cmsysMD5_Append(this->MD5, buf, sz);
+ std::vector<unsigned char> hash(rhash_get_digest_size(this->Id), 0);
+ rhash_final(this->CTX, &hash[0]);
+ return hash;
}
-std::vector<unsigned char> cmCryptoHashMD5::Finalize()
+std::string cmCryptoHash::FinalizeHex()
{
- std::vector<unsigned char> hash(16, 0);
- cmsysMD5_Finalize(this->MD5, &hash[0]);
- return hash;
+ return cmCryptoHash::ByteHashToString(this->Finalize());
}
-
-#define cmCryptoHash_SHA_CLASS_IMPL(SHA) \
- cmCryptoHash##SHA::cmCryptoHash##SHA() \
- : SHA(new SHA_CTX) \
- { \
- } \
- cmCryptoHash##SHA::~cmCryptoHash##SHA() { delete this->SHA; } \
- void cmCryptoHash##SHA::Initialize() { SHA##_Init(this->SHA); } \
- void cmCryptoHash##SHA::Append(unsigned char const* buf, int sz) \
- { \
- SHA##_Update(this->SHA, buf, sz); \
- } \
- std::vector<unsigned char> cmCryptoHash##SHA::Finalize() \
- { \
- std::vector<unsigned char> hash(SHA##_DIGEST_LENGTH, 0); \
- SHA##_Final(&hash[0], this->SHA); \
- return hash; \
- }
-
-cmCryptoHash_SHA_CLASS_IMPL(SHA1) cmCryptoHash_SHA_CLASS_IMPL(SHA224)
- cmCryptoHash_SHA_CLASS_IMPL(SHA256) cmCryptoHash_SHA_CLASS_IMPL(SHA384)
- cmCryptoHash_SHA_CLASS_IMPL(SHA512)
diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h
index 5c2d3ca..0b562da 100644
--- a/Source/cmCryptoHash.h
+++ b/Source/cmCryptoHash.h
@@ -3,23 +3,41 @@
#ifndef cmCryptoHash_h
#define cmCryptoHash_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include <cm_auto_ptr.hxx>
+#include <stddef.h>
#include <string>
#include <vector>
+#include "cm_auto_ptr.hxx"
+
/**
* @brief Abstract base class for cryptographic hash generators
*/
class cmCryptoHash
{
public:
- virtual ~cmCryptoHash() {}
+ enum Algo
+ {
+ AlgoMD5,
+ AlgoSHA1,
+ AlgoSHA224,
+ AlgoSHA256,
+ AlgoSHA384,
+ AlgoSHA512,
+ AlgoSHA3_224,
+ AlgoSHA3_256,
+ AlgoSHA3_384,
+ AlgoSHA3_512
+ };
+
+ cmCryptoHash(Algo algo);
+ ~cmCryptoHash();
/// @brief Returns a new hash generator of the requested type
/// @arg algo Hash type name. Supported hash types are
- /// MD5, SHA1, SHA224, SHA256, SHA384, SHA512
+ /// MD5, SHA1, SHA224, SHA256, SHA384, SHA512,
+ /// SHA3_224, SHA3_256, SHA3_384, SHA3_512
/// @return A valid auto pointer if algo is supported or
/// an invalid/NULL pointer otherwise
static CM_AUTO_PTR<cmCryptoHash> New(const char* algo);
@@ -53,47 +71,15 @@ public:
/// An empty string otherwise.
std::string HashFile(const std::string& file);
-protected:
- virtual void Initialize() = 0;
- virtual void Append(unsigned char const*, int) = 0;
- virtual std::vector<unsigned char> Finalize() = 0;
-};
+ void Initialize();
+ void Append(void const*, size_t);
+ void Append(std::string const& str);
+ std::vector<unsigned char> Finalize();
+ std::string FinalizeHex();
-class cmCryptoHashMD5 : public cmCryptoHash
-{
- struct cmsysMD5_s* MD5;
-
-public:
- cmCryptoHashMD5();
- ~cmCryptoHashMD5() CM_OVERRIDE;
-
-protected:
- void Initialize() CM_OVERRIDE;
- void Append(unsigned char const* buf, int sz) CM_OVERRIDE;
- std::vector<unsigned char> Finalize() CM_OVERRIDE;
+private:
+ unsigned int Id;
+ struct rhash_context* CTX;
};
-#define cmCryptoHash_SHA_CLASS_DECL(SHA) \
- class cmCryptoHash##SHA : public cmCryptoHash \
- { \
- union _SHA_CTX* SHA; \
- \
- public: \
- cmCryptoHash##SHA(); \
- ~cmCryptoHash##SHA(); \
- \
- protected: \
- virtual void Initialize(); \
- virtual void Append(unsigned char const* buf, int sz); \
- virtual std::vector<unsigned char> Finalize(); \
- }
-
-cmCryptoHash_SHA_CLASS_DECL(SHA1);
-cmCryptoHash_SHA_CLASS_DECL(SHA224);
-cmCryptoHash_SHA_CLASS_DECL(SHA256);
-cmCryptoHash_SHA_CLASS_DECL(SHA384);
-cmCryptoHash_SHA_CLASS_DECL(SHA512);
-
-#undef cmCryptoHash_SHA_CLASS_DECL
-
#endif
diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx
index 2125f1b..8bd3a89 100644
--- a/Source/cmCustomCommandGenerator.cxx
+++ b/Source/cmCustomCommandGenerator.cxx
@@ -38,32 +38,44 @@ unsigned int cmCustomCommandGenerator::GetNumberOfCommands() const
return static_cast<unsigned int>(this->CC.GetCommandLines().size());
}
-bool cmCustomCommandGenerator::UseCrossCompilingEmulator(unsigned int c) const
+const char* cmCustomCommandGenerator::GetCrossCompilingEmulator(
+ unsigned int c) const
{
+ if (!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING")) {
+ return CM_NULLPTR;
+ }
std::string const& argv0 = this->CC.GetCommandLines()[c][0];
cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
- if (target && target->GetType() == cmStateEnums::EXECUTABLE) {
- return target->GetProperty("CROSSCOMPILING_EMULATOR") != CM_NULLPTR;
+ if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
+ !target->IsImported()) {
+ return target->GetProperty("CROSSCOMPILING_EMULATOR");
}
- return false;
+ return CM_NULLPTR;
}
-std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
+const char* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const
{
std::string const& argv0 = this->CC.GetCommandLines()[c][0];
cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
(target->IsImported() ||
+ target->GetProperty("CROSSCOMPILING_EMULATOR") ||
!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING"))) {
return target->GetLocation(this->Config);
}
- if (target && target->GetType() == cmStateEnums::EXECUTABLE) {
- const char* emulator = target->GetProperty("CROSSCOMPILING_EMULATOR");
- if (emulator) {
- return std::string(emulator);
- }
+ return CM_NULLPTR;
+}
+
+std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
+{
+ if (const char* emulator = this->GetCrossCompilingEmulator(c)) {
+ return std::string(emulator);
+ }
+ if (const char* location = this->GetArgv0Location(c)) {
+ return std::string(location);
}
+ std::string const& argv0 = this->CC.GetCommandLines()[c][0];
CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(argv0);
std::string exe = cge->Evaluate(this->LG, this->Config);
@@ -99,13 +111,20 @@ void cmCustomCommandGenerator::AppendArguments(unsigned int c,
std::string& cmd) const
{
unsigned int offset = 1;
- if (this->UseCrossCompilingEmulator(c)) {
+ if (this->GetCrossCompilingEmulator(c) != CM_NULLPTR) {
offset = 0;
}
cmCustomCommandLine const& commandLine = this->CC.GetCommandLines()[c];
for (unsigned int j = offset; j < commandLine.size(); ++j) {
- std::string arg =
- this->GE->Parse(commandLine[j])->Evaluate(this->LG, this->Config);
+ std::string arg;
+ if (const char* location =
+ j == 0 ? this->GetArgv0Location(c) : CM_NULLPTR) {
+ // GetCommand returned the emulator instead of the argv0 location,
+ // so transform the latter now.
+ arg = location;
+ } else {
+ arg = this->GE->Parse(commandLine[j])->Evaluate(this->LG, this->Config);
+ }
cmd += " ";
if (this->OldStyle) {
cmd += escapeForShellOldStyle(arg);
diff --git a/Source/cmCustomCommandGenerator.h b/Source/cmCustomCommandGenerator.h
index 23cc596..8983c54 100644
--- a/Source/cmCustomCommandGenerator.h
+++ b/Source/cmCustomCommandGenerator.h
@@ -23,6 +23,9 @@ class cmCustomCommandGenerator
mutable bool DependsDone;
mutable std::vector<std::string> Depends;
+ const char* GetCrossCompilingEmulator(unsigned int c) const;
+ const char* GetArgv0Location(unsigned int c) const;
+
public:
cmCustomCommandGenerator(cmCustomCommand const& cc,
const std::string& config, cmLocalGenerator* lg);
@@ -30,7 +33,6 @@ public:
cmCustomCommand const& GetCC() const { return this->CC; }
unsigned int GetNumberOfCommands() const;
std::string GetCommand(unsigned int c) const;
- bool UseCrossCompilingEmulator(unsigned int c) const;
void AppendArguments(unsigned int c, std::string& cmd) const;
const char* GetComment() const;
std::string GetWorkingDirectory() const;
diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx
index 0b459f9..47fe76a 100644
--- a/Source/cmDefinitions.cxx
+++ b/Source/cmDefinitions.cxx
@@ -3,6 +3,7 @@
#include "cmDefinitions.h"
#include <assert.h>
+#include <cmConfigure.h>
#include <set>
#include <utility>
diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h
index 8dfb9ea..ad40665 100644
--- a/Source/cmDefinitions.h
+++ b/Source/cmDefinitions.h
@@ -3,14 +3,14 @@
#ifndef cmDefinitions_h
#define cmDefinitions_h
-#include <cmConfigure.h>
-
-#include "cmLinkedTree.h"
-#include "cm_unordered_map.hxx"
+#include <cmConfigure.h> // IWYU pragma: keep
#include <string>
#include <vector>
+#include "cmLinkedTree.h"
+#include "cm_unordered_map.hxx"
+
/** \class cmDefinitions
* \brief Store a scope of variable definitions for CMake language.
*
diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx
index 84ab072..e6000db 100644
--- a/Source/cmDependsC.cxx
+++ b/Source/cmDependsC.cxx
@@ -2,16 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmDependsC.h"
+#include <cmsys/FStream.hxx>
+#include <utility>
+
#include "cmAlgorithms.h"
#include "cmFileTimeComparison.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
-#include "cmOutputConverter.h"
#include "cmSystemTools.h"
-#include <cmsys/FStream.hxx>
-#include <utility>
-
#define INCLUDE_REGEX_LINE \
"^[ \t]*#[ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx
index c8723d0..7927402 100644
--- a/Source/cmDependsFortran.cxx
+++ b/Source/cmDependsFortran.cxx
@@ -2,14 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmDependsFortran.h"
-#include "cmFortranParser.h" /* Interface to parser object. */
-#include "cmGeneratedFileStream.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
-#include "cmOutputConverter.h"
-#include "cmStateDirectory.h"
-#include "cmSystemTools.h"
-
#include <assert.h>
#include <cmsys/FStream.hxx>
#include <iostream>
@@ -18,6 +10,15 @@
#include <string.h>
#include <utility>
+#include "cmFortranParser.h" /* Interface to parser object. */
+#include "cmGeneratedFileStream.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+
// TODO: Test compiler for the case of the mod file. Some always
// use lower case and some always use upper case. I do not know if any
// use the case from the source code.
diff --git a/Source/cmDependsJavaParserHelper.h b/Source/cmDependsJavaParserHelper.h
index 1597ea7..71b939c 100644
--- a/Source/cmDependsJavaParserHelper.h
+++ b/Source/cmDependsJavaParserHelper.h
@@ -8,6 +8,8 @@
#include <string>
#include <vector>
+class cmDependsJavaParserHelper;
+
#define YYSTYPE cmDependsJavaParserHelper::ParserType
#define YYSTYPE_IS_DECLARED
#define YY_EXTRA_TYPE cmDependsJavaParserHelper*
diff --git a/Source/cmElseCommand.cxx b/Source/cmElseCommand.cxx
deleted file mode 100644
index 207777e..0000000
--- a/Source/cmElseCommand.cxx
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmElseCommand.h"
-
-class cmExecutionStatus;
-
-bool cmElseCommand::InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&)
-{
- this->SetError("An ELSE command was found outside of a proper "
- "IF ENDIF structure. Or its arguments did not match "
- "the opening IF command.");
- return false;
-}
diff --git a/Source/cmElseCommand.h b/Source/cmElseCommand.h
deleted file mode 100644
index c0162ad..0000000
--- a/Source/cmElseCommand.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmElseCommand_h
-#define cmElseCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-
-/** \class cmElseCommand
- * \brief ends an if block
- *
- * cmElseCommand ends an if block
- */
-class cmElseCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmElseCommand; }
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "else"; }
-};
-
-#endif
diff --git a/Source/cmElseIfCommand.cxx b/Source/cmElseIfCommand.cxx
deleted file mode 100644
index 1c32248..0000000
--- a/Source/cmElseIfCommand.cxx
+++ /dev/null
@@ -1,13 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmElseIfCommand.h"
-
-class cmExecutionStatus;
-
-bool cmElseIfCommand::InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&)
-{
- this->SetError("An ELSEIF command was found outside of a proper "
- "IF ENDIF structure.");
- return false;
-}
diff --git a/Source/cmElseIfCommand.h b/Source/cmElseIfCommand.h
deleted file mode 100644
index 3f1ddde..0000000
--- a/Source/cmElseIfCommand.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmElseIfCommand_h
-#define cmElseIfCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-
-/** \class cmElseIfCommand
- * \brief ends an if block
- *
- * cmElseIfCommand ends an if block
- */
-class cmElseIfCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmElseIfCommand; }
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "elseif"; }
-};
-
-#endif
diff --git a/Source/cmEndForEachCommand.cxx b/Source/cmEndForEachCommand.cxx
deleted file mode 100644
index fe6a7f3..0000000
--- a/Source/cmEndForEachCommand.cxx
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmEndForEachCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-bool cmEndForEachCommand::InvokeInitialPass(
- std::vector<cmListFileArgument> const&, cmExecutionStatus&)
-{
- this->SetError("An ENDFOREACH command was found outside of a proper "
- "FOREACH ENDFOREACH structure. Or its arguments did "
- "not match the opening FOREACH command.");
- return false;
-}
diff --git a/Source/cmEndForEachCommand.h b/Source/cmEndForEachCommand.h
deleted file mode 100644
index 772a139..0000000
--- a/Source/cmEndForEachCommand.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmEndForEachCommand_h
-#define cmEndForEachCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-/** \class cmEndForEachCommand
- * \brief ends an if block
- *
- * cmEndForEachCommand ends an if block
- */
-class cmEndForEachCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmEndForEachCommand; }
-
- /**
- * Override cmCommand::InvokeInitialPass to get arguments before
- * expansion.
- */
- bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
- cmExecutionStatus&) CM_OVERRIDE;
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
- {
- return false;
- }
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "endforeach"; }
-};
-
-#endif
diff --git a/Source/cmEndFunctionCommand.cxx b/Source/cmEndFunctionCommand.cxx
deleted file mode 100644
index 6adb42b..0000000
--- a/Source/cmEndFunctionCommand.cxx
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmEndFunctionCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-bool cmEndFunctionCommand::InvokeInitialPass(
- std::vector<cmListFileArgument> const&, cmExecutionStatus&)
-{
- this->SetError("An ENDFUNCTION command was found outside of a proper "
- "FUNCTION ENDFUNCTION structure. Or its arguments did not "
- "match the opening FUNCTION command.");
- return false;
-}
diff --git a/Source/cmEndFunctionCommand.h b/Source/cmEndFunctionCommand.h
deleted file mode 100644
index 2599637..0000000
--- a/Source/cmEndFunctionCommand.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmEndFunctionCommand_h
-#define cmEndFunctionCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-/** \class cmEndFunctionCommand
- * \brief ends an if block
- *
- * cmEndFunctionCommand ends an if block
- */
-class cmEndFunctionCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmEndFunctionCommand; }
-
- /**
- * Override cmCommand::InvokeInitialPass to get arguments before
- * expansion.
- */
- bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
- cmExecutionStatus&) CM_OVERRIDE;
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
- {
- return false;
- }
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "endfunction"; }
-};
-
-#endif
diff --git a/Source/cmEndIfCommand.cxx b/Source/cmEndIfCommand.cxx
deleted file mode 100644
index 50c2b42..0000000
--- a/Source/cmEndIfCommand.cxx
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmEndIfCommand.h"
-
-#include <stdlib.h> // required for atof
-
-#include "cmMakefile.h"
-
-class cmExecutionStatus;
-
-bool cmEndIfCommand::InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&)
-{
- const char* versionValue =
- this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
- if (!versionValue || (atof(versionValue) <= 1.4)) {
- return true;
- }
-
- this->SetError("An ENDIF command was found outside of a proper "
- "IF ENDIF structure. Or its arguments did not match "
- "the opening IF command.");
- return false;
-}
diff --git a/Source/cmEndIfCommand.h b/Source/cmEndIfCommand.h
deleted file mode 100644
index dfd6049..0000000
--- a/Source/cmEndIfCommand.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmEndIfCommand_h
-#define cmEndIfCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-
-/** \class cmEndIfCommand
- * \brief ends an if block
- *
- * cmEndIfCommand ends an if block
- */
-class cmEndIfCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmEndIfCommand; }
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "endif"; }
-};
-
-#endif
diff --git a/Source/cmEndMacroCommand.cxx b/Source/cmEndMacroCommand.cxx
deleted file mode 100644
index 046b0af..0000000
--- a/Source/cmEndMacroCommand.cxx
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmEndMacroCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-bool cmEndMacroCommand::InvokeInitialPass(
- std::vector<cmListFileArgument> const&, cmExecutionStatus&)
-{
- this->SetError("An ENDMACRO command was found outside of a proper "
- "MACRO ENDMACRO structure. Or its arguments did not "
- "match the opening MACRO command.");
- return false;
-}
diff --git a/Source/cmEndMacroCommand.h b/Source/cmEndMacroCommand.h
deleted file mode 100644
index 3c462d4..0000000
--- a/Source/cmEndMacroCommand.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmEndMacroCommand_h
-#define cmEndMacroCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-/** \class cmEndMacroCommand
- * \brief ends an if block
- *
- * cmEndMacroCommand ends an if block
- */
-class cmEndMacroCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmEndMacroCommand; }
-
- /**
- * Override cmCommand::InvokeInitialPass to get arguments before
- * expansion.
- */
- bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
- cmExecutionStatus&) CM_OVERRIDE;
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
- {
- return false;
- }
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "endmacro"; }
-};
-
-#endif
diff --git a/Source/cmEndWhileCommand.cxx b/Source/cmEndWhileCommand.cxx
deleted file mode 100644
index 5623f33..0000000
--- a/Source/cmEndWhileCommand.cxx
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmEndWhileCommand.h"
-
-#include "cmListFileCache.h"
-
-class cmExecutionStatus;
-
-bool cmEndWhileCommand::InvokeInitialPass(
- std::vector<cmListFileArgument> const& args, cmExecutionStatus&)
-{
- if (args.empty()) {
- this->SetError("An ENDWHILE command was found outside of a proper "
- "WHILE ENDWHILE structure.");
- } else {
- this->SetError("An ENDWHILE command was found outside of a proper "
- "WHILE ENDWHILE structure. Or its arguments did not "
- "match the opening WHILE command.");
- }
-
- return false;
-}
diff --git a/Source/cmEndWhileCommand.h b/Source/cmEndWhileCommand.h
deleted file mode 100644
index d4e97b4..0000000
--- a/Source/cmEndWhileCommand.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmEndWhileCommand_h
-#define cmEndWhileCommand_h
-
-#include <cmConfigure.h>
-#include <string>
-#include <vector>
-
-#include "cmCommand.h"
-
-class cmExecutionStatus;
-struct cmListFileArgument;
-
-/** \class cmEndWhileCommand
- * \brief ends a while loop
- *
- * cmEndWhileCommand ends a while loop
- */
-class cmEndWhileCommand : public cmCommand
-{
-public:
- /**
- * This is a virtual constructor for the command.
- */
- cmCommand* Clone() CM_OVERRIDE { return new cmEndWhileCommand; }
-
- /**
- * Override cmCommand::InvokeInitialPass to get arguments before
- * expansion.
- */
- bool InvokeInitialPass(std::vector<cmListFileArgument> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
-
- /**
- * This is called when the command is first encountered in
- * the CMakeLists.txt file.
- */
- bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
- {
- return false;
- }
-
- /**
- * This determines if the command is invoked when in script mode.
- */
- bool IsScriptable() const CM_OVERRIDE { return true; }
-
- /**
- * The name of the command as specified in CMakeList.txt.
- */
- std::string GetName() const CM_OVERRIDE { return "endwhile"; }
-};
-
-#endif
diff --git a/Source/cmExecProgramCommand.cxx b/Source/cmExecProgramCommand.cxx
index df92592..6a7292d 100644
--- a/Source/cmExecProgramCommand.cxx
+++ b/Source/cmExecProgramCommand.cxx
@@ -6,6 +6,7 @@
#include <stdio.h>
#include "cmMakefile.h"
+#include "cmProcessOutput.h"
#include "cmSystemTools.h"
class cmExecutionStatus;
@@ -116,7 +117,7 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
int& retVal, const char* dir,
- bool verbose)
+ bool verbose, Encoding encoding)
{
if (cmSystemTools::GetRunCommandOutput()) {
verbose = false;
@@ -214,17 +215,28 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
int length;
char* data;
int p;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
if (p == cmsysProcess_Pipe_STDOUT || p == cmsysProcess_Pipe_STDERR) {
if (verbose) {
- cmSystemTools::Stdout(data, length);
+ processOutput.DecodeText(data, length, strdata);
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
}
output.append(data, length);
}
}
+ if (verbose) {
+ processOutput.DecodeText(std::string(), strdata);
+ if (!strdata.empty()) {
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+ }
+ }
+
// All output has been read. Wait for the process to exit.
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ processOutput.DecodeText(output, output);
// Check the result of running the process.
std::string msg;
diff --git a/Source/cmExecProgramCommand.h b/Source/cmExecProgramCommand.h
index 7cdf777..58e948e 100644
--- a/Source/cmExecProgramCommand.h
+++ b/Source/cmExecProgramCommand.h
@@ -8,6 +8,7 @@
#include <vector>
#include "cmCommand.h"
+#include "cmProcessOutput.h"
class cmExecutionStatus;
@@ -21,6 +22,7 @@ class cmExecutionStatus;
class cmExecProgramCommand : public cmCommand
{
public:
+ typedef cmProcessOutput::Encoding Encoding;
/**
* This is a virtual constructor for the command.
*/
@@ -46,7 +48,8 @@ public:
private:
static bool RunCommand(const char* command, std::string& output, int& retVal,
const char* directory = CM_NULLPTR,
- bool verbose = true);
+ bool verbose = true,
+ Encoding encoding = cmProcessOutput::Auto);
};
#endif
diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx
index c8a3a84..eb26a50 100644
--- a/Source/cmExecuteProcessCommand.cxx
+++ b/Source/cmExecuteProcessCommand.cxx
@@ -8,6 +8,7 @@
#include <stdio.h>
#include "cmMakefile.h"
+#include "cmProcessOutput.h"
#include "cmSystemTools.h"
class cmExecutionStatus;
@@ -46,6 +47,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
std::string error_variable;
std::string result_variable;
std::string working_directory;
+ cmProcessOutput::Encoding encoding = cmProcessOutput::Auto;
for (size_t i = 0; i < args.size(); ++i) {
if (args[i] == "COMMAND") {
doing_command = true;
@@ -127,6 +129,14 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
} else if (args[i] == "ERROR_STRIP_TRAILING_WHITESPACE") {
doing_command = false;
error_strip_trailing_whitespace = true;
+ } else if (args[i] == "ENCODING") {
+ doing_command = false;
+ if (++i < args.size()) {
+ encoding = cmProcessOutput::FindEncoding(args[i]);
+ } else {
+ this->SetError(" called with no value for ENCODING.");
+ return false;
+ }
} else if (doing_command) {
cmds[command_index].push_back(args[i].c_str());
} else {
@@ -222,25 +232,43 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
int length;
char* data;
int p;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
// Put the output in the right place.
if (p == cmsysProcess_Pipe_STDOUT && !output_quiet) {
if (output_variable.empty()) {
- cmSystemTools::Stdout(data, length);
+ processOutput.DecodeText(data, length, strdata, 1);
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
} else {
cmExecuteProcessCommandAppend(tempOutput, data, length);
}
} else if (p == cmsysProcess_Pipe_STDERR && !error_quiet) {
if (error_variable.empty()) {
- cmSystemTools::Stderr(data, length);
+ processOutput.DecodeText(data, length, strdata, 2);
+ cmSystemTools::Stderr(strdata.c_str(), strdata.size());
} else {
cmExecuteProcessCommandAppend(tempError, data, length);
}
}
}
+ if (!output_quiet && output_variable.empty()) {
+ processOutput.DecodeText(std::string(), strdata, 1);
+ if (!strdata.empty()) {
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+ }
+ }
+ if (!error_quiet && error_variable.empty()) {
+ processOutput.DecodeText(std::string(), strdata, 2);
+ if (!strdata.empty()) {
+ cmSystemTools::Stderr(strdata.c_str(), strdata.size());
+ }
+ }
// All output has been read. Wait for the process to exit.
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ processOutput.DecodeText(tempOutput, tempOutput);
+ processOutput.DecodeText(tempError, tempError);
// Fix the text in the output strings.
cmExecuteProcessCommandFixText(tempOutput, output_strip_trailing_whitespace);
diff --git a/Source/cmExecutionStatus.h b/Source/cmExecutionStatus.h
index 7d4e97c..fd3c416 100644
--- a/Source/cmExecutionStatus.h
+++ b/Source/cmExecutionStatus.h
@@ -3,10 +3,6 @@
#ifndef cmExecutionStatus_h
#define cmExecutionStatus_h
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
/** \class cmExecutionStatus
* \brief Superclass for all command status classes
*
diff --git a/Source/cmExpandedCommandArgument.h b/Source/cmExpandedCommandArgument.h
index 39cffce..9770fe6 100644
--- a/Source/cmExpandedCommandArgument.h
+++ b/Source/cmExpandedCommandArgument.h
@@ -3,9 +3,9 @@
#ifndef cmExpandedCommandArgument_h
#define cmExpandedCommandArgument_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <string>
/** \class cmExpandedCommandArgument
* \brief Represents an expanded command argument
diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx
index 38f95d2..dab0c2c 100644
--- a/Source/cmExportBuildAndroidMKGenerator.cxx
+++ b/Source/cmExportBuildAndroidMKGenerator.cxx
@@ -2,14 +2,22 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExportBuildAndroidMKGenerator.h"
-#include "cmExportSet.h"
+#include <algorithm>
+#include <map>
+#include <sstream>
+#include <utility>
+
+#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
-#include "cmGlobalGenerator.h"
+#include "cmLinkItem.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
-#include "cmTargetExport.h"
-
-#include <algorithm>
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
cmExportBuildAndroidMKGenerator::cmExportBuildAndroidMKGenerator()
{
diff --git a/Source/cmExportBuildAndroidMKGenerator.h b/Source/cmExportBuildAndroidMKGenerator.h
index c9e0145..2a5a42e 100644
--- a/Source/cmExportBuildAndroidMKGenerator.h
+++ b/Source/cmExportBuildAndroidMKGenerator.h
@@ -3,10 +3,16 @@
#ifndef cmExportBuildAndroidMKGenerator_h
#define cmExportBuildAndroidMKGenerator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+#include <vector>
+
#include "cmExportBuildFileGenerator.h"
-#include "cmListFileCache.h"
+#include "cmExportFileGenerator.h"
-class cmExportSet;
+class cmGeneratorTarget;
/** \class cmExportBuildAndroidMKGenerator
* \brief Generate a file exporting targets from a build tree.
diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx
index f9f5f3a..9772f49 100644
--- a/Source/cmExportInstallAndroidMKGenerator.cxx
+++ b/Source/cmExportInstallAndroidMKGenerator.cxx
@@ -2,16 +2,17 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExportInstallAndroidMKGenerator.h"
-#include "cmAlgorithms.h"
+#include <ostream>
+#include <stddef.h>
+
#include "cmExportBuildAndroidMKGenerator.h"
#include "cmExportSet.h"
-#include "cmExportSetMap.h"
-#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
-#include "cmGlobalGenerator.h"
#include "cmInstallExportGenerator.h"
#include "cmInstallTargetGenerator.h"
-#include "cmLocalGenerator.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
#include "cmTargetExport.h"
cmExportInstallAndroidMKGenerator::cmExportInstallAndroidMKGenerator(
@@ -26,7 +27,7 @@ void cmExportInstallAndroidMKGenerator::GenerateImportHeaderCode(
std::string installDir = this->IEGen->GetDestination();
os << "LOCAL_PATH := $(call my-dir)\n";
size_t numDotDot = cmSystemTools::CountChar(installDir.c_str(), '/');
- numDotDot += (installDir.size() > 0) ? 1 : 0;
+ numDotDot += installDir.empty() ? 0 : 1;
std::string path;
for (size_t n = 0; n < numDotDot; n++) {
path += "/..";
diff --git a/Source/cmExportInstallAndroidMKGenerator.h b/Source/cmExportInstallAndroidMKGenerator.h
index c713027..f2f8927 100644
--- a/Source/cmExportInstallAndroidMKGenerator.h
+++ b/Source/cmExportInstallAndroidMKGenerator.h
@@ -3,10 +3,18 @@
#ifndef cmExportInstallAndroidMKGenerator_h
#define cmExportInstallAndroidMKGenerator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "cmExportFileGenerator.h"
#include "cmExportInstallFileGenerator.h"
+class cmGeneratorTarget;
class cmInstallExportGenerator;
-class cmInstallTargetGenerator;
/** \class cmExportInstallAndroidMKGenerator
* \brief Generate a file exporting targets from an install tree.
diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx
index 41fc428..b0a4c47 100644
--- a/Source/cmExtraCodeBlocksGenerator.cxx
+++ b/Source/cmExtraCodeBlocksGenerator.cxx
@@ -2,6 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExtraCodeBlocksGenerator.h"
+#include <map>
+#include <ostream>
+#include <string.h>
+#include <utility>
+
#include "cmAlgorithms.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
@@ -14,12 +19,6 @@
#include "cmXMLWriter.h"
#include "cmake.h"
-#include <algorithm>
-#include <map>
-#include <ostream>
-#include <string.h>
-#include <utility>
-
/* Some useful URLs:
Homepage:
http://www.codeblocks.org
diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx
index c4e86a9..b4fc771 100644
--- a/Source/cmExtraEclipseCDT4Generator.cxx
+++ b/Source/cmExtraEclipseCDT4Generator.cxx
@@ -2,13 +2,20 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExtraEclipseCDT4Generator.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
#include "cmGeneratedFileStream.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
-#include "cmOutputConverter.h"
#include "cmSourceFile.h"
#include "cmSourceGroup.h"
#include "cmState.h"
@@ -17,14 +24,6 @@
#include "cmXMLWriter.h"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <map>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
static void AppendAttribute(cmXMLWriter& xml, const char* keyval)
{
xml.StartElement("attribute");
@@ -704,6 +703,14 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
* Also on the cdt-dev list didn't bring any information:
* http://web.archiveorange.com/archive/v/B4NlJDNIpYoOS1SbxFNy
* Alex */
+ // include subprojects directory to the src pathentry
+ // eclipse cdt indexer uses this entries as reference to index source files
+ if (this->GenerateLinkedResources) {
+ xml.StartElement("pathentry");
+ xml.Attribute("kind", "src");
+ xml.Attribute("path", "[Subprojects]");
+ xml.EndElement();
+ }
for (std::vector<std::string>::const_iterator it =
this->SrcLinkedResources.begin();
diff --git a/Source/cmExtraSublimeTextGenerator.cxx b/Source/cmExtraSublimeTextGenerator.cxx
index 0480d10..5712ab2 100644
--- a/Source/cmExtraSublimeTextGenerator.cxx
+++ b/Source/cmExtraSublimeTextGenerator.cxx
@@ -2,7 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExtraSublimeTextGenerator.h"
+#include <cmsys/RegularExpression.hxx>
+#include <set>
+#include <sstream>
+#include <string.h>
+#include <utility>
+
#include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
@@ -10,12 +17,7 @@
#include "cmSourceFile.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-
-#include <cmsys/RegularExpression.hxx>
-#include <ostream>
-#include <set>
-#include <string.h>
-#include <utility>
+#include "cmake.h"
/*
Sublime Text 2 Generator
@@ -62,6 +64,8 @@ void cmExtraSublimeTextGenerator::Generate()
{
this->ExcludeBuildFolder = this->GlobalGenerator->GlobalSettingIsOn(
"CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE");
+ this->EnvSettings = this->GlobalGenerator->GetSafeGlobalSetting(
+ "CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS");
// for each sub project in the project create a sublime text 2 project
for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
@@ -130,7 +134,37 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile(
// End of build_systems
fout << "\n\t]";
- fout << "\n\t}";
+ std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
+ std::vector<std::string> tokens;
+ cmSystemTools::ExpandListArgument(this->EnvSettings, tokens);
+
+ if (!this->EnvSettings.empty()) {
+ fout << ",";
+ fout << "\n\t\"env\":";
+ fout << "\n\t{";
+ fout << "\n\t\t" << systemName << ":";
+ fout << "\n\t\t{";
+ for (std::vector<std::string>::iterator i = tokens.begin();
+ i != tokens.end(); ++i) {
+ size_t const pos = i->find_first_of('=');
+
+ if (pos != std::string::npos) {
+ std::string varName = i->substr(0, pos);
+ std::string varValue = i->substr(pos + 1);
+
+ fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\"";
+ } else {
+ std::ostringstream e;
+ e << "Could not parse Env Vars specified in "
+ "\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\""
+ << ", corrupted string " << *i;
+ mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+ }
+ }
+ fout << "\n\t\t}";
+ fout << "\n\t}";
+ }
+ fout << "\n}";
}
void cmExtraSublimeTextGenerator::AppendAllTargets(
diff --git a/Source/cmExtraSublimeTextGenerator.h b/Source/cmExtraSublimeTextGenerator.h
index 0c58221..a860d34 100644
--- a/Source/cmExtraSublimeTextGenerator.h
+++ b/Source/cmExtraSublimeTextGenerator.h
@@ -66,6 +66,7 @@ private:
cmGeneratorTarget* gtgt);
bool ExcludeBuildFolder;
+ std::string EnvSettings;
};
#endif
diff --git a/Source/cmFLTKWrapUICommand.cxx b/Source/cmFLTKWrapUICommand.cxx
index 1f0ce8d..1e8ca06 100644
--- a/Source/cmFLTKWrapUICommand.cxx
+++ b/Source/cmFLTKWrapUICommand.cxx
@@ -82,8 +82,8 @@ bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args,
no_working_dir);
cmSourceFile* sf = this->Makefile->GetSource(cxxres);
- sf->AddDepend(hname.c_str());
- sf->AddDepend(origname.c_str());
+ sf->AddDepend(hname);
+ sf->AddDepend(origname);
this->GeneratedSourcesClasses.push_back(sf);
}
}
diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx
index 6285894..2f6238b 100644
--- a/Source/cmFileCommand.cxx
+++ b/Source/cmFileCommand.cxx
@@ -2,15 +2,39 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFileCommand.h"
+#include <algorithm>
+#include <assert.h>
+#include <cm_kwiml.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <cmsys/String.hxx>
+#include <list>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/types.h>
+// include sys/stat.h after sys/types.h
+#include <sys/stat.h>
+
#include "cmAlgorithms.h"
+#include "cmCommandArgumentsHelper.h"
#include "cmCryptoHash.h"
-#include "cmCryptoHash.h"
+#include "cmFileLockPool.h"
#include "cmFileTimeComparison.h"
+#include "cmGeneratorExpression.h"
#include "cmGlobalGenerator.h"
#include "cmHexFileConverter.h"
#include "cmInstallType.h"
+#include "cmListFileCache.h"
#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
#include "cmTimestamp.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
#if defined(CMAKE_BUILD_WITH_CMAKE)
@@ -18,19 +42,7 @@
#include "cmFileLockResult.h"
#endif
-#undef GetCurrentDirectory
-#include <assert.h>
-
-#include <sys/types.h>
-// include sys/stat.h after sys/types.h
-#include <sys/stat.h>
-
-#include <cm_auto_ptr.hxx>
-#include <cmsys/Directory.hxx>
-#include <cmsys/Encoding.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
+class cmSystemToolsFileTime;
// Table of permissions flags.
#if defined(_WIN32) && !defined(__CYGWIN__)
@@ -59,7 +71,7 @@ static mode_t mode_setuid = S_ISUID;
static mode_t mode_setgid = S_ISGID;
#endif
-#if defined(_WIN32) && defined(CMAKE_ENCODING_UTF8)
+#if defined(_WIN32)
// libcurl doesn't support file:// urls for unicode filenames on Windows.
// Convert string from UTF-8 to ACP if this is a file:// URL.
static std::string fix_file_url_windows(const std::string& url)
@@ -110,7 +122,9 @@ bool cmFileCommand::InitialPass(std::vector<std::string> const& args,
}
if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
subCommand == "SHA256" || subCommand == "SHA384" ||
- subCommand == "SHA512") {
+ subCommand == "SHA512" || subCommand == "SHA3_224" ||
+ subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
+ subCommand == "SHA3_512") {
return this->HandleHashCommand(args);
}
if (subCommand == "STRINGS") {
@@ -2553,7 +2567,8 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
return false;
}
- hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New("MD5"));
+ hash =
+ CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(cmCryptoHash::AlgoMD5));
hashMatchMSG = "MD5 sum";
expectedHash = cmSystemTools::LowerCase(*i);
} else if (*i == "SHOW_PROGRESS") {
@@ -2600,7 +2615,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
// Do not return error for compatibility reason.
std::string err = "Unexpected argument: ";
err += *i;
- this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err.c_str());
+ this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err);
}
++i;
}
@@ -2642,7 +2657,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
return false;
}
-#if defined(_WIN32) && defined(CMAKE_ENCODING_UTF8)
+#if defined(_WIN32)
url = fix_file_url_windows(url);
#endif
@@ -2884,7 +2899,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
// Do not return error for compatibility reason.
std::string err = "Unexpected argument: ";
err += *i;
- this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err.c_str());
+ this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err);
}
++i;
@@ -2902,7 +2917,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
unsigned long file_size = cmsys::SystemTools::FileLength(filename);
-#if defined(_WIN32) && defined(CMAKE_ENCODING_UTF8)
+#if defined(_WIN32)
url = fix_file_url_windows(url);
#endif
diff --git a/Source/cmFileMonitor.cxx b/Source/cmFileMonitor.cxx
index b55341b..03bbf42 100644
--- a/Source/cmFileMonitor.cxx
+++ b/Source/cmFileMonitor.cxx
@@ -247,7 +247,10 @@ public:
void StopWatching() final {}
- void AppendCallback(cmFileMonitor::Callback cb) { CbList.push_back(cb); }
+ void AppendCallback(cmFileMonitor::Callback const& cb)
+ {
+ this->CbList.push_back(cb);
+ }
std::string Path() const final
{
@@ -288,7 +291,7 @@ void on_directory_change(uv_fs_event_t* handle, const char* filename,
{
const cmIBaseWatcher* const watcher =
static_cast<const cmIBaseWatcher*>(handle->data);
- const std::string pathSegment(filename);
+ const std::string pathSegment(filename ? filename : "");
watcher->Trigger(pathSegment, events, status);
}
@@ -310,7 +313,7 @@ cmFileMonitor::~cmFileMonitor()
}
void cmFileMonitor::MonitorPaths(const std::vector<std::string>& paths,
- Callback cb)
+ Callback const& cb)
{
for (const auto& p : paths) {
std::vector<std::string> pathSegments;
diff --git a/Source/cmFileMonitor.h b/Source/cmFileMonitor.h
index e05f48d..48169b8 100644
--- a/Source/cmFileMonitor.h
+++ b/Source/cmFileMonitor.h
@@ -17,7 +17,7 @@ public:
~cmFileMonitor();
using Callback = std::function<void(const std::string&, int, int)>;
- void MonitorPaths(const std::vector<std::string>& paths, Callback cb);
+ void MonitorPaths(const std::vector<std::string>& paths, Callback const& cb);
void StopMonitoring();
std::vector<std::string> WatchedFiles() const;
diff --git a/Source/cmFilePathUuid.cxx b/Source/cmFilePathUuid.cxx
index ad434e3..03d2524 100644
--- a/Source/cmFilePathUuid.cxx
+++ b/Source/cmFilePathUuid.cxx
@@ -107,8 +107,8 @@ std::string cmFilePathUuid::GetChecksumString(
{
// Calculate the file ( seed + relative path + name ) checksum
std::vector<unsigned char> hashBytes =
- cmCryptoHash::New("SHA256")->ByteHashString(
- sourceRelSeed + sourceRelPath + sourceFilename);
+ cmCryptoHash(cmCryptoHash::AlgoSHA256)
+ .ByteHashString(sourceRelSeed + sourceRelPath + sourceFilename);
checksumBase32 =
cmBase32Encoder().encodeString(&hashBytes[0], hashBytes.size(), false);
diff --git a/Source/cmFileTimeComparison.cxx b/Source/cmFileTimeComparison.cxx
index 55d8c2a..991ebb8 100644
--- a/Source/cmFileTimeComparison.cxx
+++ b/Source/cmFileTimeComparison.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFileTimeComparison.h"
-#include <cmConfigure.h>
#include <string>
#include <time.h>
#include <utility>
diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx
index 3d67ac1..dce5021 100644
--- a/Source/cmFindBase.cxx
+++ b/Source/cmFindBase.cxx
@@ -2,8 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFindBase.h"
+#include <cmConfigure.h>
+#include <iostream>
+#include <map>
+#include <stddef.h>
+
#include "cmAlgorithms.h"
#include "cmMakefile.h"
+#include "cmSearchPath.h"
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
diff --git a/Source/cmFindBase.h b/Source/cmFindBase.h
index 2b8d4a2..423d453 100644
--- a/Source/cmFindBase.h
+++ b/Source/cmFindBase.h
@@ -3,6 +3,11 @@
#ifndef cmFindBase_h
#define cmFindBase_h
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
#include "cmFindCommon.h"
/** \class cmFindBase
diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx
index 75d1453..110195c 100644
--- a/Source/cmFindCommon.cxx
+++ b/Source/cmFindCommon.cxx
@@ -2,12 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFindCommon.h"
+#include <algorithm>
+#include <string.h>
+#include <utility>
+
#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include <algorithm>
-#include <functional>
-
cmFindCommon::PathGroup cmFindCommon::PathGroup::All("ALL");
cmFindCommon::PathLabel cmFindCommon::PathLabel::CMake("CMAKE");
cmFindCommon::PathLabel cmFindCommon::PathLabel::CMakeEnvironment(
diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h
index 1809c0a..4d6d569 100644
--- a/Source/cmFindCommon.h
+++ b/Source/cmFindCommon.h
@@ -3,10 +3,19 @@
#ifndef cmFindCommon_h
#define cmFindCommon_h
+#include <cmConfigure.h>
+
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
#include "cmCommand.h"
#include "cmPathLabel.h"
#include "cmSearchPath.h"
+class cmMakefile;
+
/** \class cmFindCommon
* \brief Base class for FIND_XXX implementations.
*
diff --git a/Source/cmFunctionBlocker.h b/Source/cmFunctionBlocker.h
index 388115d..b3450b3 100644
--- a/Source/cmFunctionBlocker.h
+++ b/Source/cmFunctionBlocker.h
@@ -3,12 +3,9 @@
#ifndef cmFunctionBlocker_h
#define cmFunctionBlocker_h
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
-#include "cmExecutionStatus.h"
#include "cmListFileCache.h"
+
+class cmExecutionStatus;
class cmMakefile;
class cmFunctionBlocker
diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx
index 0ba575a..31adcb7 100644
--- a/Source/cmFunctionCommand.cxx
+++ b/Source/cmFunctionCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFunctionCommand.h"
-#include <algorithm>
#include <sstream>
#include "cmAlgorithms.h"
diff --git a/Source/cmGeneratedFileStream.cxx b/Source/cmGeneratedFileStream.cxx
index 6cdb7f5..4731493 100644
--- a/Source/cmGeneratedFileStream.cxx
+++ b/Source/cmGeneratedFileStream.cxx
@@ -2,11 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGeneratedFileStream.h"
-#include "cmSystemTools.h"
-
#include <stdio.h>
+#include "cmSystemTools.h"
+
#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_codecvt.hxx"
#include <cm_zlib.h>
#endif
diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx
index 34f763c..1f2d2b4 100644
--- a/Source/cmGeneratorExpression.cxx
+++ b/Source/cmGeneratorExpression.cxx
@@ -2,6 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGeneratorExpression.h"
+#include <cmsys/RegularExpression.hxx>
+#include <utility>
+
#include "assert.h"
#include "cmAlgorithms.h"
#include "cmGeneratorExpressionContext.h"
@@ -9,9 +12,7 @@
#include "cmGeneratorExpressionLexer.h"
#include "cmGeneratorExpressionParser.h"
#include "cmSystemTools.h"
-
-#include <cmsys/RegularExpression.hxx>
-#include <utility>
+#include "cm_auto_ptr.hxx"
cmGeneratorExpression::cmGeneratorExpression(
const cmListFileBacktrace& backtrace)
diff --git a/Source/cmGeneratorExpressionEvaluationFile.cxx b/Source/cmGeneratorExpressionEvaluationFile.cxx
index c6c4c3a..aeb005f 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.cxx
+++ b/Source/cmGeneratorExpressionEvaluationFile.cxx
@@ -2,6 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGeneratorExpressionEvaluationFile.h"
+#include <cmConfigure.h>
+#include <cmsys/FStream.hxx>
+#include <sstream>
+#include <utility>
+
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmListFileCache.h"
@@ -9,13 +14,9 @@
#include "cmMakefile.h"
#include "cmSourceFile.h"
#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <cmConfigure.h>
-#include <cmsys/FStream.hxx>
-#include <sstream>
-#include <utility>
-
cmGeneratorExpressionEvaluationFile::cmGeneratorExpressionEvaluationFile(
const std::string& input,
CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr,
diff --git a/Source/cmGeneratorExpressionEvaluationFile.h b/Source/cmGeneratorExpressionEvaluationFile.h
index d597270..26135df 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.h
+++ b/Source/cmGeneratorExpressionEvaluationFile.h
@@ -5,14 +5,19 @@
#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmGeneratorExpression.h"
-
-#include <cm_auto_ptr.hxx>
#include <map>
#include <string>
-#include <sys/types.h>
#include <vector>
+#include "cmGeneratorExpression.h"
+#include "cm_auto_ptr.hxx"
+
+#if defined(_MSC_VER)
+typedef unsigned short mode_t;
+#else
+#include <sys/types.h>
+#endif
+
class cmLocalGenerator;
class cmGeneratorExpressionEvaluationFile
diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx
index ca056c0..903bcec 100644
--- a/Source/cmGeneratorTarget.cxx
+++ b/Source/cmGeneratorTarget.cxx
@@ -2,6 +2,17 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGeneratorTarget.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <errno.h>
+#include <iterator>
+#include <queue>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
#include "cmCustomCommand.h"
@@ -24,16 +35,7 @@
#include "cm_unordered_set.hxx"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <errno.h>
-#include <iterator>
-#include <queue>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+class cmMessenger;
template <>
const char* cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
@@ -2796,6 +2798,16 @@ void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const
}
}
+std::string cmGeneratorTarget::GetImportedLibName(
+ std::string const& config) const
+{
+ if (cmGeneratorTarget::ImportInfo const* info =
+ this->GetImportInfo(config)) {
+ return info->LibName;
+ }
+ return std::string();
+}
+
std::string cmGeneratorTarget::GetFullPath(const std::string& config,
bool implib, bool realname) const
{
@@ -3945,9 +3957,9 @@ std::string cmGeneratorTarget::GetFortranModuleDirectory(
std::string const& working_dir) const
{
if (!this->FortranModuleDirectoryCreated) {
- this->FortranModuleDirectory = true;
this->FortranModuleDirectory =
this->CreateFortranModuleDirectory(working_dir);
+ this->FortranModuleDirectoryCreated = true;
}
return this->FortranModuleDirectory;
@@ -4711,6 +4723,9 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
}
}
if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ if (loc) {
+ info.LibName = loc;
+ }
return;
}
diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h
index 3805bfc..4c3c14b 100644
--- a/Source/cmGeneratorTarget.h
+++ b/Source/cmGeneratorTarget.h
@@ -147,6 +147,9 @@ public:
const cmGeneratorTarget* head,
bool usage_requirements_only) const;
+ /** Get the library name for an imported interface library. */
+ std::string GetImportedLibName(std::string const& config) const;
+
/** Get the full path to the target according to the settings in its
makefile and the configuration type. */
std::string GetFullPath(const std::string& config = "", bool implib = false,
@@ -643,6 +646,7 @@ private:
std::string Location;
std::string SOName;
std::string ImportLibrary;
+ std::string LibName;
std::string Languages;
std::string Libraries;
std::string LibrariesProp;
diff --git a/Source/cmGetCMakePropertyCommand.cxx b/Source/cmGetCMakePropertyCommand.cxx
index c92ae21..7962da6 100644
--- a/Source/cmGetCMakePropertyCommand.cxx
+++ b/Source/cmGetCMakePropertyCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGetCMakePropertyCommand.h"
-#include <algorithm>
#include <set>
#include "cmAlgorithms.h"
diff --git a/Source/cmGhsMultiGpj.h b/Source/cmGhsMultiGpj.h
index 793d471..2c2b123 100644
--- a/Source/cmGhsMultiGpj.h
+++ b/Source/cmGhsMultiGpj.h
@@ -5,8 +5,6 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
-
class cmGeneratedFileStream;
class GhsMultiGpj
diff --git a/Source/cmGlobalBorlandMakefileGenerator.cxx b/Source/cmGlobalBorlandMakefileGenerator.cxx
index a0a33ea..d2372a7 100644
--- a/Source/cmGlobalBorlandMakefileGenerator.cxx
+++ b/Source/cmGlobalBorlandMakefileGenerator.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalBorlandMakefileGenerator.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmState.h"
diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx
index cf51c6a..2808051 100644
--- a/Source/cmGlobalGenerator.cxx
+++ b/Source/cmGlobalGenerator.cxx
@@ -9,6 +9,16 @@
#include "cmGlobalGenerator.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#include "cmAlgorithms.h"
#include "cmCPackPropertiesGenerator.h"
#include "cmComputeTargetDepends.h"
@@ -29,26 +39,20 @@
#include "cmQtAutoGeneratorInitializer.h"
#include "cmSourceFile.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
#include "cmStateTypes.h"
#include "cmVersion.h"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/Directory.hxx>
-#include <cmsys/FStream.hxx>
-#include <iterator>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cmCryptoHash.h"
#include <cm_jsoncpp_value.h>
#include <cm_jsoncpp_writer.h>
-#include <cmsys/MD5.h>
#endif
+const std::string kCMAKE_PLATFORM_INFO_INITIALIZED =
+ "CMAKE_PLATFORM_INFO_INITIALIZED";
+
class cmInstalledFile;
bool cmTarget::StrictTargetComparison::operator()(cmTarget const* t1,
@@ -427,6 +431,23 @@ void cmGlobalGenerator::EnableLanguage(
// set the dir for parent files so they can be used by modules
mf->AddDefinition("CMAKE_PLATFORM_INFO_DIR", rootBin.c_str());
+ if (!this->CMakeInstance->GetIsInTryCompile()) {
+ // Keep a mark in the cache to indicate that we've initialized the
+ // platform information directory. If the platform information
+ // directory exists but the mark is missing then CMakeCache.txt
+ // has been removed or replaced without also removing the CMakeFiles/
+ // directory. In this case remove the platform information directory
+ // so that it will be re-initialized and the relevant information
+ // restored in the cache.
+ if (cmSystemTools::FileIsDirectory(rootBin) &&
+ !mf->IsOn(kCMAKE_PLATFORM_INFO_INITIALIZED)) {
+ cmSystemTools::RemoveADirectory(rootBin);
+ }
+ this->GetCMakeInstance()->AddCacheEntry(
+ kCMAKE_PLATFORM_INFO_INITIALIZED, "1",
+ "Platform information initialized", cmStateEnums::INTERNAL);
+ }
+
// find and make sure CMAKE_MAKE_PROGRAM is defined
if (!this->FindMakeProgram(mf)) {
return;
@@ -2616,14 +2637,9 @@ void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs,
// Compute a hash of the rule.
RuleHash hash;
{
- unsigned char const* data =
- reinterpret_cast<unsigned char const*>(content.c_str());
- int length = static_cast<int>(content.length());
- cmsysMD5* sum = cmsysMD5_New();
- cmsysMD5_Initialize(sum);
- cmsysMD5_Append(sum, data, length);
- cmsysMD5_FinalizeHex(sum, hash.Data);
- cmsysMD5_Delete(sum);
+ cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+ std::string const md5_hex = md5.HashString(content);
+ memcpy(hash.Data, md5_hex.c_str(), 32);
}
// Shorten the output name (in expected use case).
diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h
index 4bf4bd1..88ef8da 100644
--- a/Source/cmGlobalGenerator.h
+++ b/Source/cmGlobalGenerator.h
@@ -5,8 +5,15 @@
#include <cmConfigure.h>
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "cmCustomCommandLines.h"
#include "cmExportSetMap.h"
-#include "cmStateDirectory.h"
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
@@ -14,26 +21,19 @@
#include "cm_codecvt.hxx"
#include "cm_unordered_map.hxx"
-#include <iosfwd>
-#include <map>
-#include <set>
-#include <string>
-#include <utility>
-#include <vector>
-
#if defined(CMAKE_BUILD_WITH_CMAKE)
#include "cmFileLockPool.h"
#endif
-class cmCustomCommandLines;
-class cmSourceFile;
class cmExportBuildFileGenerator;
class cmExternalMakefileProjectGenerator;
class cmGeneratorTarget;
-class cmLocalGenerator;
class cmLinkLineComputer;
+class cmLocalGenerator;
class cmMakefile;
class cmOutputConverter;
+class cmSourceFile;
+class cmStateDirectory;
class cmake;
/** \class cmGlobalGenerator
diff --git a/Source/cmGlobalGeneratorFactory.h b/Source/cmGlobalGeneratorFactory.h
index 528e118..5e948f7 100644
--- a/Source/cmGlobalGeneratorFactory.h
+++ b/Source/cmGlobalGeneratorFactory.h
@@ -5,12 +5,11 @@
#include <cmConfigure.h>
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include <string>
+#include <vector>
-class cmake;
class cmGlobalGenerator;
+class cmake;
struct cmDocumentationEntry;
/** \class cmGlobalGeneratorFactory
diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx
index 6bbfed5..286f375 100644
--- a/Source/cmGlobalGhsMultiGenerator.cxx
+++ b/Source/cmGlobalGhsMultiGenerator.cxx
@@ -2,14 +2,16 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalGhsMultiGenerator.h"
+#include <cmsys/SystemTools.hxx>
+
+#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGhsMultiTargetGenerator.h"
#include "cmLocalGhsMultiGenerator.h"
#include "cmMakefile.h"
#include "cmVersion.h"
-#include <cmAlgorithms.h>
-#include <cmsys/SystemTools.hxx>
const char* cmGlobalGhsMultiGenerator::FILE_EXTENSION = ".gpj";
const char* cmGlobalGhsMultiGenerator::DEFAULT_MAKE_PROGRAM = "gbuild";
diff --git a/Source/cmGlobalJOMMakefileGenerator.cxx b/Source/cmGlobalJOMMakefileGenerator.cxx
index 78bf5bd..18c45e0 100644
--- a/Source/cmGlobalJOMMakefileGenerator.cxx
+++ b/Source/cmGlobalJOMMakefileGenerator.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalJOMMakefileGenerator.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmState.h"
diff --git a/Source/cmGlobalMSYSMakefileGenerator.cxx b/Source/cmGlobalMSYSMakefileGenerator.cxx
index f17b915..7e0d0d4 100644
--- a/Source/cmGlobalMSYSMakefileGenerator.cxx
+++ b/Source/cmGlobalMSYSMakefileGenerator.cxx
@@ -2,11 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalMSYSMakefileGenerator.h"
+#include <cmsys/FStream.hxx>
+
+#include "cmDocumentationEntry.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmState.h"
#include "cmake.h"
-#include <cmsys/FStream.hxx>
cmGlobalMSYSMakefileGenerator::cmGlobalMSYSMakefileGenerator(cmake* cm)
: cmGlobalUnixMakefileGenerator3(cm)
diff --git a/Source/cmGlobalMinGWMakefileGenerator.cxx b/Source/cmGlobalMinGWMakefileGenerator.cxx
index 255c0f5..3c3a5d1d 100644
--- a/Source/cmGlobalMinGWMakefileGenerator.cxx
+++ b/Source/cmGlobalMinGWMakefileGenerator.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalMinGWMakefileGenerator.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmState.h"
diff --git a/Source/cmGlobalNMakeMakefileGenerator.cxx b/Source/cmGlobalNMakeMakefileGenerator.cxx
index 06aba73..da683fb 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.cxx
+++ b/Source/cmGlobalNMakeMakefileGenerator.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalNMakeMakefileGenerator.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmState.h"
diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx
index ee594b0..1bdef53 100644
--- a/Source/cmGlobalNinjaGenerator.cxx
+++ b/Source/cmGlobalNinjaGenerator.cxx
@@ -2,6 +2,17 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalNinjaGenerator.h"
+#include <algorithm>
+#include <cm_jsoncpp_reader.h>
+#include <cm_jsoncpp_value.h>
+#include <cm_jsoncpp_writer.h>
+#include <cmsys/FStream.hxx>
+#include <ctype.h>
+#include <functional>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+
#include "cmAlgorithms.h"
#include "cmDocumentationEntry.h"
#include "cmFortranParser.h"
@@ -13,6 +24,9 @@
#include "cmMakefile.h"
#include "cmNinjaLinkLineComputer.h"
#include "cmOutputConverter.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
@@ -21,19 +35,16 @@
#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include "cm_jsoncpp_reader.h"
-#include "cm_jsoncpp_writer.h"
-
-#include <algorithm>
-#include <ctype.h>
-#include <functional>
-#include <iterator>
-#include <sstream>
-#include <stdio.h>
+class cmLinkLineComputer;
const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja";
const char* cmGlobalNinjaGenerator::INDENT = " ";
+#ifdef _WIN32
+std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "cd .";
+#else
+std::string const cmGlobalNinjaGenerator::SHELL_NOOP = ":";
+#endif
void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
{
@@ -125,7 +136,7 @@ std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit)
std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path)
{
- std::string result = path;
+ std::string result = path; // NOLINT(clang-tidy)
#ifdef _WIN32
if (this->IsGCCOnWindows())
std::replace(result.begin(), result.end(), '\\', '/');
@@ -278,7 +289,7 @@ void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
bool restat, const cmNinjaDeps& outputs, const cmNinjaDeps& deps,
const cmNinjaDeps& orderOnly)
{
- std::string cmd = command;
+ std::string cmd = command; // NOLINT(clang-tidy)
#ifdef _WIN32
if (cmd.empty())
// TODO Shouldn't an empty command be handled by ninja?
diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h
index 81ec3eb..a51e919 100644
--- a/Source/cmGlobalNinjaGenerator.h
+++ b/Source/cmGlobalNinjaGenerator.h
@@ -5,12 +5,6 @@
#include <cmConfigure.h>
-#include "cmGlobalCommonGenerator.h"
-#include "cmGlobalGenerator.h"
-#include "cmGlobalGeneratorFactory.h"
-#include "cmNinjaTypes.h"
-#include "cmPolicies.h"
-
#include <iosfwd>
#include <map>
#include <set>
@@ -18,13 +12,23 @@
#include <utility>
#include <vector>
+#include "cmGlobalCommonGenerator.h"
+#include "cmGlobalGenerator.h"
+#include "cmGlobalGeneratorFactory.h"
+#include "cmNinjaTypes.h"
+#include "cmPolicies.h"
+#include "cm_codecvt.hxx"
+
class cmCustomCommand;
-class cmMakefile;
-class cmake;
-struct cmDocumentationEntry;
class cmGeneratedFileStream;
class cmGeneratorTarget;
+class cmLinkLineComputer;
class cmLocalGenerator;
+class cmMakefile;
+class cmOutputConverter;
+class cmStateDirectory;
+class cmake;
+struct cmDocumentationEntry;
/**
* \class cmGlobalNinjaGenerator
@@ -58,6 +62,9 @@ public:
/// The indentation string used when generating Ninja's build file.
static const char* INDENT;
+ /// The shell command used for a no-op.
+ static std::string const SHELL_NOOP;
+
/// Write @a count times INDENT level to output stream @a os.
static void Indent(std::ostream& os, int count);
diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx
index 17d49e8..23b3718 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.cxx
+++ b/Source/cmGlobalUnixMakefileGenerator3.cxx
@@ -2,6 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalUnixMakefileGenerator3.h"
+#include <algorithm>
+#include <functional>
+#include <sstream>
+#include <utility>
+
#include "cmAlgorithms.h"
#include "cmDocumentationEntry.h"
#include "cmGeneratedFileStream.h"
@@ -14,16 +19,12 @@
#include "cmOutputConverter.h"
#include "cmState.h"
#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmTargetDepend.h"
#include "cmake.h"
-#include <algorithm>
-#include <functional>
-#include <sstream>
-#include <utility>
-
cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
: cmGlobalCommonGenerator(cm)
{
@@ -963,7 +964,7 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
(type == cmStateEnums::OBJECT_LIBRARY) ||
(type == cmStateEnums::GLOBAL_TARGET) ||
(type == cmStateEnums::UTILITY)) {
- std::string name = target->GetName();
+ std::string const& name = target->GetName();
if (emittedTargets.insert(name).second) {
path = "... ";
path += name;
diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h
index 843e5dc..67d7bc9 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.h
+++ b/Source/cmGlobalUnixMakefileGenerator3.h
@@ -5,11 +5,6 @@
#include <cmConfigure.h>
-#include "cmGeneratorTarget.h"
-#include "cmGlobalCommonGenerator.h"
-#include "cmGlobalGeneratorFactory.h"
-#include "cmStateTypes.h"
-
#include <iosfwd>
#include <map>
#include <set>
@@ -17,6 +12,11 @@
#include <string>
#include <vector>
+#include "cmGeneratorTarget.h"
+#include "cmGlobalCommonGenerator.h"
+#include "cmGlobalGeneratorFactory.h"
+#include "cmStateSnapshot.h"
+
class cmGeneratedFileStream;
class cmLocalGenerator;
class cmLocalUnixMakefileGenerator3;
diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx
index 2ce65cd..d992aef 100644
--- a/Source/cmGlobalVisualStudio10Generator.cxx
+++ b/Source/cmGlobalVisualStudio10Generator.cxx
@@ -1,15 +1,15 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
#include "cmGlobalVisualStudio10Generator.h"
#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
#include "cmGeneratorTarget.h"
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
#include "cmSourceFile.h"
#include "cmVS10CLFlagTable.h"
+#include "cmVS10CSharpFlagTable.h"
#include "cmVS10LibFlagTable.h"
#include "cmVS10LinkFlagTable.h"
#include "cmVS10MASMFlagTable.h"
@@ -100,6 +100,7 @@ cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator(
this->MSBuildCommandInitialized = false;
this->DefaultPlatformToolset = "v100";
this->DefaultClFlagTable = cmVS10CLFlagTable;
+ this->DefaultCSharpFlagTable = cmVS10CSharpFlagTable;
this->DefaultLibFlagTable = cmVS10LibFlagTable;
this->DefaultLinkFlagTable = cmVS10LinkFlagTable;
this->DefaultMasmFlagTable = cmVS10MASMFlagTable;
@@ -627,6 +628,15 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetClFlagTable() const
return (table != CM_NULLPTR) ? table : this->DefaultClFlagTable;
}
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetCSharpFlagTable()
+ const
+{
+ cmIDEFlagTable const* table = this->ToolsetOptions.GetCSharpFlagTable(
+ this->GetPlatformName(), this->GetPlatformToolsetString());
+
+ return (table != CM_NULLPTR) ? table : this->DefaultCSharpFlagTable;
+}
+
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetRcFlagTable() const
{
cmIDEFlagTable const* table = this->ToolsetOptions.GetRcFlagTable(
diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h
index 4175104..5bfaf38 100644
--- a/Source/cmGlobalVisualStudio10Generator.h
+++ b/Source/cmGlobalVisualStudio10Generator.h
@@ -91,6 +91,7 @@ public:
static std::string GetInstalledNsightTegraVersion();
cmIDEFlagTable const* GetClFlagTable() const;
+ cmIDEFlagTable const* GetCSharpFlagTable() const;
cmIDEFlagTable const* GetRcFlagTable() const;
cmIDEFlagTable const* GetLibFlagTable() const;
cmIDEFlagTable const* GetLinkFlagTable() const;
@@ -120,6 +121,7 @@ protected:
std::string SystemVersion;
std::string NsightTegraVersion;
cmIDEFlagTable const* DefaultClFlagTable;
+ cmIDEFlagTable const* DefaultCSharpFlagTable;
cmIDEFlagTable const* DefaultLibFlagTable;
cmIDEFlagTable const* DefaultLinkFlagTable;
cmIDEFlagTable const* DefaultMasmFlagTable;
diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx
index acd2c2b..d37d4b0 100644
--- a/Source/cmGlobalVisualStudio11Generator.cxx
+++ b/Source/cmGlobalVisualStudio11Generator.cxx
@@ -3,9 +3,11 @@
#include "cmGlobalVisualStudio11Generator.h"
#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
#include "cmVS11CLFlagTable.h"
+#include "cmVS11CSharpFlagTable.h"
#include "cmVS11LibFlagTable.h"
#include "cmVS11LinkFlagTable.h"
#include "cmVS11MASMFlagTable.h"
@@ -107,6 +109,7 @@ cmGlobalVisualStudio11Generator::cmGlobalVisualStudio11Generator(
vc11Express, cmSystemTools::KeyWOW64_32);
this->DefaultPlatformToolset = "v110";
this->DefaultClFlagTable = cmVS11CLFlagTable;
+ this->DefaultCSharpFlagTable = cmVS11CSharpFlagTable;
this->DefaultLibFlagTable = cmVS11LibFlagTable;
this->DefaultLinkFlagTable = cmVS11LinkFlagTable;
this->DefaultMasmFlagTable = cmVS11MASMFlagTable;
diff --git a/Source/cmGlobalVisualStudio11Generator.h b/Source/cmGlobalVisualStudio11Generator.h
index be78544..ae99408 100644
--- a/Source/cmGlobalVisualStudio11Generator.h
+++ b/Source/cmGlobalVisualStudio11Generator.h
@@ -3,7 +3,18 @@
#ifndef cmGlobalVisualStudio11Generator_h
#define cmGlobalVisualStudio11Generator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <set>
+#include <string>
+
#include "cmGlobalVisualStudio10Generator.h"
+#include "cmStateTypes.h"
+
+class cmGlobalGeneratorFactory;
+class cmMakefile;
+class cmake;
/** \class cmGlobalVisualStudio11Generator */
class cmGlobalVisualStudio11Generator : public cmGlobalVisualStudio10Generator
diff --git a/Source/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx
index c18ff9e..2656dcc 100644
--- a/Source/cmGlobalVisualStudio12Generator.cxx
+++ b/Source/cmGlobalVisualStudio12Generator.cxx
@@ -3,9 +3,11 @@
#include "cmGlobalVisualStudio12Generator.h"
#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
#include "cmVS12CLFlagTable.h"
+#include "cmVS12CSharpFlagTable.h"
#include "cmVS12LibFlagTable.h"
#include "cmVS12LinkFlagTable.h"
#include "cmVS12MASMFlagTable.h"
@@ -89,6 +91,7 @@ cmGlobalVisualStudio12Generator::cmGlobalVisualStudio12Generator(
vc12Express, cmSystemTools::KeyWOW64_32);
this->DefaultPlatformToolset = "v120";
this->DefaultClFlagTable = cmVS12CLFlagTable;
+ this->DefaultCSharpFlagTable = cmVS12CSharpFlagTable;
this->DefaultLibFlagTable = cmVS12LibFlagTable;
this->DefaultLinkFlagTable = cmVS12LinkFlagTable;
this->DefaultMasmFlagTable = cmVS12MASMFlagTable;
diff --git a/Source/cmGlobalVisualStudio12Generator.h b/Source/cmGlobalVisualStudio12Generator.h
index cdda512..79efe52 100644
--- a/Source/cmGlobalVisualStudio12Generator.h
+++ b/Source/cmGlobalVisualStudio12Generator.h
@@ -3,8 +3,17 @@
#ifndef cmGlobalVisualStudio12Generator_h
#define cmGlobalVisualStudio12Generator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
#include "cmGlobalVisualStudio11Generator.h"
+class cmGlobalGeneratorFactory;
+class cmMakefile;
+class cmake;
+
/** \class cmGlobalVisualStudio12Generator */
class cmGlobalVisualStudio12Generator : public cmGlobalVisualStudio11Generator
{
diff --git a/Source/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx
index e0b86d7..81c305c 100644
--- a/Source/cmGlobalVisualStudio14Generator.cxx
+++ b/Source/cmGlobalVisualStudio14Generator.cxx
@@ -3,9 +3,11 @@
#include "cmGlobalVisualStudio14Generator.h"
#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
#include "cmVS140CLFlagTable.h"
+#include "cmVS140CSharpFlagTable.h"
#include "cmVS14LibFlagTable.h"
#include "cmVS14LinkFlagTable.h"
#include "cmVS14MASMFlagTable.h"
@@ -89,6 +91,7 @@ cmGlobalVisualStudio14Generator::cmGlobalVisualStudio14Generator(
vc14Express, cmSystemTools::KeyWOW64_32);
this->DefaultPlatformToolset = "v140";
this->DefaultClFlagTable = cmVS140CLFlagTable;
+ this->DefaultCSharpFlagTable = cmVS140CSharpFlagTable;
this->DefaultLibFlagTable = cmVS14LibFlagTable;
this->DefaultLinkFlagTable = cmVS14LinkFlagTable;
this->DefaultMasmFlagTable = cmVS14MASMFlagTable;
diff --git a/Source/cmGlobalVisualStudio14Generator.h b/Source/cmGlobalVisualStudio14Generator.h
index 991f018..ab22978 100644
--- a/Source/cmGlobalVisualStudio14Generator.h
+++ b/Source/cmGlobalVisualStudio14Generator.h
@@ -3,8 +3,17 @@
#ifndef cmGlobalVisualStudio14Generator_h
#define cmGlobalVisualStudio14Generator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
#include "cmGlobalVisualStudio12Generator.h"
+class cmGlobalGeneratorFactory;
+class cmMakefile;
+class cmake;
+
/** \class cmGlobalVisualStudio14Generator */
class cmGlobalVisualStudio14Generator : public cmGlobalVisualStudio12Generator
{
diff --git a/Source/cmGlobalVisualStudio15Generator.cxx b/Source/cmGlobalVisualStudio15Generator.cxx
index fbc7a10..20d30bc 100644
--- a/Source/cmGlobalVisualStudio15Generator.cxx
+++ b/Source/cmGlobalVisualStudio15Generator.cxx
@@ -3,20 +3,25 @@
#include "cmGlobalVisualStudio15Generator.h"
#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalVisualStudio10Generator.h"
#include "cmMakefile.h"
#include "cmVS141CLFlagTable.h"
+#include "cmVS141CSharpFlagTable.h"
-static const char vs15generatorName[] = "Visual Studio 15";
+static const char vs15generatorName[] = "Visual Studio 15 2017";
// Map generator name without year to name with year.
static const char* cmVS15GenName(const std::string& name, std::string& genName)
{
if (strncmp(name.c_str(), vs15generatorName,
- sizeof(vs15generatorName) - 1) != 0) {
+ sizeof(vs15generatorName) - 6) != 0) {
return 0;
}
- const char* p = name.c_str() + sizeof(vs15generatorName) - 1;
+ const char* p = name.c_str() + sizeof(vs15generatorName) - 6;
+ if (cmHasLiteralPrefix(p, " 2017")) {
+ p += 5;
+ }
genName = std::string(vs15generatorName) + p;
return p;
}
@@ -51,7 +56,7 @@ public:
virtual void GetDocumentation(cmDocumentationEntry& entry) const
{
entry.Name = std::string(vs15generatorName) + " [arch]";
- entry.Brief = "Generates Visual Studio 15 project files. "
+ entry.Brief = "Generates Visual Studio 2017 project files. "
"Optional [arch] can be \"Win64\" or \"ARM\".";
}
@@ -82,6 +87,7 @@ cmGlobalVisualStudio15Generator::cmGlobalVisualStudio15Generator(
vc15Express, cmSystemTools::KeyWOW64_32);
this->DefaultPlatformToolset = "v141";
this->DefaultClFlagTable = cmVS141CLFlagTable;
+ this->DefaultCSharpFlagTable = cmVS141CSharpFlagTable;
this->Version = VS15;
}
diff --git a/Source/cmGlobalVisualStudio15Generator.h b/Source/cmGlobalVisualStudio15Generator.h
index 2e458f4..59eb11a 100644
--- a/Source/cmGlobalVisualStudio15Generator.h
+++ b/Source/cmGlobalVisualStudio15Generator.h
@@ -3,8 +3,16 @@
#ifndef cmGlobalVisualStudio15Generator_h
#define cmGlobalVisualStudio15Generator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
#include "cmGlobalVisualStudio14Generator.h"
+class cmGlobalGeneratorFactory;
+class cmake;
+
/** \class cmGlobalVisualStudio15Generator */
class cmGlobalVisualStudio15Generator : public cmGlobalVisualStudio14Generator
{
diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx
index 8af0512..55a788f 100644
--- a/Source/cmGlobalVisualStudio71Generator.cxx
+++ b/Source/cmGlobalVisualStudio71Generator.cxx
@@ -1,9 +1,8 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
#include "cmGlobalVisualStudio71Generator.h"
+#include "cmDocumentationEntry.h"
#include "cmGeneratorTarget.h"
#include "cmLocalVisualStudio7Generator.h"
#include "cmMakefile.h"
diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx
index 773f8a0..602666e 100644
--- a/Source/cmGlobalVisualStudio7Generator.cxx
+++ b/Source/cmGlobalVisualStudio7Generator.cxx
@@ -681,20 +681,27 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild(
// default build if another target depends on it
int type = target->GetType();
if (type == cmStateEnums::GLOBAL_TARGET) {
- // check if INSTALL target is part of default build
- if (target->GetName() == "INSTALL") {
- // inspect CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD properties
- for (std::vector<std::string>::const_iterator i = configs.begin();
- i != configs.end(); ++i) {
- const char* propertyValue =
- target->Target->GetMakefile()->GetDefinition(
- "CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD");
- cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
- ge.Parse(propertyValue);
- if (cmSystemTools::IsOn(
- cge->Evaluate(target->GetLocalGenerator(), *i))) {
- activeConfigs.insert(*i);
+ std::list<std::string> targetNames;
+ targetNames.push_back("INSTALL");
+ targetNames.push_back("PACKAGE");
+ for (std::list<std::string>::const_iterator t = targetNames.begin();
+ t != targetNames.end(); ++t) {
+ // check if target <*t> is part of default build
+ if (target->GetName() == *t) {
+ const std::string propertyName =
+ "CMAKE_VS_INCLUDE_" + *t + "_TO_DEFAULT_BUILD";
+ // inspect CMAKE_VS_INCLUDE_<*t>_TO_DEFAULT_BUILD properties
+ for (std::vector<std::string>::const_iterator i = configs.begin();
+ i != configs.end(); ++i) {
+ const char* propertyValue =
+ target->Target->GetMakefile()->GetDefinition(propertyName);
+ cmGeneratorExpression ge;
+ CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ ge.Parse(propertyValue);
+ if (cmSystemTools::IsOn(
+ cge->Evaluate(target->GetLocalGenerator(), *i))) {
+ activeConfigs.insert(*i);
+ }
}
}
}
@@ -731,11 +738,5 @@ bool cmGlobalVisualStudio7Generator::IsDependedOn(
std::string cmGlobalVisualStudio7Generator::Encoding()
{
- std::ostringstream encoding;
-#ifdef CMAKE_ENCODING_UTF8
- encoding << "UTF-8";
-#else
- encoding << "Windows-1252";
-#endif
- return encoding.str();
+ return "UTF-8";
}
diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx
index 64808c9..e961a3d 100644
--- a/Source/cmGlobalVisualStudio8Generator.cxx
+++ b/Source/cmGlobalVisualStudio8Generator.cxx
@@ -1,9 +1,8 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
#include "cmGlobalVisualStudio8Generator.h"
+#include "cmDocumentationEntry.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmLocalVisualStudio7Generator.h"
@@ -161,6 +160,11 @@ void cmGlobalVisualStudio8Generator::GetDocumentation(
entry.Brief = "Generates Visual Studio 8 2005 project files.";
}
+std::string cmGlobalVisualStudio8Generator::GetGenerateStampList()
+{
+ return "generate.stamp.list";
+}
+
void cmGlobalVisualStudio8Generator::Configure()
{
this->cmGlobalVisualStudio7Generator::Configure();
@@ -244,7 +248,7 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget()
// Create a list of all stamp files for this project.
std::vector<std::string> stamps;
std::string stampList = cmake::GetCMakeFilesDirectoryPostSlash();
- stampList += "generate.stamp.list";
+ stampList += cmGlobalVisualStudio8Generator::GetGenerateStampList();
{
std::string stampListFile =
generators[0]->GetMakefile()->GetCurrentBinaryDirectory();
diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h
index b149c9d..53feb47 100644
--- a/Source/cmGlobalVisualStudio8Generator.h
+++ b/Source/cmGlobalVisualStudio8Generator.h
@@ -23,6 +23,9 @@ public:
/** Get the documentation entry for this generator. */
static void GetDocumentation(cmDocumentationEntry& entry);
+ /** Get the name of the main stamp list file. */
+ static std::string GetGenerateStampList();
+
virtual void EnableLanguage(std::vector<std::string> const& languages,
cmMakefile*, bool optional);
virtual void AddPlatformDefinitions(cmMakefile* mf);
diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx
index 32ba849..b1634e2 100644
--- a/Source/cmGlobalVisualStudio9Generator.cxx
+++ b/Source/cmGlobalVisualStudio9Generator.cxx
@@ -1,9 +1,8 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
#include "cmGlobalVisualStudio9Generator.h"
+#include "cmDocumentationEntry.h"
#include "cmLocalVisualStudio7Generator.h"
#include "cmMakefile.h"
#include "cmVisualStudioWCEPlatformParser.h"
diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx
index 354ada9..5edb81f 100644
--- a/Source/cmGlobalVisualStudioGenerator.cxx
+++ b/Source/cmGlobalVisualStudioGenerator.cxx
@@ -3,6 +3,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalVisualStudioGenerator.h"
+#include <cmsys/Encoding.hxx>
+#include <iostream>
+
#include "cmAlgorithms.h"
#include "cmCallVisualStudioMacro.h"
#include "cmGeneratedFileStream.h"
@@ -12,7 +15,6 @@
#include "cmSourceFile.h"
#include "cmState.h"
#include "cmTarget.h"
-#include <cmsys/Encoding.hxx>
cmGlobalVisualStudioGenerator::cmGlobalVisualStudioGenerator(cmake* cm)
: cmGlobalGenerator(cm)
diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h
index 0e88bce..f32f0bb 100644
--- a/Source/cmGlobalVisualStudioGenerator.h
+++ b/Source/cmGlobalVisualStudioGenerator.h
@@ -3,7 +3,22 @@
#ifndef cmGlobalVisualStudioGenerator_h
#define cmGlobalVisualStudioGenerator_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
#include "cmGlobalGenerator.h"
+#include "cmTargetDepend.h"
+
+class cmCustomCommand;
+class cmGeneratorTarget;
+class cmLocalGenerator;
+class cmMakefile;
+class cmake;
/** \class cmGlobalVisualStudioGenerator
* \brief Base class for global Visual Studio generators.
diff --git a/Source/cmGlobalWatcomWMakeGenerator.cxx b/Source/cmGlobalWatcomWMakeGenerator.cxx
index 0900797..94cdb38 100644
--- a/Source/cmGlobalWatcomWMakeGenerator.cxx
+++ b/Source/cmGlobalWatcomWMakeGenerator.cxx
@@ -5,7 +5,6 @@
#include "cmDocumentationEntry.h"
#include "cmMakefile.h"
#include "cmState.h"
-#include "cmStateTypes.h"
#include "cmake.h"
cmGlobalWatcomWMakeGenerator::cmGlobalWatcomWMakeGenerator(cmake* cm)
diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx
index 84a8c5e..50197c9 100644
--- a/Source/cmGlobalXCodeGenerator.cxx
+++ b/Source/cmGlobalXCodeGenerator.cxx
@@ -2,20 +2,35 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGlobalXCodeGenerator.h"
-#include "cmAlgorithms.h"
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <iomanip>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+
#include "cmComputeLinkInformation.h"
#include "cmCustomCommandGenerator.h"
+#include "cmDocumentationEntry.h"
#include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGeneratorFactory.h"
+#include "cmLocalGenerator.h"
#include "cmLocalXCodeGenerator.h"
#include "cmMakefile.h"
+#include "cmOutputConverter.h"
#include "cmSourceFile.h"
+#include "cmSourceGroup.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
#include "cmXCode21Object.h"
#include "cmXCodeObject.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <cm_auto_ptr.hxx>
+struct cmLinkImplementation;
#if defined(CMAKE_BUILD_WITH_CMAKE)
#include "cmXMLParser.h"
@@ -1925,40 +1940,24 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
BuildObjectListOrString dirs(this, this->XcodeVersion >= 30);
BuildObjectListOrString fdirs(this, this->XcodeVersion >= 30);
+ std::vector<std::string> includes;
+ this->CurrentLocalGenerator->GetIncludeDirectories(includes, gtgt, "C",
+ configName);
std::set<std::string> emitted;
emitted.insert("/System/Library/Frameworks");
- if (this->XcodeVersion < 60) {
- std::vector<std::string> includes;
- this->CurrentLocalGenerator->GetIncludeDirectories(includes, gtgt, "C",
- configName);
- for (std::vector<std::string>::iterator i = includes.begin();
- i != includes.end(); ++i) {
- if (this->NameResolvesToFramework(*i)) {
- std::string frameworkDir = *i;
- frameworkDir += "/../";
- frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
- if (emitted.insert(frameworkDir).second) {
- fdirs.Add(this->XCodeEscapePath(frameworkDir));
- }
- } else {
- std::string incpath = this->XCodeEscapePath(*i);
- dirs.Add(incpath);
- }
- }
- } else {
- for (std::set<std::string>::iterator li = languages.begin();
- li != languages.end(); ++li) {
- std::vector<std::string> includes;
- this->CurrentLocalGenerator->GetIncludeDirectories(includes, gtgt, *li,
- configName);
- std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
- includes, gtgt, *li, true, false, configName);
-
- std::string& flags = cflags[*li];
- if (!includeFlags.empty()) {
- flags += " " + includeFlags;
+ for (std::vector<std::string>::iterator i = includes.begin();
+ i != includes.end(); ++i) {
+ if (this->NameResolvesToFramework(*i)) {
+ std::string frameworkDir = *i;
+ frameworkDir += "/../";
+ frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
+ if (emitted.insert(frameworkDir).second) {
+ fdirs.Add(this->XCodeEscapePath(frameworkDir));
}
+ } else {
+ std::string incpath = this->XCodeEscapePath(*i);
+ dirs.Add(incpath);
}
}
// Add framework search paths needed for linking.
diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h
index ded8073..42c39aa 100644
--- a/Source/cmGlobalXCodeGenerator.h
+++ b/Source/cmGlobalXCodeGenerator.h
@@ -3,13 +3,25 @@
#ifndef cmGlobalXCodeGenerator_h
#define cmGlobalXCodeGenerator_h
-#include "cmGlobalGenerator.h"
+#include <cmConfigure.h>
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
-#include "cmCustomCommand.h"
+#include "cmGlobalGenerator.h"
#include "cmXCodeObject.h"
+
+class cmCustomCommand;
+class cmGeneratorTarget;
class cmGlobalGeneratorFactory;
+class cmLocalGenerator;
+class cmMakefile;
class cmSourceFile;
class cmSourceGroup;
+class cmake;
+struct cmDocumentationEntry;
/** \class cmGlobalXCodeGenerator
* \brief Write a Unix makefiles.
@@ -23,7 +35,7 @@ public:
static cmGlobalGeneratorFactory* NewFactory();
///! Get the name for the generator.
- virtual std::string GetName() const
+ std::string GetName() const CM_OVERRIDE
{
return cmGlobalXCodeGenerator::GetActualName();
}
@@ -33,51 +45,53 @@ public:
static void GetDocumentation(cmDocumentationEntry& entry);
///! Create a local generator appropriate to this Global Generator
- virtual cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf);
+ cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
/**
* Try to determine system information such as shared library
* extension, pthreads, byte order etc.
*/
- virtual void EnableLanguage(std::vector<std::string> const& languages,
- cmMakefile*, bool optional);
+ void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
+ bool optional) CM_OVERRIDE;
/**
* Try running cmake and building a file. This is used for dynalically
* loaded commands, not as part of the usual build process.
*/
- virtual void GenerateBuildCommand(
- std::vector<std::string>& makeCommand, const std::string& makeProgram,
- const std::string& projectName, const std::string& projectDir,
- const std::string& targetName, const std::string& config, bool fast,
- bool verbose,
- std::vector<std::string> const& makeOptions = std::vector<std::string>());
+ void GenerateBuildCommand(std::vector<std::string>& makeCommand,
+ const std::string& makeProgram,
+ const std::string& projectName,
+ const std::string& projectDir,
+ const std::string& targetName,
+ const std::string& config, bool fast, bool verbose,
+ std::vector<std::string> const& makeOptions =
+ std::vector<std::string>()) CM_OVERRIDE;
/** Append the subdirectory for the given configuration. */
- virtual void AppendDirectoryForConfig(const std::string& prefix,
- const std::string& config,
- const std::string& suffix,
- std::string& dir);
+ void AppendDirectoryForConfig(const std::string& prefix,
+ const std::string& config,
+ const std::string& suffix,
+ std::string& dir) CM_OVERRIDE;
bool FindMakeProgram(cmMakefile*) CM_OVERRIDE;
///! What is the configurations directory variable called?
- virtual const char* GetCMakeCFGIntDir() const;
+ const char* GetCMakeCFGIntDir() const CM_OVERRIDE;
///! expand CFGIntDir
- virtual std::string ExpandCFGIntDir(const std::string& str,
- const std::string& config) const;
+ std::string ExpandCFGIntDir(const std::string& str,
+ const std::string& config) const CM_OVERRIDE;
void SetCurrentLocalGenerator(cmLocalGenerator*);
/** Return true if the generated build tree may contain multiple builds.
i.e. "Can I build Debug and Release in the same tree?" */
- virtual bool IsMultiConfig() const;
+ bool IsMultiConfig() const CM_OVERRIDE;
- virtual bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf);
+ bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf) CM_OVERRIDE;
void AppendFlag(std::string& flags, std::string const& flag);
protected:
- virtual void AddExtraIDETargets();
- virtual void Generate();
+ void AddExtraIDETargets() CM_OVERRIDE;
+ void Generate() CM_OVERRIDE;
private:
cmXCodeObject* CreateOrGetPBXGroup(cmGeneratorTarget* gtgt,
@@ -120,7 +134,7 @@ private:
cmXCodeObject* CreateFlatClone(cmXCodeObject*);
cmXCodeObject* CreateXCodeTarget(cmGeneratorTarget* gtgt,
cmXCodeObject* buildPhases);
- void ForceLinkerLanguages();
+ void ForceLinkerLanguages() CM_OVERRIDE;
void ForceLinkerLanguage(cmGeneratorTarget* gtgt);
const char* GetTargetLinkFlagsVar(const cmGeneratorTarget* target) const;
const char* GetTargetFileType(cmGeneratorTarget* target);
@@ -192,11 +206,11 @@ private:
std::vector<std::string> const& defines,
bool dflag = false);
- void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const;
+ void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
protected:
- virtual const char* GetInstallTargetName() const { return "install"; }
- virtual const char* GetPackageTargetName() const { return "package"; }
+ const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
+ const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
unsigned int XcodeVersion;
std::string VersionString;
@@ -211,7 +225,7 @@ private:
bool XcodeBuildCommandInitialized;
void PrintCompilerAdvice(std::ostream&, std::string const&,
- const char*) const
+ const char*) const CM_OVERRIDE
{
}
diff --git a/Source/cmGraphAdjacencyList.h b/Source/cmGraphAdjacencyList.h
index a154373..e6aec47 100644
--- a/Source/cmGraphAdjacencyList.h
+++ b/Source/cmGraphAdjacencyList.h
@@ -3,9 +3,9 @@
#ifndef cmGraphAdjacencyList_h
#define cmGraphAdjacencyList_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <vector>
/**
* Graph edge representation. Most use cases just need the
diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx
index 6b32f73..0f69aaa 100644
--- a/Source/cmGraphVizWriter.cxx
+++ b/Source/cmGraphVizWriter.cxx
@@ -2,21 +2,22 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGraphVizWriter.h"
+#include <cmConfigure.h>
+#include <iostream>
+#include <sstream>
+#include <utility>
+
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <cmConfigure.h>
-#include <iostream>
-#include <sstream>
-#include <utility>
-
static const char* getShapeForTarget(const cmGeneratorTarget* target)
{
if (!target) {
diff --git a/Source/cmHexFileConverter.cxx b/Source/cmHexFileConverter.cxx
index db855d2..d9d6598 100644
--- a/Source/cmHexFileConverter.cxx
+++ b/Source/cmHexFileConverter.cxx
@@ -2,11 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmHexFileConverter.h"
-#include "cmSystemTools.h"
-
+#include <cmConfigure.h>
#include <stdio.h>
#include <string.h>
+#include "cmSystemTools.h"
+
#define INTEL_HEX_MIN_LINE_LENGTH (1 + 8 + 2)
#define INTEL_HEX_MAX_LINE_LENGTH (1 + 8 + (256 * 2) + 2)
#define MOTOROLA_SREC_MIN_LINE_LENGTH (2 + 2 + 4 + 2)
diff --git a/Source/cmHexFileConverter.h b/Source/cmHexFileConverter.h
index cb550bb..1050bc1 100644
--- a/Source/cmHexFileConverter.h
+++ b/Source/cmHexFileConverter.h
@@ -3,10 +3,6 @@
#ifndef cmHexFileConverter_h
#define cmHexFileConverter_h
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
/** \class cmHexFileConverter
* \brief Can detects Intel Hex and Motorola S-record files and convert them
* to binary files.
diff --git a/Source/cmIDEOptions.cxx b/Source/cmIDEOptions.cxx
index 286076f..c6c0e05 100644
--- a/Source/cmIDEOptions.cxx
+++ b/Source/cmIDEOptions.cxx
@@ -2,9 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmIDEOptions.h"
-#include "cmSystemTools.h"
-
#include <cmsys/String.h>
+#include <iterator>
+#include <string.h>
+
+#include "cmIDEFlagTable.h"
+#include "cmSystemTools.h"
cmIDEOptions::cmIDEOptions()
{
diff --git a/Source/cmIDEOptions.h b/Source/cmIDEOptions.h
index 1067c40..a0696e1 100644
--- a/Source/cmIDEOptions.h
+++ b/Source/cmIDEOptions.h
@@ -5,9 +5,11 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <map>
+#include <string>
+#include <vector>
-#include "cmIDEFlagTable.h"
+struct cmIDEFlagTable;
/** \class cmIDEOptions
* \brief Superclass for IDE option processing
diff --git a/Source/cmIncludeCommand.cxx b/Source/cmIncludeCommand.cxx
index 0f7799e..12e0c9a 100644
--- a/Source/cmIncludeCommand.cxx
+++ b/Source/cmIncludeCommand.cxx
@@ -69,7 +69,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
module += ".cmake";
std::string mfile = this->Makefile->GetModulesFile(module.c_str());
if (!mfile.empty()) {
- fname = mfile.c_str();
+ fname = mfile;
}
}
@@ -111,7 +111,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
}
std::string listFile = cmSystemTools::CollapseFullPath(
- fname.c_str(), this->Makefile->GetCurrentSourceDirectory());
+ fname, this->Makefile->GetCurrentSourceDirectory());
if (optional && !cmSystemTools::FileExists(listFile.c_str())) {
if (!resultVarName.empty()) {
this->Makefile->AddDefinition(resultVarName, "NOTFOUND");
diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx
index 7bf9462..fadebb4 100644
--- a/Source/cmInstallCommand.cxx
+++ b/Source/cmInstallCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmInstallCommand.h"
-#include <algorithm>
#include <cmsys/Glob.hxx>
#include <sstream>
#include <stddef.h>
@@ -986,7 +985,7 @@ bool cmInstallCommand::HandleDirectoryMode(
std::ostringstream e;
e << args[0] << " does not allow \"" << args[i]
<< "\" after PATTERN or REGEX.";
- this->SetError(e.str().c_str());
+ this->SetError(e.str());
return false;
}
exclude_from_all = true;
diff --git a/Source/cmInstallCommandArguments.cxx b/Source/cmInstallCommandArguments.cxx
index de6919b..6b15468 100644
--- a/Source/cmInstallCommandArguments.cxx
+++ b/Source/cmInstallCommandArguments.cxx
@@ -2,6 +2,8 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmInstallCommandArguments.h"
+#include <cmConfigure.h>
+
#include "cmSystemTools.h"
// Table of valid permissions.
diff --git a/Source/cmInstallCommandArguments.h b/Source/cmInstallCommandArguments.h
index 82c2310..c1523b2 100644
--- a/Source/cmInstallCommandArguments.h
+++ b/Source/cmInstallCommandArguments.h
@@ -3,9 +3,10 @@
#ifndef cmInstallCommandArguments_h
#define cmInstallCommandArguments_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <string>
+#include <vector>
#include "cmCommandArgumentsHelper.h"
diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx
index f1df073..4dfa40f 100644
--- a/Source/cmInstallTargetGenerator.cxx
+++ b/Source/cmInstallTargetGenerator.cxx
@@ -2,6 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmInstallTargetGenerator.h"
+#include <assert.h>
+#include <map>
+#include <set>
+#include <sstream>
+#include <utility>
+
#include "cmComputeLinkInformation.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
@@ -12,15 +18,8 @@
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <assert.h>
-#include <map>
-#include <set>
-#include <sstream>
-#include <utility>
-
cmInstallTargetGenerator::cmInstallTargetGenerator(
const std::string& targetName, const char* dest, bool implib,
const char* file_permissions, std::vector<std::string> const& configurations,
diff --git a/Source/cmLinkItem.h b/Source/cmLinkItem.h
index 74d6774..6fd6f50 100644
--- a/Source/cmLinkItem.h
+++ b/Source/cmLinkItem.h
@@ -3,8 +3,16 @@
#ifndef cmLinkItem_h
#define cmLinkItem_h
+#include <cmConfigure.h>
+
+#include <algorithm>
+#include <map>
+#include <string>
+#include <vector>
+
#include "cmListFileCache.h"
#include "cmSystemTools.h"
+#include "cmTargetLinkLibraryType.h"
class cmGeneratorTarget;
diff --git a/Source/cmLinkLineComputer.cxx b/Source/cmLinkLineComputer.cxx
index c271246..cf0cf88 100644
--- a/Source/cmLinkLineComputer.cxx
+++ b/Source/cmLinkLineComputer.cxx
@@ -2,10 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmLinkLineComputer.h"
+
+#include <sstream>
+#include <vector>
+
#include "cmComputeLinkInformation.h"
#include "cmGeneratorTarget.h"
#include "cmOutputConverter.h"
#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
cmLinkLineComputer::cmLinkLineComputer(cmOutputConverter* outputConverter,
cmStateDirectory stateDir)
diff --git a/Source/cmLinkLineComputer.h b/Source/cmLinkLineComputer.h
index 6bbb69e..bb13717 100644
--- a/Source/cmLinkLineComputer.h
+++ b/Source/cmLinkLineComputer.h
@@ -4,6 +4,10 @@
#ifndef cmLinkLineComputer_h
#define cmLinkLineComputer_h
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+
#include "cmStateDirectory.h"
class cmComputeLinkInformation;
@@ -29,10 +33,10 @@ public:
std::string ComputeFrameworkPath(cmComputeLinkInformation& cli,
std::string const& fwSearchFlag);
- std::string ComputeLinkLibraries(cmComputeLinkInformation& cli,
- std::string const& stdLibString);
+ virtual std::string ComputeLinkLibraries(cmComputeLinkInformation& cli,
+ std::string const& stdLibString);
-private:
+protected:
std::string ComputeLinkLibs(cmComputeLinkInformation& cli);
std::string ComputeRPath(cmComputeLinkInformation& cli);
diff --git a/Source/cmLinkLineDeviceComputer.cxx b/Source/cmLinkLineDeviceComputer.cxx
new file mode 100644
index 0000000..75e5ef5
--- /dev/null
+++ b/Source/cmLinkLineDeviceComputer.cxx
@@ -0,0 +1,74 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmLinkLineDeviceComputer.h"
+#include "cmComputeLinkInformation.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalNinjaGenerator.h"
+#include "cmOutputConverter.h"
+
+cmLinkLineDeviceComputer::cmLinkLineDeviceComputer(
+ cmOutputConverter* outputConverter, cmStateDirectory stateDir)
+ : cmLinkLineComputer(outputConverter, stateDir)
+{
+}
+
+cmLinkLineDeviceComputer::~cmLinkLineDeviceComputer()
+{
+}
+
+std::string cmLinkLineDeviceComputer::ComputeLinkLibraries(
+ cmComputeLinkInformation& cli, std::string const& stdLibString)
+{
+ // Write the library flags to the build rule.
+ std::ostringstream fout;
+ typedef cmComputeLinkInformation::ItemVector ItemVector;
+ ItemVector const& items = cli.GetItems();
+ std::string config = cli.GetConfig();
+ for (ItemVector::const_iterator li = items.begin(); li != items.end();
+ ++li) {
+ if (!li->Target) {
+ continue;
+ }
+
+ if (li->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
+ li->Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
+ li->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
+ continue;
+ }
+
+ std::set<std::string> langs;
+ li->Target->GetLanguages(langs, config);
+ if (langs.count("CUDA") == 0) {
+ continue;
+ }
+
+ if (li->IsPath) {
+ fout << this->ConvertToOutputFormat(
+ this->ConvertToLinkReference(li->Value));
+ } else {
+ fout << li->Value;
+ }
+ fout << " ";
+ }
+
+ if (!stdLibString.empty()) {
+ fout << stdLibString << " ";
+ }
+
+ return fout.str();
+}
+
+cmNinjaLinkLineDeviceComputer::cmNinjaLinkLineDeviceComputer(
+ cmOutputConverter* outputConverter, cmStateDirectory stateDir,
+ cmGlobalNinjaGenerator const* gg)
+ : cmLinkLineDeviceComputer(outputConverter, stateDir)
+ , GG(gg)
+{
+}
+
+std::string cmNinjaLinkLineDeviceComputer::ConvertToLinkReference(
+ std::string const& lib) const
+{
+ return GG->ConvertToNinjaPath(lib);
+}
diff --git a/Source/cmLinkLineDeviceComputer.h b/Source/cmLinkLineDeviceComputer.h
new file mode 100644
index 0000000..d1079d7
--- /dev/null
+++ b/Source/cmLinkLineDeviceComputer.h
@@ -0,0 +1,36 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#ifndef cmLinkLineDeviceComputer_h
+#define cmLinkLineDeviceComputer_h
+
+#include "cmLinkLineComputer.h"
+class cmGlobalNinjaGenerator;
+
+class cmLinkLineDeviceComputer : public cmLinkLineComputer
+{
+public:
+ cmLinkLineDeviceComputer(cmOutputConverter* outputConverter,
+ cmStateDirectory stateDir);
+ ~cmLinkLineDeviceComputer() CM_OVERRIDE;
+
+ std::string ComputeLinkLibraries(cmComputeLinkInformation& cli,
+ std::string const& stdLibString)
+ CM_OVERRIDE;
+};
+
+class cmNinjaLinkLineDeviceComputer : public cmLinkLineDeviceComputer
+{
+public:
+ cmNinjaLinkLineDeviceComputer(cmOutputConverter* outputConverter,
+ cmStateDirectory stateDir,
+ cmGlobalNinjaGenerator const* gg);
+
+ std::string ConvertToLinkReference(std::string const& input) const
+ CM_OVERRIDE;
+
+private:
+ cmGlobalNinjaGenerator const* GG;
+};
+
+#endif
diff --git a/Source/cmLinkedTree.h b/Source/cmLinkedTree.h
index d2c6f33..4f95522 100644
--- a/Source/cmLinkedTree.h
+++ b/Source/cmLinkedTree.h
@@ -5,9 +5,9 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
-
#include <assert.h>
+#include <iterator>
+#include <vector>
/**
@brief A adaptor for traversing a tree structure in a vector
diff --git a/Source/cmLoadCommandCommand.cxx b/Source/cmLoadCommandCommand.cxx
index e042b07..b6743f1 100644
--- a/Source/cmLoadCommandCommand.cxx
+++ b/Source/cmLoadCommandCommand.cxx
@@ -208,7 +208,7 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
}
// Try to find the program.
- std::string fullPath = cmSystemTools::FindFile(moduleName.c_str(), path);
+ std::string fullPath = cmSystemTools::FindFile(moduleName, path);
if (fullPath == "") {
std::ostringstream e;
e << "Attempt to load command failed from file \"" << moduleName << "\"";
@@ -237,14 +237,14 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
// find the init function
std::string initFuncName = args[0] + "Init";
CM_INIT_FUNCTION initFunction =
- (CM_INIT_FUNCTION)cmsys::DynamicLoader::GetSymbolAddress(
- lib, initFuncName.c_str());
+ (CM_INIT_FUNCTION)cmsys::DynamicLoader::GetSymbolAddress(lib,
+ initFuncName);
if (!initFunction) {
initFuncName = "_";
initFuncName += args[0];
initFuncName += "Init";
initFunction = (CM_INIT_FUNCTION)(
- cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName.c_str()));
+ cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName));
}
// if the symbol is found call it to set the name on the
// function blocker
diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx
index 6b49f1e..d5f9d27 100644
--- a/Source/cmLocalCommonGenerator.cxx
+++ b/Source/cmLocalCommonGenerator.cxx
@@ -2,10 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmLocalCommonGenerator.h"
+#include <vector>
+
#include "cmGeneratorTarget.h"
#include "cmMakefile.h"
-
-#include <vector>
+#include "cmOutputConverter.h"
class cmGlobalGenerator;
diff --git a/Source/cmLocalCommonGenerator.h b/Source/cmLocalCommonGenerator.h
index eb5f850..f83f371 100644
--- a/Source/cmLocalCommonGenerator.h
+++ b/Source/cmLocalCommonGenerator.h
@@ -5,11 +5,10 @@
#include <cmConfigure.h>
-#include "cmLocalGenerator.h"
-#include "cmOutputConverter.h"
-
#include <string>
+#include "cmLocalGenerator.h"
+
class cmGeneratorTarget;
class cmGlobalGenerator;
class cmMakefile;
diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx
index 4aecb1d..46e49dc 100644
--- a/Source/cmLocalGenerator.cxx
+++ b/Source/cmLocalGenerator.cxx
@@ -18,6 +18,7 @@
#include "cmSourceFile.h"
#include "cmState.h"
#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmTestGenerator.h"
@@ -26,16 +27,16 @@
#if defined(CMAKE_BUILD_WITH_CMAKE)
#define CM_LG_ENCODE_OBJECT_NAMES
-#include <cmsys/MD5.h>
+#include "cmCryptoHash.h"
#endif
#include <algorithm>
#include <assert.h>
#include <cmsys/RegularExpression.hxx>
-#include <ctype.h>
#include <iterator>
#include <sstream>
#include <stdio.h>
+#include <string.h>
#include <utility>
#if defined(__HAIKU__)
@@ -62,6 +63,8 @@ static const char* ruleReplaceVars[] = {
"CMAKE_CURRENT_BINARY_DIR",
"CMAKE_RANLIB",
"CMAKE_LINKER",
+ "CMAKE_CUDA_HOST_COMPILER",
+ "CMAKE_CUDA_HOST_LINK_LAUNCHER",
"CMAKE_CL_SHOWINCLUDES_PREFIX"
};
@@ -210,7 +213,14 @@ void cmLocalGenerator::TraceDependencies()
void cmLocalGenerator::GenerateTestFiles()
{
+ std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
+ file += "/";
+ file += "CTestTestfile.cmake";
+
if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
+ if (cmSystemTools::FileExists(file)) {
+ cmSystemTools::RemoveFile(file);
+ }
return;
}
@@ -219,10 +229,6 @@ void cmLocalGenerator::GenerateTestFiles()
const std::string& config =
this->Makefile->GetConfigurations(configurationTypes, false);
- std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
- file += "/";
- file += "CTestTestfile.cmake";
-
cmGeneratedFileStream fout(file.c_str());
fout.SetCopyIfDifferent(true);
@@ -1471,6 +1477,9 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
langStdMap["C"].push_back("11");
langStdMap["C"].push_back("99");
langStdMap["C"].push_back("90");
+
+ langStdMap["CUDA"].push_back("11");
+ langStdMap["CUDA"].push_back("98");
}
std::string standard(standardProp);
@@ -2001,17 +2010,6 @@ void cmLocalGenerator::GenerateTargetInstallRules(
}
#if defined(CM_LG_ENCODE_OBJECT_NAMES)
-static std::string cmLocalGeneratorMD5(const char* input)
-{
- char md5out[32];
- cmsysMD5* md5 = cmsysMD5_New();
- cmsysMD5_Initialize(md5);
- cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(input), -1);
- cmsysMD5_FinalizeHex(md5, md5out);
- cmsysMD5_Delete(md5);
- return std::string(md5out, 32);
-}
-
static bool cmLocalGeneratorShortenObjectName(std::string& objName,
std::string::size_type max_len)
{
@@ -2020,7 +2018,8 @@ static bool cmLocalGeneratorShortenObjectName(std::string& objName,
std::string::size_type pos =
objName.find('/', objName.size() - max_len + 32);
if (pos != objName.npos) {
- std::string md5name = cmLocalGeneratorMD5(objName.substr(0, pos).c_str());
+ cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+ std::string md5name = md5.HashString(objName.substr(0, pos));
md5name += objName.substr(pos);
objName = md5name;
diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h
index 6314aff..fdca78a 100644
--- a/Source/cmLocalGenerator.h
+++ b/Source/cmLocalGenerator.h
@@ -5,29 +5,28 @@
#include <cmConfigure.h>
-#include "cmListFileCache.h"
-#include "cmOutputConverter.h"
-#include "cmPolicies.h"
-#include "cmRulePlaceholderExpander.h"
-#include "cmStateTypes.h"
-#include "cmake.h"
-
#include <cm_kwiml.h>
#include <iosfwd>
#include <map>
#include <set>
-#include <string.h>
#include <string>
#include <vector>
+#include "cmListFileCache.h"
+#include "cmOutputConverter.h"
+#include "cmPolicies.h"
+#include "cmStateSnapshot.h"
+#include "cmake.h"
+
class cmComputeLinkInformation;
class cmCustomCommandGenerator;
class cmGeneratorTarget;
class cmGlobalGenerator;
-class cmRulePlaceholderExpander;
+class cmLinkLineComputer;
class cmMakefile;
+class cmRulePlaceholderExpander;
class cmSourceFile;
-class cmLinkLineComputer;
+class cmState;
/** \class cmLocalGenerator
* \brief Create required build files for a directory.
diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx
index cd9af54..c2d9d57 100644
--- a/Source/cmLocalNinjaGenerator.cxx
+++ b/Source/cmLocalNinjaGenerator.cxx
@@ -2,6 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmLocalNinjaGenerator.h"
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
#include "cmCustomCommand.h"
#include "cmCustomCommandGenerator.h"
#include "cmGeneratedFileStream.h"
@@ -15,15 +22,9 @@
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <iterator>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
cmMakefile* mf)
: cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
@@ -299,15 +300,11 @@ void cmLocalNinjaGenerator::AppendCustomCommandDeps(
std::string cmLocalNinjaGenerator::BuildCommandLine(
const std::vector<std::string>& cmdLines)
{
- // If we have no commands but we need to build a command anyway, use ":".
+ // If we have no commands but we need to build a command anyway, use noop.
// This happens when building a POST_BUILD value for link targets that
// don't use POST_BUILD.
if (cmdLines.empty()) {
-#ifdef _WIN32
- return "cd .";
-#else
- return ":";
-#endif
+ return cmGlobalNinjaGenerator::SHELL_NOOP;
}
std::ostringstream cmd;
diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h
index 95d8eb8..1080319 100644
--- a/Source/cmLocalNinjaGenerator.h
+++ b/Source/cmLocalNinjaGenerator.h
@@ -5,17 +5,16 @@
#include <cmConfigure.h>
-#include "cmLocalCommonGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmNinjaTypes.h"
-#include "cmOutputConverter.h"
-
#include <iosfwd>
#include <map>
#include <set>
#include <string>
#include <vector>
+#include "cmLocalCommonGenerator.h"
+#include "cmNinjaTypes.h"
+#include "cmOutputConverter.h"
+
class cmCustomCommand;
class cmCustomCommandGenerator;
class cmGeneratedFileStream;
@@ -23,6 +22,7 @@ class cmGeneratorTarget;
class cmGlobalGenerator;
class cmGlobalNinjaGenerator;
class cmMakefile;
+class cmRulePlaceholderExpander;
class cmSourceFile;
class cmake;
diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx
index 4f81ef1..ba17f81 100644
--- a/Source/cmLocalUnixMakefileGenerator3.cxx
+++ b/Source/cmLocalUnixMakefileGenerator3.cxx
@@ -2,6 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmLocalUnixMakefileGenerator3.h"
+#include <algorithm>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Terminal.h>
+#include <functional>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
#include "cmAlgorithms.h"
#include "cmCustomCommand.h"
#include "cmCustomCommandGenerator.h"
@@ -18,9 +26,11 @@
#include "cmSourceFile.h"
#include "cmState.h"
#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
// Include dependency scanners for supported languages. Only the
@@ -31,15 +41,6 @@
#include "cmDependsJava.h"
#endif
-#include <algorithm>
-#include <cm_auto_ptr.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Terminal.h>
-#include <functional>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
// Escape special characters in Makefile dependency lines
class cmMakeSafe
{
@@ -284,8 +285,8 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
for (std::vector<LocalObjectEntry>::const_iterator ei = lo->second.begin();
ei != lo->second.end(); ++ei) {
if (ei->Language == "C" || ei->Language == "CXX" ||
- ei->Language == "Fortran") {
- // Right now, C, C++ and Fortran have both a preprocessor and the
+ ei->Language == "CUDA" || ei->Language == "Fortran") {
+ // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
// ability to generate assembly code
lang_has_preprocessor = true;
lang_has_assembly = true;
@@ -1457,7 +1458,8 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies(
// Create the scanner for this language
cmDepends* scanner = CM_NULLPTR;
- if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM") {
+ if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
+ lang == "CUDA") {
// TODO: Handle RC (resource files) dependencies correctly.
scanner = new cmDependsC(this, targetDir, lang, &validDeps);
}
diff --git a/Source/cmLocalVisualStudio10Generator.h b/Source/cmLocalVisualStudio10Generator.h
index 4becfee..1ed57ec 100644
--- a/Source/cmLocalVisualStudio10Generator.h
+++ b/Source/cmLocalVisualStudio10Generator.h
@@ -3,8 +3,15 @@
#ifndef cmLocalVisualStudio10Generator_h
#define cmLocalVisualStudio10Generator_h
+#include <cmConfigure.h>
+
+#include <string>
+
#include "cmLocalVisualStudio7Generator.h"
+class cmGlobalGenerator;
+class cmMakefile;
+
/** \class cmLocalVisualStudio10Generator
* \brief Write Visual Studio 10 project files.
*
diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h
index 6665bb0..d69cce1 100644
--- a/Source/cmLocalVisualStudio7Generator.h
+++ b/Source/cmLocalVisualStudio7Generator.h
@@ -3,17 +3,23 @@
#ifndef cmLocalVisualStudio7Generator_h
#define cmLocalVisualStudio7Generator_h
-#include "cmLocalVisualStudioGenerator.h"
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+#include <vector>
+#include "cmLocalVisualStudioGenerator.h"
#include "cmVisualStudioGeneratorOptions.h"
-class cmSourceFile;
class cmCustomCommand;
-class cmSourceGroup;
-
-class cmLocalVisualStudio7GeneratorOptions;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
class cmLocalVisualStudio7GeneratorFCInfo;
class cmLocalVisualStudio7GeneratorInternals;
+class cmMakefile;
+class cmSourceFile;
+class cmSourceGroup;
/** \class cmLocalVisualStudio7Generator
* \brief Write Visual Studio .NET project files.
@@ -119,6 +125,7 @@ private:
friend class cmLocalVisualStudio7GeneratorInternals;
class EventWriter;
+
friend class EventWriter;
std::string ModuleDefinitionFile;
diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h
index 169ecaf..39188f9 100644
--- a/Source/cmLocalVisualStudioGenerator.h
+++ b/Source/cmLocalVisualStudioGenerator.h
@@ -3,16 +3,22 @@
#ifndef cmLocalVisualStudioGenerator_h
#define cmLocalVisualStudioGenerator_h
-#include "cmLocalGenerator.h"
+#include <cmConfigure.h>
-#include "cmGlobalVisualStudioGenerator.h"
+#include <map>
+#include <memory>
+#include <string>
-#include <cm_auto_ptr.hxx>
+#include "cmGlobalVisualStudioGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cm_auto_ptr.hxx"
-class cmSourceFile;
-class cmSourceGroup;
class cmCustomCommand;
class cmCustomCommandGenerator;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
+class cmSourceFile;
/** \class cmLocalVisualStudioGenerator
* \brief Base class for Visual Studio generators.
diff --git a/Source/cmLocalXCodeGenerator.cxx b/Source/cmLocalXCodeGenerator.cxx
index b596a8f..739ef43 100644
--- a/Source/cmLocalXCodeGenerator.cxx
+++ b/Source/cmLocalXCodeGenerator.cxx
@@ -4,9 +4,12 @@
#include "cmGeneratorTarget.h"
#include "cmGlobalXCodeGenerator.h"
-#include "cmMakefile.h"
#include "cmSourceFile.h"
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
+
cmLocalXCodeGenerator::cmLocalXCodeGenerator(cmGlobalGenerator* gg,
cmMakefile* mf)
: cmLocalGenerator(gg, mf)
diff --git a/Source/cmLocalXCodeGenerator.h b/Source/cmLocalXCodeGenerator.h
index 3756b61..b4a8c6c 100644
--- a/Source/cmLocalXCodeGenerator.h
+++ b/Source/cmLocalXCodeGenerator.h
@@ -3,8 +3,17 @@
#ifndef cmLocalXCodeGenerator_h
#define cmLocalXCodeGenerator_h
+#include <cmConfigure.h> // IWYU pragma: keep
+#include <map>
+#include <string>
+
#include "cmLocalGenerator.h"
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
+class cmSourceFile;
+
/** \class cmLocalXCodeGenerator
* \brief Write a local Xcode project
*
diff --git a/Source/cmLocale.h b/Source/cmLocale.h
index f35e528..e8e751d 100644
--- a/Source/cmLocale.h
+++ b/Source/cmLocale.h
@@ -5,8 +5,6 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
-
#include <locale.h>
class cmLocaleRAII
diff --git a/Source/cmMSVC60LinkLineComputer.cxx b/Source/cmMSVC60LinkLineComputer.cxx
index 9308d91..d761e7b 100644
--- a/Source/cmMSVC60LinkLineComputer.cxx
+++ b/Source/cmMSVC60LinkLineComputer.cxx
@@ -3,7 +3,13 @@
#include "cmMSVC60LinkLineComputer.h"
+#include "cmStateDirectory.h"
+
+#if defined(_WIN32) && !defined(__CYGWIN__)
#include "cmSystemTools.h"
+#endif
+
+class cmOutputConverter;
cmMSVC60LinkLineComputer::cmMSVC60LinkLineComputer(
cmOutputConverter* outputConverter, cmStateDirectory stateDir)
diff --git a/Source/cmMSVC60LinkLineComputer.h b/Source/cmMSVC60LinkLineComputer.h
index 381b8a2..9a28dca 100644
--- a/Source/cmMSVC60LinkLineComputer.h
+++ b/Source/cmMSVC60LinkLineComputer.h
@@ -4,8 +4,15 @@
#ifndef cmMSVC60LinkLineComputer_h
#define cmMSVC60LinkLineComputer_h
+#include <cmConfigure.h>
+
+#include <string>
+
#include "cmLinkLineComputer.h"
+class cmOutputConverter;
+class cmStateDirectory;
+
class cmMSVC60LinkLineComputer : public cmLinkLineComputer
{
public:
diff --git a/Source/cmMachO.cxx b/Source/cmMachO.cxx
index 95518f9..586e6c6 100644
--- a/Source/cmMachO.cxx
+++ b/Source/cmMachO.cxx
@@ -1,10 +1,12 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmStandardIncludes.h" // to get CMAKE_USE_MACH_PARSER first
-
#include "cmMachO.h"
+#include <algorithm>
#include <cmsys/FStream.hxx>
+#include <stddef.h>
+#include <string>
+#include <vector>
// Include the Mach-O format information system header.
#include <mach-o/fat.h>
diff --git a/Source/cmMachO.h b/Source/cmMachO.h
index a754c1f..901f17a 100644
--- a/Source/cmMachO.h
+++ b/Source/cmMachO.h
@@ -3,6 +3,11 @@
#ifndef cmMachO_h
#define cmMachO_h
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
#if !defined(CMAKE_USE_MACH_PARSER)
#error "This file may be included only if CMAKE_USE_MACH_PARSER is enabled."
#endif
diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx
index d777bd5..583f801 100644
--- a/Source/cmMacroCommand.cxx
+++ b/Source/cmMacroCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMacroCommand.h"
-#include <algorithm>
#include <sstream>
#include <stdio.h>
diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx
index 741ffb8..fecc983 100644
--- a/Source/cmMakefile.cxx
+++ b/Source/cmMakefile.cxx
@@ -2,6 +2,16 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMakefile.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <ctype.h>
+#include <sstream>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
+
#include "cmAlgorithms.h"
#include "cmCommand.h"
#include "cmCommandArgumentParserHelper.h"
@@ -14,6 +24,7 @@
#include "cmGeneratorExpression.h"
#include "cmGeneratorExpressionEvaluationFile.h"
#include "cmGlobalGenerator.h"
+#include "cmInstallGenerator.h" // IWYU pragma: keep
#include "cmListFileCache.h"
#include "cmSourceFile.h"
#include "cmSourceFileLocation.h"
@@ -21,28 +32,17 @@
#include "cmStateDirectory.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cmTargetLinkLibraryType.h"
#include "cmTest.h"
+#include "cmTestGenerator.h" // IWYU pragma: keep
#include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include "cmInstallGenerator.h" // IWYU pragma: keep
-#include "cmTestGenerator.h" // IWYU pragma: keep
-
#ifdef CMAKE_BUILD_WITH_CMAKE
#include "cmVariableWatch.h"
#endif
-#include <algorithm>
-#include <assert.h>
-#include <cm_auto_ptr.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/RegularExpression.hxx>
-#include <ctype.h>
-#include <sstream>
-#include <stdlib.h>
-#include <string.h>
-#include <utility>
-
class cmMessenger;
// default is not to be building executables
@@ -4413,10 +4413,13 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
if (setCxx14) {
target->SetProperty("CXX_STANDARD", "14");
+ target->SetProperty("CUDA_STANDARD", "14");
} else if (setCxx11) {
target->SetProperty("CXX_STANDARD", "11");
+ target->SetProperty("CUDA_STANDARD", "11");
} else if (setCxx98) {
target->SetProperty("CXX_STANDARD", "98");
+ target->SetProperty("CUDA_STANDARD", "98");
}
return true;
}
diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h
index 3067f2c..859b3c8 100644
--- a/Source/cmMakefile.h
+++ b/Source/cmMakefile.h
@@ -5,13 +5,21 @@
#include <cmConfigure.h>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <set>
+#include <stack>
+#include <string>
+#include <vector>
+
#include "cmAlgorithms.h"
#include "cmListFileCache.h"
#include "cmNewLineStyle.h"
#include "cmPolicies.h"
#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
#include "cmTarget.h"
-#include "cmTargetLinkLibraryType.h"
+#include "cm_auto_ptr.hxx"
#include "cm_unordered_map.hxx"
#include "cmake.h"
@@ -19,15 +27,6 @@
#include "cmSourceGroup.h"
#endif
-#include <cm_auto_ptr.hxx>
-#include <cmsys/RegularExpression.hxx>
-
-#include <map>
-#include <set>
-#include <stack>
-#include <string>
-#include <vector>
-
class cmCommand;
class cmCompiledGeneratorExpression;
class cmCustomCommandLines;
@@ -40,6 +39,7 @@ class cmGlobalGenerator;
class cmInstallGenerator;
class cmMessenger;
class cmSourceFile;
+class cmState;
class cmTest;
class cmTestGenerator;
class cmVariableWatch;
diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx
index cbbd2e6..069011d 100644
--- a/Source/cmMakefileExecutableTargetGenerator.cxx
+++ b/Source/cmMakefileExecutableTargetGenerator.cxx
@@ -2,10 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMakefileExecutableTargetGenerator.h"
+#include <sstream>
+#include <string>
+#include <vector>
+
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalUnixMakefileGenerator3.h"
#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
#include "cmLocalGenerator.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
@@ -13,13 +18,12 @@
#include "cmOutputConverter.h"
#include "cmRulePlaceholderExpander.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <sstream>
-#include <string>
-#include <vector>
-
cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator(
cmGeneratorTarget* target)
: cmMakefileTargetGenerator(target)
@@ -53,6 +57,9 @@ void cmMakefileExecutableTargetGenerator::WriteRuleFiles()
// write in rules for object files and custom commands
this->WriteTargetBuildRules();
+ // write the device link rules
+ this->WriteDeviceExecutableRule(false);
+
// write the link rules
this->WriteExecutableRule(false);
if (this->GeneratorTarget->NeedRelinkBeforeInstall(this->ConfigName)) {
@@ -74,6 +81,218 @@ void cmMakefileExecutableTargetGenerator::WriteRuleFiles()
this->CloseFileStreams();
}
+void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule(
+ bool relink)
+{
+#ifdef CMAKE_BUILD_WITH_CMAKE
+ const std::string cuda_lang("CUDA");
+ cmGeneratorTarget::LinkClosure const* closure =
+ this->GeneratorTarget->GetLinkClosure(this->ConfigName);
+
+ const bool hasCUDA =
+ (std::find(closure->Languages.begin(), closure->Languages.end(),
+ cuda_lang) != closure->Languages.end());
+ if (!hasCUDA) {
+ return;
+ }
+
+ std::vector<std::string> commands;
+
+ // Build list of dependencies.
+ std::vector<std::string> depends;
+ this->AppendLinkDepends(depends);
+
+ // Get the language to use for linking this library.
+ std::string linkLanguage = "CUDA";
+
+ // Get the name of the device object to generate.
+ std::string const targetOutputReal =
+ this->GeneratorTarget->ObjectDirectory + "cmake_device_link.o";
+ this->DeviceLinkObject = targetOutputReal;
+
+ this->NumberOfProgressActions++;
+ if (!this->NoRuleMessages) {
+ cmLocalUnixMakefileGenerator3::EchoProgress progress;
+ this->MakeEchoProgress(progress);
+ // Add the link message.
+ std::string buildEcho = "Linking ";
+ buildEcho += linkLanguage;
+ buildEcho += " device code ";
+ buildEcho += targetOutputReal;
+ this->LocalGenerator->AppendEcho(
+ commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
+ }
+
+ // Build a list of compiler flags and linker flags.
+ std::string flags;
+ std::string linkFlags;
+
+ // Add flags to create an executable.
+ // Add symbol export flags if necessary.
+ if (this->GeneratorTarget->IsExecutableWithExports()) {
+ std::string export_flag_var = "CMAKE_EXE_EXPORTS_";
+ export_flag_var += linkLanguage;
+ export_flag_var += "_FLAG";
+ this->LocalGenerator->AppendFlags(
+ linkFlags, this->Makefile->GetDefinition(export_flag_var));
+ }
+
+ this->LocalGenerator->AppendFlags(linkFlags,
+ this->LocalGenerator->GetLinkLibsCMP0065(
+ linkLanguage, *this->GeneratorTarget));
+
+ // Add language feature flags.
+ this->AddFeatureFlags(flags, linkLanguage);
+
+ this->LocalGenerator->AddArchitectureFlags(flags, this->GeneratorTarget,
+ linkLanguage, this->ConfigName);
+
+ // Add target-specific linker flags.
+ this->LocalGenerator->AppendFlags(
+ linkFlags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
+ std::string linkFlagsConfig = "LINK_FLAGS_";
+ linkFlagsConfig += cmSystemTools::UpperCase(this->ConfigName);
+ this->LocalGenerator->AppendFlags(
+ linkFlags, this->GeneratorTarget->GetProperty(linkFlagsConfig));
+
+ {
+ CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ this->CreateLinkLineComputer(
+ this->LocalGenerator,
+ this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+
+ this->AddModuleDefinitionFlag(linkLineComputer.get(), linkFlags);
+ }
+
+ // Construct a list of files associated with this executable that
+ // may need to be cleaned.
+ std::vector<std::string> exeCleanFiles;
+ exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal));
+
+ // Determine whether a link script will be used.
+ bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
+
+ // Construct the main link rule.
+ std::vector<std::string> real_link_commands;
+ const std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE";
+ const std::string linkRule = this->GetLinkRule(linkRuleVar);
+ std::vector<std::string> commands1;
+ cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
+
+ bool useResponseFileForObjects =
+ this->CheckUseResponseFileForObjects(linkLanguage);
+ bool const useResponseFileForLibs =
+ this->CheckUseResponseFileForLibraries(linkLanguage);
+
+ // Expand the rule variables.
+ {
+ bool useWatcomQuote =
+ this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
+
+ // Set path conversion for link script shells.
+ this->LocalGenerator->SetLinkScriptShell(useLinkScript);
+
+ CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ new cmLinkLineDeviceComputer(
+ this->LocalGenerator,
+ this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+ linkLineComputer->SetForResponse(useResponseFileForLibs);
+ linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+ linkLineComputer->SetRelink(relink);
+
+ // Collect up flags to link in needed libraries.
+ std::string linkLibs;
+ this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
+ useResponseFileForLibs, depends);
+
+ // Construct object file lists that may be needed to expand the
+ // rule.
+ std::string buildObjs;
+ this->CreateObjectLists(useLinkScript, false, useResponseFileForObjects,
+ buildObjs, depends, useWatcomQuote);
+
+ cmRulePlaceholderExpander::RuleVariables vars;
+ std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
+
+ objectDir = this->LocalGenerator->ConvertToOutputFormat(
+ this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+ cmOutputConverter::SHELL);
+
+ cmOutputConverter::OutputFormat output = (useWatcomQuote)
+ ? cmOutputConverter::WATCOMQUOTE
+ : cmOutputConverter::SHELL;
+ std::string target = this->LocalGenerator->ConvertToOutputFormat(
+ this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal),
+ output);
+
+ vars.Language = linkLanguage.c_str();
+ vars.Objects = buildObjs.c_str();
+ vars.ObjectDir = objectDir.c_str();
+ vars.Target = target.c_str();
+ vars.LinkLibraries = linkLibs.c_str();
+ vars.Flags = flags.c_str();
+ vars.LinkFlags = linkFlags.c_str();
+
+ std::string launcher;
+
+ const char* val = this->LocalGenerator->GetRuleLauncher(
+ this->GeneratorTarget, "RULE_LAUNCH_LINK");
+ if (val && *val) {
+ launcher = val;
+ launcher += " ";
+ }
+
+ CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ this->LocalGenerator->CreateRulePlaceholderExpander());
+
+ // Expand placeholders in the commands.
+ rulePlaceholderExpander->SetTargetImpLib(targetOutputReal);
+ for (std::vector<std::string>::iterator i = real_link_commands.begin();
+ i != real_link_commands.end(); ++i) {
+ *i = launcher + *i;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+ vars);
+ }
+
+ // Restore path conversion to normal shells.
+ this->LocalGenerator->SetLinkScriptShell(false);
+ }
+
+ // Optionally convert the build rule to use a script to avoid long
+ // command lines in the make shell.
+ if (useLinkScript) {
+ // Use a link script.
+ const char* name = (relink ? "drelink.txt" : "dlink.txt");
+ this->CreateLinkScript(name, real_link_commands, commands1, depends);
+ } else {
+ // No link script. Just use the link rule directly.
+ commands1 = real_link_commands;
+ }
+ this->LocalGenerator->CreateCDCommand(
+ commands1, this->Makefile->GetCurrentBinaryDirectory(),
+ this->LocalGenerator->GetBinaryDirectory());
+ commands.insert(commands.end(), commands1.begin(), commands1.end());
+ commands1.clear();
+
+ // Write the build rule.
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ targetOutputReal, depends, commands,
+ false);
+
+ // Write the main driver rule to build everything in this target.
+ this->WriteTargetDriverRule(targetOutputReal, relink);
+
+ // Clean all the possible executable names and symlinks.
+ this->CleanFiles.insert(this->CleanFiles.end(), exeCleanFiles.begin(),
+ exeCleanFiles.end());
+#else
+ static_cast<void>(relink);
+#endif
+}
+
void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
{
std::vector<std::string> commands;
@@ -81,6 +300,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
// Build list of dependencies.
std::vector<std::string> depends;
this->AppendLinkDepends(depends);
+ if (!this->DeviceLinkObject.empty()) {
+ depends.push_back(this->DeviceLinkObject);
+ }
// Get the name of the executable to generate.
std::string targetName;
@@ -324,6 +546,14 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
std::string buildObjs;
this->CreateObjectLists(useLinkScript, false, useResponseFileForObjects,
buildObjs, depends, useWatcomQuote);
+ if (!this->DeviceLinkObject.empty()) {
+ buildObjs += " " +
+ this->LocalGenerator->ConvertToOutputFormat(
+ this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(),
+ this->DeviceLinkObject),
+ cmOutputConverter::SHELL);
+ }
// maybe create .def file from list of objects
if (this->GeneratorTarget->IsExecutableWithExports() &&
diff --git a/Source/cmMakefileExecutableTargetGenerator.h b/Source/cmMakefileExecutableTargetGenerator.h
index 36cfe40..642182b 100644
--- a/Source/cmMakefileExecutableTargetGenerator.h
+++ b/Source/cmMakefileExecutableTargetGenerator.h
@@ -21,6 +21,10 @@ public:
protected:
virtual void WriteExecutableRule(bool relink);
+ virtual void WriteDeviceExecutableRule(bool relink);
+
+private:
+ std::string DeviceLinkObject;
};
#endif
diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx
index a249efd..2b0e1b1 100644
--- a/Source/cmMakefileLibraryTargetGenerator.cxx
+++ b/Source/cmMakefileLibraryTargetGenerator.cxx
@@ -2,10 +2,16 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMakefileLibraryTargetGenerator.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <sstream>
+#include <vector>
+
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalUnixMakefileGenerator3.h"
#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
#include "cmLocalGenerator.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
@@ -13,13 +19,13 @@
#include "cmOutputConverter.h"
#include "cmRulePlaceholderExpander.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <sstream>
-#include <vector>
-
cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
cmGeneratorTarget* target)
: cmMakefileTargetGenerator(target)
@@ -146,6 +152,24 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
this->WriteFrameworkRules(relink);
return;
}
+
+ if (!relink) {
+ const std::string cuda_lang("CUDA");
+ cmGeneratorTarget::LinkClosure const* closure =
+ this->GeneratorTarget->GetLinkClosure(this->ConfigName);
+
+ const bool hasCUDA =
+ (std::find(closure->Languages.begin(), closure->Languages.end(),
+ cuda_lang) != closure->Languages.end());
+ if (hasCUDA) {
+ std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
+ std::string extraFlags;
+ this->LocalGenerator->AppendFlags(
+ extraFlags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
+ this->WriteDeviceLibraryRules(linkRuleVar, extraFlags, relink);
+ }
+ }
+
std::string linkLanguage =
this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
std::string linkRuleVar = "CMAKE_";
@@ -178,6 +202,24 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
{
+
+ if (!relink) {
+ const std::string cuda_lang("CUDA");
+ cmGeneratorTarget::LinkClosure const* closure =
+ this->GeneratorTarget->GetLinkClosure(this->ConfigName);
+
+ const bool hasCUDA =
+ (std::find(closure->Languages.begin(), closure->Languages.end(),
+ cuda_lang) != closure->Languages.end());
+ if (hasCUDA) {
+ std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
+ std::string extraFlags;
+ this->LocalGenerator->AppendFlags(
+ extraFlags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
+ this->WriteDeviceLibraryRules(linkRuleVar, extraFlags, relink);
+ }
+ }
+
std::string linkLanguage =
this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
std::string linkRuleVar = "CMAKE_";
@@ -225,6 +267,180 @@ void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink)
this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
}
+void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
+ const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
+{
+#ifdef CMAKE_BUILD_WITH_CMAKE
+ // TODO: Merge the methods that call this method to avoid
+ // code duplication.
+ std::vector<std::string> commands;
+
+ // Build list of dependencies.
+ std::vector<std::string> depends;
+ this->AppendLinkDepends(depends);
+
+ // Get the language to use for linking this library.
+ std::string linkLanguage = "CUDA";
+
+ // Create set of linking flags.
+ std::string linkFlags;
+ this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
+
+ // Get the name of the device object to generate.
+ std::string const targetOutputReal =
+ this->GeneratorTarget->ObjectDirectory + "cmake_device_link.o";
+ this->DeviceLinkObject = targetOutputReal;
+
+ this->NumberOfProgressActions++;
+ if (!this->NoRuleMessages) {
+ cmLocalUnixMakefileGenerator3::EchoProgress progress;
+ this->MakeEchoProgress(progress);
+ // Add the link message.
+ std::string buildEcho = "Linking " + linkLanguage + " device code";
+ buildEcho += targetOutputReal;
+ this->LocalGenerator->AppendEcho(
+ commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
+ }
+ // Clean files associated with this library.
+ std::vector<std::string> libCleanFiles;
+ libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal));
+
+ // Determine whether a link script will be used.
+ bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
+
+ bool useResponseFileForObjects =
+ this->CheckUseResponseFileForObjects(linkLanguage);
+ bool const useResponseFileForLibs =
+ this->CheckUseResponseFileForLibraries(linkLanguage);
+
+ cmRulePlaceholderExpander::RuleVariables vars;
+ vars.Language = linkLanguage.c_str();
+
+ // Expand the rule variables.
+ std::vector<std::string> real_link_commands;
+ {
+ bool useWatcomQuote =
+ this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
+
+ // Set path conversion for link script shells.
+ this->LocalGenerator->SetLinkScriptShell(useLinkScript);
+
+ // Collect up flags to link in needed libraries.
+ std::string linkLibs;
+ if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
+
+ CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ new cmLinkLineDeviceComputer(
+ this->LocalGenerator,
+ this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+ linkLineComputer->SetForResponse(useResponseFileForLibs);
+ linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+ linkLineComputer->SetRelink(relink);
+
+ this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
+ useResponseFileForLibs, depends);
+ }
+
+ // Construct object file lists that may be needed to expand the
+ // rule.
+ std::string buildObjs;
+ this->CreateObjectLists(useLinkScript, false, // useArchiveRules
+ useResponseFileForObjects, buildObjs, depends,
+ useWatcomQuote);
+
+ cmOutputConverter::OutputFormat output = (useWatcomQuote)
+ ? cmOutputConverter::WATCOMQUOTE
+ : cmOutputConverter::SHELL;
+
+ std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
+ objectDir = this->LocalGenerator->ConvertToOutputFormat(
+ this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+ cmOutputConverter::SHELL);
+
+ std::string target = this->LocalGenerator->ConvertToOutputFormat(
+ this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal),
+ output);
+
+ vars.Objects = buildObjs.c_str();
+ vars.ObjectDir = objectDir.c_str();
+ vars.Target = target.c_str();
+ vars.LinkLibraries = linkLibs.c_str();
+ vars.ObjectsQuoted = buildObjs.c_str();
+ vars.LinkFlags = linkFlags.c_str();
+
+ // Add language feature flags.
+ std::string langFlags;
+ this->AddFeatureFlags(langFlags, linkLanguage);
+
+ vars.LanguageCompileFlags = langFlags.c_str();
+
+ std::string launcher;
+ const char* val = this->LocalGenerator->GetRuleLauncher(
+ this->GeneratorTarget, "RULE_LAUNCH_LINK");
+ if (val && *val) {
+ launcher = val;
+ launcher += " ";
+ }
+
+ CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ this->LocalGenerator->CreateRulePlaceholderExpander());
+
+ // Construct the main link rule and expand placeholders.
+ rulePlaceholderExpander->SetTargetImpLib(targetOutputReal);
+ std::string linkRule = this->GetLinkRule(linkRuleVar);
+ cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
+
+ // Expand placeholders.
+ for (std::vector<std::string>::iterator i = real_link_commands.begin();
+ i != real_link_commands.end(); ++i) {
+ *i = launcher + *i;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+ vars);
+ }
+ // Restore path conversion to normal shells.
+ this->LocalGenerator->SetLinkScriptShell(false);
+
+ // Clean all the possible library names and symlinks.
+ this->CleanFiles.insert(this->CleanFiles.end(), libCleanFiles.begin(),
+ libCleanFiles.end());
+ }
+
+ std::vector<std::string> commands1;
+ // Optionally convert the build rule to use a script to avoid long
+ // command lines in the make shell.
+ if (useLinkScript) {
+ // Use a link script.
+ const char* name = (relink ? "drelink.txt" : "dlink.txt");
+ this->CreateLinkScript(name, real_link_commands, commands1, depends);
+ } else {
+ // No link script. Just use the link rule directly.
+ commands1 = real_link_commands;
+ }
+ this->LocalGenerator->CreateCDCommand(
+ commands1, this->Makefile->GetCurrentBinaryDirectory(),
+ this->LocalGenerator->GetBinaryDirectory());
+ commands.insert(commands.end(), commands1.begin(), commands1.end());
+ commands1.clear();
+
+ // Compute the list of outputs.
+ std::vector<std::string> outputs(1, targetOutputReal);
+
+ // Write the build rule.
+ this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+ commands, false);
+
+ // Write the main driver rule to build everything in this target.
+ this->WriteTargetDriverRule(targetOutputReal, relink);
+#else
+ static_cast<void>(linkRuleVar);
+ static_cast<void>(extraFlags);
+ static_cast<void>(relink);
+#endif
+}
+
void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
{
@@ -235,6 +451,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
// Build list of dependencies.
std::vector<std::string> depends;
this->AppendLinkDepends(depends);
+ if (!this->DeviceLinkObject.empty()) {
+ depends.push_back(this->DeviceLinkObject);
+ }
// Get the language to use for linking this library.
std::string linkLanguage =
@@ -513,6 +732,14 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
this->CreateObjectLists(useLinkScript, useArchiveRules,
useResponseFileForObjects, buildObjs, depends,
useWatcomQuote);
+ if (!this->DeviceLinkObject.empty()) {
+ buildObjs += " " +
+ this->LocalGenerator->ConvertToOutputFormat(
+ this->LocalGenerator->MaybeConvertToRelativePath(
+ this->LocalGenerator->GetCurrentBinaryDirectory(),
+ this->DeviceLinkObject),
+ cmOutputConverter::SHELL);
+ }
// maybe create .def file from list of objects
if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY &&
diff --git a/Source/cmMakefileLibraryTargetGenerator.h b/Source/cmMakefileLibraryTargetGenerator.h
index dda41b8..93ce902 100644
--- a/Source/cmMakefileLibraryTargetGenerator.h
+++ b/Source/cmMakefileLibraryTargetGenerator.h
@@ -26,6 +26,9 @@ protected:
void WriteStaticLibraryRules();
void WriteSharedLibraryRules(bool relink);
void WriteModuleLibraryRules(bool relink);
+
+ void WriteDeviceLibraryRules(const std::string& linkRule,
+ const std::string& extraFlags, bool relink);
void WriteLibraryRules(const std::string& linkRule,
const std::string& extraFlags, bool relink);
// MacOSX Framework support methods
@@ -33,6 +36,9 @@ protected:
// Store the computd framework version for OS X Frameworks.
std::string FrameworkVersion;
+
+private:
+ std::string DeviceLinkObject;
};
#endif
diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx
index 68aabef..6906a90 100644
--- a/Source/cmMakefileTargetGenerator.cxx
+++ b/Source/cmMakefileTargetGenerator.cxx
@@ -2,6 +2,10 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMakefileTargetGenerator.h"
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
#include "cmCustomCommand.h"
@@ -10,8 +14,6 @@
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLinkLineComputer.h"
-#include "cmLocalGenerator.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmMakefileExecutableTargetGenerator.h"
@@ -21,17 +23,13 @@
#include "cmRulePlaceholderExpander.h"
#include "cmSourceFile.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <algorithm>
-#include <ctype.h>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
#ifndef _WIN32
#include <unistd.h>
#endif
@@ -522,8 +520,15 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
targetFullPathCompilePDB =
this->GeneratorTarget->GetCompilePDBPath(this->ConfigName);
if (targetFullPathCompilePDB.empty()) {
+ // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
+ // A trailing slash tells the toolchain to add its default file name.
targetFullPathCompilePDB =
this->GeneratorTarget->GetSupportDirectory() + "/";
+ if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
+ // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
+ targetFullPathCompilePDB += this->GeneratorTarget->GetName();
+ targetFullPathCompilePDB += ".pdb";
+ }
}
}
@@ -585,11 +590,11 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
std::string const includesString = "$(" + lang + "_INCLUDES)";
vars.Includes = includesString.c_str();
- // At the moment, it is assumed that C, C++, and Fortran have both
+ // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
// assembly and preprocessor capabilities. The same is true for the
// ability to export compile commands
- bool lang_has_preprocessor =
- ((lang == "C") || (lang == "CXX") || (lang == "Fortran"));
+ bool lang_has_preprocessor = ((lang == "C") || (lang == "CXX") ||
+ (lang == "Fortran") || (lang == "CUDA"));
bool const lang_has_assembly = lang_has_preprocessor;
bool const lang_can_export_cmds = lang_has_preprocessor;
@@ -598,13 +603,22 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
// Construct the compile rules.
{
- std::string compileRuleVar = "CMAKE_";
- compileRuleVar += lang;
- compileRuleVar += "_COMPILE_OBJECT";
- std::string compileRule =
- this->Makefile->GetRequiredDefinition(compileRuleVar);
std::vector<std::string> compileCommands;
- cmSystemTools::ExpandListArgument(compileRule, compileCommands);
+ if (lang == "CUDA") {
+ std::string cmdVar;
+ if (this->GeneratorTarget->GetProperty("CUDA_SEPARABLE_COMPILATION")) {
+ cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
+ } else {
+ cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
+ }
+ std::string compileRule = this->Makefile->GetRequiredDefinition(cmdVar);
+ cmSystemTools::ExpandListArgument(compileRule, compileCommands);
+ } else {
+ const std::string cmdVar =
+ std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
+ std::string compileRule = this->Makefile->GetRequiredDefinition(cmdVar);
+ cmSystemTools::ExpandListArgument(compileRule, compileCommands);
+ }
if (this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS") &&
lang_can_export_cmds && compileCommands.size() == 1) {
diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h
index e44f64a..347f9f2 100644
--- a/Source/cmMakefileTargetGenerator.h
+++ b/Source/cmMakefileTargetGenerator.h
@@ -5,22 +5,24 @@
#include <cmConfigure.h>
-#include "cmCommonTargetGenerator.h"
-#include "cmLocalUnixMakefileGenerator3.h"
-#include "cmOSXBundleGenerator.h"
-
#include <iosfwd>
#include <map>
#include <set>
#include <string>
#include <vector>
+#include "cmCommonTargetGenerator.h"
+#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmOSXBundleGenerator.h"
+
class cmCustomCommandGenerator;
class cmGeneratedFileStream;
class cmGeneratorTarget;
class cmGlobalUnixMakefileGenerator3;
-class cmSourceFile;
class cmLinkLineComputer;
+class cmOutputConverter;
+class cmSourceFile;
+class cmStateDirectory;
/** \class cmMakefileTargetGenerator
* \brief Support Routines for writing makefiles
diff --git a/Source/cmMakefileUtilityTargetGenerator.cxx b/Source/cmMakefileUtilityTargetGenerator.cxx
index ecb29cb..a7c5d27 100644
--- a/Source/cmMakefileUtilityTargetGenerator.cxx
+++ b/Source/cmMakefileUtilityTargetGenerator.cxx
@@ -2,17 +2,17 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMakefileUtilityTargetGenerator.h"
+#include <ostream>
+#include <string>
+#include <vector>
+
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalUnixMakefileGenerator3.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmOSXBundleGenerator.h"
-#include "cmOutputConverter.h"
-
-#include <ostream>
-#include <string>
-#include <vector>
+#include "cmSystemTools.h"
cmMakefileUtilityTargetGenerator::cmMakefileUtilityTargetGenerator(
cmGeneratorTarget* target)
diff --git a/Source/cmMessageCommand.cxx b/Source/cmMessageCommand.cxx
index 2e15720..43fb5f5 100644
--- a/Source/cmMessageCommand.cxx
+++ b/Source/cmMessageCommand.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMessageCommand.h"
-#include <algorithm>
-
#include "cmAlgorithms.h"
#include "cmMakefile.h"
#include "cmMessenger.h"
diff --git a/Source/cmNinjaLinkLineComputer.cxx b/Source/cmNinjaLinkLineComputer.cxx
index fa9df6d..2546b55 100644
--- a/Source/cmNinjaLinkLineComputer.cxx
+++ b/Source/cmNinjaLinkLineComputer.cxx
@@ -2,7 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmNinjaLinkLineComputer.h"
+
#include "cmGlobalNinjaGenerator.h"
+#include "cmStateDirectory.h"
+
+class cmOutputConverter;
cmNinjaLinkLineComputer::cmNinjaLinkLineComputer(
cmOutputConverter* outputConverter, cmStateDirectory stateDir,
diff --git a/Source/cmNinjaLinkLineComputer.h b/Source/cmNinjaLinkLineComputer.h
index daecea4..ff0771b 100644
--- a/Source/cmNinjaLinkLineComputer.h
+++ b/Source/cmNinjaLinkLineComputer.h
@@ -4,10 +4,15 @@
#ifndef cmNinjaLinkLineComputer_h
#define cmNinjaLinkLineComputer_h
+#include <cmConfigure.h>
+
+#include <string>
+
#include "cmLinkLineComputer.h"
-#include "cmState.h"
class cmGlobalNinjaGenerator;
+class cmOutputConverter;
+class cmStateDirectory;
class cmNinjaLinkLineComputer : public cmLinkLineComputer
{
diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx
index 11773f9..6c5b2b2 100644
--- a/Source/cmNinjaNormalTargetGenerator.cxx
+++ b/Source/cmNinjaNormalTargetGenerator.cxx
@@ -2,6 +2,15 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmNinjaNormalTargetGenerator.h"
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <limits>
+#include <map>
+#include <set>
+#include <sstream>
+#include <stddef.h>
+
#include "cmAlgorithms.h"
#include "cmCustomCommand.h"
#include "cmCustomCommandGenerator.h"
@@ -9,6 +18,7 @@
#include "cmGeneratorTarget.h"
#include "cmGlobalNinjaGenerator.h"
#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
#include "cmLocalGenerator.h"
#include "cmLocalNinjaGenerator.h"
#include "cmMakefile.h"
@@ -18,19 +28,13 @@
#include "cmRulePlaceholderExpander.h"
#include "cmSourceFile.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <iterator>
-#include <limits>
-#include <map>
-#include <set>
-#include <sstream>
-#include <stddef.h>
-
#ifndef _WIN32
#include <unistd.h>
#endif
@@ -44,6 +48,7 @@ cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
, TargetNameImport()
, TargetNamePDB()
, TargetLinkLanguage("")
+ , DeviceLinkObject()
{
this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
if (target->GetType() == cmStateEnums::EXECUTABLE) {
@@ -91,6 +96,9 @@ void cmNinjaNormalTargetGenerator::Generate()
if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
this->WriteObjectLibStatement();
} else {
+ // If this target has cuda language link inputs, and we need to do
+ // device linking
+ this->WriteDeviceLinkStatement();
this->WriteLinkStatement();
}
}
@@ -152,6 +160,14 @@ std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
this->GetGeneratorTarget()->GetName());
}
+std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule() const
+{
+ return this->TargetLinkLanguage + "_" +
+ cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
+ "_DEVICE_LINKER__" + cmGlobalNinjaGenerator::EncodeRuleName(
+ this->GetGeneratorTarget()->GetName());
+}
+
struct cmNinjaRemoveNoOpCommands
{
bool operator()(std::string const& cmd)
@@ -160,6 +176,115 @@ struct cmNinjaRemoveNoOpCommands
}
};
+void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile)
+{
+ cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
+ std::string ruleName = this->LanguageLinkerDeviceRule();
+ // Select whether to use a response file for objects.
+ std::string rspfile;
+ std::string rspcontent;
+
+ if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
+ cmRulePlaceholderExpander::RuleVariables vars;
+ vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
+ vars.CMTargetType =
+ cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
+
+ vars.Language = "CUDA";
+
+ std::string responseFlag;
+ if (!useResponseFile) {
+ vars.Objects = "$in";
+ vars.LinkLibraries = "$LINK_LIBRARIES";
+ } else {
+ std::string cmakeVarLang = "CMAKE_";
+ cmakeVarLang += this->TargetLinkLanguage;
+
+ // build response file name
+ std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
+ const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
+ if (flag) {
+ responseFlag = flag;
+ } else {
+ responseFlag = "@";
+ }
+ rspfile = "$RSP_FILE";
+ responseFlag += rspfile;
+
+ // build response file content
+ if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
+ rspcontent = "$in";
+ } else {
+ rspcontent = "$in_newline";
+ }
+ rspcontent += " $LINK_LIBRARIES";
+ vars.Objects = responseFlag.c_str();
+ vars.LinkLibraries = "";
+ }
+
+ vars.ObjectDir = "$OBJECT_DIR";
+
+ vars.Target = "$TARGET_FILE";
+
+ vars.SONameFlag = "$SONAME_FLAG";
+ vars.TargetSOName = "$SONAME";
+ vars.TargetPDB = "$TARGET_PDB";
+
+ vars.Flags = "$FLAGS";
+ vars.LinkFlags = "$LINK_FLAGS";
+ vars.Manifests = "$MANIFESTS";
+
+ std::string langFlags;
+ if (targetType != cmStateEnums::EXECUTABLE) {
+ langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
+ vars.LanguageCompileFlags = langFlags.c_str();
+ }
+
+ std::string launcher;
+ const char* val = this->GetLocalGenerator()->GetRuleLauncher(
+ this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
+ if (val && *val) {
+ launcher = val;
+ launcher += " ";
+ }
+
+ CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ this->GetLocalGenerator()->CreateRulePlaceholderExpander());
+
+ // Rule for linking library/executable.
+ std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
+ for (std::vector<std::string>::iterator i = linkCmds.begin();
+ i != linkCmds.end(); ++i) {
+ *i = launcher + *i;
+ rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
+ *i, vars);
+ }
+ {
+ // If there is no ranlib the command will be ":". Skip it.
+ std::vector<std::string>::iterator newEnd = std::remove_if(
+ linkCmds.begin(), linkCmds.end(), cmNinjaRemoveNoOpCommands());
+ linkCmds.erase(newEnd, linkCmds.end());
+ }
+
+ std::string linkCmd =
+ this->GetLocalGenerator()->BuildCommandLine(linkCmds);
+
+ // Write the linker rule with response file if needed.
+ std::ostringstream comment;
+ comment << "Rule for linking " << this->TargetLinkLanguage << " "
+ << this->GetVisibleTypeName() << ".";
+ std::ostringstream description;
+ description << "Linking " << this->TargetLinkLanguage << " "
+ << this->GetVisibleTypeName() << " $TARGET_FILE";
+ this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
+ comment.str(),
+ /*depfile*/ "",
+ /*deptype*/ "", rspfile, rspcontent,
+ /*restat*/ "$RESTAT",
+ /*generator*/ false);
+ }
+}
+
void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
{
cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
@@ -324,11 +449,40 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
}
}
+std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
+{
+ std::vector<std::string> linkCmds;
+
+ // this target requires separable cuda compilation
+ // now build the correct command depending on if the target is
+ // an executable or a dynamic library.
+ std::string linkCmd;
+ switch (this->GetGeneratorTarget()->GetType()) {
+ case cmStateEnums::SHARED_LIBRARY:
+ case cmStateEnums::MODULE_LIBRARY: {
+ const std::string cudaLinkCmd(
+ this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY"));
+ cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds);
+ } break;
+ case cmStateEnums::EXECUTABLE: {
+ const std::string cudaLinkCmd(this->GetMakefile()->GetDefinition(
+ "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"));
+ cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds);
+ } break;
+ default:
+ break;
+ }
+ return linkCmds;
+}
+
std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
{
std::vector<std::string> linkCmds;
cmMakefile* mf = this->GetMakefile();
{
+ // If we have a rule variable prefer it. In the case of static libraries
+ // this occurs when things like IPO is enabled, and we need to use the
+ // CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
this->TargetLinkLanguage, this->GetConfigName());
const char* linkCmd = mf->GetDefinition(linkCmdVar);
@@ -415,6 +569,211 @@ static int calculateCommandLineLengthLimit(int linkRuleLength)
return sz - linkRuleLength;
}
+void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
+{
+ cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
+
+ // determine if we need to do any device linking for this target
+ const std::string cuda_lang("CUDA");
+ cmGeneratorTarget::LinkClosure const* closure =
+ genTarget.GetLinkClosure(this->GetConfigName());
+
+ const bool hasCUDA =
+ (std::find(closure->Languages.begin(), closure->Languages.end(),
+ cuda_lang) != closure->Languages.end());
+
+ bool shouldHaveDeviceLinking = false;
+ switch (genTarget.GetType()) {
+ case cmStateEnums::SHARED_LIBRARY:
+ case cmStateEnums::MODULE_LIBRARY:
+ case cmStateEnums::EXECUTABLE:
+ shouldHaveDeviceLinking = true;
+ break;
+ default:
+ break;
+ }
+
+ if (!shouldHaveDeviceLinking || !hasCUDA) {
+ return;
+ }
+
+ // Now we can do device linking
+
+ // First and very important step is to make sure while inside this
+ // step our link language is set to CUDA
+ std::string cudaLinkLanguage = "CUDA";
+
+ std::string const cfgName = this->GetConfigName();
+ std::string const targetOutputReal =
+ ConvertToNinjaPath(genTarget.ObjectDirectory + "cmake_device_link.o");
+
+ std::string const targetOutputImplib =
+ ConvertToNinjaPath(genTarget.GetFullPath(cfgName,
+ /*implib=*/true));
+
+ this->DeviceLinkObject = targetOutputReal;
+
+ // Write comments.
+ cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
+ const cmStateEnums::TargetType targetType = genTarget.GetType();
+ this->GetBuildFileStream() << "# Device Link build statements for "
+ << cmState::GetTargetTypeName(targetType)
+ << " target " << this->GetTargetName() << "\n\n";
+
+ // Compute the comment.
+ std::ostringstream comment;
+ comment << "Link the " << this->GetVisibleTypeName() << " "
+ << targetOutputReal;
+
+ cmNinjaDeps emptyDeps;
+ cmNinjaVars vars;
+
+ // Compute outputs.
+ cmNinjaDeps outputs;
+ outputs.push_back(targetOutputReal);
+ // Compute specific libraries to link with.
+ cmNinjaDeps explicitDeps = this->GetObjects();
+ cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
+
+ std::string frameworkPath;
+ std::string linkPath;
+
+ std::string createRule = genTarget.GetCreateRuleVariable(
+ this->TargetLinkLanguage, this->GetConfigName());
+ const bool useWatcomQuote =
+ this->GetMakefile()->IsOn(createRule + "_USE_WATCOM_QUOTE");
+ cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
+
+ vars["TARGET_FILE"] =
+ localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
+
+ CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ new cmNinjaLinkLineDeviceComputer(
+ this->GetLocalGenerator(),
+ this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(),
+ this->GetGlobalGenerator()));
+ linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+
+ localGen.GetTargetFlags(
+ linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
+ vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
+
+ this->addPoolNinjaVariable("JOB_POOL_LINK", &genTarget, vars);
+
+ this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
+ vars["LINK_FLAGS"] =
+ cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
+
+ vars["MANIFESTS"] = this->GetManifests();
+
+ vars["LINK_PATH"] = frameworkPath + linkPath;
+
+ // Compute architecture specific link flags. Yes, these go into a different
+ // variable for executables, probably due to a mistake made when duplicating
+ // code between the Makefile executable and library generators.
+ if (targetType == cmStateEnums::EXECUTABLE) {
+ std::string t = vars["FLAGS"];
+ localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
+ vars["FLAGS"] = t;
+ } else {
+ std::string t = vars["ARCH_FLAGS"];
+ localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
+ vars["ARCH_FLAGS"] = t;
+ t = "";
+ localGen.AddLanguageFlags(t, cudaLinkLanguage, cfgName);
+ vars["LANGUAGE_COMPILE_FLAGS"] = t;
+ }
+ if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
+ vars["SONAME_FLAG"] =
+ this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage);
+ vars["SONAME"] = this->TargetNameSO;
+ if (targetType == cmStateEnums::SHARED_LIBRARY) {
+ std::string install_dir =
+ this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
+ if (!install_dir.empty()) {
+ vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
+ install_dir, cmOutputConverter::SHELL);
+ }
+ }
+ }
+
+ cmNinjaDeps byproducts;
+
+ if (!this->TargetNameImport.empty()) {
+ const std::string impLibPath = localGen.ConvertToOutputFormat(
+ targetOutputImplib, cmOutputConverter::SHELL);
+ vars["TARGET_IMPLIB"] = impLibPath;
+ EnsureParentDirectoryExists(impLibPath);
+ if (genTarget.HasImportLibrary()) {
+ byproducts.push_back(targetOutputImplib);
+ }
+ }
+
+ const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
+ vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
+ this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
+ EnsureDirectoryExists(objPath);
+
+ if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
+ // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
+ std::string& linkLibraries = vars["LINK_LIBRARIES"];
+ std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
+ std::string& link_path = vars["LINK_PATH"];
+ std::replace(link_path.begin(), link_path.end(), '\\', '/');
+ }
+
+ const std::vector<cmCustomCommand>* cmdLists[3] = {
+ &genTarget.GetPreBuildCommands(), &genTarget.GetPreLinkCommands(),
+ &genTarget.GetPostBuildCommands()
+ };
+
+ std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
+ vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
+ vars["POST_BUILD"] = localGen.BuildCommandLine(postBuildCmdLines);
+
+ std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
+ &preLinkCmdLines,
+ &postBuildCmdLines };
+
+ for (unsigned i = 0; i != 3; ++i) {
+ for (std::vector<cmCustomCommand>::const_iterator ci =
+ cmdLists[i]->begin();
+ ci != cmdLists[i]->end(); ++ci) {
+ cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
+ localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
+ std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
+ std::transform(ccByproducts.begin(), ccByproducts.end(),
+ std::back_inserter(byproducts), MapToNinjaPath());
+ }
+ }
+
+ cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
+
+ int commandLineLengthLimit = -1;
+ if (!this->ForceResponseFile()) {
+ commandLineLengthLimit = calculateCommandLineLengthLimit(
+ globalGen.GetRuleCmdLength(this->LanguageLinkerDeviceRule()));
+ }
+
+ const std::string rspfile =
+ std::string(cmake::GetCMakeFilesDirectoryPostSlash()) +
+ genTarget.GetName() + ".rsp";
+
+ // Gather order-only dependencies.
+ cmNinjaDeps orderOnlyDeps;
+ this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
+ orderOnlyDeps);
+
+ // Write the build statement for this target.
+ bool usedResponseFile = false;
+ globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
+ this->LanguageLinkerDeviceRule(), outputs,
+ /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
+ implicitDeps, orderOnlyDeps, vars, rspfile,
+ commandLineLengthLimit, &usedResponseFile);
+ this->WriteDeviceLinkRule(usedResponseFile);
+}
+
void cmNinjaNormalTargetGenerator::WriteLinkStatement()
{
cmGeneratorTarget& gt = *this->GetGeneratorTarget();
@@ -475,6 +834,10 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
cmNinjaDeps explicitDeps = this->GetObjects();
cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
+ if (!this->DeviceLinkObject.empty()) {
+ explicitDeps.push_back(this->DeviceLinkObject);
+ }
+
cmMakefile* mf = this->GetMakefile();
std::string frameworkPath;
@@ -498,6 +861,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
localGen.GetTargetFlags(
linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
+
if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
(gt.GetType() == cmStateEnums::SHARED_LIBRARY ||
gt.IsExecutableWithExports())) {
@@ -675,7 +1039,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
if (!symlinkNeeded) {
vars["POST_BUILD"] = postBuildCmdLine;
} else {
- vars["POST_BUILD"] = ":";
+ vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
symlinkVars["POST_BUILD"] = postBuildCmdLine;
}
cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
diff --git a/Source/cmNinjaNormalTargetGenerator.h b/Source/cmNinjaNormalTargetGenerator.h
index 5bd906f..e5595ea 100644
--- a/Source/cmNinjaNormalTargetGenerator.h
+++ b/Source/cmNinjaNormalTargetGenerator.h
@@ -22,12 +22,21 @@ public:
private:
std::string LanguageLinkerRule() const;
+ std::string LanguageLinkerDeviceRule() const;
+
const char* GetVisibleTypeName() const;
void WriteLanguagesRules();
+
void WriteLinkRule(bool useResponseFile);
+ void WriteDeviceLinkRule(bool useResponseFile);
+
void WriteLinkStatement();
+ void WriteDeviceLinkStatement();
+
void WriteObjectLibStatement();
+
std::vector<std::string> ComputeLinkCmd();
+ std::vector<std::string> ComputeDeviceLinkCmd();
private:
// Target name info.
@@ -37,6 +46,7 @@ private:
std::string TargetNameImport;
std::string TargetNamePDB;
std::string TargetLinkLanguage;
+ std::string DeviceLinkObject;
};
#endif // ! cmNinjaNormalTargetGenerator_h
diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx
index cf60892..8090542 100644
--- a/Source/cmNinjaTargetGenerator.cxx
+++ b/Source/cmNinjaTargetGenerator.cxx
@@ -2,10 +2,20 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmNinjaTargetGenerator.h"
+#include <algorithm>
+#include <assert.h>
+#include <cm_jsoncpp_value.h>
+#include <cm_jsoncpp_writer.h>
+#include <iterator>
+#include <map>
+#include <sstream>
+#include <string.h>
+
#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
#include "cmCustomCommandGenerator.h"
#include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalNinjaGenerator.h"
#include "cmLocalGenerator.h"
@@ -19,16 +29,9 @@
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include "cm_jsoncpp_writer.h"
-
-#include <algorithm>
-#include <iterator>
-#include <map>
-#include <sstream>
-#include <string.h>
-
cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
{
switch (target->GetType()) {
@@ -356,7 +359,14 @@ bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const
compilePdbPath =
this->GeneratorTarget->GetCompilePDBPath(this->GetConfigName());
if (compilePdbPath.empty()) {
+ // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
+ // A trailing slash tells the toolchain to add its default file name.
compilePdbPath = this->GeneratorTarget->GetSupportDirectory() + "/";
+ if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
+ // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
+ compilePdbPath += this->GeneratorTarget->GetName();
+ compilePdbPath += ".pdb";
+ }
}
}
@@ -580,10 +590,22 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
}
// Rule for compiling object file.
- const std::string cmdVar = std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
- std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
std::vector<std::string> compileCmds;
- cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
+ if (lang == "CUDA") {
+ std::string cmdVar;
+ if (this->GeneratorTarget->GetProperty("CUDA_SEPARABLE_COMPILATION")) {
+ cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
+ } else {
+ cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
+ }
+ std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
+ cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
+ } else {
+ const std::string cmdVar =
+ std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
+ std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
+ cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
+ }
// Maybe insert an include-what-you-use runner.
if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
diff --git a/Source/cmNinjaTypes.h b/Source/cmNinjaTypes.h
index b4eaa59..3fd536a 100644
--- a/Source/cmNinjaTypes.h
+++ b/Source/cmNinjaTypes.h
@@ -3,9 +3,11 @@
#ifndef cmNinjaTypes_h
#define cmNinjaTypes_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <map>
+#include <string>
+#include <vector>
typedef std::vector<std::string> cmNinjaDeps;
typedef std::map<std::string, std::string> cmNinjaVars;
diff --git a/Source/cmOptionCommand.cxx b/Source/cmOptionCommand.cxx
index bbd6090..00a2d2b 100644
--- a/Source/cmOptionCommand.cxx
+++ b/Source/cmOptionCommand.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmOptionCommand.h"
-#include <algorithm>
-
#include "cmAlgorithms.h"
#include "cmMakefile.h"
#include "cmState.h"
diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx
index 445ad0b..d6864a6 100644
--- a/Source/cmOutputConverter.cxx
+++ b/Source/cmOutputConverter.cxx
@@ -2,16 +2,17 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmOutputConverter.h"
-#include "cmAlgorithms.h"
-#include "cmState.h"
-#include "cmStateDirectory.h"
-#include "cmSystemTools.h"
-
#include <algorithm>
#include <assert.h>
#include <ctype.h>
#include <set>
#include <sstream>
+#include <vector>
+
+#include "cmAlgorithms.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmSystemTools.h"
cmOutputConverter::cmOutputConverter(cmStateSnapshot snapshot)
: StateSnapshot(snapshot)
diff --git a/Source/cmOutputConverter.h b/Source/cmOutputConverter.h
index dabb091..a3da4cd 100644
--- a/Source/cmOutputConverter.h
+++ b/Source/cmOutputConverter.h
@@ -5,10 +5,12 @@
#include <cmConfigure.h> // IWYU pragma: keep
+#include <string>
+
#include "cmStateSnapshot.h"
-#include <string>
-#include <vector>
+class cmState;
+class cmStateDirectory;
class cmOutputConverter
{
diff --git a/Source/cmOutputRequiredFilesCommand.cxx b/Source/cmOutputRequiredFilesCommand.cxx
index 32b0a92..7a17f2c 100644
--- a/Source/cmOutputRequiredFilesCommand.cxx
+++ b/Source/cmOutputRequiredFilesCommand.cxx
@@ -180,33 +180,30 @@ protected:
while (cmSystemTools::GetLineFromStream(fin, line)) {
if (cmHasLiteralPrefix(line.c_str(), "#include")) {
// if it is an include line then create a string class
- std::string currentline = line;
- size_t qstart = currentline.find('\"', 8);
+ size_t qstart = line.find('\"', 8);
size_t qend;
// if a quote is not found look for a <
if (qstart == std::string::npos) {
- qstart = currentline.find('<', 8);
+ qstart = line.find('<', 8);
// if a < is not found then move on
if (qstart == std::string::npos) {
- cmSystemTools::Error("unknown include directive ",
- currentline.c_str());
+ cmSystemTools::Error("unknown include directive ", line.c_str());
continue;
} else {
- qend = currentline.find('>', qstart + 1);
+ qend = line.find('>', qstart + 1);
}
} else {
- qend = currentline.find('\"', qstart + 1);
+ qend = line.find('\"', qstart + 1);
}
// extract the file being included
- std::string includeFile =
- currentline.substr(qstart + 1, qend - qstart - 1);
+ std::string includeFile = line.substr(qstart + 1, qend - qstart - 1);
// see if the include matches the regular expression
if (!this->IncludeFileRegularExpression.find(includeFile)) {
if (this->Verbose) {
std::string message = "Skipping ";
message += includeFile;
message += " for file ";
- message += info->FullPath.c_str();
+ message += info->FullPath;
cmSystemTools::Error(message.c_str(), CM_NULLPTR);
}
continue;
@@ -520,7 +517,7 @@ bool cmOutputRequiredFilesCommand::InitialPass(
const cmDependInformation* info = md.FindDependencies(this->File.c_str());
if (info) {
// write them out
- FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile.c_str(), "w");
+ FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile, "w");
if (!fout) {
std::string err = "Can not open output file: ";
err += this->OutputFile;
diff --git a/Source/cmParseArgumentsCommand.cxx b/Source/cmParseArgumentsCommand.cxx
index 0a2dd12..d75ee8e 100644
--- a/Source/cmParseArgumentsCommand.cxx
+++ b/Source/cmParseArgumentsCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmParseArgumentsCommand.h"
-#include <algorithm>
#include <map>
#include <set>
#include <sstream>
diff --git a/Source/cmPathLabel.cxx b/Source/cmPathLabel.cxx
index 19e6820..30ba081 100644
--- a/Source/cmPathLabel.cxx
+++ b/Source/cmPathLabel.cxx
@@ -2,6 +2,8 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmPathLabel.h"
+#include <stddef.h>
+
cmPathLabel::cmPathLabel(const std::string& label)
: Label(label)
, Hash(0)
diff --git a/Source/cmPathLabel.h b/Source/cmPathLabel.h
index 5e9e423..cd9743c 100644
--- a/Source/cmPathLabel.h
+++ b/Source/cmPathLabel.h
@@ -3,9 +3,9 @@
#ifndef cmPathLabel_h
#define cmPathLabel_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <string>
/** \class cmPathLabel
* \brief Helper class for text based labels
diff --git a/Source/cmProcessOutput.cxx b/Source/cmProcessOutput.cxx
new file mode 100644
index 0000000..8b4d0e1
--- /dev/null
+++ b/Source/cmProcessOutput.cxx
@@ -0,0 +1,170 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmProcessOutput.h"
+
+#if defined(_WIN32)
+#include <windows.h>
+unsigned int cmProcessOutput::defaultCodepage =
+ KWSYS_ENCODING_DEFAULT_CODEPAGE;
+#endif
+
+cmProcessOutput::Encoding cmProcessOutput::FindEncoding(std::string name)
+{
+ Encoding encoding = Auto;
+ if (name == "UTF8") {
+ encoding = UTF8;
+ } else if (name == "NONE") {
+ encoding = None;
+ } else if (name == "ANSI") {
+ encoding = ANSI;
+ } else if (name == "OEM") {
+ encoding = OEM;
+ }
+ return encoding;
+}
+
+cmProcessOutput::cmProcessOutput(Encoding encoding, unsigned int maxSize)
+{
+#if defined(_WIN32)
+ codepage = 0;
+ bufferSize = maxSize;
+ if (encoding == None) {
+ codepage = defaultCodepage;
+ } else if (encoding == Auto) {
+ codepage = GetConsoleCP();
+ } else if (encoding == UTF8) {
+ codepage = CP_UTF8;
+ } else if (encoding == OEM) {
+ codepage = GetOEMCP();
+ }
+ if (!codepage || encoding == ANSI) {
+ codepage = GetACP();
+ }
+#else
+ static_cast<void>(encoding);
+ static_cast<void>(maxSize);
+#endif
+}
+
+cmProcessOutput::~cmProcessOutput()
+{
+}
+
+bool cmProcessOutput::DecodeText(std::string raw, std::string& decoded,
+ size_t id)
+{
+ bool success = true;
+ decoded = raw;
+#if defined(_WIN32)
+ if (id > 0) {
+ if (rawparts.size() < id) {
+ rawparts.reserve(id);
+ while (rawparts.size() < id)
+ rawparts.push_back(std::string());
+ }
+ raw = rawparts[id - 1] + raw;
+ rawparts[id - 1].clear();
+ decoded = raw;
+ }
+ if (raw.size() > 0 && codepage != defaultCodepage) {
+ success = false;
+ CPINFOEXW cpinfo;
+ if (id > 0 && bufferSize > 0 && raw.size() == bufferSize &&
+ GetCPInfoExW(codepage, 0, &cpinfo) == 1 && cpinfo.MaxCharSize > 1) {
+ if (cpinfo.MaxCharSize == 2 && cpinfo.LeadByte[0] != 0) {
+ LPSTR prevChar =
+ CharPrevExA(codepage, raw.c_str(), raw.c_str() + raw.size(), 0);
+ bool isLeadByte =
+ (*(prevChar + 1) == 0) && IsDBCSLeadByteEx(codepage, *prevChar);
+ if (isLeadByte) {
+ rawparts[id - 1] += *(raw.end() - 1);
+ raw.resize(raw.size() - 1);
+ }
+ success = DoDecodeText(raw, decoded, NULL);
+ } else {
+ bool restoreDecoded = false;
+ std::string firstDecoded = decoded;
+ wchar_t lastChar = 0;
+ for (UINT i = 0; i < cpinfo.MaxCharSize; i++) {
+ success = DoDecodeText(raw, decoded, &lastChar);
+ if (success && lastChar != 0) {
+ if (i == 0) {
+ firstDecoded = decoded;
+ }
+ if (lastChar == cpinfo.UnicodeDefaultChar) {
+ restoreDecoded = true;
+ rawparts[id - 1] = *(raw.end() - 1) + rawparts[id - 1];
+ raw.resize(raw.size() - 1);
+ } else {
+ restoreDecoded = false;
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ if (restoreDecoded) {
+ decoded = firstDecoded;
+ rawparts[id - 1].clear();
+ }
+ }
+ } else {
+ success = DoDecodeText(raw, decoded, NULL);
+ }
+ }
+#else
+ static_cast<void>(id);
+#endif
+ return success;
+}
+
+bool cmProcessOutput::DecodeText(const char* data, size_t length,
+ std::string& decoded, size_t id)
+{
+ return DecodeText(std::string(data, length), decoded, id);
+}
+
+bool cmProcessOutput::DecodeText(std::vector<char> raw,
+ std::vector<char>& decoded, size_t id)
+{
+ std::string str;
+ const bool success =
+ DecodeText(std::string(raw.begin(), raw.end()), str, id);
+ decoded.assign(str.begin(), str.end());
+ return success;
+}
+
+#if defined(_WIN32)
+bool cmProcessOutput::DoDecodeText(std::string raw, std::string& decoded,
+ wchar_t* lastChar)
+{
+ 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);
+ if (r > 0) {
+ if (lastChar) {
+ *lastChar = 0;
+ if ((wlength >= 2 && wdata[wlength - 2] != wdata[wlength - 1]) ||
+ wlength >= 1) {
+ *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);
+ if (r > 0) {
+ decoded = std::string(data, length);
+ success = true;
+ }
+ delete[] data;
+ }
+ delete[] wdata;
+ return success;
+}
+#endif
diff --git a/Source/cmProcessOutput.h b/Source/cmProcessOutput.h
new file mode 100644
index 0000000..6046f57
--- /dev/null
+++ b/Source/cmProcessOutput.h
@@ -0,0 +1,88 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmProcessOutput_h
+#define cmProcessOutput_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <stddef.h>
+#include <string>
+#include <vector>
+
+/** \class cmProcessOutput
+ * \brief Decode text data to internal encoding.
+ *
+ * cmProcessOutput is used to decode text output from external process
+ * using external encoding to our internal encoding.
+ */
+class cmProcessOutput
+{
+public:
+ enum Encoding
+ {
+ None,
+ Auto,
+ UTF8,
+ ANSI,
+ OEM
+ };
+
+ /**
+ * Find encoding enum value for given encoding \a name.
+ * \param name a encoding name.
+ * \return encoding enum value or Auto if \a name was not found.
+ */
+ static Encoding FindEncoding(std::string name);
+
+ /// The code page that is used as internal encoding to which we will encode.
+ static unsigned int defaultCodepage;
+
+ /**
+ * A class constructor.
+ * \param encoding external process encoding from which we will decode.
+ * \param maxSize a maximal size for process output buffer. It should match
+ * to KWSYSPE_PIPE_BUFFER_SIZE. If text we decode is same size as \a maxSize
+ * then we will check for incomplete character at end of buffer and
+ * we will not return last incomplete character. This character will be
+ * returned with next DecodeText() call. To disable this behavior specify
+ * 0 as \a maxSize.
+ */
+ cmProcessOutput(Encoding encoding = Auto, unsigned int maxSize = 1024);
+ ~cmProcessOutput();
+ /**
+ * Decode \a raw string using external encoding to internal
+ * encoding in \a decoded.
+ * \a id specifies which internal buffer to use. This is important when we
+ * are decoding both stdout and stderr from process output and we need to
+ * keep incomplete characters in separate buffers for each stream.
+ * \return true if successfully decoded \a raw to \a decoded or false if not.
+ */
+ bool DecodeText(std::string raw, std::string& decoded, size_t id = 0);
+ /**
+ * Decode \a data with \a length from external encoding to internal
+ * encoding in \a decoded.
+ * \param data a pointer to process output text data.
+ * \param length a size of data buffer.
+ * \param decoded a string which will contain decoded text.
+ * \param id an internal buffer id to use.
+ * \return true if successfully decoded \a data to \a decoded or false if
+ * not.
+ */
+ bool DecodeText(const char* data, size_t length, std::string& decoded,
+ size_t id = 0);
+ /**
+ * \overload
+ */
+ bool DecodeText(std::vector<char> raw, std::vector<char>& decoded,
+ size_t id = 0);
+
+private:
+#if defined(_WIN32)
+ unsigned int codepage;
+ unsigned int bufferSize;
+ std::vector<std::string> rawparts;
+ bool DoDecodeText(std::string raw, std::string& decoded, wchar_t* lastChar);
+#endif
+};
+
+#endif
diff --git a/Source/cmProcessTools.cxx b/Source/cmProcessTools.cxx
index e7b6051..b756650 100644
--- a/Source/cmProcessTools.cxx
+++ b/Source/cmProcessTools.cxx
@@ -1,29 +1,46 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmProcessTools.h"
+#include "cmProcessOutput.h"
#include <cmsys/Process.h>
#include <ostream>
void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
- OutputParser* err)
+ OutputParser* err, Encoding encoding)
{
cmsysProcess_Execute(cp);
char* data = CM_NULLPTR;
int length = 0;
int p;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
while ((out || err) &&
(p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
if (out && p == cmsysProcess_Pipe_STDOUT) {
- if (!out->Process(data, length)) {
+ processOutput.DecodeText(data, length, strdata, 1);
+ if (!out->Process(strdata.c_str(), int(strdata.size()))) {
out = CM_NULLPTR;
}
} else if (err && p == cmsysProcess_Pipe_STDERR) {
- if (!err->Process(data, length)) {
+ processOutput.DecodeText(data, length, strdata, 2);
+ if (!err->Process(strdata.c_str(), int(strdata.size()))) {
err = CM_NULLPTR;
}
}
}
+ if (out) {
+ processOutput.DecodeText(std::string(), strdata, 1);
+ if (!strdata.empty()) {
+ out->Process(strdata.c_str(), int(strdata.size()));
+ }
+ }
+ if (err) {
+ processOutput.DecodeText(std::string(), strdata, 2);
+ if (!strdata.empty()) {
+ out->Process(strdata.c_str(), int(strdata.size()));
+ }
+ }
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
}
diff --git a/Source/cmProcessTools.h b/Source/cmProcessTools.h
index e5a3fe9..df131b9 100644
--- a/Source/cmProcessTools.h
+++ b/Source/cmProcessTools.h
@@ -3,6 +3,7 @@
#ifndef cmProcessTools_h
#define cmProcessTools_h
+#include "cmProcessOutput.h"
#include <cmConfigure.h>
#include <iosfwd>
@@ -16,6 +17,7 @@
class cmProcessTools
{
public:
+ typedef cmProcessOutput::Encoding Encoding;
/** Abstract interface for process output parsers. */
class OutputParser
{
@@ -79,7 +81,8 @@ public:
/** Run a process and send output to given parsers. */
static void RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
- OutputParser* err = CM_NULLPTR);
+ OutputParser* err = CM_NULLPTR,
+ Encoding encoding = cmProcessOutput::Auto);
};
#endif
diff --git a/Source/cmQtAutoGeneratorInitializer.cxx b/Source/cmQtAutoGeneratorInitializer.cxx
index f0373a1..8afd532 100644
--- a/Source/cmQtAutoGeneratorInitializer.cxx
+++ b/Source/cmQtAutoGeneratorInitializer.cxx
@@ -13,7 +13,6 @@
#include "cmSourceFile.h"
#include "cmSourceFileLocation.h"
#include "cmState.h"
-#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmake.h"
@@ -27,7 +26,6 @@
#include <cmConfigure.h>
#include <cmsys/FStream.hxx>
#include <cmsys/RegularExpression.hxx>
-#include <iostream>
#include <map>
#include <set>
#include <sstream>
diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx
index f56f575..fa33cf2 100644
--- a/Source/cmQtAutoGenerators.cxx
+++ b/Source/cmQtAutoGenerators.cxx
@@ -2,18 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmQtAutoGenerators.h"
-#include "cmAlgorithms.h"
-#include "cmFilePathUuid.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmOutputConverter.h"
-#include "cmState.h"
-#include "cmStateDirectory.h"
-#include "cmStateTypes.h"
-#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
-#include "cmake.h"
-
#include <algorithm>
#include <assert.h>
#include <cmConfigure.h>
@@ -26,6 +14,17 @@
#include <string.h>
#include <utility>
+#include "cmAlgorithms.h"
+#include "cmFilePathUuid.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
#if defined(__APPLE__)
#include <unistd.h>
#endif
@@ -457,8 +456,8 @@ static std::string ReadAll(const std::string& filename)
bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
{
- if (!cmsys::SystemTools::FileExists(this->OutMocCppFilenameAbs.c_str()) ||
- (this->OldCompileSettingsStr != this->CurrentCompileSettingsStr)) {
+ // If settings changed everything needs to be re-generated.
+ if (this->OldCompileSettingsStr != this->CurrentCompileSettingsStr) {
this->GenerateAll = true;
}
diff --git a/Source/cmRulePlaceholderExpander.cxx b/Source/cmRulePlaceholderExpander.cxx
index 361321e..f190a5c 100644
--- a/Source/cmRulePlaceholderExpander.cxx
+++ b/Source/cmRulePlaceholderExpander.cxx
@@ -2,6 +2,10 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmRulePlaceholderExpander.h"
+#include <ctype.h>
+#include <string.h>
+#include <utility>
+
#include "cmOutputConverter.h"
#include "cmSystemTools.h"
@@ -212,7 +216,7 @@ std::string cmRulePlaceholderExpander::ExpandRuleVariable(
std::string ret = outputConverter->ConvertToOutputForExisting(
this->VariableMappings["CMAKE_" + compIt->second + "_COMPILER"]);
std::string const& compilerArg1 =
- this->VariableMappings[compIt->first + "_COMPILER_ARG1"];
+ this->VariableMappings["CMAKE_" + compIt->second + "_COMPILER_ARG1"];
std::string const& compilerTarget =
this->VariableMappings["CMAKE_" + compIt->second + "_COMPILER_TARGET"];
std::string const& compilerOptionTarget =
diff --git a/Source/cmRulePlaceholderExpander.h b/Source/cmRulePlaceholderExpander.h
index 444419c..5223ae9 100644
--- a/Source/cmRulePlaceholderExpander.h
+++ b/Source/cmRulePlaceholderExpander.h
@@ -9,7 +9,6 @@
#include <map>
#include <string>
-class cmGeneratorTarget;
class cmOutputConverter;
class cmRulePlaceholderExpander
diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx
index ff0b836..0df6e0c 100644
--- a/Source/cmSearchPath.cxx
+++ b/Source/cmSearchPath.cxx
@@ -2,7 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmSearchPath.h"
+#include <algorithm>
#include <cassert>
+#include <utility>
#include "cmAlgorithms.h"
#include "cmFindCommon.h"
diff --git a/Source/cmSearchPath.h b/Source/cmSearchPath.h
index 80815ed..9ffa871 100644
--- a/Source/cmSearchPath.h
+++ b/Source/cmSearchPath.h
@@ -5,7 +5,9 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <set>
+#include <string>
+#include <vector>
class cmFindCommon;
diff --git a/Source/cmServer.cxx b/Source/cmServer.cxx
index 51a363f..5a71dc0 100644
--- a/Source/cmServer.cxx
+++ b/Source/cmServer.cxx
@@ -14,6 +14,7 @@
#include "cm_jsoncpp_value.h"
#endif
+#include <algorithm>
#include <fstream>
#include <iostream>
#include <memory>
diff --git a/Source/cmServerConnection.cxx b/Source/cmServerConnection.cxx
index b4af52b..008052b 100644
--- a/Source/cmServerConnection.cxx
+++ b/Source/cmServerConnection.cxx
@@ -8,6 +8,7 @@
#include "cmServer.h"
#include <assert.h>
+#include <string.h>
namespace {
diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx
index e899190..c08a36b 100644
--- a/Source/cmServerProtocol.cxx
+++ b/Source/cmServerProtocol.cxx
@@ -82,7 +82,7 @@ static void getCMakeInputs(const cmGlobalGenerator* gg,
std::vector<std::string>* tmpFiles)
{
const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/';
- const std::vector<cmMakefile*> makefiles = gg->GetMakefiles();
+ std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles();
for (auto it = makefiles.begin(); it != makefiles.end(); ++it) {
const std::vector<std::string> listFiles = (*it)->GetListFiles();
@@ -386,25 +386,9 @@ bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
return false;
}
- const std::string fullGeneratorName =
- cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
- generator, extraGenerator);
-
- cm->SetGeneratorToolset(toolset);
- cm->SetGeneratorPlatform(platform);
-
- cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
- if (!gg) {
- setErrorMessage(
- errorMessage,
- std::string("Could not set up the requested combination of \"") +
- kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"");
- return false;
- }
-
- cm->SetGlobalGenerator(gg);
- cm->SetHomeDirectory(sourceDirectory);
- cm->SetHomeOutputDirectory(buildDirectory);
+ this->GeneratorInfo =
+ GeneratorInformation(generator, extraGenerator, toolset, platform,
+ sourceDirectory, buildDirectory);
this->m_State = STATE_ACTIVE;
return true;
@@ -856,7 +840,7 @@ static Json::Value DumpTargetsList(
return result;
}
-static Json::Value DumpProjectList(const cmake* cm, const std::string config)
+static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
{
Json::Value result = Json::arrayValue;
@@ -945,8 +929,15 @@ cmServerResponse cmServerProtocol1_0::ProcessConfigure(
FileMonitor()->StopMonitoring();
+ std::string errorMessage;
+ cmake* cm = this->CMakeInstance();
+ this->GeneratorInfo.SetupGenerator(cm, &errorMessage);
+ if (!errorMessage.empty()) {
+ return request.ReportError(errorMessage);
+ }
+
// Make sure the types of cacheArguments matches (if given):
- std::vector<std::string> cacheArgs;
+ std::vector<std::string> cacheArgs = { "unused" };
bool cacheArgumentsError = false;
const Json::Value passedArgs = request.Data[kCACHE_ARGUMENTS_KEY];
if (!passedArgs.isNull()) {
@@ -969,15 +960,13 @@ cmServerResponse cmServerProtocol1_0::ProcessConfigure(
"cacheArguments must be unset, a string or an array of strings.");
}
- cmake* cm = this->CMakeInstance();
std::string sourceDir = cm->GetHomeDirectory();
const std::string buildDir = cm->GetHomeOutputDirectory();
cmGlobalGenerator* gg = cm->GetGlobalGenerator();
if (buildDir.empty()) {
- return request.ReportError(
- "No build directory set via setGlobalSettings.");
+ return request.ReportError("No build directory set via Handshake.");
}
if (cm->LoadCache(buildDir)) {
@@ -1052,20 +1041,18 @@ cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli();
obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars();
- obj[kSOURCE_DIRECTORY_KEY] = cm->GetHomeDirectory();
- obj[kBUILD_DIRECTORY_KEY] = cm->GetHomeOutputDirectory();
+ obj[kSOURCE_DIRECTORY_KEY] = this->GeneratorInfo.SourceDirectory;
+ obj[kBUILD_DIRECTORY_KEY] = this->GeneratorInfo.BuildDirectory;
// Currently used generator:
- cmGlobalGenerator* gen = cm->GetGlobalGenerator();
- obj[kGENERATOR_KEY] = gen ? gen->GetName() : std::string();
- obj[kEXTRA_GENERATOR_KEY] =
- gen ? gen->GetExtraGeneratorName() : std::string();
+ obj[kGENERATOR_KEY] = this->GeneratorInfo.GeneratorName;
+ obj[kEXTRA_GENERATOR_KEY] = this->GeneratorInfo.ExtraGeneratorName;
return request.Reply(obj);
}
static void setBool(const cmServerRequest& request, const std::string& key,
- std::function<void(bool)> setter)
+ std::function<void(bool)> const& setter)
{
if (request.Data[key].isNull()) {
return;
@@ -1123,3 +1110,41 @@ cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
return request.Reply(result);
}
+
+cmServerProtocol1_0::GeneratorInformation::GeneratorInformation(
+ const std::string& generatorName, const std::string& extraGeneratorName,
+ const std::string& toolset, const std::string& platform,
+ const std::string& sourceDirectory, const std::string& buildDirectory)
+ : GeneratorName(generatorName)
+ , ExtraGeneratorName(extraGeneratorName)
+ , Toolset(toolset)
+ , Platform(platform)
+ , SourceDirectory(sourceDirectory)
+ , BuildDirectory(buildDirectory)
+{
+}
+
+void cmServerProtocol1_0::GeneratorInformation::SetupGenerator(
+ cmake* cm, std::string* errorMessage)
+{
+ const std::string fullGeneratorName =
+ cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
+ GeneratorName, ExtraGeneratorName);
+
+ cm->SetHomeDirectory(SourceDirectory);
+ cm->SetHomeOutputDirectory(BuildDirectory);
+
+ cmGlobalGenerator* gg = cm->CreateGlobalGenerator(fullGeneratorName);
+ if (!gg) {
+ setErrorMessage(
+ errorMessage,
+ std::string("Could not set up the requested combination of \"") +
+ kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\"");
+ return;
+ }
+
+ cm->SetGlobalGenerator(gg);
+
+ cm->SetGeneratorToolset(Toolset);
+ cm->SetGeneratorPlatform(Platform);
+}
diff --git a/Source/cmServerProtocol.h b/Source/cmServerProtocol.h
index 5238d5d..027f145 100644
--- a/Source/cmServerProtocol.h
+++ b/Source/cmServerProtocol.h
@@ -131,4 +131,28 @@ private:
State m_State = STATE_INACTIVE;
bool m_isDirty = false;
+
+ struct GeneratorInformation
+ {
+ public:
+ GeneratorInformation() = default;
+ GeneratorInformation(const std::string& generatorName,
+ const std::string& extraGeneratorName,
+ const std::string& toolset,
+ const std::string& platform,
+ const std::string& sourceDirectory,
+ const std::string& buildDirectory);
+
+ void SetupGenerator(cmake* cm, std::string* errorMessage);
+
+ std::string GeneratorName;
+ std::string ExtraGeneratorName;
+ std::string Toolset;
+ std::string Platform;
+
+ std::string SourceDirectory;
+ std::string BuildDirectory;
+ };
+
+ GeneratorInformation GeneratorInfo;
};
diff --git a/Source/cmSetCommand.cxx b/Source/cmSetCommand.cxx
index e49f142..820e7f6 100644
--- a/Source/cmSetCommand.cxx
+++ b/Source/cmSetCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmSetCommand.h"
-#include <algorithm>
#include <string.h>
#include "cmAlgorithms.h"
diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx
index 79221c8..60c198a 100644
--- a/Source/cmSetPropertyCommand.cxx
+++ b/Source/cmSetPropertyCommand.cxx
@@ -342,7 +342,7 @@ bool cmSetPropertyCommand::HandleCacheMode()
return false;
}
} else if (this->PropertyName == "TYPE") {
- if (!cmState::IsCacheEntryType(this->PropertyValue.c_str())) {
+ if (!cmState::IsCacheEntryType(this->PropertyValue)) {
std::ostringstream e;
e << "given invalid CACHE entry TYPE \"" << this->PropertyValue << "\"";
this->SetError(e.str());
diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx
index 6f29b18..5c4f18b 100644
--- a/Source/cmSourceFile.cxx
+++ b/Source/cmSourceFile.cxx
@@ -2,17 +2,16 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmSourceFile.h"
+#include <sstream>
+
#include "cmCustomCommand.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmProperty.h"
#include "cmState.h"
-#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmake.h"
-#include <sstream>
-
cmSourceFile::cmSourceFile(cmMakefile* mf, const std::string& name)
: Location(mf, name)
{
diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx
index ff3ec7f..3f20d4e 100644
--- a/Source/cmSourceGroupCommand.cxx
+++ b/Source/cmSourceGroupCommand.cxx
@@ -69,7 +69,7 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
src += "/";
src += args[i];
}
- src = cmSystemTools::CollapseFullPath(src.c_str());
+ src = cmSystemTools::CollapseFullPath(src);
sg->AddGroupFile(src);
} else {
std::ostringstream err;
diff --git a/Source/cmState.cxx b/Source/cmState.cxx
index db1e542..6e934e2 100644
--- a/Source/cmState.cxx
+++ b/Source/cmState.cxx
@@ -2,24 +2,22 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmState.h"
-#include "cmStatePrivate.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <string.h>
+#include <utility>
#include "cmAlgorithms.h"
#include "cmCacheManager.h"
#include "cmCommand.h"
#include "cmDefinitions.h"
#include "cmListFileCache.h"
+#include "cmStatePrivate.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <iterator>
-#include <stdio.h>
-#include <string.h>
-#include <utility>
-
cmState::cmState()
: IsInTryCompile(false)
, WindowsShell(false)
diff --git a/Source/cmState.h b/Source/cmState.h
index 6d74815..41ffcdc 100644
--- a/Source/cmState.h
+++ b/Source/cmState.h
@@ -5,25 +5,22 @@
#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmAlgorithms.h"
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
#include "cmDefinitions.h"
#include "cmLinkedTree.h"
#include "cmProperty.h"
#include "cmPropertyDefinitionMap.h"
#include "cmPropertyMap.h"
+#include "cmStatePrivate.h"
#include "cmStateTypes.h"
-#include <map>
-#include <set>
-#include <string>
-#include <vector>
-
class cmCacheManager;
class cmCommand;
-class cmListFileBacktrace;
class cmPropertyDefinition;
-
-class cmStateDirectory;
class cmStateSnapshot;
class cmState
diff --git a/Source/cmStateDirectory.cxx b/Source/cmStateDirectory.cxx
index 01e1e7e..46a1858 100644
--- a/Source/cmStateDirectory.cxx
+++ b/Source/cmStateDirectory.cxx
@@ -2,8 +2,18 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmStateDirectory.h"
+
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <map>
+#include <utility>
+
+#include "cmProperty.h"
+#include "cmPropertyMap.h"
#include "cmState.h"
#include "cmStatePrivate.h"
+#include "cmStateTypes.h"
#include "cmSystemTools.h"
static std::string const kBINARY_DIR = "BINARY_DIR";
diff --git a/Source/cmStateDirectory.h b/Source/cmStateDirectory.h
index 17a89d8..8accc8e 100644
--- a/Source/cmStateDirectory.h
+++ b/Source/cmStateDirectory.h
@@ -10,9 +10,10 @@
#include <vector>
#include "cmAlgorithms.h"
+#include "cmLinkedTree.h"
#include "cmListFileCache.h"
+#include "cmStatePrivate.h"
#include "cmStateSnapshot.h"
-#include "cmStateTypes.h"
class cmStateDirectory
{
diff --git a/Source/cmStatePrivate.h b/Source/cmStatePrivate.h
index 8daa3cf..20700f2 100644
--- a/Source/cmStatePrivate.h
+++ b/Source/cmStatePrivate.h
@@ -12,9 +12,16 @@
#include "cmDefinitions.h"
#include "cmLinkedTree.h"
#include "cmListFileCache.h"
+#include "cmPolicies.h"
#include "cmPropertyMap.h"
+#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
+namespace cmStateDetail {
+struct BuildsystemDirectoryStateType;
+struct PolicyStackEntry;
+} // namespace cmStateDetail
+
static const std::string cmPropertySentinal = std::string();
struct cmStateDetail::SnapshotDataType
diff --git a/Source/cmStateSnapshot.cxx b/Source/cmStateSnapshot.cxx
index 7f86221..c6288a5 100644
--- a/Source/cmStateSnapshot.cxx
+++ b/Source/cmStateSnapshot.cxx
@@ -3,13 +3,25 @@
#include "cmStateSnapshot.h"
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <stdio.h>
+
+#include "cmAlgorithms.h"
+#include "cmDefinitions.h"
+#include "cmListFileCache.h"
+#include "cmPropertyMap.h"
#include "cmState.h"
#include "cmStateDirectory.h"
#include "cmStatePrivate.h"
-#include "cmSystemTools.h"
#include "cmVersion.h"
#include "cmake.h"
+#if defined(__CYGWIN__)
+#include "cmSystemTools.h"
+#endif
+
cmStateSnapshot::cmStateSnapshot(cmState* state)
: State(state)
, Position()
diff --git a/Source/cmStateSnapshot.h b/Source/cmStateSnapshot.h
index 63b581d..72d0349 100644
--- a/Source/cmStateSnapshot.h
+++ b/Source/cmStateSnapshot.h
@@ -6,10 +6,10 @@
#include <cmConfigure.h> // IWYU pragma: keep
-#include <map>
#include <string>
#include <vector>
+#include "cmLinkedTree.h"
#include "cmPolicies.h"
#include "cmStateTypes.h"
diff --git a/Source/cmStateTypes.h b/Source/cmStateTypes.h
index 75f9e60..2c974c1 100644
--- a/Source/cmStateTypes.h
+++ b/Source/cmStateTypes.h
@@ -4,12 +4,12 @@
#ifndef cmStateTypes_h
#define cmStateTypes_h
+#include <cmConfigure.h> // IWYU pragma: keep
+
#include "cmLinkedTree.h"
namespace cmStateDetail {
-struct BuildsystemDirectoryStateType;
struct SnapshotDataType;
-struct PolicyStackEntry;
typedef cmLinkedTree<cmStateDetail::SnapshotDataType>::iterator PositionType;
}
diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx
index 512bc91..603c990 100644
--- a/Source/cmStringCommand.cxx
+++ b/Source/cmStringCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmStringCommand.h"
-#include <algorithm>
#include <cmsys/RegularExpression.hxx>
#include <ctype.h>
#include <sstream>
@@ -37,7 +36,9 @@ bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
}
if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
subCommand == "SHA256" || subCommand == "SHA384" ||
- subCommand == "SHA512") {
+ subCommand == "SHA512" || subCommand == "SHA3_224" ||
+ subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
+ subCommand == "SHA3_512") {
return this->HandleHashCommand(args);
}
if (subCommand == "TOLOWER") {
diff --git a/Source/cmSubdirCommand.cxx b/Source/cmSubdirCommand.cxx
index 55761bf..3727dfa 100644
--- a/Source/cmSubdirCommand.cxx
+++ b/Source/cmSubdirCommand.cxx
@@ -31,12 +31,10 @@ bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args,
// if they specified a relative path then compute the full
std::string srcPath =
- std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" +
- i->c_str();
+ std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + *i;
if (cmSystemTools::FileIsDirectory(srcPath)) {
std::string binPath =
- std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" +
- i->c_str();
+ std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + *i;
this->Makefile->AddSubDirectory(srcPath, binPath, excludeFromAll, false);
}
// otherwise it is a full path
diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx
index 0a3a1ab..029594f 100644
--- a/Source/cmSystemTools.cxx
+++ b/Source/cmSystemTools.cxx
@@ -3,6 +3,7 @@
#include "cmSystemTools.h"
#include "cmAlgorithms.h"
+#include "cmProcessOutput.h"
#if defined(CMAKE_BUILD_WITH_CMAKE)
#include "cmArchiveWrite.h"
@@ -573,7 +574,7 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
std::string* captureStdOut,
std::string* captureStdErr, int* retVal,
const char* dir, OutputOption outputflag,
- double timeout)
+ double timeout, Encoding encoding)
{
std::vector<const char*> argv;
for (std::vector<std::string>::const_iterator a = command.begin();
@@ -609,6 +610,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
char* data;
int length;
int pipe;
+ cmProcessOutput processOutput(encoding);
+ std::string strdata;
if (outputflag != OUTPUT_PASSTHROUGH &&
(captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) >
@@ -624,28 +627,44 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
if (pipe == cmsysProcess_Pipe_STDOUT) {
if (outputflag != OUTPUT_NONE) {
- cmSystemTools::Stdout(data, length);
+ processOutput.DecodeText(data, length, strdata, 1);
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
}
if (captureStdOut) {
tempStdOut.insert(tempStdOut.end(), data, data + length);
}
} else if (pipe == cmsysProcess_Pipe_STDERR) {
if (outputflag != OUTPUT_NONE) {
- cmSystemTools::Stderr(data, length);
+ processOutput.DecodeText(data, length, strdata, 2);
+ cmSystemTools::Stderr(strdata.c_str(), strdata.size());
}
if (captureStdErr) {
tempStdErr.insert(tempStdErr.end(), data, data + length);
}
}
}
+
+ if (outputflag != OUTPUT_NONE) {
+ processOutput.DecodeText(std::string(), strdata, 1);
+ if (!strdata.empty()) {
+ cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+ }
+ processOutput.DecodeText(std::string(), strdata, 2);
+ if (!strdata.empty()) {
+ cmSystemTools::Stderr(strdata.c_str(), strdata.size());
+ }
+ }
}
cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+
if (captureStdOut) {
captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
+ processOutput.DecodeText(*captureStdOut, *captureStdOut);
}
if (captureStdErr) {
captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
+ processOutput.DecodeText(*captureStdErr, *captureStdErr);
}
bool result = true;
@@ -847,8 +866,8 @@ bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
{
#if defined(CMAKE_BUILD_WITH_CMAKE)
- cmCryptoHashMD5 md5;
- std::string str = md5.HashFile(source);
+ cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+ std::string const str = md5.HashFile(source);
strncpy(md5out, str.c_str(), 32);
return !str.empty();
#else
@@ -863,7 +882,7 @@ bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
std::string cmSystemTools::ComputeStringMD5(const std::string& input)
{
#if defined(CMAKE_BUILD_WITH_CMAKE)
- cmCryptoHashMD5 md5;
+ cmCryptoHash md5(cmCryptoHash::AlgoMD5);
return md5.HashString(input);
#else
(void)input;
@@ -1643,6 +1662,8 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
line = "";
std::vector<char>::iterator outiter = out.begin();
std::vector<char>::iterator erriter = err.begin();
+ cmProcessOutput processOutput;
+ std::string strdata;
while (1) {
// Check for a newline in stdout.
for (; outiter != out.end(); ++outiter) {
@@ -1687,17 +1708,31 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
return pipe;
}
if (pipe == cmsysProcess_Pipe_STDOUT) {
+ processOutput.DecodeText(data, length, strdata, 1);
// Append to the stdout buffer.
std::vector<char>::size_type size = out.size();
- out.insert(out.end(), data, data + length);
+ out.insert(out.end(), strdata.begin(), strdata.end());
outiter = out.begin() + size;
} else if (pipe == cmsysProcess_Pipe_STDERR) {
+ processOutput.DecodeText(data, length, strdata, 2);
// Append to the stderr buffer.
std::vector<char>::size_type size = err.size();
- err.insert(err.end(), data, data + length);
+ err.insert(err.end(), strdata.begin(), strdata.end());
erriter = err.begin() + size;
} else if (pipe == cmsysProcess_Pipe_None) {
// Both stdout and stderr pipes have broken. Return leftover data.
+ processOutput.DecodeText(std::string(), strdata, 1);
+ if (!strdata.empty()) {
+ std::vector<char>::size_type size = out.size();
+ out.insert(out.end(), strdata.begin(), strdata.end());
+ outiter = out.begin() + size;
+ }
+ processOutput.DecodeText(std::string(), strdata, 2);
+ if (!strdata.empty()) {
+ std::vector<char>::size_type size = err.size();
+ err.insert(err.end(), strdata.begin(), strdata.end());
+ erriter = err.begin() + size;
+ }
if (!out.empty()) {
line.append(&out[0], outiter - out.begin());
out.erase(out.begin(), out.end());
diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h
index 9817a3c..10e8280 100644
--- a/Source/cmSystemTools.h
+++ b/Source/cmSystemTools.h
@@ -5,12 +5,19 @@
#include <cmConfigure.h> // IWYU pragma: keep
+#include <cmProcessOutput.h>
#include <cmsys/Process.h>
#include <cmsys/SystemTools.hxx>
#include <stddef.h>
#include <string>
#include <vector>
+#if defined(_MSC_VER)
+typedef unsigned short mode_t;
+#else
+#include <sys/types.h>
+#endif
+
class cmSystemToolsFileTime;
/** \class cmSystemTools
@@ -23,6 +30,7 @@ class cmSystemTools : public cmsys::SystemTools
{
public:
typedef cmsys::SystemTools Superclass;
+ typedef cmProcessOutput::Encoding Encoding;
/** Expand out any arguments in the vector that have ; separated
* strings into multiple arguments. A new vector is created
@@ -233,7 +241,8 @@ public:
int* retVal = CM_NULLPTR,
const char* dir = CM_NULLPTR,
OutputOption outputflag = OUTPUT_MERGE,
- double timeout = 0.0);
+ double timeout = 0.0,
+ Encoding encoding = cmProcessOutput::Auto);
static std::string PrintSingleCommand(std::vector<std::string> const&);
diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx
index 25ae339..ee4ff39 100644
--- a/Source/cmTarget.cxx
+++ b/Source/cmTarget.cxx
@@ -2,6 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTarget.h"
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <set>
+#include <sstream>
+#include <string.h>
+
#include "cmAlgorithms.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
@@ -14,19 +22,13 @@
#include "cmSourceFile.h"
#include "cmSourceFileLocation.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmTargetPropertyComputer.h"
#include "cm_unordered_set.hxx"
#include "cmake.h"
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <map>
-#include <set>
-#include <sstream>
-#include <string.h>
-
template <>
const char* cmTargetPropertyComputer::ComputeLocationForBuild<cmTarget>(
cmTarget const* tgt)
@@ -251,7 +253,6 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
this->SetPropertyDefault("WIN32_EXECUTABLE", CM_NULLPTR);
this->SetPropertyDefault("MACOSX_BUNDLE", CM_NULLPTR);
this->SetPropertyDefault("MACOSX_RPATH", CM_NULLPTR);
- this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", CM_NULLPTR);
this->SetPropertyDefault("C_CLANG_TIDY", CM_NULLPTR);
this->SetPropertyDefault("C_COMPILER_LAUNCHER", CM_NULLPTR);
this->SetPropertyDefault("C_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
@@ -265,10 +266,17 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
this->SetPropertyDefault("CXX_STANDARD", CM_NULLPTR);
this->SetPropertyDefault("CXX_STANDARD_REQUIRED", CM_NULLPTR);
this->SetPropertyDefault("CXX_EXTENSIONS", CM_NULLPTR);
+ this->SetPropertyDefault("CUDA_STANDARD", CM_NULLPTR);
+ this->SetPropertyDefault("CUDA_STANDARD_REQUIRED", CM_NULLPTR);
+ this->SetPropertyDefault("CUDA_EXTENSIONS", CM_NULLPTR);
this->SetPropertyDefault("LINK_SEARCH_START_STATIC", CM_NULLPTR);
this->SetPropertyDefault("LINK_SEARCH_END_STATIC", CM_NULLPTR);
}
+ if (this->GetType() != cmStateEnums::UTILITY) {
+ this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", CM_NULLPTR);
+ }
+
// Collect the set of configuration types.
std::vector<std::string> configNames;
mf->GetConfigurations(configNames);
@@ -289,6 +297,8 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
ci != configNames.end(); ++ci) {
std::string configUpper = cmSystemTools::UpperCase(*ci);
for (const char** p = configProps; *p; ++p) {
+ // Interface libraries have no output locations, so honor only
+ // the configuration map.
if (this->TargetTypeValue == cmStateEnums::INTERFACE_LIBRARY &&
strcmp(*p, "MAP_IMPORTED_CONFIG_") != 0) {
continue;
@@ -353,6 +363,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
this->GetType() != cmStateEnums::UTILITY) {
this->SetPropertyDefault("C_VISIBILITY_PRESET", CM_NULLPTR);
this->SetPropertyDefault("CXX_VISIBILITY_PRESET", CM_NULLPTR);
+ this->SetPropertyDefault("CUDA_VISIBILITY_PRESET", CM_NULLPTR);
this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", CM_NULLPTR);
}
@@ -910,6 +921,9 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
this->Internal->SourceEntries.push_back(value);
this->Internal->SourceBacktraces.push_back(lfbt);
}
+ } else if (cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME") &&
+ !this->CheckImportedLibName(prop, value ? value : "")) {
+ /* error was reported by check method */
} else {
this->Properties.SetProperty(prop, value);
}
@@ -977,6 +991,9 @@ void cmTarget::AppendProperty(const std::string& prop, const char* value,
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
this->Internal->SourceEntries.push_back(value);
this->Internal->SourceBacktraces.push_back(lfbt);
+ } else if (cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME")) {
+ this->Makefile->IssueMessage(cmake::FATAL_ERROR,
+ prop + " property may not be APPENDed.");
} else {
this->Properties.AppendProperty(prop, value, asString);
}
@@ -1372,18 +1389,41 @@ void cmTarget::SetPropertyDefault(const std::string& property,
}
}
+bool cmTarget::CheckImportedLibName(std::string const& prop,
+ std::string const& value) const
+{
+ if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY ||
+ !this->IsImported()) {
+ this->Makefile->IssueMessage(
+ cmake::FATAL_ERROR, prop +
+ " property may be set only on imported INTERFACE library targets.");
+ return false;
+ }
+ if (!value.empty()) {
+ if (value[0] == '-') {
+ this->Makefile->IssueMessage(cmake::FATAL_ERROR, prop +
+ " property value\n " + value +
+ "\nmay not start with '-'.");
+ return false;
+ }
+ std::string::size_type bad = value.find_first_of(":/\\;");
+ if (bad != value.npos) {
+ this->Makefile->IssueMessage(
+ cmake::FATAL_ERROR, prop + " property value\n " + value +
+ "\nmay not contain '" + value.substr(bad, 1) + "'.");
+ return false;
+ }
+ }
+ return true;
+}
+
bool cmTarget::GetMappedConfig(std::string const& desired_config,
const char** loc, const char** imp,
std::string& suffix) const
{
- if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
- // This method attempts to find a config-specific LOCATION for the
- // IMPORTED library. In the case of cmStateEnums::INTERFACE_LIBRARY, there
- // is no
- // LOCATION at all, so leaving *loc and *imp unchanged is the appropriate
- // and valid response.
- return true;
- }
+ std::string const locPropBase =
+ this->GetType() == cmStateEnums::INTERFACE_LIBRARY ? "IMPORTED_LIBNAME"
+ : "IMPORTED_LOCATION";
// Track the configuration-specific property suffix.
suffix = "_";
@@ -1410,7 +1450,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
if (mci->empty()) {
// An empty string in the mapping has a special meaning:
// look up the config-less properties.
- *loc = this->GetProperty("IMPORTED_LOCATION");
+ *loc = this->GetProperty(locPropBase);
if (allowImp) {
*imp = this->GetProperty("IMPORTED_IMPLIB");
}
@@ -1420,7 +1460,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
}
} else {
std::string mcUpper = cmSystemTools::UpperCase(*mci);
- std::string locProp = "IMPORTED_LOCATION_";
+ std::string locProp = locPropBase + "_";
locProp += mcUpper;
*loc = this->GetProperty(locProp);
if (allowImp) {
@@ -1438,16 +1478,18 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
}
// If we needed to find one of the mapped configurations but did not
- // then the target is not found. The project does not want any
- // other configuration.
+ // then the target location is not found. The project does not want
+ // any other configuration.
if (!mappedConfigs.empty() && !*loc && !*imp) {
- return false;
+ // Interface libraries are always available because their
+ // library name is optional so it is okay to leave *loc empty.
+ return this->GetType() == cmStateEnums::INTERFACE_LIBRARY;
}
// If we have not yet found it then there are no mapped
// configurations. Look for an exact-match.
if (!*loc && !*imp) {
- std::string locProp = "IMPORTED_LOCATION";
+ std::string locProp = locPropBase;
locProp += suffix;
*loc = this->GetProperty(locProp);
if (allowImp) {
@@ -1465,7 +1507,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
// Look for a configuration-less location. This may be set by
// manually-written code.
- *loc = this->GetProperty("IMPORTED_LOCATION");
+ *loc = this->GetProperty(locPropBase);
if (allowImp) {
*imp = this->GetProperty("IMPORTED_IMPLIB");
}
@@ -1483,7 +1525,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
!*loc && !*imp && aci != availableConfigs.end(); ++aci) {
suffix = "_";
suffix += cmSystemTools::UpperCase(*aci);
- std::string locProp = "IMPORTED_LOCATION";
+ std::string locProp = locPropBase;
locProp += suffix;
*loc = this->GetProperty(locProp);
if (allowImp) {
@@ -1493,9 +1535,11 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
}
}
}
- // If we have not yet found it then the target is not available.
+ // If we have not yet found it then the target location is not available.
if (!*loc && !*imp) {
- return false;
+ // Interface libraries are always available because their
+ // library name is optional so it is okay to leave *loc empty.
+ return this->GetType() == cmStateEnums::INTERFACE_LIBRARY;
}
return true;
diff --git a/Source/cmTarget.h b/Source/cmTarget.h
index 1f035a1..1d40d20 100644
--- a/Source/cmTarget.h
+++ b/Source/cmTarget.h
@@ -5,6 +5,13 @@
#include <cmConfigure.h> // IWYU pragma: keep
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
#include "cmAlgorithms.h"
#include "cmCustomCommand.h"
#include "cmListFileCache.h"
@@ -14,16 +21,10 @@
#include "cmTargetLinkLibraryType.h"
#include "cm_unordered_map.hxx"
-#include <iosfwd>
-#include <map>
-#include <set>
-#include <string>
-#include <utility>
-#include <vector>
-
+class cmGlobalGenerator;
class cmMakefile;
+class cmMessenger;
class cmSourceFile;
-class cmGlobalGenerator;
class cmTargetInternals;
class cmTargetInternalPointer
@@ -277,6 +278,9 @@ private:
void SetPropertyDefault(const std::string& property,
const char* default_value);
+ bool CheckImportedLibName(std::string const& prop,
+ std::string const& value) const;
+
private:
cmPropertyMap Properties;
std::set<std::string> SystemIncludeDirectories;
diff --git a/Source/cmTargetCompileFeaturesCommand.cxx b/Source/cmTargetCompileFeaturesCommand.cxx
index a1c9b82..1b6c008 100644
--- a/Source/cmTargetCompileFeaturesCommand.cxx
+++ b/Source/cmTargetCompileFeaturesCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTargetCompileFeaturesCommand.h"
-#include <algorithm>
#include <sstream>
#include "cmAlgorithms.h"
diff --git a/Source/cmTargetCompileOptionsCommand.cxx b/Source/cmTargetCompileOptionsCommand.cxx
index a4db55b..1b4056d 100644
--- a/Source/cmTargetCompileOptionsCommand.cxx
+++ b/Source/cmTargetCompileOptionsCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTargetCompileOptionsCommand.h"
-#include <algorithm>
#include <sstream>
#include "cmAlgorithms.h"
diff --git a/Source/cmTargetDepend.h b/Source/cmTargetDepend.h
index acea6ea..a953efb 100644
--- a/Source/cmTargetDepend.h
+++ b/Source/cmTargetDepend.h
@@ -3,9 +3,9 @@
#ifndef cmTargetDepend_h
#define cmTargetDepend_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <set>
class cmGeneratorTarget;
diff --git a/Source/cmTargetExport.h b/Source/cmTargetExport.h
index 634148b..b08ede2 100644
--- a/Source/cmTargetExport.h
+++ b/Source/cmTargetExport.h
@@ -3,13 +3,13 @@
#ifndef cmTargetExport_h
#define cmTargetExport_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <string>
class cmGeneratorTarget;
-class cmInstallTargetGenerator;
class cmInstallFilesGenerator;
+class cmInstallTargetGenerator;
/** \brief A member of an ExportSet
*
diff --git a/Source/cmTargetPropCommandBase.cxx b/Source/cmTargetPropCommandBase.cxx
index 7aba0f8..9a5c1da 100644
--- a/Source/cmTargetPropCommandBase.cxx
+++ b/Source/cmTargetPropCommandBase.cxx
@@ -4,6 +4,9 @@
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmTarget.h"
+#include "cmake.h"
bool cmTargetPropCommandBase::HandleArguments(
std::vector<std::string> const& args, const std::string& prop,
diff --git a/Source/cmTargetPropCommandBase.h b/Source/cmTargetPropCommandBase.h
index 485a7f3..8b49653 100644
--- a/Source/cmTargetPropCommandBase.h
+++ b/Source/cmTargetPropCommandBase.h
@@ -3,6 +3,11 @@
#ifndef cmTargetPropCommandBase_h
#define cmTargetPropCommandBase_h
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
#include "cmCommand.h"
class cmTarget;
diff --git a/Source/cmTargetPropertyComputer.cxx b/Source/cmTargetPropertyComputer.cxx
index 7cf1fd8..a57bc5a 100644
--- a/Source/cmTargetPropertyComputer.cxx
+++ b/Source/cmTargetPropertyComputer.cxx
@@ -3,14 +3,13 @@
#include "cmTargetPropertyComputer.h"
-#include "cmGeneratorTarget.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
+#include <sstream>
+
#include "cmMessenger.h"
-#include "cmSourceFile.h"
-#include "cmSourceFileLocation.h"
-#include "cmTarget.h"
+#include "cmPolicies.h"
+#include "cmStateSnapshot.h"
#include "cm_unordered_set.hxx"
+#include "cmake.h"
bool cmTargetPropertyComputer::HandleLocationPropertyPolicy(
std::string const& tgtName, cmMessenger* messenger,
@@ -66,7 +65,10 @@ bool cmTargetPropertyComputer::WhiteListedInterfaceProperty(
return true;
}
- if (cmHasLiteralPrefix(prop, "MAP_IMPORTED_CONFIG_")) {
+ if (prop == "IMPORTED_CONFIGURATIONS" || prop == "IMPORTED_LIBNAME" ||
+ prop == "NO_SYSTEM_FROM_IMPORTED" ||
+ cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME_") ||
+ cmHasLiteralPrefix(prop, "MAP_IMPORTED_CONFIG_")) {
return true;
}
diff --git a/Source/cmTargetPropertyComputer.h b/Source/cmTargetPropertyComputer.h
index 7989589..45d31be 100644
--- a/Source/cmTargetPropertyComputer.h
+++ b/Source/cmTargetPropertyComputer.h
@@ -5,14 +5,13 @@
#include <cmConfigure.h> // IWYU pragma: keep
+#include <string>
+
#include "cmAlgorithms.h"
#include "cmListFileCache.h"
+#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include <map>
-#include <string>
-
-class cmTarget;
class cmMessenger;
class cmTargetPropertyComputer
diff --git a/Source/cmTargetSourcesCommand.cxx b/Source/cmTargetSourcesCommand.cxx
index 13c9a8f..058659a 100644
--- a/Source/cmTargetSourcesCommand.cxx
+++ b/Source/cmTargetSourcesCommand.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTargetSourcesCommand.h"
-#include <algorithm>
#include <sstream>
#include "cmAlgorithms.h"
diff --git a/Source/cmTest.cxx b/Source/cmTest.cxx
index 1c36dc6..4d0cbaa 100644
--- a/Source/cmTest.cxx
+++ b/Source/cmTest.cxx
@@ -5,7 +5,6 @@
#include "cmMakefile.h"
#include "cmProperty.h"
#include "cmState.h"
-#include "cmStateTypes.h"
#include "cmSystemTools.h"
cmTest::cmTest(cmMakefile* mf)
diff --git a/Source/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx
index 843f7b1..4164f3a 100644
--- a/Source/cmTestGenerator.cxx
+++ b/Source/cmTestGenerator.cxx
@@ -2,6 +2,10 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTestGenerator.h"
+#include <map>
+#include <ostream>
+#include <utility>
+
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmLocalGenerator.h"
@@ -11,11 +15,6 @@
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTest.h"
-#include "cm_auto_ptr.hxx"
-
-#include <map>
-#include <ostream>
-#include <utility>
cmTestGenerator::cmTestGenerator(
cmTest* test, std::vector<std::string> const& configurations)
diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx
index 9597e09..589f195 100644
--- a/Source/cmTimestamp.cxx
+++ b/Source/cmTimestamp.cxx
@@ -2,15 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTimestamp.h"
-#include "cmSystemTools.h"
-
-#include <cstdlib>
+#include <cmConfigure.h>
#include <cstring>
#include <sstream>
-#include <sys/types.h>
-// include sys/stat.h after sys/types.h
-#include <sys/stat.h>
+#include "cmSystemTools.h"
std::string cmTimestamp::CurrentTime(const std::string& formatString,
bool utcFlag)
diff --git a/Source/cmTimestamp.h b/Source/cmTimestamp.h
index 44e397b..fdee564 100644
--- a/Source/cmTimestamp.h
+++ b/Source/cmTimestamp.h
@@ -3,9 +3,7 @@
#ifndef cmTimestamp_h
#define cmTimestamp_h
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
#include <string>
#include <time.h>
diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx
index 9457d5b..c4fc94e 100644
--- a/Source/cmTryRunCommand.cxx
+++ b/Source/cmTryRunCommand.cxx
@@ -86,8 +86,9 @@ bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
// although they could be used together, don't allow it, because
// using OUTPUT_VARIABLE makes crosscompiling harder
- if (this->OutputVariable.size() && (!this->RunOutputVariable.empty() ||
- !this->CompileOutputVariable.empty())) {
+ if (!this->OutputVariable.empty() &&
+ (!this->RunOutputVariable.empty() ||
+ !this->CompileOutputVariable.empty())) {
cmSystemTools::Error(
"You cannot use OUTPUT_VARIABLE together with COMPILE_OUTPUT_VARIABLE "
"or RUN_OUTPUT_VARIABLE. Please use only COMPILE_OUTPUT_VARIABLE and/or "
diff --git a/Source/cmUnexpectedCommand.cxx b/Source/cmUnexpectedCommand.cxx
new file mode 100644
index 0000000..a8de9e6
--- /dev/null
+++ b/Source/cmUnexpectedCommand.cxx
@@ -0,0 +1,22 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmUnexpectedCommand.h"
+
+#include <stdlib.h>
+
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
+bool cmUnexpectedCommand::InitialPass(std::vector<std::string> const&,
+ cmExecutionStatus&)
+{
+ const char* versionValue =
+ this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
+ if (this->Name == "endif" && (!versionValue || atof(versionValue) <= 1.4)) {
+ return true;
+ }
+
+ this->SetError(this->Error);
+ return false;
+}
diff --git a/Source/cmUnexpectedCommand.h b/Source/cmUnexpectedCommand.h
new file mode 100644
index 0000000..897dfb6
--- /dev/null
+++ b/Source/cmUnexpectedCommand.h
@@ -0,0 +1,40 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmUnexpectedCommand_h
+#define cmUnexpectedCommand_h
+
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
+#include "cmCommand.h"
+
+class cmExecutionStatus;
+
+class cmUnexpectedCommand : public cmCommand
+{
+public:
+ cmUnexpectedCommand(std::string const& name, const char* error)
+ : Name(name)
+ , Error(error)
+ {
+ }
+
+ cmCommand* Clone() CM_OVERRIDE
+ {
+ return new cmUnexpectedCommand(this->Name, this->Error);
+ }
+
+ bool InitialPass(std::vector<std::string> const& args,
+ cmExecutionStatus& status) CM_OVERRIDE;
+
+ bool IsScriptable() const CM_OVERRIDE { return true; }
+
+ std::string GetName() const CM_OVERRIDE { return this->Name; }
+
+private:
+ std::string Name;
+ const char* Error;
+};
+
+#endif
diff --git a/Source/cmUseMangledMesaCommand.cxx b/Source/cmUseMangledMesaCommand.cxx
index ffeaa51..3e72d75 100644
--- a/Source/cmUseMangledMesaCommand.cxx
+++ b/Source/cmUseMangledMesaCommand.cxx
@@ -108,5 +108,5 @@ void cmUseMangledMesaCommand::CopyAndFullPathMesaHeader(const char* source,
fin.close();
fout.close();
cmSystemTools::CopyFileIfDifferent(tempOutputFile.c_str(), outFile.c_str());
- cmSystemTools::RemoveFile(tempOutputFile.c_str());
+ cmSystemTools::RemoveFile(tempOutputFile);
}
diff --git a/Source/cmUuid.cxx b/Source/cmUuid.cxx
index 904bcbb..201e1cc 100644
--- a/Source/cmUuid.cxx
+++ b/Source/cmUuid.cxx
@@ -2,9 +2,8 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmUuid.h"
-#include "cm_sha2.h"
+#include "cmCryptoHash.h"
-#include <cmsys/MD5.h>
#include <string.h>
cmUuid::cmUuid()
@@ -22,16 +21,12 @@ std::string cmUuid::FromMd5(std::vector<unsigned char> const& uuidNamespace,
std::vector<unsigned char> hashInput;
this->CreateHashInput(uuidNamespace, name, hashInput);
- cmsysMD5_s* md5 = cmsysMD5_New();
- cmsysMD5_Initialize(md5);
- cmsysMD5_Append(md5, &hashInput[0], int(hashInput.size()));
+ cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+ md5.Initialize();
+ md5.Append(&hashInput[0], hashInput.size());
+ std::vector<unsigned char> digest = md5.Finalize();
- unsigned char digest[16] = { 0 };
- cmsysMD5_Finalize(md5, digest);
-
- cmsysMD5_Delete(md5);
-
- return this->FromDigest(digest, 3);
+ return this->FromDigest(&digest[0], 3);
}
std::string cmUuid::FromSha1(std::vector<unsigned char> const& uuidNamespace,
@@ -40,16 +35,12 @@ std::string cmUuid::FromSha1(std::vector<unsigned char> const& uuidNamespace,
std::vector<unsigned char> hashInput;
this->CreateHashInput(uuidNamespace, name, hashInput);
- SHA_CTX* sha = new SHA_CTX;
- SHA1_Init(sha);
- SHA1_Update(sha, &hashInput[0], hashInput.size());
-
- unsigned char digest[SHA1_DIGEST_LENGTH] = { 0 };
- SHA1_Final(digest, sha);
-
- delete sha;
+ cmCryptoHash sha1(cmCryptoHash::AlgoSHA1);
+ sha1.Initialize();
+ sha1.Append(&hashInput[0], hashInput.size());
+ std::vector<unsigned char> digest = sha1.Finalize();
- return this->FromDigest(digest, 5);
+ return this->FromDigest(&digest[0], 5);
}
void cmUuid::CreateHashInput(std::vector<unsigned char> const& uuidNamespace,
diff --git a/Source/cmVS10CSharpFlagTable.h b/Source/cmVS10CSharpFlagTable.h
new file mode 100644
index 0000000..493ec2b
--- /dev/null
+++ b/Source/cmVS10CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS10CSharpFlagTable[] = {
+ { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "OutputType", "target:exe", "", "Exe", 0 },
+ { "OutputType", "target:winexe", "", "Winexe", 0 },
+ { "OutputType", "target:library", "", "Library", 0 },
+ { "OutputType", "target:module", "", "Module", 0 },
+
+ { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "Platform", "platform:x86", "", "x86", 0 },
+ { "Platform", "platform:Itanium", "", "Itanium", 0 },
+ { "Platform", "platform:x64", "", "x64", 0 },
+ { "Platform", "platform:arm", "", "arm", 0 },
+ { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+ 0 },
+ { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+ { "References", "reference:", "mit alias", "", 0 },
+ { "References", "reference:", "dateiliste", "", 0 },
+ { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+ { "", "link", "", "", 0 },
+
+ { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+ { "ApplicationIcon", "win32icon", "", "",
+ cmIDEFlagTable::UserValueRequired },
+
+ { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+ { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+ { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+ { "DebugSymbols", "debug", "", "true", 0 },
+ { "DebugSymbols", "debug-", "", "false", 0 },
+ { "DebugSymbols", "debug+", "", "true", 0 },
+
+ { "DebugType", "debug:none", "", "none", 0 },
+ { "DebugType", "debug:full", "", "full", 0 },
+ { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+ { "Optimize", "optimize", "", "true", 0 },
+ { "Optimize", "optimize-", "", "false", 0 },
+ { "Optimize", "optimize+", "", "true", 0 },
+
+ { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+ { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+ { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+ { "WarningsAsErrors", "warnaserror", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+ { "WarningLevel", "warn:0", "", "0", 0 },
+ { "WarningLevel", "warn:1", "", "1", 0 },
+ { "WarningLevel", "warn:2", "", "2", 0 },
+ { "WarningLevel", "warn:3", "", "3", 0 },
+ { "WarningLevel", "warn:4", "", "4", 0 },
+ { "DisabledWarnings", "nowarn", "", "", 0 },
+
+ { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+ { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+ { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+ { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+ { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+ { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+ { "DefineConstants", "define:", "", "",
+ cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+ { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+ { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+ { "LangVersion", "langversion:3", "", "3", 0 },
+ { "LangVersion", "langversion:4", "", "4", 0 },
+ { "LangVersion", "langversion:5", "", "5", 0 },
+ { "LangVersion", "langversion:6", "", "6", 0 },
+ { "LangVersion", "langversion:default", "", "default", 0 },
+
+ { "DelaySign", "delaysign", "", "true", 0 },
+ { "DelaySign", "delaysign-", "", "false", 0 },
+ { "DelaySign", "delaysign+", "", "true", 0 },
+
+ { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+ { "KeyContainerName", "keycontainer", "", "", 0 },
+
+ { "NoLogo", "nologo", "", "", 0 },
+
+ { "NoConfig", "noconfig", "", "true", 0 },
+
+ { "BaseAddress", "baseaddress:", "", "", 0 },
+
+ { "CodePage", "codepage", "", "", 0 },
+
+ { "Utf8Output", "utf8output", "", "", 0 },
+
+ { "MainEntryPoint", "main:", "", "", 0 },
+
+ { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+ { "FileAlignment", "filealign", "", "", 0 },
+
+ { "PdbFile", "pdb:", "", "", 0 },
+
+ { "NoStandardLib", "nostdlib", "", "true", 0 },
+ { "NoStandardLib", "nostdlib-", "", "false", 0 },
+ { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+ { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+ { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+ { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+ { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+ { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+ { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+ { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS11CSharpFlagTable.h b/Source/cmVS11CSharpFlagTable.h
new file mode 100644
index 0000000..71870b6
--- /dev/null
+++ b/Source/cmVS11CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS11CSharpFlagTable[] = {
+ { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "OutputType", "target:exe", "", "Exe", 0 },
+ { "OutputType", "target:winexe", "", "Winexe", 0 },
+ { "OutputType", "target:library", "", "Library", 0 },
+ { "OutputType", "target:module", "", "Module", 0 },
+
+ { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "Platform", "platform:x86", "", "x86", 0 },
+ { "Platform", "platform:Itanium", "", "Itanium", 0 },
+ { "Platform", "platform:x64", "", "x64", 0 },
+ { "Platform", "platform:arm", "", "arm", 0 },
+ { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+ 0 },
+ { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+ { "References", "reference:", "mit alias", "", 0 },
+ { "References", "reference:", "dateiliste", "", 0 },
+ { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+ { "", "link", "", "", 0 },
+
+ { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+ { "ApplicationIcon", "win32icon", "", "",
+ cmIDEFlagTable::UserValueRequired },
+
+ { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+ { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+ { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+ { "DebugSymbols", "debug", "", "true", 0 },
+ { "DebugSymbols", "debug-", "", "false", 0 },
+ { "DebugSymbols", "debug+", "", "true", 0 },
+
+ { "DebugType", "debug:none", "", "none", 0 },
+ { "DebugType", "debug:full", "", "full", 0 },
+ { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+ { "Optimize", "optimize", "", "true", 0 },
+ { "Optimize", "optimize-", "", "false", 0 },
+ { "Optimize", "optimize+", "", "true", 0 },
+
+ { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+ { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+ { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+ { "WarningsAsErrors", "warnaserror", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+ { "WarningLevel", "warn:0", "", "0", 0 },
+ { "WarningLevel", "warn:1", "", "1", 0 },
+ { "WarningLevel", "warn:2", "", "2", 0 },
+ { "WarningLevel", "warn:3", "", "3", 0 },
+ { "WarningLevel", "warn:4", "", "4", 0 },
+ { "DisabledWarnings", "nowarn", "", "", 0 },
+
+ { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+ { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+ { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+ { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+ { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+ { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+ { "DefineConstants", "define:", "", "",
+ cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+ { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+ { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+ { "LangVersion", "langversion:3", "", "3", 0 },
+ { "LangVersion", "langversion:4", "", "4", 0 },
+ { "LangVersion", "langversion:5", "", "5", 0 },
+ { "LangVersion", "langversion:6", "", "6", 0 },
+ { "LangVersion", "langversion:default", "", "default", 0 },
+
+ { "DelaySign", "delaysign", "", "true", 0 },
+ { "DelaySign", "delaysign-", "", "false", 0 },
+ { "DelaySign", "delaysign+", "", "true", 0 },
+
+ { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+ { "KeyContainerName", "keycontainer", "", "", 0 },
+
+ { "NoLogo", "nologo", "", "", 0 },
+
+ { "NoConfig", "noconfig", "", "true", 0 },
+
+ { "BaseAddress", "baseaddress:", "", "", 0 },
+
+ { "CodePage", "codepage", "", "", 0 },
+
+ { "Utf8Output", "utf8output", "", "", 0 },
+
+ { "MainEntryPoint", "main:", "", "", 0 },
+
+ { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+ { "FileAlignment", "filealign", "", "", 0 },
+
+ { "PdbFile", "pdb:", "", "", 0 },
+
+ { "NoStandardLib", "nostdlib", "", "true", 0 },
+ { "NoStandardLib", "nostdlib-", "", "false", 0 },
+ { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+ { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+ { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+ { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+ { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+ { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+ { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+ { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS12CSharpFlagTable.h b/Source/cmVS12CSharpFlagTable.h
new file mode 100644
index 0000000..f98b184
--- /dev/null
+++ b/Source/cmVS12CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS12CSharpFlagTable[] = {
+ { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "OutputType", "target:exe", "", "Exe", 0 },
+ { "OutputType", "target:winexe", "", "Winexe", 0 },
+ { "OutputType", "target:library", "", "Library", 0 },
+ { "OutputType", "target:module", "", "Module", 0 },
+
+ { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "Platform", "platform:x86", "", "x86", 0 },
+ { "Platform", "platform:Itanium", "", "Itanium", 0 },
+ { "Platform", "platform:x64", "", "x64", 0 },
+ { "Platform", "platform:arm", "", "arm", 0 },
+ { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+ 0 },
+ { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+ { "References", "reference:", "mit alias", "", 0 },
+ { "References", "reference:", "dateiliste", "", 0 },
+ { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+ { "", "link", "", "", 0 },
+
+ { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+ { "ApplicationIcon", "win32icon", "", "",
+ cmIDEFlagTable::UserValueRequired },
+
+ { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+ { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+ { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+ { "DebugSymbols", "debug", "", "true", 0 },
+ { "DebugSymbols", "debug-", "", "false", 0 },
+ { "DebugSymbols", "debug+", "", "true", 0 },
+
+ { "DebugType", "debug:none", "", "none", 0 },
+ { "DebugType", "debug:full", "", "full", 0 },
+ { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+ { "Optimize", "optimize", "", "true", 0 },
+ { "Optimize", "optimize-", "", "false", 0 },
+ { "Optimize", "optimize+", "", "true", 0 },
+
+ { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+ { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+ { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+ { "WarningsAsErrors", "warnaserror", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+ { "WarningLevel", "warn:0", "", "0", 0 },
+ { "WarningLevel", "warn:1", "", "1", 0 },
+ { "WarningLevel", "warn:2", "", "2", 0 },
+ { "WarningLevel", "warn:3", "", "3", 0 },
+ { "WarningLevel", "warn:4", "", "4", 0 },
+ { "DisabledWarnings", "nowarn", "", "", 0 },
+
+ { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+ { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+ { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+ { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+ { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+ { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+ { "DefineConstants", "define:", "", "",
+ cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+ { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+ { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+ { "LangVersion", "langversion:3", "", "3", 0 },
+ { "LangVersion", "langversion:4", "", "4", 0 },
+ { "LangVersion", "langversion:5", "", "5", 0 },
+ { "LangVersion", "langversion:6", "", "6", 0 },
+ { "LangVersion", "langversion:default", "", "default", 0 },
+
+ { "DelaySign", "delaysign", "", "true", 0 },
+ { "DelaySign", "delaysign-", "", "false", 0 },
+ { "DelaySign", "delaysign+", "", "true", 0 },
+
+ { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+ { "KeyContainerName", "keycontainer", "", "", 0 },
+
+ { "NoLogo", "nologo", "", "", 0 },
+
+ { "NoConfig", "noconfig", "", "true", 0 },
+
+ { "BaseAddress", "baseaddress:", "", "", 0 },
+
+ { "CodePage", "codepage", "", "", 0 },
+
+ { "Utf8Output", "utf8output", "", "", 0 },
+
+ { "MainEntryPoint", "main:", "", "", 0 },
+
+ { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+ { "FileAlignment", "filealign", "", "", 0 },
+
+ { "PdbFile", "pdb:", "", "", 0 },
+
+ { "NoStandardLib", "nostdlib", "", "true", 0 },
+ { "NoStandardLib", "nostdlib-", "", "false", 0 },
+ { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+ { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+ { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+ { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+ { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+ { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+ { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+ { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS140CLFlagTable.h b/Source/cmVS140CLFlagTable.h
index 317cc18..60b4379 100644
--- a/Source/cmVS140CLFlagTable.h
+++ b/Source/cmVS140CLFlagTable.h
@@ -164,6 +164,8 @@ static cmVS7FlagTable cmVS140CLFlagTable[] = {
{ "TreatWChar_tAsBuiltInType", "Zc:wchar_t", "", "true", 0 },
{ "ForceConformanceInForLoopScope", "Zc:forScope-", "", "false", 0 },
{ "ForceConformanceInForLoopScope", "Zc:forScope", "", "true", 0 },
+ { "RemoveUnreferencedCodeData", "Zc:inline-", "", "false", 0 },
+ { "RemoveUnreferencedCodeData", "Zc:inline", "", "true", 0 },
{ "RuntimeTypeInfo", "GR-", "", "false", 0 },
{ "RuntimeTypeInfo", "GR", "", "true", 0 },
{ "OpenMPSupport", "openmp-", "", "false", 0 },
diff --git a/Source/cmVS140CSharpFlagTable.h b/Source/cmVS140CSharpFlagTable.h
new file mode 100644
index 0000000..256c35f
--- /dev/null
+++ b/Source/cmVS140CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS140CSharpFlagTable[] = {
+ { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "OutputType", "target:exe", "", "Exe", 0 },
+ { "OutputType", "target:winexe", "", "Winexe", 0 },
+ { "OutputType", "target:library", "", "Library", 0 },
+ { "OutputType", "target:module", "", "Module", 0 },
+
+ { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "Platform", "platform:x86", "", "x86", 0 },
+ { "Platform", "platform:Itanium", "", "Itanium", 0 },
+ { "Platform", "platform:x64", "", "x64", 0 },
+ { "Platform", "platform:arm", "", "arm", 0 },
+ { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+ 0 },
+ { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+ { "References", "reference:", "mit alias", "", 0 },
+ { "References", "reference:", "dateiliste", "", 0 },
+ { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+ { "", "link", "", "", 0 },
+
+ { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+ { "ApplicationIcon", "win32icon", "", "",
+ cmIDEFlagTable::UserValueRequired },
+
+ { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+ { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+ { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+ { "DebugSymbols", "debug", "", "true", 0 },
+ { "DebugSymbols", "debug-", "", "false", 0 },
+ { "DebugSymbols", "debug+", "", "true", 0 },
+
+ { "DebugType", "debug:none", "", "none", 0 },
+ { "DebugType", "debug:full", "", "full", 0 },
+ { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+ { "Optimize", "optimize", "", "true", 0 },
+ { "Optimize", "optimize-", "", "false", 0 },
+ { "Optimize", "optimize+", "", "true", 0 },
+
+ { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+ { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+ { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+ { "WarningsAsErrors", "warnaserror", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+ { "WarningLevel", "warn:0", "", "0", 0 },
+ { "WarningLevel", "warn:1", "", "1", 0 },
+ { "WarningLevel", "warn:2", "", "2", 0 },
+ { "WarningLevel", "warn:3", "", "3", 0 },
+ { "WarningLevel", "warn:4", "", "4", 0 },
+ { "DisabledWarnings", "nowarn", "", "", 0 },
+
+ { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+ { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+ { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+ { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+ { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+ { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+ { "DefineConstants", "define:", "", "",
+ cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+ { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+ { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+ { "LangVersion", "langversion:3", "", "3", 0 },
+ { "LangVersion", "langversion:4", "", "4", 0 },
+ { "LangVersion", "langversion:5", "", "5", 0 },
+ { "LangVersion", "langversion:6", "", "6", 0 },
+ { "LangVersion", "langversion:default", "", "default", 0 },
+
+ { "DelaySign", "delaysign", "", "true", 0 },
+ { "DelaySign", "delaysign-", "", "false", 0 },
+ { "DelaySign", "delaysign+", "", "true", 0 },
+
+ { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+ { "KeyContainerName", "keycontainer", "", "", 0 },
+
+ { "NoLogo", "nologo", "", "", 0 },
+
+ { "NoConfig", "noconfig", "", "true", 0 },
+
+ { "BaseAddress", "baseaddress:", "", "", 0 },
+
+ { "CodePage", "codepage", "", "", 0 },
+
+ { "Utf8Output", "utf8output", "", "", 0 },
+
+ { "MainEntryPoint", "main:", "", "", 0 },
+
+ { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+ { "FileAlignment", "filealign", "", "", 0 },
+
+ { "PdbFile", "pdb:", "", "", 0 },
+
+ { "NoStandardLib", "nostdlib", "", "true", 0 },
+ { "NoStandardLib", "nostdlib-", "", "false", 0 },
+ { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+ { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+ { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+ { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+ { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+ { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+ { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+ { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS141CLFlagTable.h b/Source/cmVS141CLFlagTable.h
index 895b3e8..f751fc8 100644
--- a/Source/cmVS141CLFlagTable.h
+++ b/Source/cmVS141CLFlagTable.h
@@ -171,6 +171,7 @@ static cmVS7FlagTable cmVS141CLFlagTable[] = {
{ "TreatWChar_tAsBuiltInType", "Zc:wchar_t", "", "true", 0 },
{ "ForceConformanceInForLoopScope", "Zc:forScope-", "", "false", 0 },
{ "ForceConformanceInForLoopScope", "Zc:forScope", "", "true", 0 },
+ { "RemoveUnreferencedCodeData", "Zc:inline-", "", "false", 0 },
{ "RemoveUnreferencedCodeData", "Zc:inline", "", "true", 0 },
{ "EnforceTypeConversionRules", "Zc:rvalueCast-", "", "false", 0 },
{ "EnforceTypeConversionRules", "Zc:rvalueCast", "", "true", 0 },
diff --git a/Source/cmVS141CSharpFlagTable.h b/Source/cmVS141CSharpFlagTable.h
new file mode 100644
index 0000000..8508581
--- /dev/null
+++ b/Source/cmVS141CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS141CSharpFlagTable[] = {
+ { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "OutputType", "target:exe", "", "Exe", 0 },
+ { "OutputType", "target:winexe", "", "Winexe", 0 },
+ { "OutputType", "target:library", "", "Library", 0 },
+ { "OutputType", "target:module", "", "Module", 0 },
+
+ { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+ { "Platform", "platform:x86", "", "x86", 0 },
+ { "Platform", "platform:Itanium", "", "Itanium", 0 },
+ { "Platform", "platform:x64", "", "x64", 0 },
+ { "Platform", "platform:arm", "", "arm", 0 },
+ { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+ 0 },
+ { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+ { "References", "reference:", "mit alias", "", 0 },
+ { "References", "reference:", "dateiliste", "", 0 },
+ { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+ { "", "link", "", "", 0 },
+
+ { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+ { "ApplicationIcon", "win32icon", "", "",
+ cmIDEFlagTable::UserValueRequired },
+
+ { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+ { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+ { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+ { "DebugSymbols", "debug", "", "true", 0 },
+ { "DebugSymbols", "debug-", "", "false", 0 },
+ { "DebugSymbols", "debug+", "", "true", 0 },
+
+ { "DebugType", "debug:none", "", "none", 0 },
+ { "DebugType", "debug:full", "", "full", 0 },
+ { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+ { "Optimize", "optimize", "", "true", 0 },
+ { "Optimize", "optimize-", "", "false", 0 },
+ { "Optimize", "optimize+", "", "true", 0 },
+
+ { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+ { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+ { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+ { "WarningsAsErrors", "warnaserror", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+ { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+ { "WarningLevel", "warn:0", "", "0", 0 },
+ { "WarningLevel", "warn:1", "", "1", 0 },
+ { "WarningLevel", "warn:2", "", "2", 0 },
+ { "WarningLevel", "warn:3", "", "3", 0 },
+ { "WarningLevel", "warn:4", "", "4", 0 },
+ { "DisabledWarnings", "nowarn", "", "", 0 },
+
+ { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+ { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+ { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+ { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+ { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+ { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+ { "DefineConstants", "define:", "", "",
+ cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+ { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+ { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+ { "LangVersion", "langversion:3", "", "3", 0 },
+ { "LangVersion", "langversion:4", "", "4", 0 },
+ { "LangVersion", "langversion:5", "", "5", 0 },
+ { "LangVersion", "langversion:6", "", "6", 0 },
+ { "LangVersion", "langversion:default", "", "default", 0 },
+
+ { "DelaySign", "delaysign", "", "true", 0 },
+ { "DelaySign", "delaysign-", "", "false", 0 },
+ { "DelaySign", "delaysign+", "", "true", 0 },
+
+ { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+ { "KeyContainerName", "keycontainer", "", "", 0 },
+
+ { "NoLogo", "nologo", "", "", 0 },
+
+ { "NoConfig", "noconfig", "", "true", 0 },
+
+ { "BaseAddress", "baseaddress:", "", "", 0 },
+
+ { "CodePage", "codepage", "", "", 0 },
+
+ { "Utf8Output", "utf8output", "", "", 0 },
+
+ { "MainEntryPoint", "main:", "", "", 0 },
+
+ { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+ { "FileAlignment", "filealign", "", "", 0 },
+
+ { "PdbFile", "pdb:", "", "", 0 },
+
+ { "NoStandardLib", "nostdlib", "", "true", 0 },
+ { "NoStandardLib", "nostdlib-", "", "false", 0 },
+ { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+ { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+ { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+ { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+ { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+ { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+ { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+ { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index 97eb3c7..8ab3b04 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -53,6 +53,22 @@ static std::string cmVS10EscapeComment(std::string comment)
return echoable;
}
+static bool cmVS10IsTargetsFile(std::string const& path)
+{
+ std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
+ return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
+}
+
+static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
+{
+ std::string res;
+ res = ".vcxproj";
+ if (cmGlobalVisualStudioGenerator::TargetIsCSharpOnly(t)) {
+ res = ".csproj";
+ }
+ return res;
+}
+
cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
{
@@ -73,12 +89,16 @@ cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
&this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
&this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
this->MSTools = !this->NsightTegra;
+ this->Managed = false;
this->TargetCompileAsWinRT = false;
this->BuildFileStream = 0;
this->IsMissingFiles = false;
this->DefaultArtifactDir =
this->LocalGenerator->GetCurrentBinaryDirectory() + std::string("/") +
this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
+ this->InSourceBuild =
+ (strcmp(this->Makefile->GetCurrentSourceDirectory(),
+ this->Makefile->GetCurrentBinaryDirectory()) == 0);
}
cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
@@ -95,7 +115,7 @@ cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
return;
}
if (this->BuildFileStream->Close()) {
- this->GlobalGenerator->FileReplacedDuringGenerate(this->PathToVcxproj);
+ this->GlobalGenerator->FileReplacedDuringGenerate(this->PathToProjectFile);
}
delete this->BuildFileStream;
}
@@ -133,7 +153,11 @@ void cmVisualStudio10TargetGenerator::WriteString(const char* line,
(*this->BuildFileStream) << line;
}
-#define VS10_USER_PROPS "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
+#define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
+#define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
+#define VS10_CXX_USER_PROPS \
+ "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
+#define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
void cmVisualStudio10TargetGenerator::Generate()
{
@@ -142,11 +166,20 @@ void cmVisualStudio10TargetGenerator::Generate()
this->GeneratorTarget->GetProperty("EXTERNAL_MSPROJECT")) {
return;
}
+ this->ProjectFileExtension =
+ computeProjectFileExtension(this->GeneratorTarget);
+ if (this->ProjectFileExtension == ".vcxproj") {
+ this->ProjectType = vcxproj;
+ this->Managed = false;
+ } else if (this->ProjectFileExtension == ".csproj") {
+ this->ProjectType = csproj;
+ this->Managed = true;
+ }
// Tell the global generator the name of the project file
this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
this->Name.c_str());
- this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
- ".vcxproj");
+ this->GeneratorTarget->Target->SetProperty(
+ "GENERATOR_FILE_NAME_EXT", this->ProjectFileExtension.c_str());
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
if (!this->ComputeClOptions()) {
return;
@@ -160,13 +193,16 @@ void cmVisualStudio10TargetGenerator::Generate()
if (!this->ComputeLinkOptions()) {
return;
}
+ if (!this->ComputeLibOptions()) {
+ return;
+ }
}
std::string path = this->LocalGenerator->GetCurrentBinaryDirectory();
path += "/";
path += this->Name;
- path += ".vcxproj";
+ path += this->ProjectFileExtension;
this->BuildFileStream = new cmGeneratedFileStream(path.c_str());
- this->PathToVcxproj = path;
+ this->PathToProjectFile = path;
this->BuildFileStream->SetCopyIfDifferent(true);
// Write the encoding header into the file
@@ -305,6 +341,16 @@ void cmVisualStudio10TargetGenerator::Generate()
<< "</TargetFrameworkVersion>\n";
}
+ // Disable the project upgrade prompt that is displayed the first time a
+ // project using an older toolset version is opened in a newer version of
+ // the IDE (respected by VS 2013 and above).
+ if (this->GlobalGenerator->GetVersion() >=
+ cmGlobalVisualStudioGenerator::VS12) {
+ this->WriteString("<VCProjectUpgraderObjectName>NoUpgrade"
+ "</VCProjectUpgraderObjectName>\n",
+ 2);
+ }
+
std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
for (std::vector<std::string>::const_iterator keyIt = keys.begin();
keyIt != keys.end(); ++keyIt) {
@@ -326,12 +372,9 @@ void cmVisualStudio10TargetGenerator::Generate()
}
this->WriteString("</PropertyGroup>\n", 1);
- this->WriteString("<Import Project="
- "\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n",
- 1);
+ this->WriteString("<Import Project=\"" VS10_CXX_DEFAULT_PROPS "\" />\n", 1);
this->WriteProjectConfigurationValues();
- this->WriteString(
- "<Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n", 1);
+ this->WriteString("<Import Project=\"" VS10_CXX_PROPS "\" />\n", 1);
this->WriteString("<ImportGroup Label=\"ExtensionSettings\">\n", 1);
if (this->GlobalGenerator->IsMasmEnabled()) {
this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
@@ -340,10 +383,19 @@ void cmVisualStudio10TargetGenerator::Generate()
}
this->WriteString("</ImportGroup>\n", 1);
this->WriteString("<ImportGroup Label=\"PropertySheets\">\n", 1);
- this->WriteString("<Import Project=\"" VS10_USER_PROPS "\""
- " Condition=\"exists('" VS10_USER_PROPS "')\""
- " Label=\"LocalAppDataPlatform\" />\n",
- 2);
+ {
+ std::string props = VS10_CXX_USER_PROPS;
+ if (const char* p =
+ this->GeneratorTarget->GetProperty("VS_USER_PROPS_CXX")) {
+ props = p;
+ this->ConvertToWindowsSlash(props);
+ }
+ this->WriteString("", 2);
+ (*this->BuildFileStream)
+ << "<Import Project=\"" << cmVS10EscapeXML(props) << "\""
+ << " Condition=\"exists('" << cmVS10EscapeXML(props) << "')\""
+ << " Label=\"LocalAppDataPlatform\" />\n";
+ }
this->WritePlatformExtensions();
this->WriteString("</ImportGroup>\n", 1);
this->WriteString("<PropertyGroup Label=\"UserMacros\" />\n", 1);
@@ -358,12 +410,11 @@ void cmVisualStudio10TargetGenerator::Generate()
this->WriteWinRTReferences();
this->WriteProjectReferences();
this->WriteSDKReferences();
- this->WriteString(
- "<Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\""
- " />\n",
- 1);
+ this->WriteString("<Import Project=\"" VS10_CXX_TARGETS "\" />\n", 1);
+
this->WriteTargetSpecificReferences();
this->WriteString("<ImportGroup Label=\"ExtensionTargets\">\n", 1);
+ this->WriteTargetsFileReferences();
if (this->GlobalGenerator->IsMasmEnabled()) {
this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
"BuildCustomizations\\masm.targets\" />\n",
@@ -479,6 +530,31 @@ void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences()
}
}
+void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences()
+{
+ for (std::vector<TargetsFileAndConfigs>::iterator i =
+ this->TargetsFileAndConfigsVec.begin();
+ i != this->TargetsFileAndConfigsVec.end(); ++i) {
+ TargetsFileAndConfigs const& tac = *i;
+ this->WriteString("<Import Project=\"", 3);
+ (*this->BuildFileStream) << tac.File << "\" ";
+ (*this->BuildFileStream) << "Condition=\"";
+ (*this->BuildFileStream) << "Exists('" << tac.File << "')";
+ if (!tac.Configs.empty()) {
+ (*this->BuildFileStream) << " And (";
+ for (size_t j = 0; j < tac.Configs.size(); ++j) {
+ if (j > 0) {
+ (*this->BuildFileStream) << " Or ";
+ }
+ (*this->BuildFileStream) << "'$(Configuration)'=='" << tac.Configs[j]
+ << "'";
+ }
+ (*this->BuildFileStream) << ")";
+ }
+ (*this->BuildFileStream) << "\" />\n";
+ }
+}
+
void cmVisualStudio10TargetGenerator::WriteWinRTReferences()
{
std::vector<std::string> references;
@@ -818,7 +894,8 @@ void cmVisualStudio10TargetGenerator::WriteGroups()
std::string path = this->LocalGenerator->GetCurrentBinaryDirectory();
path += "/";
path += this->Name;
- path += ".vcxproj.filters";
+ path += computeProjectFileExtension(this->GeneratorTarget);
+ path += ".filters";
cmGeneratedFileStream fout(path.c_str());
fout.SetCopyIfDifferent(true);
char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
@@ -1516,6 +1593,14 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
*this->BuildFileStream << cmVS10EscapeXML(intermediateDir)
<< "</IntDir>\n";
+ if (const char* workingDir = this->GeneratorTarget->GetProperty(
+ "VS_DEBUGGER_WORKING_DIRECTORY")) {
+ this->WritePlatformConfigTag("LocalDebuggerWorkingDirectory",
+ config->c_str(), 3);
+ *this->BuildFileStream << cmVS10EscapeXML(workingDir)
+ << "</LocalDebuggerWorkingDirectory>\n";
+ }
+
std::string name =
cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
this->WritePlatformConfigTag("TargetName", config->c_str(), 3);
@@ -1686,6 +1771,15 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
}
}
+ if (csproj != this->ProjectType && clOptions.IsManaged()) {
+ this->Managed = true;
+ std::string managedType = clOptions.GetFlag("CompileAsManaged");
+ if (managedType == "Safe") {
+ // force empty calling convention if safe clr is used
+ clOptions.AddFlag("CallingConvention", "");
+ }
+ }
+
this->ClOptions[configName] = pOptions.release();
return true;
}
@@ -2148,9 +2242,16 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
}
// add the libraries for the target to libs string
cmComputeLinkInformation& cli = *pcli;
- this->AddLibraries(cli, libVec);
+ std::vector<std::string> vsTargetVec;
+ this->AddLibraries(cli, libVec, vsTargetVec);
linkOptions.AddFlag("AdditionalDependencies", libVec);
+ // Populate TargetsFileAndConfigsVec
+ for (std::vector<std::string>::iterator ti = vsTargetVec.begin();
+ ti != vsTargetVec.end(); ++ti) {
+ this->AddTargetsFileAndConfigPair(*ti, config);
+ }
+
std::vector<std::string> const& ldirs = cli.GetDirectories();
std::vector<std::string> linkDirs;
for (std::vector<std::string>::const_iterator d = ldirs.begin();
@@ -2305,6 +2406,49 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
return true;
}
+bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
+{
+ if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
+ for (std::vector<std::string>::const_iterator i =
+ this->Configurations.begin();
+ i != this->Configurations.end(); ++i) {
+ if (!this->ComputeLibOptions(*i)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
+ std::string const& config)
+{
+ cmComputeLinkInformation* pcli =
+ this->GeneratorTarget->GetLinkInformation(config.c_str());
+ if (!pcli) {
+ cmSystemTools::Error(
+ "CMake can not compute cmComputeLinkInformation for target: ",
+ this->Name.c_str());
+ return false;
+ }
+
+ cmComputeLinkInformation& cli = *pcli;
+ typedef cmComputeLinkInformation::ItemVector ItemVector;
+ const ItemVector& libs = cli.GetItems();
+ std::string currentBinDir =
+ this->LocalGenerator->GetCurrentBinaryDirectory();
+ for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
+ if (l->IsPath && cmVS10IsTargetsFile(l->Value)) {
+ std::string path = this->LocalGenerator->ConvertToRelativePath(
+ currentBinDir, l->Value.c_str());
+ this->ConvertToWindowsSlash(path);
+ this->AddTargetsFileAndConfigPair(path, config);
+ }
+ }
+
+ return true;
+}
+
void cmVisualStudio10TargetGenerator::WriteLinkOptions(
std::string const& config)
{
@@ -2329,10 +2473,11 @@ void cmVisualStudio10TargetGenerator::WriteLinkOptions(
}
void cmVisualStudio10TargetGenerator::AddLibraries(
- cmComputeLinkInformation& cli, std::vector<std::string>& libVec)
+ cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
+ std::vector<std::string>& vsTargetVec)
{
typedef cmComputeLinkInformation::ItemVector ItemVector;
- ItemVector libs = cli.GetItems();
+ ItemVector const& libs = cli.GetItems();
std::string currentBinDir =
this->LocalGenerator->GetCurrentBinaryDirectory();
for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
@@ -2340,7 +2485,11 @@ void cmVisualStudio10TargetGenerator::AddLibraries(
std::string path = this->LocalGenerator->ConvertToRelativePath(
currentBinDir, l->Value.c_str());
this->ConvertToWindowsSlash(path);
- libVec.push_back(path);
+ if (cmVS10IsTargetsFile(l->Value)) {
+ vsTargetVec.push_back(path);
+ } else {
+ libVec.push_back(path);
+ }
} else if (!l->Target ||
l->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
libVec.push_back(l->Value);
@@ -2348,6 +2497,26 @@ void cmVisualStudio10TargetGenerator::AddLibraries(
}
}
+void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
+ std::string const& targetsFile, std::string const& config)
+{
+ for (std::vector<TargetsFileAndConfigs>::iterator i =
+ this->TargetsFileAndConfigsVec.begin();
+ i != this->TargetsFileAndConfigsVec.end(); ++i) {
+ if (cmSystemTools::ComparePath(targetsFile, i->File)) {
+ if (std::find(i->Configs.begin(), i->Configs.end(), config) ==
+ i->Configs.end()) {
+ i->Configs.push_back(config);
+ }
+ return;
+ }
+ }
+ TargetsFileAndConfigs entry;
+ entry.File = targetsFile;
+ entry.Configs.push_back(config);
+ this->TargetsFileAndConfigsVec.push_back(entry);
+}
+
void cmVisualStudio10TargetGenerator::WriteMidlOptions(
std::string const& /*config*/, std::vector<std::string> const& includes)
{
@@ -2522,8 +2691,9 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences()
path = lg->GetCurrentBinaryDirectory();
path += "/";
path += dt->GetName();
- path += ".vcxproj";
+ path += computeProjectFileExtension(dt);
}
+ this->ConvertToWindowsSlash(path);
(*this->BuildFileStream) << cmVS10EscapeXML(path) << "\">\n";
this->WriteString("<Project>", 3);
(*this->BuildFileStream) << this->GlobalGenerator->GetGUID(name.c_str())
diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h
index 54b9569..e68bf1a 100644
--- a/Source/cmVisualStudio10TargetGenerator.h
+++ b/Source/cmVisualStudio10TargetGenerator.h
@@ -5,19 +5,22 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
-class cmMakefile;
-class cmGeneratorTarget;
+class cmComputeLinkInformation;
+class cmCustomCommand;
class cmGeneratedFileStream;
+class cmGeneratorTarget;
class cmGlobalVisualStudio10Generator;
-class cmSourceFile;
-class cmCustomCommand;
class cmLocalVisualStudio7Generator;
-class cmComputeLinkInformation;
+class cmMakefile;
+class cmSourceFile;
+class cmSourceGroup;
class cmVisualStudioGeneratorOptions;
-struct cmIDEFlagTable;
-#include "cmSourceGroup.h"
class cmVisualStudio10TargetGenerator
{
@@ -41,6 +44,12 @@ private:
{
};
+ struct TargetsFileAndConfigs
+ {
+ std::string File;
+ std::vector<std::string> Configs;
+ };
+
std::string ConvertPath(std::string const& path, bool forceRelative);
void ConvertToWindowsSlash(std::string& s);
void WriteString(const char* line, int indentLevel);
@@ -77,6 +86,7 @@ private:
std::string const& version);
void WriteCommonMissingFiles(const std::string& manifestFile);
void WriteTargetSpecificReferences();
+ void WriteTargetsFileReferences();
bool ComputeClOptions();
bool ComputeClOptions(std::string const& configName);
@@ -92,6 +102,8 @@ private:
std::vector<std::string> const& includes);
bool ComputeLinkOptions();
bool ComputeLinkOptions(std::string const& config);
+ bool ComputeLibOptions();
+ bool ComputeLibOptions(std::string const& config);
void WriteLinkOptions(std::string const& config);
void WriteMidlOptions(std::string const& config,
std::vector<std::string> const& includes);
@@ -106,7 +118,10 @@ private:
void WriteApplicationTypeSettings();
bool OutputSourceSpecificFlags(cmSourceFile const* source);
void AddLibraries(cmComputeLinkInformation& cli,
- std::vector<std::string>& libVec);
+ std::vector<std::string>& libVec,
+ std::vector<std::string>& vsTargetVec);
+ void AddTargetsFileAndConfigPair(std::string const& targetsFile,
+ std::string const& config);
void WriteLibOptions(std::string const& config);
void WriteManifestOptions(std::string const& config);
void WriteEvents(std::string const& configName);
@@ -130,14 +145,23 @@ private:
OptionsMap RcOptions;
OptionsMap MasmOptions;
OptionsMap LinkOptions;
- std::string PathToVcxproj;
+ std::string PathToProjectFile;
+ std::string ProjectFileExtension;
+ enum VsProjectType
+ {
+ vcxproj,
+ csproj
+ } ProjectType;
+ bool InSourceBuild;
std::vector<std::string> Configurations;
+ std::vector<TargetsFileAndConfigs> TargetsFileAndConfigsVec;
cmGeneratorTarget* GeneratorTarget;
cmMakefile* Makefile;
std::string Platform;
std::string GUID;
std::string Name;
bool MSTools;
+ bool Managed;
bool NsightTegra;
int NsightTegraVersion[4];
bool TargetCompileAsWinRT;
diff --git a/Source/cmVisualStudio10ToolsetOptions.cxx b/Source/cmVisualStudio10ToolsetOptions.cxx
index b928f43..afca216 100644
--- a/Source/cmVisualStudio10ToolsetOptions.cxx
+++ b/Source/cmVisualStudio10ToolsetOptions.cxx
@@ -7,22 +7,27 @@
#include "cmVisualStudioGeneratorOptions.h"
#include "cmVS10CLFlagTable.h"
+#include "cmVS10CSharpFlagTable.h"
#include "cmVS10LibFlagTable.h"
#include "cmVS10LinkFlagTable.h"
#include "cmVS10MASMFlagTable.h"
#include "cmVS10RCFlagTable.h"
#include "cmVS11CLFlagTable.h"
+#include "cmVS11CSharpFlagTable.h"
#include "cmVS11LibFlagTable.h"
#include "cmVS11LinkFlagTable.h"
#include "cmVS11MASMFlagTable.h"
#include "cmVS11RCFlagTable.h"
#include "cmVS12CLFlagTable.h"
+#include "cmVS12CSharpFlagTable.h"
#include "cmVS12LibFlagTable.h"
#include "cmVS12LinkFlagTable.h"
#include "cmVS12MASMFlagTable.h"
#include "cmVS12RCFlagTable.h"
#include "cmVS140CLFlagTable.h"
+#include "cmVS140CSharpFlagTable.h"
#include "cmVS141CLFlagTable.h"
+#include "cmVS141CSharpFlagTable.h"
#include "cmVS14LibFlagTable.h"
#include "cmVS14LinkFlagTable.h"
#include "cmVS14MASMFlagTable.h"
@@ -48,6 +53,26 @@ cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetClFlagTable(
}
}
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetCSharpFlagTable(
+ std::string const& name, std::string const& toolset) const
+{
+ std::string const useToolset = this->GetToolsetName(name, toolset);
+
+ if ((useToolset == "v141")) {
+ return cmVS141CSharpFlagTable;
+ } else if (useToolset == "v140") {
+ return cmVS140CSharpFlagTable;
+ } else if (useToolset == "v120") {
+ return cmVS12CSharpFlagTable;
+ } else if (useToolset == "v110") {
+ return cmVS11CSharpFlagTable;
+ } else if (useToolset == "v100") {
+ return cmVS10CSharpFlagTable;
+ } else {
+ return 0;
+ }
+}
+
cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetRcFlagTable(
std::string const& name, std::string const& toolset) const
{
diff --git a/Source/cmVisualStudio10ToolsetOptions.h b/Source/cmVisualStudio10ToolsetOptions.h
index ea6c9c8..2459f5e 100644
--- a/Source/cmVisualStudio10ToolsetOptions.h
+++ b/Source/cmVisualStudio10ToolsetOptions.h
@@ -3,7 +3,9 @@
#ifndef cmVisualStudio10ToolsetOptions_h
#define cmVisualStudio10ToolsetOptions_h
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h>
+
+#include <string>
struct cmIDEFlagTable;
@@ -17,6 +19,8 @@ class cmVisualStudio10ToolsetOptions
public:
cmIDEFlagTable const* GetClFlagTable(std::string const& name,
std::string const& toolset) const;
+ cmIDEFlagTable const* GetCSharpFlagTable(std::string const& name,
+ std::string const& toolset) const;
cmIDEFlagTable const* GetRcFlagTable(std::string const& name,
std::string const& toolset) const;
cmIDEFlagTable const* GetLibFlagTable(std::string const& name,
diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx
index 4be183d..62200ce 100644
--- a/Source/cmVisualStudioGeneratorOptions.cxx
+++ b/Source/cmVisualStudioGeneratorOptions.cxx
@@ -1,5 +1,6 @@
#include "cmVisualStudioGeneratorOptions.h"
+#include "cmLocalVisualStudioGenerator.h"
#include "cmOutputConverter.h"
#include "cmSystemTools.h"
#include "cmVisualStudio10TargetGenerator.h"
@@ -334,8 +335,9 @@ void cmVisualStudioGeneratorOptions::OutputAdditionalOptions(
} else {
fout << "<AdditionalOptions>";
}
- fout << cmVisualStudio10GeneratorOptionsEscapeForXML(this->FlagString)
- << " %(AdditionalOptions)</AdditionalOptions>\n";
+ fout << "%(AdditionalOptions) "
+ << cmVisualStudio10GeneratorOptionsEscapeForXML(this->FlagString)
+ << "</AdditionalOptions>\n";
} else {
fout << prefix << "AdditionalOptions=\"";
fout << cmVisualStudioGeneratorOptionsEscapeForXML(this->FlagString);
diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h
index 0a0b96d..e27c5d3 100644
--- a/Source/cmVisualStudioGeneratorOptions.h
+++ b/Source/cmVisualStudioGeneratorOptions.h
@@ -3,9 +3,17 @@
#ifndef cmVisualStudioGeneratorOptions_h
#define cmVisualStudioGeneratorOptions_h
-#include "cmLocalVisualStudioGenerator.h"
+#include <cmConfigure.h>
+#include <iosfwd>
+#include <string>
+
+#include "cmGlobalVisualStudioGenerator.h"
+#include "cmIDEFlagTable.h"
#include "cmIDEOptions.h"
+
+class cmLocalVisualStudioGenerator;
+
typedef cmIDEFlagTable cmVS7FlagTable;
class cmVisualStudio10TargetGenerator;
diff --git a/Source/cmVisualStudioSlnData.h b/Source/cmVisualStudioSlnData.h
index 9f5ccb7..b2f8db9 100644
--- a/Source/cmVisualStudioSlnData.h
+++ b/Source/cmVisualStudioSlnData.h
@@ -5,7 +5,9 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <map>
+#include <string>
+#include <vector>
class cmSlnProjectEntry
{
diff --git a/Source/cmVisualStudioSlnParser.h b/Source/cmVisualStudioSlnParser.h
index 8939ab5..a3391a6 100644
--- a/Source/cmVisualStudioSlnParser.h
+++ b/Source/cmVisualStudioSlnParser.h
@@ -5,9 +5,10 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
-
#include <bitset>
+#include <iosfwd>
+#include <stddef.h>
+#include <string>
class cmSlnData;
@@ -65,6 +66,7 @@ public:
protected:
class State;
+
friend class State;
class ParsedLine;
diff --git a/Source/cmVisualStudioWCEPlatformParser.h b/Source/cmVisualStudioWCEPlatformParser.h
index 25f1a18..8ed6083 100644
--- a/Source/cmVisualStudioWCEPlatformParser.h
+++ b/Source/cmVisualStudioWCEPlatformParser.h
@@ -5,7 +5,10 @@
#include <cmConfigure.h>
-#include "cmStandardIncludes.h"
+#include <map>
+#include <stddef.h>
+#include <string>
+#include <vector>
#include "cmXMLParser.h"
diff --git a/Source/cmWriteFileCommand.cxx b/Source/cmWriteFileCommand.cxx
index b3ac31c..96c8e27 100644
--- a/Source/cmWriteFileCommand.cxx
+++ b/Source/cmWriteFileCommand.cxx
@@ -65,7 +65,7 @@ bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args,
overwrite ? std::ios::out : std::ios::app);
if (!file) {
std::string error = "Internal CMake error when trying to open file: ";
- error += fileName.c_str();
+ error += fileName;
error += " for writing.";
this->SetError(error);
return false;
diff --git a/Source/cmXCode21Object.cxx b/Source/cmXCode21Object.cxx
index a783c70..719e627 100644
--- a/Source/cmXCode21Object.cxx
+++ b/Source/cmXCode21Object.cxx
@@ -2,6 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmXCode21Object.h"
+#include <ostream>
+#include <string>
+
#include "cmSystemTools.h"
cmXCode21Object::cmXCode21Object(PBXType ptype, Type type)
diff --git a/Source/cmXCode21Object.h b/Source/cmXCode21Object.h
index 0db20e6..083d229 100644
--- a/Source/cmXCode21Object.h
+++ b/Source/cmXCode21Object.h
@@ -3,6 +3,11 @@
#ifndef cmXCode21Object_h
#define cmXCode21Object_h
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <iosfwd>
+#include <vector>
+
#include "cmXCodeObject.h"
class cmXCode21Object : public cmXCodeObject
diff --git a/Source/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx
index b1dc7ea..3689ac4 100644
--- a/Source/cmXCodeObject.cxx
+++ b/Source/cmXCodeObject.cxx
@@ -2,9 +2,10 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmXCodeObject.h"
-#include "cmSystemTools.h"
+#include <CoreFoundation/CoreFoundation.h>
+#include <ostream>
-#include <CoreFoundation/CoreFoundation.h> // CFUUIDCreate
+#include "cmSystemTools.h"
const char* cmXCodeObject::PBXTypeNames[] = {
/* clang-format needs this comment to break after the opening brace */
diff --git a/Source/cmXCodeObject.h b/Source/cmXCodeObject.h
index d495130..3bfecdf 100644
--- a/Source/cmXCodeObject.h
+++ b/Source/cmXCodeObject.h
@@ -3,9 +3,14 @@
#ifndef cmXCodeObject_h
#define cmXCodeObject_h
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
-#include "cmStandardIncludes.h"
+#include <algorithm>
+#include <iosfwd>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
class cmGeneratorTarget;
diff --git a/Source/cm_codecvt.hxx b/Source/cm_codecvt.hxx
index 5f16bd8..fcd9954 100644
--- a/Source/cm_codecvt.hxx
+++ b/Source/cm_codecvt.hxx
@@ -3,10 +3,11 @@
#ifndef cm_codecvt_hxx
#define cm_codecvt_hxx
-#include <cmConfigure.h> // IWYU pragma: keep
+#include <cmConfigure.h>
#include <locale>
#include <vector>
+#include <wchar.h>
class codecvt : public std::codecvt<char, char, mbstate_t>
{
diff --git a/Source/cm_sha2.c b/Source/cm_sha2.c
deleted file mode 100644
index 649c39a..0000000
--- a/Source/cm_sha2.c
+++ /dev/null
@@ -1,1613 +0,0 @@
-/*
- * FILE: sha2.c
- * AUTHOR: Aaron D. Gifford
- * http://www.aarongifford.com/computers/sha.html
- *
- * Copyright (c) 2000-2003, Aaron D. Gifford
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * $Id: sha2.c,v 1.4 2004/01/07 22:58:18 adg Exp $
- */
-
-#include <string.h> /* memcpy()/memset() or bcopy()/bzero() */
-#include <assert.h> /* assert() */
-#include "cm_sha2.h" /* "sha2.h" -> "cm_sha2.h" renamed for CMake */
-
-/*
- * ASSERT NOTE:
- * Some sanity checking code is included using assert(). On my FreeBSD
- * system, this additional code can be removed by compiling with NDEBUG
- * defined. Check your own systems manpage on assert() to see how to
- * compile WITHOUT the sanity checking code on your system.
- *
- * UNROLLED TRANSFORM LOOP NOTE:
- * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
- * loop version for the hash transform rounds (defined using macros
- * later in this file). Either define on the command line, for example:
- *
- * cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
- *
- * or define below:
- *
- * #define SHA2_UNROLL_TRANSFORM
- *
- */
-
-
-/*** SHA-224/256/384/512 Machine Architecture Definitions *************/
-/*
- * BYTE_ORDER NOTE:
- *
- * Please make sure that your system defines BYTE_ORDER. If your
- * architecture is little-endian, make sure it also defines
- * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
- * equivilent.
- *
- * If your system does not define the above, then you can do so by
- * hand like this:
- *
- * #define LITTLE_ENDIAN 1234
- * #define BIG_ENDIAN 4321
- *
- * And for little-endian machines, add:
- *
- * #define BYTE_ORDER LITTLE_ENDIAN
- *
- * Or for big-endian machines:
- *
- * #define BYTE_ORDER BIG_ENDIAN
- *
- * The FreeBSD machine this was written on defines BYTE_ORDER
- * appropriately by including <sys/types.h> (which in turn includes
- * <machine/endian.h> where the appropriate definitions are actually
- * made).
- */
-#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
-/* CMake modification: use byte order from KWIML. */
-# undef BYTE_ORDER
-# undef BIG_ENDIAN
-# undef LITTLE_ENDIAN
-# define BYTE_ORDER KWIML_ABI_ENDIAN_ID
-# define BIG_ENDIAN KWIML_ABI_ENDIAN_ID_BIG
-# define LITTLE_ENDIAN KWIML_ABI_ENDIAN_ID_LITTLE
-#endif
-
-/* CMake modification: use types computed in header. */
-typedef cm_sha2_uint8_t sha_byte; /* Exactly 1 byte */
-typedef cm_sha2_uint32_t sha_word32; /* Exactly 4 bytes */
-typedef cm_sha2_uint64_t sha_word64; /* Exactly 8 bytes */
-#define SHA_UINT32_C(x) KWIML_INT_UINT32_C(x)
-#define SHA_UINT64_C(x) KWIML_INT_UINT64_C(x)
-#if defined(__clang__)
-# pragma clang diagnostic ignored "-Wcast-align"
-#endif
-
-/*** ENDIAN REVERSAL MACROS *******************************************/
-#if BYTE_ORDER == LITTLE_ENDIAN
-#define REVERSE32(w,x) { \
- sha_word32 tmp = (w); \
- tmp = (tmp >> 16) | (tmp << 16); \
- (x) = ((tmp & SHA_UINT32_C(0xff00ff00)) >> 8) | \
- ((tmp & SHA_UINT32_C(0x00ff00ff)) << 8); \
-}
-#define REVERSE64(w,x) { \
- sha_word64 tmp = (w); \
- tmp = (tmp >> 32) | (tmp << 32); \
- tmp = ((tmp & SHA_UINT64_C(0xff00ff00ff00ff00)) >> 8) | \
- ((tmp & SHA_UINT64_C(0x00ff00ff00ff00ff)) << 8); \
- (x) = ((tmp & SHA_UINT64_C(0xffff0000ffff0000)) >> 16) | \
- ((tmp & SHA_UINT64_C(0x0000ffff0000ffff)) << 16); \
-}
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-/*
- * Macro for incrementally adding the unsigned 64-bit integer n to the
- * unsigned 128-bit integer (represented using a two-element array of
- * 64-bit words):
- */
-#define ADDINC128(w,n) { \
- (w)[0] += (sha_word64)(n); \
- if ((w)[0] < (n)) { \
- (w)[1]++; \
- } \
-}
-
-/*
- * Macros for copying blocks of memory and for zeroing out ranges
- * of memory. Using these macros makes it easy to switch from
- * using memset()/memcpy() and using bzero()/bcopy().
- *
- * Please define either SHA2_USE_MEMSET_MEMCPY or define
- * SHA2_USE_BZERO_BCOPY depending on which function set you
- * choose to use:
- */
-#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
-/* Default to memset()/memcpy() if no option is specified */
-#define SHA2_USE_MEMSET_MEMCPY 1
-#endif
-#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
-/* Abort with an error if BOTH options are defined */
-#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
-#endif
-
-#ifdef SHA2_USE_MEMSET_MEMCPY
-#define MEMSET_BZERO(p,l) memset((p), 0, (l))
-#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l))
-#endif
-#ifdef SHA2_USE_BZERO_BCOPY
-#define MEMSET_BZERO(p,l) bzero((p), (l))
-#define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l))
-#endif
-
-
-/*** THE SIX LOGICAL FUNCTIONS ****************************************/
-/*
- * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
- *
- * NOTE: In the original SHA-256/384/512 document, the shift-right
- * function was named R and the rotate-right function was called S.
- * (See: http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf on the
- * web.)
- *
- * The newer NIST FIPS 180-2 document uses a much clearer naming
- * scheme, SHR for shift-right, ROTR for rotate-right, and ROTL for
- * rotate-left. (See:
- * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
- * on the web.)
- *
- * WARNING: These macros must be used cautiously, since they reference
- * supplied parameters sometimes more than once, and thus could have
- * unexpected side-effects if used without taking this into account.
- */
-/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
-#define SHR(b,x) ((x) >> (b))
-/* 32-bit Rotate-right (used in SHA-256): */
-#define ROTR32(b,x) (((x) >> (b)) | ((x) << (32 - (b))))
-/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
-#define ROTR64(b,x) (((x) >> (b)) | ((x) << (64 - (b))))
-/* 32-bit Rotate-left (used in SHA-1): */
-#define ROTL32(b,x) (((x) << (b)) | ((x) >> (32 - (b))))
-
-/* Two logical functions used in SHA-1, SHA-254, SHA-256, SHA-384, and SHA-512: */
-#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
-#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
-
-/* Function used in SHA-1: */
-#define Parity(x,y,z) ((x) ^ (y) ^ (z))
-
-/* Four logical functions used in SHA-256: */
-#define Sigma0_256(x) (ROTR32(2, (x)) ^ ROTR32(13, (x)) ^ ROTR32(22, (x)))
-#define Sigma1_256(x) (ROTR32(6, (x)) ^ ROTR32(11, (x)) ^ ROTR32(25, (x)))
-#define sigma0_256(x) (ROTR32(7, (x)) ^ ROTR32(18, (x)) ^ SHR( 3 , (x)))
-#define sigma1_256(x) (ROTR32(17, (x)) ^ ROTR32(19, (x)) ^ SHR( 10, (x)))
-
-/* Four of six logical functions used in SHA-384 and SHA-512: */
-#define Sigma0_512(x) (ROTR64(28, (x)) ^ ROTR64(34, (x)) ^ ROTR64(39, (x)))
-#define Sigma1_512(x) (ROTR64(14, (x)) ^ ROTR64(18, (x)) ^ ROTR64(41, (x)))
-#define sigma0_512(x) (ROTR64( 1, (x)) ^ ROTR64( 8, (x)) ^ SHR( 7, (x)))
-#define sigma1_512(x) (ROTR64(19, (x)) ^ ROTR64(61, (x)) ^ SHR( 6, (x)))
-
-/*** INTERNAL FUNCTION PROTOTYPES *************************************/
-
-/* SHA-224 and SHA-256: */
-void SHA256_Internal_Init(SHA_CTX*, const sha_word32*);
-void SHA256_Internal_Last(SHA_CTX*);
-void SHA256_Internal_Transform(SHA_CTX*, const sha_word32*);
-
-/* SHA-384 and SHA-512: */
-void SHA512_Internal_Init(SHA_CTX*, const sha_word64*);
-void SHA512_Internal_Last(SHA_CTX*);
-void SHA512_Internal_Transform(SHA_CTX*, const sha_word64*);
-
-
-/*** SHA2 INITIAL HASH VALUES AND CONSTANTS ***************************/
-
-/* Hash constant words K for SHA-1: */
-#define K1_0_TO_19 SHA_UINT32_C(0x5a827999)
-#define K1_20_TO_39 SHA_UINT32_C(0x6ed9eba1)
-#define K1_40_TO_59 SHA_UINT32_C(0x8f1bbcdc)
-#define K1_60_TO_79 SHA_UINT32_C(0xca62c1d6)
-
-/* Initial hash value H for SHA-1: */
-static const sha_word32 sha1_initial_hash_value[5] = {
- SHA_UINT32_C(0x67452301),
- SHA_UINT32_C(0xefcdab89),
- SHA_UINT32_C(0x98badcfe),
- SHA_UINT32_C(0x10325476),
- SHA_UINT32_C(0xc3d2e1f0)
-};
-
-/* Hash constant words K for SHA-224 and SHA-256: */
-static const sha_word32 K256[64] = {
- SHA_UINT32_C(0x428a2f98), SHA_UINT32_C(0x71374491),
- SHA_UINT32_C(0xb5c0fbcf), SHA_UINT32_C(0xe9b5dba5),
- SHA_UINT32_C(0x3956c25b), SHA_UINT32_C(0x59f111f1),
- SHA_UINT32_C(0x923f82a4), SHA_UINT32_C(0xab1c5ed5),
- SHA_UINT32_C(0xd807aa98), SHA_UINT32_C(0x12835b01),
- SHA_UINT32_C(0x243185be), SHA_UINT32_C(0x550c7dc3),
- SHA_UINT32_C(0x72be5d74), SHA_UINT32_C(0x80deb1fe),
- SHA_UINT32_C(0x9bdc06a7), SHA_UINT32_C(0xc19bf174),
- SHA_UINT32_C(0xe49b69c1), SHA_UINT32_C(0xefbe4786),
- SHA_UINT32_C(0x0fc19dc6), SHA_UINT32_C(0x240ca1cc),
- SHA_UINT32_C(0x2de92c6f), SHA_UINT32_C(0x4a7484aa),
- SHA_UINT32_C(0x5cb0a9dc), SHA_UINT32_C(0x76f988da),
- SHA_UINT32_C(0x983e5152), SHA_UINT32_C(0xa831c66d),
- SHA_UINT32_C(0xb00327c8), SHA_UINT32_C(0xbf597fc7),
- SHA_UINT32_C(0xc6e00bf3), SHA_UINT32_C(0xd5a79147),
- SHA_UINT32_C(0x06ca6351), SHA_UINT32_C(0x14292967),
- SHA_UINT32_C(0x27b70a85), SHA_UINT32_C(0x2e1b2138),
- SHA_UINT32_C(0x4d2c6dfc), SHA_UINT32_C(0x53380d13),
- SHA_UINT32_C(0x650a7354), SHA_UINT32_C(0x766a0abb),
- SHA_UINT32_C(0x81c2c92e), SHA_UINT32_C(0x92722c85),
- SHA_UINT32_C(0xa2bfe8a1), SHA_UINT32_C(0xa81a664b),
- SHA_UINT32_C(0xc24b8b70), SHA_UINT32_C(0xc76c51a3),
- SHA_UINT32_C(0xd192e819), SHA_UINT32_C(0xd6990624),
- SHA_UINT32_C(0xf40e3585), SHA_UINT32_C(0x106aa070),
- SHA_UINT32_C(0x19a4c116), SHA_UINT32_C(0x1e376c08),
- SHA_UINT32_C(0x2748774c), SHA_UINT32_C(0x34b0bcb5),
- SHA_UINT32_C(0x391c0cb3), SHA_UINT32_C(0x4ed8aa4a),
- SHA_UINT32_C(0x5b9cca4f), SHA_UINT32_C(0x682e6ff3),
- SHA_UINT32_C(0x748f82ee), SHA_UINT32_C(0x78a5636f),
- SHA_UINT32_C(0x84c87814), SHA_UINT32_C(0x8cc70208),
- SHA_UINT32_C(0x90befffa), SHA_UINT32_C(0xa4506ceb),
- SHA_UINT32_C(0xbef9a3f7), SHA_UINT32_C(0xc67178f2)
-};
-
-/* Initial hash value H for SHA-224: */
-static const sha_word32 sha224_initial_hash_value[8] = {
- SHA_UINT32_C(0xc1059ed8),
- SHA_UINT32_C(0x367cd507),
- SHA_UINT32_C(0x3070dd17),
- SHA_UINT32_C(0xf70e5939),
- SHA_UINT32_C(0xffc00b31),
- SHA_UINT32_C(0x68581511),
- SHA_UINT32_C(0x64f98fa7),
- SHA_UINT32_C(0xbefa4fa4)
-};
-
-/* Initial hash value H for SHA-256: */
-static const sha_word32 sha256_initial_hash_value[8] = {
- SHA_UINT32_C(0x6a09e667),
- SHA_UINT32_C(0xbb67ae85),
- SHA_UINT32_C(0x3c6ef372),
- SHA_UINT32_C(0xa54ff53a),
- SHA_UINT32_C(0x510e527f),
- SHA_UINT32_C(0x9b05688c),
- SHA_UINT32_C(0x1f83d9ab),
- SHA_UINT32_C(0x5be0cd19)
-};
-
-/* Hash constant words K for SHA-384 and SHA-512: */
-static const sha_word64 K512[80] = {
- SHA_UINT64_C(0x428a2f98d728ae22), SHA_UINT64_C(0x7137449123ef65cd),
- SHA_UINT64_C(0xb5c0fbcfec4d3b2f), SHA_UINT64_C(0xe9b5dba58189dbbc),
- SHA_UINT64_C(0x3956c25bf348b538), SHA_UINT64_C(0x59f111f1b605d019),
- SHA_UINT64_C(0x923f82a4af194f9b), SHA_UINT64_C(0xab1c5ed5da6d8118),
- SHA_UINT64_C(0xd807aa98a3030242), SHA_UINT64_C(0x12835b0145706fbe),
- SHA_UINT64_C(0x243185be4ee4b28c), SHA_UINT64_C(0x550c7dc3d5ffb4e2),
- SHA_UINT64_C(0x72be5d74f27b896f), SHA_UINT64_C(0x80deb1fe3b1696b1),
- SHA_UINT64_C(0x9bdc06a725c71235), SHA_UINT64_C(0xc19bf174cf692694),
- SHA_UINT64_C(0xe49b69c19ef14ad2), SHA_UINT64_C(0xefbe4786384f25e3),
- SHA_UINT64_C(0x0fc19dc68b8cd5b5), SHA_UINT64_C(0x240ca1cc77ac9c65),
- SHA_UINT64_C(0x2de92c6f592b0275), SHA_UINT64_C(0x4a7484aa6ea6e483),
- SHA_UINT64_C(0x5cb0a9dcbd41fbd4), SHA_UINT64_C(0x76f988da831153b5),
- SHA_UINT64_C(0x983e5152ee66dfab), SHA_UINT64_C(0xa831c66d2db43210),
- SHA_UINT64_C(0xb00327c898fb213f), SHA_UINT64_C(0xbf597fc7beef0ee4),
- SHA_UINT64_C(0xc6e00bf33da88fc2), SHA_UINT64_C(0xd5a79147930aa725),
- SHA_UINT64_C(0x06ca6351e003826f), SHA_UINT64_C(0x142929670a0e6e70),
- SHA_UINT64_C(0x27b70a8546d22ffc), SHA_UINT64_C(0x2e1b21385c26c926),
- SHA_UINT64_C(0x4d2c6dfc5ac42aed), SHA_UINT64_C(0x53380d139d95b3df),
- SHA_UINT64_C(0x650a73548baf63de), SHA_UINT64_C(0x766a0abb3c77b2a8),
- SHA_UINT64_C(0x81c2c92e47edaee6), SHA_UINT64_C(0x92722c851482353b),
- SHA_UINT64_C(0xa2bfe8a14cf10364), SHA_UINT64_C(0xa81a664bbc423001),
- SHA_UINT64_C(0xc24b8b70d0f89791), SHA_UINT64_C(0xc76c51a30654be30),
- SHA_UINT64_C(0xd192e819d6ef5218), SHA_UINT64_C(0xd69906245565a910),
- SHA_UINT64_C(0xf40e35855771202a), SHA_UINT64_C(0x106aa07032bbd1b8),
- SHA_UINT64_C(0x19a4c116b8d2d0c8), SHA_UINT64_C(0x1e376c085141ab53),
- SHA_UINT64_C(0x2748774cdf8eeb99), SHA_UINT64_C(0x34b0bcb5e19b48a8),
- SHA_UINT64_C(0x391c0cb3c5c95a63), SHA_UINT64_C(0x4ed8aa4ae3418acb),
- SHA_UINT64_C(0x5b9cca4f7763e373), SHA_UINT64_C(0x682e6ff3d6b2b8a3),
- SHA_UINT64_C(0x748f82ee5defb2fc), SHA_UINT64_C(0x78a5636f43172f60),
- SHA_UINT64_C(0x84c87814a1f0ab72), SHA_UINT64_C(0x8cc702081a6439ec),
- SHA_UINT64_C(0x90befffa23631e28), SHA_UINT64_C(0xa4506cebde82bde9),
- SHA_UINT64_C(0xbef9a3f7b2c67915), SHA_UINT64_C(0xc67178f2e372532b),
- SHA_UINT64_C(0xca273eceea26619c), SHA_UINT64_C(0xd186b8c721c0c207),
- SHA_UINT64_C(0xeada7dd6cde0eb1e), SHA_UINT64_C(0xf57d4f7fee6ed178),
- SHA_UINT64_C(0x06f067aa72176fba), SHA_UINT64_C(0x0a637dc5a2c898a6),
- SHA_UINT64_C(0x113f9804bef90dae), SHA_UINT64_C(0x1b710b35131c471b),
- SHA_UINT64_C(0x28db77f523047d84), SHA_UINT64_C(0x32caab7b40c72493),
- SHA_UINT64_C(0x3c9ebe0a15c9bebc), SHA_UINT64_C(0x431d67c49c100d4c),
- SHA_UINT64_C(0x4cc5d4becb3e42b6), SHA_UINT64_C(0x597f299cfc657e2a),
- SHA_UINT64_C(0x5fcb6fab3ad6faec), SHA_UINT64_C(0x6c44198c4a475817)
-};
-
-/* Initial hash value H for SHA-384 */
-static const sha_word64 sha384_initial_hash_value[8] = {
- SHA_UINT64_C(0xcbbb9d5dc1059ed8),
- SHA_UINT64_C(0x629a292a367cd507),
- SHA_UINT64_C(0x9159015a3070dd17),
- SHA_UINT64_C(0x152fecd8f70e5939),
- SHA_UINT64_C(0x67332667ffc00b31),
- SHA_UINT64_C(0x8eb44a8768581511),
- SHA_UINT64_C(0xdb0c2e0d64f98fa7),
- SHA_UINT64_C(0x47b5481dbefa4fa4)
-};
-
-/* Initial hash value H for SHA-512 */
-static const sha_word64 sha512_initial_hash_value[8] = {
- SHA_UINT64_C(0x6a09e667f3bcc908),
- SHA_UINT64_C(0xbb67ae8584caa73b),
- SHA_UINT64_C(0x3c6ef372fe94f82b),
- SHA_UINT64_C(0xa54ff53a5f1d36f1),
- SHA_UINT64_C(0x510e527fade682d1),
- SHA_UINT64_C(0x9b05688c2b3e6c1f),
- SHA_UINT64_C(0x1f83d9abfb41bd6b),
- SHA_UINT64_C(0x5be0cd19137e2179)
-};
-
-/*
- * Constant used by SHA224/256/384/512_End() functions for converting the
- * digest to a readable hexadecimal character string:
- */
-static const char *sha_hex_digits = "0123456789abcdef";
-
-
-/*** SHA-1: ***********************************************************/
-void SHA1_Init(SHA_CTX* context) {
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- MEMCPY_BCOPY(context->s1.state, sha1_initial_hash_value, sizeof(sha_word32) * 5);
- MEMSET_BZERO(context->s1.buffer, 64);
- context->s1.bitcount = 0;
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-1 round macros: */
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-
-#define ROUND1_0_TO_15(a,b,c,d,e) \
- REVERSE32(*data++, W1[j]); \
- (e) = ROTL32(5, (a)) + Ch((b), (c), (d)) + (e) + \
- K1_0_TO_19 + W1[j]; \
- (b) = ROTL32(30, (b)); \
- j++;
-
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND1_0_TO_15(a,b,c,d,e) \
- (e) = ROTL32(5, (a)) + Ch((b), (c), (d)) + (e) + \
- K1_0_TO_19 + ( W1[j] = *data++ ); \
- (b) = ROTL32(30, (b)); \
- j++;
-
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND1_16_TO_19(a,b,c,d,e) \
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
- (e) = ROTL32(5, a) + Ch(b,c,d) + e + K1_0_TO_19 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
- (b) = ROTL32(30, b); \
- j++;
-
-#define ROUND1_20_TO_39(a,b,c,d,e) \
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
- (e) = ROTL32(5, a) + Parity(b,c,d) + e + K1_20_TO_39 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
- (b) = ROTL32(30, b); \
- j++;
-
-#define ROUND1_40_TO_59(a,b,c,d,e) \
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
- (e) = ROTL32(5, a) + Maj(b,c,d) + e + K1_40_TO_59 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
- (b) = ROTL32(30, b); \
- j++;
-
-#define ROUND1_60_TO_79(a,b,c,d,e) \
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
- (e) = ROTL32(5, a) + Parity(b,c,d) + e + K1_60_TO_79 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
- (b) = ROTL32(30, b); \
- j++;
-
-void SHA1_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
- sha_word32 a, b, c, d, e;
- sha_word32 T1, *W1;
- int j;
-
- W1 = (sha_word32*)context->s1.buffer;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->s1.state[0];
- b = context->s1.state[1];
- c = context->s1.state[2];
- d = context->s1.state[3];
- e = context->s1.state[4];
-
- j = 0;
-
- /* Rounds 0 to 15 unrolled: */
- ROUND1_0_TO_15(a,b,c,d,e);
- ROUND1_0_TO_15(e,a,b,c,d);
- ROUND1_0_TO_15(d,e,a,b,c);
- ROUND1_0_TO_15(c,d,e,a,b);
- ROUND1_0_TO_15(b,c,d,e,a);
- ROUND1_0_TO_15(a,b,c,d,e);
- ROUND1_0_TO_15(e,a,b,c,d);
- ROUND1_0_TO_15(d,e,a,b,c);
- ROUND1_0_TO_15(c,d,e,a,b);
- ROUND1_0_TO_15(b,c,d,e,a);
- ROUND1_0_TO_15(a,b,c,d,e);
- ROUND1_0_TO_15(e,a,b,c,d);
- ROUND1_0_TO_15(d,e,a,b,c);
- ROUND1_0_TO_15(c,d,e,a,b);
- ROUND1_0_TO_15(b,c,d,e,a);
- ROUND1_0_TO_15(a,b,c,d,e);
-
- /* Rounds 16 to 19 unrolled: */
- ROUND1_16_TO_19(e,a,b,c,d);
- ROUND1_16_TO_19(d,e,a,b,c);
- ROUND1_16_TO_19(c,d,e,a,b);
- ROUND1_16_TO_19(b,c,d,e,a);
-
- /* Rounds 20 to 39 unrolled: */
- ROUND1_20_TO_39(a,b,c,d,e);
- ROUND1_20_TO_39(e,a,b,c,d);
- ROUND1_20_TO_39(d,e,a,b,c);
- ROUND1_20_TO_39(c,d,e,a,b);
- ROUND1_20_TO_39(b,c,d,e,a);
- ROUND1_20_TO_39(a,b,c,d,e);
- ROUND1_20_TO_39(e,a,b,c,d);
- ROUND1_20_TO_39(d,e,a,b,c);
- ROUND1_20_TO_39(c,d,e,a,b);
- ROUND1_20_TO_39(b,c,d,e,a);
- ROUND1_20_TO_39(a,b,c,d,e);
- ROUND1_20_TO_39(e,a,b,c,d);
- ROUND1_20_TO_39(d,e,a,b,c);
- ROUND1_20_TO_39(c,d,e,a,b);
- ROUND1_20_TO_39(b,c,d,e,a);
- ROUND1_20_TO_39(a,b,c,d,e);
- ROUND1_20_TO_39(e,a,b,c,d);
- ROUND1_20_TO_39(d,e,a,b,c);
- ROUND1_20_TO_39(c,d,e,a,b);
- ROUND1_20_TO_39(b,c,d,e,a);
-
- /* Rounds 40 to 59 unrolled: */
- ROUND1_40_TO_59(a,b,c,d,e);
- ROUND1_40_TO_59(e,a,b,c,d);
- ROUND1_40_TO_59(d,e,a,b,c);
- ROUND1_40_TO_59(c,d,e,a,b);
- ROUND1_40_TO_59(b,c,d,e,a);
- ROUND1_40_TO_59(a,b,c,d,e);
- ROUND1_40_TO_59(e,a,b,c,d);
- ROUND1_40_TO_59(d,e,a,b,c);
- ROUND1_40_TO_59(c,d,e,a,b);
- ROUND1_40_TO_59(b,c,d,e,a);
- ROUND1_40_TO_59(a,b,c,d,e);
- ROUND1_40_TO_59(e,a,b,c,d);
- ROUND1_40_TO_59(d,e,a,b,c);
- ROUND1_40_TO_59(c,d,e,a,b);
- ROUND1_40_TO_59(b,c,d,e,a);
- ROUND1_40_TO_59(a,b,c,d,e);
- ROUND1_40_TO_59(e,a,b,c,d);
- ROUND1_40_TO_59(d,e,a,b,c);
- ROUND1_40_TO_59(c,d,e,a,b);
- ROUND1_40_TO_59(b,c,d,e,a);
-
- /* Rounds 60 to 79 unrolled: */
- ROUND1_60_TO_79(a,b,c,d,e);
- ROUND1_60_TO_79(e,a,b,c,d);
- ROUND1_60_TO_79(d,e,a,b,c);
- ROUND1_60_TO_79(c,d,e,a,b);
- ROUND1_60_TO_79(b,c,d,e,a);
- ROUND1_60_TO_79(a,b,c,d,e);
- ROUND1_60_TO_79(e,a,b,c,d);
- ROUND1_60_TO_79(d,e,a,b,c);
- ROUND1_60_TO_79(c,d,e,a,b);
- ROUND1_60_TO_79(b,c,d,e,a);
- ROUND1_60_TO_79(a,b,c,d,e);
- ROUND1_60_TO_79(e,a,b,c,d);
- ROUND1_60_TO_79(d,e,a,b,c);
- ROUND1_60_TO_79(c,d,e,a,b);
- ROUND1_60_TO_79(b,c,d,e,a);
- ROUND1_60_TO_79(a,b,c,d,e);
- ROUND1_60_TO_79(e,a,b,c,d);
- ROUND1_60_TO_79(d,e,a,b,c);
- ROUND1_60_TO_79(c,d,e,a,b);
- ROUND1_60_TO_79(b,c,d,e,a);
-
- /* Compute the current intermediate hash value */
- context->s1.state[0] += a;
- context->s1.state[1] += b;
- context->s1.state[2] += c;
- context->s1.state[3] += d;
- context->s1.state[4] += e;
-
- /* Clean up */
- a = b = c = d = e = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA1_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
- sha_word32 a, b, c, d, e;
- sha_word32 T1, *W1;
- int j;
-
- W1 = (sha_word32*)context->s1.buffer;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->s1.state[0];
- b = context->s1.state[1];
- c = context->s1.state[2];
- d = context->s1.state[3];
- e = context->s1.state[4];
- j = 0;
- do {
-#if BYTE_ORDER == LITTLE_ENDIAN
- T1 = data[j];
- /* Copy data while converting to host byte order */
- REVERSE32(*data++, W1[j]);
- T1 = ROTL32(5, a) + Ch(b, c, d) + e + K1_0_TO_19 + W1[j];
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
- T1 = ROTL32(5, a) + Ch(b, c, d) + e + K1_0_TO_19 + (W1[j] = *data++);
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
- e = d;
- d = c;
- c = ROTL32(30, b);
- b = a;
- a = T1;
- j++;
- } while (j < 16);
-
- do {
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
- T1 = ROTL32(5, a) + Ch(b,c,d) + e + K1_0_TO_19 + (W1[j&0x0f] = ROTL32(1, T1));
- e = d;
- d = c;
- c = ROTL32(30, b);
- b = a;
- a = T1;
- j++;
- } while (j < 20);
-
- do {
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
- T1 = ROTL32(5, a) + Parity(b,c,d) + e + K1_20_TO_39 + (W1[j&0x0f] = ROTL32(1, T1));
- e = d;
- d = c;
- c = ROTL32(30, b);
- b = a;
- a = T1;
- j++;
- } while (j < 40);
-
- do {
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
- T1 = ROTL32(5, a) + Maj(b,c,d) + e + K1_40_TO_59 + (W1[j&0x0f] = ROTL32(1, T1));
- e = d;
- d = c;
- c = ROTL32(30, b);
- b = a;
- a = T1;
- j++;
- } while (j < 60);
-
- do {
- T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
- T1 = ROTL32(5, a) + Parity(b,c,d) + e + K1_60_TO_79 + (W1[j&0x0f] = ROTL32(1, T1));
- e = d;
- d = c;
- c = ROTL32(30, b);
- b = a;
- a = T1;
- j++;
- } while (j < 80);
-
-
- /* Compute the current intermediate hash value */
- context->s1.state[0] += a;
- context->s1.state[1] += b;
- context->s1.state[2] += c;
- context->s1.state[3] += d;
- context->s1.state[4] += e;
-
- /* Clean up */
- a = b = c = d = e = T1 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA1_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
- unsigned int freespace, usedspace;
- if (len == 0) {
- /* Calling with no data is valid - we do nothing */
- return;
- }
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0 && data != (sha_byte*)0);
-
- usedspace = (unsigned int)((context->s1.bitcount >> 3) % 64);
- if (usedspace > 0) {
- /* Calculate how much free space is available in the buffer */
- freespace = 64 - usedspace;
-
- if (len >= freespace) {
- /* Fill the buffer completely and process it */
- MEMCPY_BCOPY(&context->s1.buffer[usedspace], data, freespace);
- context->s1.bitcount += freespace << 3;
- len -= freespace;
- data += freespace;
- SHA1_Internal_Transform(context, (const sha_word32*)context->s1.buffer);
- } else {
- /* The buffer is not yet full */
- MEMCPY_BCOPY(&context->s1.buffer[usedspace], data, len);
- context->s1.bitcount += len << 3;
- /* Clean up: */
- usedspace = freespace = 0;
- return;
- }
- }
- while (len >= 64) {
- /* Process as many complete blocks as we can */
- SHA1_Internal_Transform(context, (const sha_word32*)data);
- context->s1.bitcount += 512;
- len -= 64;
- data += 64;
- }
- if (len > 0) {
- /* There's left-overs, so save 'em */
- MEMCPY_BCOPY(context->s1.buffer, data, len);
- context->s1.bitcount += len << 3;
- }
- /* Clean up: */
- usedspace = freespace = 0;
-}
-
-void SHA1_Final(sha_byte digest[], SHA_CTX* context) {
- sha_word32 *d = (sha_word32*)digest;
- unsigned int usedspace;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- if (digest == (sha_byte*)0) {
- /*
- * No digest buffer, so we can do nothing
- * except clean up and go home
- */
- MEMSET_BZERO(context, sizeof(*context));
- return;
- }
-
- usedspace = (unsigned int)((context->s1.bitcount >> 3) % 64);
- if (usedspace == 0) {
- /* Set-up for the last transform: */
- MEMSET_BZERO(context->s1.buffer, 56);
-
- /* Begin padding with a 1 bit: */
- *context->s1.buffer = 0x80;
- } else {
- /* Begin padding with a 1 bit: */
- context->s1.buffer[usedspace++] = 0x80;
-
- if (usedspace <= 56) {
- /* Set-up for the last transform: */
- MEMSET_BZERO(&context->s1.buffer[usedspace], 56 - usedspace);
- } else {
- if (usedspace < 64) {
- MEMSET_BZERO(&context->s1.buffer[usedspace], 64 - usedspace);
- }
- /* Do second-to-last transform: */
- SHA1_Internal_Transform(context, (const sha_word32*)context->s1.buffer);
-
- /* And set-up for the last transform: */
- MEMSET_BZERO(context->s1.buffer, 56);
- }
- /* Clean up: */
- usedspace = 0;
- }
- /* Set the bit count: */
-#if BYTE_ORDER == LITTLE_ENDIAN
- /* Convert FROM host byte order */
- REVERSE64(context->s1.bitcount,context->s1.bitcount);
-#endif
- MEMCPY_BCOPY(&context->s1.buffer[56], &context->s1.bitcount,
- sizeof(sha_word64));
-
- /* Final transform: */
- SHA1_Internal_Transform(context, (const sha_word32*)context->s1.buffer);
-
- /* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < (SHA1_DIGEST_LENGTH >> 2); j++) {
- REVERSE32(context->s1.state[j],context->s1.state[j]);
- *d++ = context->s1.state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->s1.state, SHA1_DIGEST_LENGTH);
-#endif
-
- /* Clean up: */
- MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA1_End(SHA_CTX* context, char buffer[]) {
- sha_byte digest[SHA1_DIGEST_LENGTH], *d = digest;
- int i;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- if (buffer != (char*)0) {
- SHA1_Final(digest, context);
-
- for (i = 0; i < SHA1_DIGEST_LENGTH; i++) {
- *buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char)0;
- } else {
- MEMSET_BZERO(context, sizeof(*context));
- }
- MEMSET_BZERO(digest, SHA1_DIGEST_LENGTH);
- return buffer;
-}
-
-char* SHA1_Data(const sha_byte* data, size_t len, char digest[SHA1_DIGEST_STRING_LENGTH]) {
- SHA_CTX context;
-
- SHA1_Init(&context);
- SHA1_Update(&context, data, len);
- return SHA1_End(&context, digest);
-}
-
-
-/*** SHA-256: *********************************************************/
-void SHA256_Internal_Init(SHA_CTX* context, const sha_word32* ihv) {
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- MEMCPY_BCOPY(context->s256.state, ihv, sizeof(sha_word32) * 8);
- MEMSET_BZERO(context->s256.buffer, 64);
- context->s256.bitcount = 0;
-}
-
-void SHA256_Init(SHA_CTX* context) {
- SHA256_Internal_Init(context, sha256_initial_hash_value);
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-256 round macros: */
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-
-#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
- REVERSE32(*data++, W256[j]); \
- T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
- K256[j] + W256[j]; \
- (d) += T1; \
- (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
- j++
-
-
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
- T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
- K256[j] + (W256[j] = *data++); \
- (d) += T1; \
- (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
- j++
-
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND256(a,b,c,d,e,f,g,h) \
- s0 = W256[(j+1)&0x0f]; \
- s0 = sigma0_256(s0); \
- s1 = W256[(j+14)&0x0f]; \
- s1 = sigma1_256(s1); \
- T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
- (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
- (d) += T1; \
- (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
- j++
-
-void SHA256_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
- sha_word32 a, b, c, d, e, f, g, h, s0, s1;
- sha_word32 T1, *W256;
- int j;
-
- W256 = (sha_word32*)context->s256.buffer;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->s256.state[0];
- b = context->s256.state[1];
- c = context->s256.state[2];
- d = context->s256.state[3];
- e = context->s256.state[4];
- f = context->s256.state[5];
- g = context->s256.state[6];
- h = context->s256.state[7];
-
- j = 0;
- do {
- /* Rounds 0 to 15 (unrolled): */
- ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
- ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
- ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
- ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
- ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
- ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
- ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
- ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
- } while (j < 16);
-
- /* Now for the remaining rounds to 64: */
- do {
- ROUND256(a,b,c,d,e,f,g,h);
- ROUND256(h,a,b,c,d,e,f,g);
- ROUND256(g,h,a,b,c,d,e,f);
- ROUND256(f,g,h,a,b,c,d,e);
- ROUND256(e,f,g,h,a,b,c,d);
- ROUND256(d,e,f,g,h,a,b,c);
- ROUND256(c,d,e,f,g,h,a,b);
- ROUND256(b,c,d,e,f,g,h,a);
- } while (j < 64);
-
- /* Compute the current intermediate hash value */
- context->s256.state[0] += a;
- context->s256.state[1] += b;
- context->s256.state[2] += c;
- context->s256.state[3] += d;
- context->s256.state[4] += e;
- context->s256.state[5] += f;
- context->s256.state[6] += g;
- context->s256.state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA256_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
- sha_word32 a, b, c, d, e, f, g, h, s0, s1;
- sha_word32 T1, T2, *W256;
- int j;
-
- W256 = (sha_word32*)context->s256.buffer;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->s256.state[0];
- b = context->s256.state[1];
- c = context->s256.state[2];
- d = context->s256.state[3];
- e = context->s256.state[4];
- f = context->s256.state[5];
- g = context->s256.state[6];
- h = context->s256.state[7];
-
- j = 0;
- do {
-#if BYTE_ORDER == LITTLE_ENDIAN
- /* Copy data while converting to host byte order */
- REVERSE32(*data++,W256[j]);
- /* Apply the SHA-256 compression function to update a..h */
- T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
- /* Apply the SHA-256 compression function to update a..h with copy */
- T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
- T2 = Sigma0_256(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 16);
-
- do {
- /* Part of the message block expansion: */
- s0 = W256[(j+1)&0x0f];
- s0 = sigma0_256(s0);
- s1 = W256[(j+14)&0x0f];
- s1 = sigma1_256(s1);
-
- /* Apply the SHA-256 compression function to update a..h */
- T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] +
- (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
- T2 = Sigma0_256(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 64);
-
- /* Compute the current intermediate hash value */
- context->s256.state[0] += a;
- context->s256.state[1] += b;
- context->s256.state[2] += c;
- context->s256.state[3] += d;
- context->s256.state[4] += e;
- context->s256.state[5] += f;
- context->s256.state[6] += g;
- context->s256.state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = T2 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA256_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
- unsigned int freespace, usedspace;
-
- if (len == 0) {
- /* Calling with no data is valid - we do nothing */
- return;
- }
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0 && data != (sha_byte*)0);
-
- usedspace = (unsigned int)((context->s256.bitcount >> 3) % 64);
- if (usedspace > 0) {
- /* Calculate how much free space is available in the buffer */
- freespace = 64 - usedspace;
-
- if (len >= freespace) {
- /* Fill the buffer completely and process it */
- MEMCPY_BCOPY(&context->s256.buffer[usedspace], data, freespace);
- context->s256.bitcount += freespace << 3;
- len -= freespace;
- data += freespace;
- SHA256_Internal_Transform(context, (const sha_word32*)context->s256.buffer);
- } else {
- /* The buffer is not yet full */
- MEMCPY_BCOPY(&context->s256.buffer[usedspace], data, len);
- context->s256.bitcount += len << 3;
- /* Clean up: */
- usedspace = freespace = 0;
- return;
- }
- }
- while (len >= 64) {
- /* Process as many complete blocks as we can */
- SHA256_Internal_Transform(context, (const sha_word32*)data);
- context->s256.bitcount += 512;
- len -= 64;
- data += 64;
- }
- if (len > 0) {
- /* There's left-overs, so save 'em */
- MEMCPY_BCOPY(context->s256.buffer, data, len);
- context->s256.bitcount += len << 3;
- }
- /* Clean up: */
- usedspace = freespace = 0;
-}
-
-void SHA256_Internal_Last(SHA_CTX* context) {
- unsigned int usedspace;
-
- usedspace = (unsigned int)((context->s256.bitcount >> 3) % 64);
-#if BYTE_ORDER == LITTLE_ENDIAN
- /* Convert FROM host byte order */
- REVERSE64(context->s256.bitcount,context->s256.bitcount);
-#endif
- if (usedspace > 0) {
- /* Begin padding with a 1 bit: */
- context->s256.buffer[usedspace++] = 0x80;
-
- if (usedspace <= 56) {
- /* Set-up for the last transform: */
- MEMSET_BZERO(&context->s256.buffer[usedspace], 56 - usedspace);
- } else {
- if (usedspace < 64) {
- MEMSET_BZERO(&context->s256.buffer[usedspace], 64 - usedspace);
- }
- /* Do second-to-last transform: */
- SHA256_Internal_Transform(context, (const sha_word32*)context->s256.buffer);
-
- /* And set-up for the last transform: */
- MEMSET_BZERO(context->s256.buffer, 56);
- }
- /* Clean up: */
- usedspace = 0;
- } else {
- /* Set-up for the last transform: */
- MEMSET_BZERO(context->s256.buffer, 56);
-
- /* Begin padding with a 1 bit: */
- *context->s256.buffer = 0x80;
- }
- /* Set the bit count: */
- MEMCPY_BCOPY(&context->s256.buffer[56], &context->s256.bitcount,
- sizeof(sha_word64));
-
- /* Final transform: */
- SHA256_Internal_Transform(context, (const sha_word32*)context->s256.buffer);
-}
-
-void SHA256_Final(sha_byte digest[], SHA_CTX* context) {
- sha_word32 *d = (sha_word32*)digest;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha_byte*)0) {
- SHA256_Internal_Last(context);
-
- /* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < (SHA256_DIGEST_LENGTH >> 2); j++) {
- REVERSE32(context->s256.state[j],context->s256.state[j]);
- *d++ = context->s256.state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->s256.state, SHA256_DIGEST_LENGTH);
-#endif
- }
-
- /* Clean up state data: */
- MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA256_End(SHA_CTX* context, char buffer[]) {
- sha_byte digest[SHA256_DIGEST_LENGTH], *d = digest;
- int i;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- if (buffer != (char*)0) {
- SHA256_Final(digest, context);
-
- for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
- *buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char)0;
- } else {
- MEMSET_BZERO(context, sizeof(*context));
- }
- MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH);
- return buffer;
-}
-
-char* SHA256_Data(const sha_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
- SHA_CTX context;
-
- SHA256_Init(&context);
- SHA256_Update(&context, data, len);
- return SHA256_End(&context, digest);
-}
-
-
-/*** SHA-224: *********************************************************/
-void SHA224_Init(SHA_CTX* context) {
- SHA256_Internal_Init(context, sha224_initial_hash_value);
-}
-
-void SHA224_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
- SHA256_Internal_Transform(context, data);
-}
-
-void SHA224_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
- SHA256_Update(context, data, len);
-}
-
-void SHA224_Final(sha_byte digest[], SHA_CTX* context) {
- sha_word32 *d = (sha_word32*)digest;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha_byte*)0) {
- SHA256_Internal_Last(context);
-
- /* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < (SHA224_DIGEST_LENGTH >> 2); j++) {
- REVERSE32(context->s256.state[j],context->s256.state[j]);
- *d++ = context->s256.state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->s256.state, SHA224_DIGEST_LENGTH);
-#endif
- }
-
- /* Clean up state data: */
- MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA224_End(SHA_CTX* context, char buffer[]) {
- sha_byte digest[SHA224_DIGEST_LENGTH], *d = digest;
- int i;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- if (buffer != (char*)0) {
- SHA224_Final(digest, context);
-
- for (i = 0; i < SHA224_DIGEST_LENGTH; i++) {
- *buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char)0;
- } else {
- MEMSET_BZERO(context, sizeof(*context));
- }
- MEMSET_BZERO(digest, SHA224_DIGEST_LENGTH);
- return buffer;
-}
-
-char* SHA224_Data(const sha_byte* data, size_t len, char digest[SHA224_DIGEST_STRING_LENGTH]) {
- SHA_CTX context;
-
- SHA224_Init(&context);
- SHA224_Update(&context, data, len);
- return SHA224_End(&context, digest);
-}
-
-
-/*** SHA-512: *********************************************************/
-void SHA512_Internal_Init(SHA_CTX* context, const sha_word64* ihv) {
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- MEMCPY_BCOPY(context->s512.state, ihv, sizeof(sha_word64) * 8);
- MEMSET_BZERO(context->s512.buffer, 128);
- context->s512.bitcount[0] = context->s512.bitcount[1] = 0;
-}
-
-void SHA512_Init(SHA_CTX* context) {
- SHA512_Internal_Init(context, sha512_initial_hash_value);
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-512 round macros: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-
-#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
- REVERSE64(*data++, W512[j]); \
- T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
- K512[j] + W512[j]; \
- (d) += T1, \
- (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \
- j++
-
-
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
- T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
- K512[j] + (W512[j] = *data++); \
- (d) += T1; \
- (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
- j++
-
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND512(a,b,c,d,e,f,g,h) \
- s0 = W512[(j+1)&0x0f]; \
- s0 = sigma0_512(s0); \
- s1 = W512[(j+14)&0x0f]; \
- s1 = sigma1_512(s1); \
- T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
- (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
- (d) += T1; \
- (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
- j++
-
-void SHA512_Internal_Transform(SHA_CTX* context, const sha_word64* data) {
- sha_word64 a, b, c, d, e, f, g, h, s0, s1;
- sha_word64 T1, *W512 = (sha_word64*)context->s512.buffer;
- int j;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->s512.state[0];
- b = context->s512.state[1];
- c = context->s512.state[2];
- d = context->s512.state[3];
- e = context->s512.state[4];
- f = context->s512.state[5];
- g = context->s512.state[6];
- h = context->s512.state[7];
-
- j = 0;
- do {
- ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
- ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
- ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
- ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
- ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
- ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
- ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
- ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
- } while (j < 16);
-
- /* Now for the remaining rounds up to 79: */
- do {
- ROUND512(a,b,c,d,e,f,g,h);
- ROUND512(h,a,b,c,d,e,f,g);
- ROUND512(g,h,a,b,c,d,e,f);
- ROUND512(f,g,h,a,b,c,d,e);
- ROUND512(e,f,g,h,a,b,c,d);
- ROUND512(d,e,f,g,h,a,b,c);
- ROUND512(c,d,e,f,g,h,a,b);
- ROUND512(b,c,d,e,f,g,h,a);
- } while (j < 80);
-
- /* Compute the current intermediate hash value */
- context->s512.state[0] += a;
- context->s512.state[1] += b;
- context->s512.state[2] += c;
- context->s512.state[3] += d;
- context->s512.state[4] += e;
- context->s512.state[5] += f;
- context->s512.state[6] += g;
- context->s512.state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA512_Internal_Transform(SHA_CTX* context, const sha_word64* data) {
- sha_word64 a, b, c, d, e, f, g, h, s0, s1;
- sha_word64 T1, T2, *W512 = (sha_word64*)context->s512.buffer;
- int j;
-
- /* Initialize registers with the prev. intermediate value */
- a = context->s512.state[0];
- b = context->s512.state[1];
- c = context->s512.state[2];
- d = context->s512.state[3];
- e = context->s512.state[4];
- f = context->s512.state[5];
- g = context->s512.state[6];
- h = context->s512.state[7];
-
- j = 0;
- do {
-#if BYTE_ORDER == LITTLE_ENDIAN
- /* Convert TO host byte order */
- REVERSE64(*data++, W512[j]);
- /* Apply the SHA-512 compression function to update a..h */
- T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
- /* Apply the SHA-512 compression function to update a..h with copy */
- T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
- T2 = Sigma0_512(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 16);
-
- do {
- /* Part of the message block expansion: */
- s0 = W512[(j+1)&0x0f];
- s0 = sigma0_512(s0);
- s1 = W512[(j+14)&0x0f];
- s1 = sigma1_512(s1);
-
- /* Apply the SHA-512 compression function to update a..h */
- T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
- (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
- T2 = Sigma0_512(a) + Maj(a, b, c);
- h = g;
- g = f;
- f = e;
- e = d + T1;
- d = c;
- c = b;
- b = a;
- a = T1 + T2;
-
- j++;
- } while (j < 80);
-
- /* Compute the current intermediate hash value */
- context->s512.state[0] += a;
- context->s512.state[1] += b;
- context->s512.state[2] += c;
- context->s512.state[3] += d;
- context->s512.state[4] += e;
- context->s512.state[5] += f;
- context->s512.state[6] += g;
- context->s512.state[7] += h;
-
- /* Clean up */
- a = b = c = d = e = f = g = h = T1 = T2 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA512_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
- unsigned int freespace, usedspace;
-
- if (len == 0) {
- /* Calling with no data is valid - we do nothing */
- return;
- }
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0 && data != (sha_byte*)0);
-
- usedspace = (unsigned int)((context->s512.bitcount[0] >> 3) % 128);
- if (usedspace > 0) {
- /* Calculate how much free space is available in the buffer */
- freespace = 128 - usedspace;
-
- if (len >= freespace) {
- /* Fill the buffer completely and process it */
- MEMCPY_BCOPY(&context->s512.buffer[usedspace], data, freespace);
- ADDINC128(context->s512.bitcount, freespace << 3);
- len -= freespace;
- data += freespace;
- SHA512_Internal_Transform(context, (const sha_word64*)context->s512.buffer);
- } else {
- /* The buffer is not yet full */
- MEMCPY_BCOPY(&context->s512.buffer[usedspace], data, len);
- ADDINC128(context->s512.bitcount, len << 3);
- /* Clean up: */
- usedspace = freespace = 0;
- return;
- }
- }
- while (len >= 128) {
- /* Process as many complete blocks as we can */
- SHA512_Internal_Transform(context, (const sha_word64*)data);
- ADDINC128(context->s512.bitcount, 1024);
- len -= 128;
- data += 128;
- }
- if (len > 0) {
- /* There's left-overs, so save 'em */
- MEMCPY_BCOPY(context->s512.buffer, data, len);
- ADDINC128(context->s512.bitcount, len << 3);
- }
- /* Clean up: */
- usedspace = freespace = 0;
-}
-
-void SHA512_Internal_Last(SHA_CTX* context) {
- unsigned int usedspace;
-
- usedspace = (unsigned int)((context->s512.bitcount[0] >> 3) % 128);
-#if BYTE_ORDER == LITTLE_ENDIAN
- /* Convert FROM host byte order */
- REVERSE64(context->s512.bitcount[0],context->s512.bitcount[0]);
- REVERSE64(context->s512.bitcount[1],context->s512.bitcount[1]);
-#endif
- if (usedspace > 0) {
- /* Begin padding with a 1 bit: */
- context->s512.buffer[usedspace++] = 0x80;
-
- if (usedspace <= 112) {
- /* Set-up for the last transform: */
- MEMSET_BZERO(&context->s512.buffer[usedspace], 112 - usedspace);
- } else {
- if (usedspace < 128) {
- MEMSET_BZERO(&context->s512.buffer[usedspace], 128 - usedspace);
- }
- /* Do second-to-last transform: */
- SHA512_Internal_Transform(context, (const sha_word64*)context->s512.buffer);
-
- /* And set-up for the last transform: */
- MEMSET_BZERO(context->s512.buffer, 112);
- }
- /* Clean up: */
- usedspace = 0;
- } else {
- /* Prepare for final transform: */
- MEMSET_BZERO(context->s512.buffer, 112);
-
- /* Begin padding with a 1 bit: */
- *context->s512.buffer = 0x80;
- }
- /* Store the length of input data (in bits): */
- MEMCPY_BCOPY(&context->s512.buffer[112], &context->s512.bitcount[1],
- sizeof(sha_word64));
- MEMCPY_BCOPY(&context->s512.buffer[120], &context->s512.bitcount[0],
- sizeof(sha_word64));
-
- /* Final transform: */
- SHA512_Internal_Transform(context, (const sha_word64*)context->s512.buffer);
-}
-
-void SHA512_Final(sha_byte digest[], SHA_CTX* context) {
- sha_word64 *d = (sha_word64*)digest;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha_byte*)0) {
- SHA512_Internal_Last(context);
-
- /* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < (SHA512_DIGEST_LENGTH >> 3); j++) {
- REVERSE64(context->s512.state[j],context->s512.state[j]);
- *d++ = context->s512.state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->s512.state, SHA512_DIGEST_LENGTH);
-#endif
- }
-
- /* Zero out state data */
- MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA512_End(SHA_CTX* context, char buffer[]) {
- sha_byte digest[SHA512_DIGEST_LENGTH], *d = digest;
- int i;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- if (buffer != (char*)0) {
- SHA512_Final(digest, context);
-
- for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
- *buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char)0;
- } else {
- MEMSET_BZERO(context, sizeof(*context));
- }
- MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH);
- return buffer;
-}
-
-char* SHA512_Data(const sha_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) {
- SHA_CTX context;
-
- SHA512_Init(&context);
- SHA512_Update(&context, data, len);
- return SHA512_End(&context, digest);
-}
-
-
-/*** SHA-384: *********************************************************/
-void SHA384_Init(SHA_CTX* context) {
- SHA512_Internal_Init(context, sha384_initial_hash_value);
-}
-
-void SHA384_Update(SHA_CTX* context, const sha_byte* data, size_t len) {
- SHA512_Update(context, data, len);
-}
-
-void SHA384_Final(sha_byte digest[], SHA_CTX* context) {
- sha_word64 *d = (sha_word64*)digest;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- /* If no digest buffer is passed, we don't bother doing this: */
- if (digest != (sha_byte*)0) {
- SHA512_Internal_Last(context);
-
- /* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
- {
- /* Convert TO host byte order */
- int j;
- for (j = 0; j < (SHA384_DIGEST_LENGTH >> 3); j++) {
- REVERSE64(context->s512.state[j],context->s512.state[j]);
- *d++ = context->s512.state[j];
- }
- }
-#else
- MEMCPY_BCOPY(d, context->s512.state, SHA384_DIGEST_LENGTH);
-#endif
- }
-
- /* Zero out state data */
- MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA384_End(SHA_CTX* context, char buffer[]) {
- sha_byte digest[SHA384_DIGEST_LENGTH], *d = digest;
- int i;
-
- /* Sanity check: */
- assert(context != (SHA_CTX*)0);
-
- if (buffer != (char*)0) {
- SHA384_Final(digest, context);
-
- for (i = 0; i < SHA384_DIGEST_LENGTH; i++) {
- *buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
- *buffer++ = sha_hex_digits[*d & 0x0f];
- d++;
- }
- *buffer = (char)0;
- } else {
- MEMSET_BZERO(context, sizeof(*context));
- }
- MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH);
- return buffer;
-}
-
-char* SHA384_Data(const sha_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) {
- SHA_CTX context;
-
- SHA384_Init(&context);
- SHA384_Update(&context, data, len);
- return SHA384_End(&context, digest);
-}
diff --git a/Source/cm_sha2.h b/Source/cm_sha2.h
deleted file mode 100644
index f151031..0000000
--- a/Source/cm_sha2.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * FILE: sha2.h
- * AUTHOR: Aaron D. Gifford
- * http://www.aarongifford.com/computers/sha.html
- *
- * Copyright (c) 2000-2003, Aaron D. Gifford
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * $Id: sha2.h,v 1.4 2004/01/07 19:06:18 adg Exp $
- */
-
-#ifndef __SHA2_H__
-#define __SHA2_H__
-
-#include "cm_sha2_mangle.h"
-
-/* CMake modification: use integer types from KWIML. */
-#include <cm_kwiml.h>
-typedef KWIML_INT_uint8_t cm_sha2_uint8_t;
-typedef KWIML_INT_uint32_t cm_sha2_uint32_t;
-typedef KWIML_INT_uint64_t cm_sha2_uint64_t;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/*
- * Import u_intXX_t size_t type definitions from system headers. You
- * may need to change this, or define these things yourself in this
- * file.
- */
-#include <sys/types.h>
-
-/*** SHA-224/256/384/512 Various Length Definitions *******************/
-
-/* Digest lengths for SHA-1/224/256/384/512 */
-#define SHA1_DIGEST_LENGTH 20
-#define SHA1_DIGEST_STRING_LENGTH (SHA1_DIGEST_LENGTH * 2 + 1)
-#define SHA224_DIGEST_LENGTH 28
-#define SHA224_DIGEST_STRING_LENGTH (SHA224_DIGEST_LENGTH * 2 + 1)
-#define SHA256_DIGEST_LENGTH 32
-#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1)
-#define SHA384_DIGEST_LENGTH 48
-#define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1)
-#define SHA512_DIGEST_LENGTH 64
-#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1)
-
-
-/*** SHA-224/256/384/512 Context Structures ***************************/
-
-typedef union _SHA_CTX {
- /* SHA-1 uses this part of the union: */
- struct {
- cm_sha2_uint32_t state[5];
- cm_sha2_uint64_t bitcount;
- cm_sha2_uint8_t buffer[64];
- } s1;
-
- /* SHA-224 and SHA-256 use this part of the union: */
- struct {
- cm_sha2_uint32_t state[8];
- cm_sha2_uint64_t bitcount;
- cm_sha2_uint8_t buffer[64];
- } s256;
-
- /* SHA-384 and SHA-512 use this part of the union: */
- struct {
- cm_sha2_uint64_t state[8];
- cm_sha2_uint64_t bitcount[2];
- cm_sha2_uint8_t buffer[128];
- } s512;
-} SHA_CTX;
-
-/*** SHA-256/384/512 Function Prototypes ******************************/
-
-void SHA1_Init(SHA_CTX*);
-void SHA1_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA1_Final(cm_sha2_uint8_t[SHA1_DIGEST_LENGTH], SHA_CTX*);
-char* SHA1_End(SHA_CTX*, char[SHA1_DIGEST_STRING_LENGTH]);
-char* SHA1_Data(const cm_sha2_uint8_t*, size_t,
- char[SHA1_DIGEST_STRING_LENGTH]);
-
-void SHA224_Init(SHA_CTX*);
-void SHA224_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA224_Final(cm_sha2_uint8_t[SHA224_DIGEST_LENGTH], SHA_CTX*);
-char* SHA224_End(SHA_CTX*, char[SHA224_DIGEST_STRING_LENGTH]);
-char* SHA224_Data(const cm_sha2_uint8_t*, size_t,
- char[SHA224_DIGEST_STRING_LENGTH]);
-
-void SHA256_Init(SHA_CTX*);
-void SHA256_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA256_Final(cm_sha2_uint8_t[SHA256_DIGEST_LENGTH], SHA_CTX*);
-char* SHA256_End(SHA_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);
-char* SHA256_Data(const cm_sha2_uint8_t*, size_t,
- char[SHA256_DIGEST_STRING_LENGTH]);
-
-void SHA384_Init(SHA_CTX*);
-void SHA384_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA384_Final(cm_sha2_uint8_t[SHA384_DIGEST_LENGTH], SHA_CTX*);
-char* SHA384_End(SHA_CTX*, char[SHA384_DIGEST_STRING_LENGTH]);
-char* SHA384_Data(const cm_sha2_uint8_t*, size_t,
- char[SHA384_DIGEST_STRING_LENGTH]);
-
-void SHA512_Init(SHA_CTX*);
-void SHA512_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA512_Final(cm_sha2_uint8_t[SHA512_DIGEST_LENGTH], SHA_CTX*);
-char* SHA512_End(SHA_CTX*, char[SHA512_DIGEST_STRING_LENGTH]);
-char* SHA512_Data(const cm_sha2_uint8_t*, size_t,
- char[SHA512_DIGEST_STRING_LENGTH]);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* __SHA2_H__ */
diff --git a/Source/cm_sha2_mangle.h b/Source/cm_sha2_mangle.h
deleted file mode 100644
index 3dce819..0000000
--- a/Source/cm_sha2_mangle.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cm_sha2_mangle_h
-#define cm_sha2_mangle_h
-
-/* Mangle sha2 symbol names to avoid possible conflict with
- implementations in other libraries to which CMake links. */
-#define SHA1_Data cmSHA1_Data
-#define SHA1_End cmSHA1_End
-#define SHA1_Final cmSHA1_Final
-#define SHA1_Init cmSHA1_Init
-#define SHA1_Internal_Transform cmSHA1_Internal_Transform
-#define SHA1_Update cmSHA1_Update
-#define SHA224_Data cmSHA224_Data
-#define SHA224_End cmSHA224_End
-#define SHA224_Final cmSHA224_Final
-#define SHA224_Init cmSHA224_Init
-#define SHA224_Internal_Transform cmSHA224_Internal_Transform
-#define SHA224_Update cmSHA224_Update
-#define SHA256_Data cmSHA256_Data
-#define SHA256_End cmSHA256_End
-#define SHA256_Final cmSHA256_Final
-#define SHA256_Init cmSHA256_Init
-#define SHA256_Internal_Init cmSHA256_Internal_Init
-#define SHA256_Internal_Last cmSHA256_Internal_Last
-#define SHA256_Internal_Transform cmSHA256_Internal_Transform
-#define SHA256_Update cmSHA256_Update
-#define SHA384_Data cmSHA384_Data
-#define SHA384_End cmSHA384_End
-#define SHA384_Final cmSHA384_Final
-#define SHA384_Init cmSHA384_Init
-#define SHA384_Update cmSHA384_Update
-#define SHA512_Data cmSHA512_Data
-#define SHA512_End cmSHA512_End
-#define SHA512_Final cmSHA512_Final
-#define SHA512_Init cmSHA512_Init
-#define SHA512_Internal_Init cmSHA512_Internal_Init
-#define SHA512_Internal_Last cmSHA512_Internal_Last
-#define SHA512_Internal_Transform cmSHA512_Internal_Transform
-#define SHA512_Update cmSHA512_Update
-
-#endif
diff --git a/Source/cmake.cxx b/Source/cmake.cxx
index eb76ca0..733e0e4 100644
--- a/Source/cmake.cxx
+++ b/Source/cmake.cxx
@@ -17,6 +17,7 @@
#include "cmMakefile.h"
#include "cmMessenger.h"
#include "cmState.h"
+#include "cmStateDirectory.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmTargetLinkLibraryType.h"
@@ -25,11 +26,11 @@
#include "cm_auto_ptr.hxx"
#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cm_jsoncpp_writer.h>
+
#include "cmGraphVizWriter.h"
#include "cmVariableWatch.h"
#include "cm_unordered_map.hxx"
-
-#include <cm_jsoncpp_writer.h>
#endif
// only build kdevelop generator on non-windows platforms
@@ -128,8 +129,8 @@ typedef CM_UNORDERED_MAP<std::string, Json::Value> JsonValueMapType;
} // namespace
-static bool cmakeCheckStampFile(const char* stampName);
-static bool cmakeCheckStampList(const char* stampName);
+static bool cmakeCheckStampFile(const char* stampName, bool verbose = true);
+static bool cmakeCheckStampList(const char* stampList, bool verbose = true);
void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
void* ctx, const char* /*unused*/,
@@ -1456,7 +1457,7 @@ void cmake::CreateDefaultGlobalGenerator()
const char* GeneratorName;
};
static VSVersionedGenerator const vsGenerators[] = {
- { "15.0", "Visual Studio 15" }, //
+ { "15.0", "Visual Studio 15 2017" }, //
{ "14.0", "Visual Studio 14 2015" }, //
{ "12.0", "Visual Studio 12 2013" }, //
{ "11.0", "Visual Studio 11 2012" }, //
@@ -2232,7 +2233,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args)
return 0;
}
-static bool cmakeCheckStampFile(const char* stampName)
+static bool cmakeCheckStampFile(const char* stampName, bool verbose)
{
// The stamp file does not exist. Use the stamp dependencies to
// determine whether it is really out of date. This works in
@@ -2286,11 +2287,13 @@ static bool cmakeCheckStampFile(const char* stampName)
stamp << "# CMake generation timestamp file for this directory.\n";
}
if (cmSystemTools::RenameFile(stampTemp, stampName)) {
- // Notify the user why CMake is not re-running. It is safe to
- // just print to stdout here because this code is only reachable
- // through an undocumented flag used by the VS generator.
- std::cout << "CMake does not need to re-run because " << stampName
- << " is up-to-date.\n";
+ if (verbose) {
+ // Notify the user why CMake is not re-running. It is safe to
+ // just print to stdout here because this code is only reachable
+ // through an undocumented flag used by the VS generator.
+ std::cout << "CMake does not need to re-run because " << stampName
+ << " is up-to-date.\n";
+ }
return true;
}
cmSystemTools::RemoveFile(stampTemp);
@@ -2298,7 +2301,7 @@ static bool cmakeCheckStampFile(const char* stampName)
return false;
}
-static bool cmakeCheckStampList(const char* stampList)
+static bool cmakeCheckStampList(const char* stampList, bool verbose)
{
// If the stamp list does not exist CMake must rerun to generate it.
if (!cmSystemTools::FileExists(stampList)) {
@@ -2316,7 +2319,7 @@ static bool cmakeCheckStampList(const char* stampList)
// Check each stamp.
std::string stampName;
while (cmSystemTools::GetLineFromStream(fin, stampName)) {
- if (!cmakeCheckStampFile(stampName.c_str())) {
+ if (!cmakeCheckStampFile(stampName.c_str(), verbose)) {
return false;
}
}
@@ -2396,6 +2399,48 @@ int cmake::Build(const std::string& dir, const std::string& target,
if (cachedVerbose) {
verbose = cmSystemTools::IsOn(cachedVerbose);
}
+
+#ifdef CMAKE_HAVE_VS_GENERATORS
+ // For VS generators, explicitly check if regeneration is necessary before
+ // actually starting the build. If not done separately from the build
+ // itself, there is the risk of building an out-of-date solution file due
+ // to limitations of the underlying build system.
+ std::string const stampList = cachePath + "/" +
+ GetCMakeFilesDirectoryPostSlash() +
+ cmGlobalVisualStudio8Generator::GetGenerateStampList();
+
+ // Note that the stampList file only exists for VS generators.
+ if (cmSystemTools::FileExists(stampList.c_str()) &&
+ !cmakeCheckStampList(stampList.c_str(), false)) {
+
+ // Correctly initialize the home (=source) and home output (=binary)
+ // directories, which is required for running the generation step.
+ std::string homeOrig = this->GetHomeDirectory();
+ std::string homeOutputOrig = this->GetHomeOutputDirectory();
+ this->SetDirectoriesFromFile(cachePath.c_str());
+
+ int ret = this->Configure();
+ if (ret) {
+ cmSystemTools::Message("CMake Configure step failed. "
+ "Build files cannot be regenerated correctly.");
+ return ret;
+ }
+ ret = this->Generate();
+ if (ret) {
+ cmSystemTools::Message("CMake Generate step failed. "
+ "Build files cannot be regenerated correctly.");
+ return ret;
+ }
+ std::string message = "Build files have been written to: ";
+ message += this->GetHomeOutputDirectory();
+ this->UpdateProgress(message.c_str(), -1);
+
+ // Restore the previously set directories to their original value.
+ this->SetHomeDirectory(homeOrig);
+ this->SetHomeOutputDirectory(homeOutputOrig);
+ }
+#endif
+
return gen->Build("", dir, projName, target, output, "", config, clean,
false, verbose, 0, cmSystemTools::OUTPUT_PASSTHROUGH,
nativeOptions);
diff --git a/Source/cmake.h b/Source/cmake.h
index cd00c61..0f1891d 100644
--- a/Source/cmake.h
+++ b/Source/cmake.h
@@ -5,17 +5,18 @@
#include <cmConfigure.h>
-#include "cmInstalledFile.h"
-#include "cmListFileCache.h"
-#include "cmStateSnapshot.h"
-
#include <map>
#include <set>
#include <string>
#include <vector>
+#include "cmInstalledFile.h"
+#include "cmListFileCache.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
+
#if defined(CMAKE_BUILD_WITH_CMAKE)
-#include "cm_jsoncpp_value.h"
+#include <cm_jsoncpp_value.h>
#endif
class cmExternalMakefileProjectGeneratorFactory;
@@ -24,6 +25,7 @@ class cmGlobalGenerator;
class cmGlobalGeneratorFactory;
class cmMakefile;
class cmMessenger;
+class cmState;
class cmVariableWatch;
struct cmDocumentationEntry;
@@ -535,12 +537,18 @@ private:
}
#define FOR_EACH_C_FEATURE(F) \
+ F(c_std_90) \
+ F(c_std_99) \
+ F(c_std_11) \
F(c_function_prototypes) \
F(c_restrict) \
F(c_static_assert) \
F(c_variadic_macros)
#define FOR_EACH_CXX_FEATURE(F) \
+ F(cxx_std_98) \
+ F(cxx_std_11) \
+ F(cxx_std_14) \
F(cxx_aggregate_default_initializers) \
F(cxx_alias_templates) \
F(cxx_alignas) \
diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx
index 44af966..b8e227f 100644
--- a/Source/cmakemain.cxx
+++ b/Source/cmakemain.cxx
@@ -12,6 +12,7 @@
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmState.h"
+#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmake.h"
#include "cmcmd.h"
@@ -159,7 +160,9 @@ int main(int ac, char const* const* av)
#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
// Replace streambuf so we can output Unicode to console
cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+ consoleOut.SetUTF8Pipes();
cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
+ consoleErr.SetUTF8Pipes();
#endif
cmsys::Encoding::CommandLineArguments args =
cmsys::Encoding::CommandLineArguments::Main(ac, av);
@@ -406,6 +409,8 @@ static int do_build(int ac, char const* const* av)
}
cmake cm;
+ cmSystemTools::SetMessageCallback(cmakemainMessageCallback, (void*)&cm);
+ cm.SetProgressCallback(cmakemainProgressCallback, (void*)&cm);
return cm.Build(dir, target, config, nativeOptions, clean);
#endif
}
diff --git a/Source/cmakexbuild.cxx b/Source/cmakexbuild.cxx
index 82db012..e166bee 100644
--- a/Source/cmakexbuild.cxx
+++ b/Source/cmakexbuild.cxx
@@ -1,9 +1,14 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmStandardIncludes.h"
-#include "cmSystemTools.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
#include <cmsys/Process.h>
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include "cmSystemTools.h"
// This is a wrapper program for xcodebuild
// it calls xcodebuild, and does two things
diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx
index c008791..f1ce75a 100644
--- a/Source/cmcmd.cxx
+++ b/Source/cmcmd.cxx
@@ -8,6 +8,7 @@
#include "cmMakefile.h"
#include "cmQtAutoGenerators.h"
#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmUtils.hxx"
#include "cmVersion.h"
@@ -326,6 +327,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
iwyu_cmd.insert(iwyu_cmd.end(), orig_cmd.begin() + 1, orig_cmd.end());
// Run the iwyu command line. Capture its stderr and hide its stdout.
+ // Ignore its return code because the tool always returns non-zero.
std::string stdErr;
if (!cmSystemTools::RunSingleCommand(iwyu_cmd, CM_NULLPTR, &stdErr,
&ret, CM_NULLPTR,
@@ -356,14 +358,21 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
// Run the tidy command line. Capture its stdout and hide its stderr.
std::string stdOut;
- if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, CM_NULLPTR,
- &ret, CM_NULLPTR,
+ std::string stdErr;
+ if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
+ CM_NULLPTR,
cmSystemTools::OUTPUT_NONE)) {
- std::cerr << "Error running '" << tidy_cmd[0] << "'\n";
+ std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr
+ << "\n";
return 1;
}
// Output the stdout from clang-tidy to stderr
std::cerr << stdOut;
+ // If clang-tidy exited with an error do the same.
+ if (ret != 0) {
+ std::cerr << stdErr;
+ return ret;
+ }
}
if (!lwyu.empty()) {
// Construct the ldd -r -u (link what you use lwyu) command line
@@ -376,11 +385,15 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
// Run the ldd -u -r command line.
// Capture its stdout and hide its stderr.
+ // Ignore its return code because the tool always returns non-zero
+ // if there are any warnings, but we just want to warn.
std::string stdOut;
- if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, CM_NULLPTR,
- &ret, CM_NULLPTR,
+ std::string stdErr;
+ if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
+ CM_NULLPTR,
cmSystemTools::OUTPUT_NONE)) {
- std::cerr << "Error running '" << lwyu_cmd[0] << "'\n";
+ std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr
+ << "\n";
return 1;
}
diff --git a/Source/ctest.cxx b/Source/ctest.cxx
index 1acd240..1cf75c8 100644
--- a/Source/ctest.cxx
+++ b/Source/ctest.cxx
@@ -116,7 +116,9 @@ int main(int argc, char const* const* argv)
#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
// Replace streambuf so we can output Unicode to console
cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+ consoleOut.SetUTF8Pipes();
cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
+ consoleErr.SetUTF8Pipes();
#endif
cmsys::Encoding::CommandLineArguments encoding_args =
cmsys::Encoding::CommandLineArguments::Main(argc, argv);
diff --git a/Source/kwsys/Base64.c b/Source/kwsys/Base64.c
index 4b8ede2..37c3b8c 100644
--- a/Source/kwsys/Base64.c
+++ b/Source/kwsys/Base64.c
@@ -1,65 +1,43 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Base64.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Base64.h.in"
+#include "Base64.h.in"
#endif
/*--------------------------------------------------------------------------*/
static const unsigned char kwsysBase64EncodeTable[65] =
-"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-"abcdefghijklmnopqrstuvwxyz"
-"0123456789+/";
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "0123456789+/";
/*--------------------------------------------------------------------------*/
-static const unsigned char kwsysBase64DecodeTable[256] =
-{
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0x3E,0xFF,0xFF,0xFF,0x3F,
- 0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,
- 0x3C,0x3D,0xFF,0xFF,0xFF,0x00,0xFF,0xFF,
- 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06,
- 0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,
- 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,
- 0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,
- 0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
- 0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,
- 0x31,0x32,0x33,0xFF,0xFF,0xFF,0xFF,0xFF,
+static const unsigned char kwsysBase64DecodeTable[256] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xFF, 0xFF, 0x3F, 0x34, 0x35, 0x36, 0x37,
+ 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF,
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
+ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
+ 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D,
+ 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/*------------------------------------*/
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
- 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
/*--------------------------------------------------------------------------*/
@@ -76,27 +54,30 @@ static unsigned char kwsysBase64DecodeChar(unsigned char c)
/*--------------------------------------------------------------------------*/
/* Encode 3 bytes into a 4 byte string. */
-void kwsysBase64_Encode3(const unsigned char *src, unsigned char *dest)
+void kwsysBase64_Encode3(const unsigned char* src, unsigned char* dest)
{
dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
- dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30)|((src[1] >> 4) & 0x0F));
- dest[2] = kwsysBase64EncodeChar(((src[1] << 2) & 0x3C)|((src[2] >> 6) & 0x03));
+ dest[1] =
+ kwsysBase64EncodeChar(((src[0] << 4) & 0x30) | ((src[1] >> 4) & 0x0F));
+ dest[2] =
+ kwsysBase64EncodeChar(((src[1] << 2) & 0x3C) | ((src[2] >> 6) & 0x03));
dest[3] = kwsysBase64EncodeChar(src[2] & 0x3F);
}
/*--------------------------------------------------------------------------*/
/* Encode 2 bytes into a 4 byte string. */
-void kwsysBase64_Encode2(const unsigned char *src, unsigned char *dest)
+void kwsysBase64_Encode2(const unsigned char* src, unsigned char* dest)
{
dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
- dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30)|((src[1] >> 4) & 0x0F));
+ dest[1] =
+ kwsysBase64EncodeChar(((src[0] << 4) & 0x30) | ((src[1] >> 4) & 0x0F));
dest[2] = kwsysBase64EncodeChar(((src[1] << 2) & 0x3C));
dest[3] = '=';
}
/*--------------------------------------------------------------------------*/
/* Encode 1 bytes into a 4 byte string. */
-void kwsysBase64_Encode1(const unsigned char *src, unsigned char *dest)
+void kwsysBase64_Encode1(const unsigned char* src, unsigned char* dest)
{
dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30));
@@ -115,54 +96,48 @@ void kwsysBase64_Encode1(const unsigned char *src, unsigned char *dest)
actually knowing how much data to expect (if the input is not a multiple of
3 bytes then the extra padding needed to complete the encode 4 bytes will
stop the decoding anyway). */
-size_t kwsysBase64_Encode(const unsigned char *input,
- size_t length,
- unsigned char *output,
- int mark_end)
+size_t kwsysBase64_Encode(const unsigned char* input, size_t length,
+ unsigned char* output, int mark_end)
{
- const unsigned char *ptr = input;
- const unsigned char *end = input + length;
- unsigned char *optr = output;
+ const unsigned char* ptr = input;
+ const unsigned char* end = input + length;
+ unsigned char* optr = output;
/* Encode complete triplet */
- while ((end - ptr) >= 3)
- {
+ while ((end - ptr) >= 3) {
kwsysBase64_Encode3(ptr, optr);
ptr += 3;
optr += 4;
- }
+ }
/* Encodes a 2-byte ending into 3 bytes and 1 pad byte and writes. */
- if (end - ptr == 2)
- {
+ if (end - ptr == 2) {
kwsysBase64_Encode2(ptr, optr);
optr += 4;
- }
+ }
/* Encodes a 1-byte ending into 2 bytes and 2 pad bytes */
-
- else if (end - ptr == 1)
- {
+
+ else if (end - ptr == 1) {
kwsysBase64_Encode1(ptr, optr);
optr += 4;
- }
+ }
/* Do we need to mark the end */
- else if (mark_end)
- {
+ else if (mark_end) {
optr[0] = optr[1] = optr[2] = optr[3] = '=';
optr += 4;
- }
+ }
return (size_t)(optr - output);
}
/*--------------------------------------------------------------------------*/
/* Decode 4 bytes into a 3 byte string. */
-int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
+int kwsysBase64_Decode3(const unsigned char* src, unsigned char* dest)
{
unsigned char d0, d1, d2, d3;
@@ -170,35 +145,32 @@ int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
d1 = kwsysBase64DecodeChar(src[1]);
d2 = kwsysBase64DecodeChar(src[2]);
d3 = kwsysBase64DecodeChar(src[3]);
-
+
/* Make sure all characters were valid */
- if (d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || d3 == 0xFF)
- {
- return 0;
- }
-
+ if (d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || d3 == 0xFF) {
+ return 0;
+ }
+
/* Decode the 3 bytes */
dest[0] = (unsigned char)(((d0 << 2) & 0xFC) | ((d1 >> 4) & 0x03));
dest[1] = (unsigned char)(((d1 << 4) & 0xF0) | ((d2 >> 2) & 0x0F));
dest[2] = (unsigned char)(((d2 << 6) & 0xC0) | ((d3 >> 0) & 0x3F));
-
+
/* Return the number of bytes actually decoded */
- if (src[2] == '=')
- {
- return 1;
- }
- if (src[3] == '=')
- {
- return 2;
- }
+ if (src[2] == '=') {
+ return 1;
+ }
+ if (src[3] == '=') {
+ return 2;
+ }
return 3;
}
/*--------------------------------------------------------------------------*/
-/* Decode bytes from the input buffer and store the decoded stream
+/* Decode bytes from the input buffer and store the decoded stream
into the output buffer until 'length' bytes have been decoded. Return the
real length of the decoded stream (which should be equal to 'length'). Note
that the output buffer must be allocated by the caller. If
@@ -207,73 +179,57 @@ int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
'length' parameter is ignored. This enables the caller to decode a stream
without actually knowing how much decoded data to expect (of course, the
buffer must be large enough). */
-size_t kwsysBase64_Decode(const unsigned char *input,
- size_t length,
- unsigned char *output,
- size_t max_input_length)
+size_t kwsysBase64_Decode(const unsigned char* input, size_t length,
+ unsigned char* output, size_t max_input_length)
{
- const unsigned char *ptr = input;
- unsigned char *optr = output;
+ const unsigned char* ptr = input;
+ unsigned char* optr = output;
/* Decode complete triplet */
- if (max_input_length)
- {
- const unsigned char *end = input + max_input_length;
- while (ptr < end)
- {
+ if (max_input_length) {
+ const unsigned char* end = input + max_input_length;
+ while (ptr < end) {
int len = kwsysBase64_Decode3(ptr, optr);
optr += len;
- if(len < 3)
- {
+ if (len < 3) {
return (size_t)(optr - output);
- }
- ptr += 4;
}
- }
- else
- {
- unsigned char *oend = output + length;
- while ((oend - optr) >= 3)
- {
+ ptr += 4;
+ }
+ } else {
+ unsigned char* oend = output + length;
+ while ((oend - optr) >= 3) {
int len = kwsysBase64_Decode3(ptr, optr);
optr += len;
- if(len < 3)
- {
+ if (len < 3) {
return (size_t)(optr - output);
- }
- ptr += 4;
}
+ ptr += 4;
+ }
/* Decode the last triplet */
-
- if (oend - optr == 2)
- {
+
+ if (oend - optr == 2) {
unsigned char temp[3];
int len = kwsysBase64_Decode3(ptr, temp);
- if(len >= 2)
- {
+ if (len >= 2) {
optr[0] = temp[0];
optr[1] = temp[1];
optr += 2;
- }
- else if(len > 0)
- {
+ } else if (len > 0) {
optr[0] = temp[0];
optr += 1;
- }
}
- else if (oend - optr == 1)
- {
+ } else if (oend - optr == 1) {
unsigned char temp[3];
int len = kwsysBase64_Decode3(ptr, temp);
- if(len > 0)
- {
+ if (len > 0) {
optr[0] = temp[0];
optr += 1;
- }
}
}
+ }
return (size_t)(optr - output);
}
diff --git a/Source/kwsys/Base64.h.in b/Source/kwsys/Base64.h.in
index 36ed3cc..3536757 100644
--- a/Source/kwsys/Base64.h.in
+++ b/Source/kwsys/Base64.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Base64_h
#define @KWSYS_NAMESPACE@_Base64_h
@@ -21,41 +12,40 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysBase64 kwsys_ns(Base64)
-# define kwsysBase64_Decode kwsys_ns(Base64_Decode)
-# define kwsysBase64_Decode3 kwsys_ns(Base64_Decode3)
-# define kwsysBase64_Encode kwsys_ns(Base64_Encode)
-# define kwsysBase64_Encode1 kwsys_ns(Base64_Encode1)
-# define kwsysBase64_Encode2 kwsys_ns(Base64_Encode2)
-# define kwsysBase64_Encode3 kwsys_ns(Base64_Encode3)
+#define kwsysBase64 kwsys_ns(Base64)
+#define kwsysBase64_Decode kwsys_ns(Base64_Decode)
+#define kwsysBase64_Decode3 kwsys_ns(Base64_Decode3)
+#define kwsysBase64_Encode kwsys_ns(Base64_Encode)
+#define kwsysBase64_Encode1 kwsys_ns(Base64_Encode1)
+#define kwsysBase64_Encode2 kwsys_ns(Base64_Encode2)
+#define kwsysBase64_Encode3 kwsys_ns(Base64_Encode3)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
/**
* Encode 3 bytes into a 4 byte string.
*/
-kwsysEXPORT void kwsysBase64_Encode3(const unsigned char *src,
- unsigned char *dest);
+kwsysEXPORT void kwsysBase64_Encode3(const unsigned char* src,
+ unsigned char* dest);
/**
* Encode 2 bytes into a 4 byte string.
*/
-kwsysEXPORT void kwsysBase64_Encode2(const unsigned char *src,
- unsigned char *dest);
+kwsysEXPORT void kwsysBase64_Encode2(const unsigned char* src,
+ unsigned char* dest);
/**
* Encode 1 bytes into a 4 byte string.
*/
-kwsysEXPORT void kwsysBase64_Encode1(const unsigned char *src,
- unsigned char *dest);
+kwsysEXPORT void kwsysBase64_Encode1(const unsigned char* src,
+ unsigned char* dest);
/**
* Encode 'length' bytes from the input buffer and store the encoded
@@ -70,17 +60,16 @@ kwsysEXPORT void kwsysBase64_Encode1(const unsigned char *src,
* the extra padding needed to complete the encode 4 bytes will stop
* the decoding anyway).
*/
-kwsysEXPORT size_t kwsysBase64_Encode(const unsigned char *input,
- size_t length,
- unsigned char *output,
+kwsysEXPORT size_t kwsysBase64_Encode(const unsigned char* input,
+ size_t length, unsigned char* output,
int mark_end);
/**
* Decode 4 bytes into a 3 byte string. Returns the number of bytes
* actually decoded.
*/
-kwsysEXPORT int kwsysBase64_Decode3(const unsigned char *src,
- unsigned char *dest);
+kwsysEXPORT int kwsysBase64_Decode3(const unsigned char* src,
+ unsigned char* dest);
/**
* Decode bytes from the input buffer and store the decoded stream
@@ -94,9 +83,8 @@ kwsysEXPORT int kwsysBase64_Decode3(const unsigned char *src,
* much decoded data to expect (of course, the buffer must be large
* enough).
*/
-kwsysEXPORT size_t kwsysBase64_Decode(const unsigned char *input,
- size_t length,
- unsigned char *output,
+kwsysEXPORT size_t kwsysBase64_Decode(const unsigned char* input,
+ size_t length, unsigned char* output,
size_t max_input_length);
#if defined(__cplusplus)
@@ -106,17 +94,17 @@ kwsysEXPORT size_t kwsysBase64_Decode(const unsigned char *input,
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysBase64
-# undef kwsysBase64_Decode
-# undef kwsysBase64_Decode3
-# undef kwsysBase64_Encode
-# undef kwsysBase64_Encode1
-# undef kwsysBase64_Encode2
-# undef kwsysBase64_Encode3
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysBase64
+#undef kwsysBase64_Decode
+#undef kwsysBase64_Decode3
+#undef kwsysBase64_Encode
+#undef kwsysBase64_Encode1
+#undef kwsysBase64_Encode2
+#undef kwsysBase64_Encode3
+#endif
#endif
#endif
diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt
index c4fe5e8..b8a9a6b 100644
--- a/Source/kwsys/CMakeLists.txt
+++ b/Source/kwsys/CMakeLists.txt
@@ -1,14 +1,5 @@
-#=============================================================================
-# KWSys - Kitware System Library
-# Copyright 2000-2011 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
# The Kitware System Library is intended to be included in other
# projects. It is completely configurable in that the library's
@@ -76,12 +67,15 @@
# written.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.3 FATAL_ERROR)
-IF(POLICY CMP0025)
- CMAKE_POLICY(SET CMP0025 NEW)
-ENDIF()
-IF(POLICY CMP0056)
- CMAKE_POLICY(SET CMP0056 NEW)
-ENDIF()
+FOREACH(p
+ CMP0025 # CMake 3.0, Compiler id for Apple Clang is now AppleClang.
+ CMP0056 # CMake 3.2, Honor link flags in try_compile() source-file signature.
+ CMP0063 # CMake 3.3, Honor visibility properties for all target types.
+ )
+ IF(POLICY ${p})
+ CMAKE_POLICY(SET ${p} NEW)
+ ENDIF()
+ENDFOREACH()
SET(CMAKE_LEGACY_CYGWIN_WIN32 0)
#-----------------------------------------------------------------------------
diff --git a/Source/kwsys/CONTRIBUTING.rst b/Source/kwsys/CONTRIBUTING.rst
index 960eea4..47dffee 100644
--- a/Source/kwsys/CONTRIBUTING.rst
+++ b/Source/kwsys/CONTRIBUTING.rst
@@ -24,6 +24,19 @@ KWSys has no independent issue tracker. After encountering an issue
Otherwise please report the issue to the tracker for the project that
hosts the copy of KWSys in which the problem was found.
+Code Style
+==========
+
+We use `clang-format`_ to define our style for C++ code in the KWSys source
+tree. See the `.clang-format`_ configuration file for our style settings.
+Use ``clang-format`` version 3.8 or higher to format source files.
+See also the `clang-format.bash`_ script.
+
+.. _`clang-format`: http://clang.llvm.org/docs/ClangFormat.html
+.. _`.clang-format`: .clang-format
+.. _`clang-format.bash`: clang-format.bash
+
+
License
=======
diff --git a/Source/kwsys/CTestConfig.cmake b/Source/kwsys/CTestConfig.cmake
index d977b47..33ea84c 100644
--- a/Source/kwsys/CTestConfig.cmake
+++ b/Source/kwsys/CTestConfig.cmake
@@ -1,14 +1,6 @@
-#=============================================================================
-# KWSys - Kitware System Library
-# Copyright 2000-2012 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
+
set(CTEST_PROJECT_NAME "KWSys")
set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
set(CTEST_DROP_METHOD "http")
diff --git a/Source/kwsys/CommandLineArguments.cxx b/Source/kwsys/CommandLineArguments.cxx
index f713294..226263c 100644
--- a/Source/kwsys/CommandLineArguments.cxx
+++ b/Source/kwsys/CommandLineArguments.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(CommandLineArguments.hxx)
@@ -18,38 +9,37 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "CommandLineArguments.hxx.in"
-# include "Configure.hxx.in"
-# include "String.hxx.in"
+#include "CommandLineArguments.hxx.in"
+#include "Configure.hxx.in"
+#include "String.hxx.in"
#endif
-#include <vector>
+#include <iostream>
#include <map>
#include <set>
#include <sstream>
-#include <iostream>
+#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
-# pragma warning (disable: 4786)
+#pragma warning(disable : 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1375 /* base class destructor not virtual */
+#pragma set woff 1375 /* base class destructor not virtual */
#endif
#if 0
-# define CommandLineArguments_DEBUG(x) \
+#define CommandLineArguments_DEBUG(x) \
std::cout << __LINE__ << " CLA: " << x << std::endl
#else
-# define CommandLineArguments_DEBUG(x)
+#define CommandLineArguments_DEBUG(x)
#endif
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
//============================================================================
@@ -63,24 +53,27 @@ struct CommandLineArgumentsCallbackStructure
int VariableType;
const char* Help;
};
-
-class CommandLineArgumentsVectorOfStrings :
- public std::vector<kwsys::String> {};
-class CommandLineArgumentsSetOfStrings :
- public std::set<kwsys::String> {};
-class CommandLineArgumentsMapOfStrucs :
- public std::map<kwsys::String,
- CommandLineArgumentsCallbackStructure> {};
+
+class CommandLineArgumentsVectorOfStrings : public std::vector<kwsys::String>
+{
+};
+class CommandLineArgumentsSetOfStrings : public std::set<kwsys::String>
+{
+};
+class CommandLineArgumentsMapOfStrucs
+ : public std::map<kwsys::String, CommandLineArgumentsCallbackStructure>
+{
+};
class CommandLineArgumentsInternal
{
public:
CommandLineArgumentsInternal()
- {
+ {
this->UnknownArgumentCallback = 0;
this->ClientData = 0;
this->LastArgument = 0;
- }
+ }
typedef CommandLineArgumentsVectorOfStrings VectorOfStrings;
typedef CommandLineArgumentsMapOfStrucs CallbacksMap;
@@ -92,7 +85,7 @@ public:
CallbacksMap Callbacks;
CommandLineArguments::ErrorCallbackType UnknownArgumentCallback;
- void* ClientData;
+ void* ClientData;
VectorOfStrings::size_type LastArgument;
@@ -123,10 +116,9 @@ void CommandLineArguments::Initialize(int argc, const char* const argv[])
this->Initialize();
this->Internals->Argv0 = argv[0];
- for ( cc = 1; cc < argc; cc ++ )
- {
+ for (cc = 1; cc < argc; cc++) {
this->ProcessArgument(argv[cc]);
- }
+ }
}
//----------------------------------------------------------------------------
@@ -150,32 +142,25 @@ void CommandLineArguments::ProcessArgument(const char* arg)
//----------------------------------------------------------------------------
bool CommandLineArguments::GetMatchedArguments(
- std::vector<std::string>* matches,
- const std::string& arg)
+ std::vector<std::string>* matches, const std::string& arg)
{
matches->clear();
CommandLineArguments::Internal::CallbacksMap::iterator it;
// Does the argument match to any we know about?
- for ( it = this->Internals->Callbacks.begin();
- it != this->Internals->Callbacks.end();
- it ++ )
- {
+ for (it = this->Internals->Callbacks.begin();
+ it != this->Internals->Callbacks.end(); it++) {
const CommandLineArguments::Internal::String& parg = it->first;
- CommandLineArgumentsCallbackStructure *cs = &it->second;
+ CommandLineArgumentsCallbackStructure* cs = &it->second;
if (cs->ArgumentType == CommandLineArguments::NO_ARGUMENT ||
- cs->ArgumentType == CommandLineArguments::SPACE_ARGUMENT)
- {
- if ( arg == parg )
- {
+ cs->ArgumentType == CommandLineArguments::SPACE_ARGUMENT) {
+ if (arg == parg) {
matches->push_back(parg);
- }
}
- else if ( arg.find( parg ) == 0 )
- {
+ } else if (arg.find(parg) == 0) {
matches->push_back(parg);
- }
}
+ }
return !matches->empty();
}
@@ -184,163 +169,143 @@ int CommandLineArguments::Parse()
{
std::vector<std::string>::size_type cc;
std::vector<std::string> matches;
- if ( this->StoreUnusedArgumentsFlag )
- {
+ if (this->StoreUnusedArgumentsFlag) {
this->Internals->UnusedArguments.clear();
- }
- for ( cc = 0; cc < this->Internals->Argv.size(); cc ++ )
- {
+ }
+ for (cc = 0; cc < this->Internals->Argv.size(); cc++) {
const std::string& arg = this->Internals->Argv[cc];
CommandLineArguments_DEBUG("Process argument: " << arg);
this->Internals->LastArgument = cc;
- if ( this->GetMatchedArguments(&matches, arg) )
- {
+ if (this->GetMatchedArguments(&matches, arg)) {
// Ok, we found one or more arguments that match what user specified.
// Let's find the longest one.
CommandLineArguments::Internal::VectorOfStrings::size_type kk;
CommandLineArguments::Internal::VectorOfStrings::size_type maxidx = 0;
CommandLineArguments::Internal::String::size_type maxlen = 0;
- for ( kk = 0; kk < matches.size(); kk ++ )
- {
- if ( matches[kk].size() > maxlen )
- {
+ for (kk = 0; kk < matches.size(); kk++) {
+ if (matches[kk].size() > maxlen) {
maxlen = matches[kk].size();
maxidx = kk;
- }
}
+ }
// So, the longest one is probably the right one. Now see if it has any
// additional value
- CommandLineArgumentsCallbackStructure *cs
- = &this->Internals->Callbacks[matches[maxidx]];
+ CommandLineArgumentsCallbackStructure* cs =
+ &this->Internals->Callbacks[matches[maxidx]];
const std::string& sarg = matches[maxidx];
- if ( cs->Argument != sarg )
- {
+ if (cs->Argument != sarg) {
abort();
- }
- switch ( cs->ArgumentType )
- {
- case NO_ARGUMENT:
- // No value
- if ( !this->PopulateVariable(cs, 0) )
- {
- return 0;
+ }
+ switch (cs->ArgumentType) {
+ case NO_ARGUMENT:
+ // No value
+ if (!this->PopulateVariable(cs, 0)) {
+ return 0;
}
- break;
- case SPACE_ARGUMENT:
- if ( cc == this->Internals->Argv.size()-1 )
- {
- this->Internals->LastArgument --;
- return 0;
+ break;
+ case SPACE_ARGUMENT:
+ if (cc == this->Internals->Argv.size() - 1) {
+ this->Internals->LastArgument--;
+ return 0;
}
- CommandLineArguments_DEBUG("This is a space argument: " << arg
- << " value: " << this->Internals->Argv[cc+1]);
- // Value is the next argument
- if ( !this->PopulateVariable(cs, this->Internals->Argv[cc+1].c_str()) )
- {
- return 0;
+ CommandLineArguments_DEBUG("This is a space argument: "
+ << arg << " value: "
+ << this->Internals->Argv[cc + 1]);
+ // Value is the next argument
+ if (!this->PopulateVariable(cs,
+ this->Internals->Argv[cc + 1].c_str())) {
+ return 0;
}
- cc ++;
- break;
- case EQUAL_ARGUMENT:
- if ( arg.size() == sarg.size() || arg.at(sarg.size()) != '=' )
- {
- this->Internals->LastArgument --;
- return 0;
+ cc++;
+ break;
+ case EQUAL_ARGUMENT:
+ if (arg.size() == sarg.size() || arg.at(sarg.size()) != '=') {
+ this->Internals->LastArgument--;
+ return 0;
}
- // Value is everythng followed the '=' sign
- if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size() + 1) )
- {
- return 0;
+ // Value is everythng followed the '=' sign
+ if (!this->PopulateVariable(cs, arg.c_str() + sarg.size() + 1)) {
+ return 0;
}
- break;
- case CONCAT_ARGUMENT:
- // Value is whatever follows the argument
- if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size()) )
- {
- return 0;
+ break;
+ case CONCAT_ARGUMENT:
+ // Value is whatever follows the argument
+ if (!this->PopulateVariable(cs, arg.c_str() + sarg.size())) {
+ return 0;
}
- break;
- case MULTI_ARGUMENT:
- // Suck in all the rest of the arguments
- CommandLineArguments_DEBUG("This is a multi argument: " << arg);
- for (cc++; cc < this->Internals->Argv.size(); ++ cc )
- {
- const std::string& marg = this->Internals->Argv[cc];
- CommandLineArguments_DEBUG(" check multi argument value: " << marg);
- if ( this->GetMatchedArguments(&matches, marg) )
- {
- CommandLineArguments_DEBUG("End of multi argument " << arg << " with value: " << marg);
- break;
+ break;
+ case MULTI_ARGUMENT:
+ // Suck in all the rest of the arguments
+ CommandLineArguments_DEBUG("This is a multi argument: " << arg);
+ for (cc++; cc < this->Internals->Argv.size(); ++cc) {
+ const std::string& marg = this->Internals->Argv[cc];
+ CommandLineArguments_DEBUG(
+ " check multi argument value: " << marg);
+ if (this->GetMatchedArguments(&matches, marg)) {
+ CommandLineArguments_DEBUG("End of multi argument "
+ << arg << " with value: " << marg);
+ break;
}
- CommandLineArguments_DEBUG(" populate multi argument value: " << marg);
- if ( !this->PopulateVariable(cs, marg.c_str()) )
- {
- return 0;
+ CommandLineArguments_DEBUG(
+ " populate multi argument value: " << marg);
+ if (!this->PopulateVariable(cs, marg.c_str())) {
+ return 0;
}
}
- if ( cc != this->Internals->Argv.size() )
- {
- CommandLineArguments_DEBUG("Again End of multi argument " << arg);
- cc--;
- continue;
+ if (cc != this->Internals->Argv.size()) {
+ CommandLineArguments_DEBUG("Again End of multi argument " << arg);
+ cc--;
+ continue;
}
- break;
- default:
- std::cerr << "Got unknown argument type: \"" << cs->ArgumentType << "\"" << std::endl;
- this->Internals->LastArgument --;
- return 0;
- }
+ break;
+ default:
+ std::cerr << "Got unknown argument type: \"" << cs->ArgumentType
+ << "\"" << std::endl;
+ this->Internals->LastArgument--;
+ return 0;
}
- else
- {
+ } else {
// Handle unknown arguments
- if ( this->Internals->UnknownArgumentCallback )
- {
- if ( !this->Internals->UnknownArgumentCallback(arg.c_str(),
- this->Internals->ClientData) )
- {
- this->Internals->LastArgument --;
+ if (this->Internals->UnknownArgumentCallback) {
+ if (!this->Internals->UnknownArgumentCallback(
+ arg.c_str(), this->Internals->ClientData)) {
+ this->Internals->LastArgument--;
return 0;
- }
- return 1;
}
- else if ( this->StoreUnusedArgumentsFlag )
- {
+ return 1;
+ } else if (this->StoreUnusedArgumentsFlag) {
CommandLineArguments_DEBUG("Store unused argument " << arg);
this->Internals->UnusedArguments.push_back(arg);
- }
- else
- {
+ } else {
std::cerr << "Got unknown argument: \"" << arg << "\"" << std::endl;
- this->Internals->LastArgument --;
+ this->Internals->LastArgument--;
return 0;
- }
}
}
+ }
return 1;
}
//----------------------------------------------------------------------------
void CommandLineArguments::GetRemainingArguments(int* argc, char*** argv)
{
- CommandLineArguments::Internal::VectorOfStrings::size_type size
- = this->Internals->Argv.size() - this->Internals->LastArgument + 1;
+ CommandLineArguments::Internal::VectorOfStrings::size_type size =
+ this->Internals->Argv.size() - this->Internals->LastArgument + 1;
CommandLineArguments::Internal::VectorOfStrings::size_type cc;
// Copy Argv0 as the first argument
- char** args = new char*[ size ];
- args[0] = new char[ this->Internals->Argv0.size() + 1 ];
+ char** args = new char*[size];
+ args[0] = new char[this->Internals->Argv0.size() + 1];
strcpy(args[0], this->Internals->Argv0.c_str());
int cnt = 1;
// Copy everything after the LastArgument, since that was not parsed.
- for ( cc = this->Internals->LastArgument+1;
- cc < this->Internals->Argv.size(); cc ++ )
- {
- args[cnt] = new char[ this->Internals->Argv[cc].size() + 1];
+ for (cc = this->Internals->LastArgument + 1;
+ cc < this->Internals->Argv.size(); cc++) {
+ args[cnt] = new char[this->Internals->Argv[cc].size() + 1];
strcpy(args[cnt], this->Internals->Argv[cc].c_str());
- cnt ++;
- }
+ cnt++;
+ }
*argc = cnt;
*argv = args;
}
@@ -348,25 +313,23 @@ void CommandLineArguments::GetRemainingArguments(int* argc, char*** argv)
//----------------------------------------------------------------------------
void CommandLineArguments::GetUnusedArguments(int* argc, char*** argv)
{
- CommandLineArguments::Internal::VectorOfStrings::size_type size
- = this->Internals->UnusedArguments.size() + 1;
+ CommandLineArguments::Internal::VectorOfStrings::size_type size =
+ this->Internals->UnusedArguments.size() + 1;
CommandLineArguments::Internal::VectorOfStrings::size_type cc;
// Copy Argv0 as the first argument
- char** args = new char*[ size ];
- args[0] = new char[ this->Internals->Argv0.size() + 1 ];
+ char** args = new char*[size];
+ args[0] = new char[this->Internals->Argv0.size() + 1];
strcpy(args[0], this->Internals->Argv0.c_str());
int cnt = 1;
// Copy everything after the LastArgument, since that was not parsed.
- for ( cc = 0;
- cc < this->Internals->UnusedArguments.size(); cc ++ )
- {
- kwsys::String &str = this->Internals->UnusedArguments[cc];
- args[cnt] = new char[ str.size() + 1];
+ for (cc = 0; cc < this->Internals->UnusedArguments.size(); cc++) {
+ kwsys::String& str = this->Internals->UnusedArguments[cc];
+ args[cnt] = new char[str.size() + 1];
strcpy(args[cnt], str.c_str());
- cnt ++;
- }
+ cnt++;
+ }
*argc = cnt;
*argv = args;
}
@@ -375,84 +338,95 @@ void CommandLineArguments::GetUnusedArguments(int* argc, char*** argv)
void CommandLineArguments::DeleteRemainingArguments(int argc, char*** argv)
{
int cc;
- for ( cc = 0; cc < argc; ++ cc )
- {
- delete [] (*argv)[cc];
- }
- delete [] *argv;
+ for (cc = 0; cc < argc; ++cc) {
+ delete[](*argv)[cc];
+ }
+ delete[] * argv;
}
//----------------------------------------------------------------------------
-void CommandLineArguments::AddCallback(const char* argument, ArgumentTypeEnum type,
- CallbackType callback, void* call_data, const char* help)
+void CommandLineArguments::AddCallback(const char* argument,
+ ArgumentTypeEnum type,
+ CallbackType callback, void* call_data,
+ const char* help)
{
CommandLineArgumentsCallbackStructure s;
- s.Argument = argument;
+ s.Argument = argument;
s.ArgumentType = type;
- s.Callback = callback;
- s.CallData = call_data;
+ s.Callback = callback;
+ s.CallData = call_data;
s.VariableType = CommandLineArguments::NO_VARIABLE_TYPE;
- s.Variable = 0;
- s.Help = help;
+ s.Variable = 0;
+ s.Help = help;
this->Internals->Callbacks[argument] = s;
this->GenerateHelp();
}
//----------------------------------------------------------------------------
-void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type,
- VariableTypeEnum vtype, void* variable, const char* help)
+void CommandLineArguments::AddArgument(const char* argument,
+ ArgumentTypeEnum type,
+ VariableTypeEnum vtype, void* variable,
+ const char* help)
{
CommandLineArgumentsCallbackStructure s;
- s.Argument = argument;
+ s.Argument = argument;
s.ArgumentType = type;
- s.Callback = 0;
- s.CallData = 0;
+ s.Callback = 0;
+ s.CallData = 0;
s.VariableType = vtype;
- s.Variable = variable;
- s.Help = help;
+ s.Variable = variable;
+ s.Help = help;
this->Internals->Callbacks[argument] = s;
this->GenerateHelp();
}
//----------------------------------------------------------------------------
-#define CommandLineArgumentsAddArgumentMacro(type, ctype) \
- void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type, \
- ctype* variable, const char* help) \
- { \
- this->AddArgument(argument, type, CommandLineArguments::type##_TYPE, variable, help); \
+#define CommandLineArgumentsAddArgumentMacro(type, ctype) \
+ void CommandLineArguments::AddArgument(const char* argument, \
+ ArgumentTypeEnum type, \
+ ctype* variable, const char* help) \
+ { \
+ this->AddArgument(argument, type, CommandLineArguments::type##_TYPE, \
+ variable, help); \
}
-CommandLineArgumentsAddArgumentMacro(BOOL, bool)
-CommandLineArgumentsAddArgumentMacro(INT, int)
-CommandLineArgumentsAddArgumentMacro(DOUBLE, double)
-CommandLineArgumentsAddArgumentMacro(STRING, char*)
-CommandLineArgumentsAddArgumentMacro(STL_STRING, std::string)
-
-CommandLineArgumentsAddArgumentMacro(VECTOR_BOOL, std::vector<bool>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_INT, std::vector<int>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_DOUBLE, std::vector<double>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_STRING, std::vector<char*>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_STL_STRING, std::vector<std::string>)
-
-//----------------------------------------------------------------------------
-#define CommandLineArgumentsAddBooleanArgumentMacro(type, ctype) \
- void CommandLineArguments::AddBooleanArgument(const char* argument, \
- ctype* variable, const char* help) \
- { \
- this->AddArgument(argument, CommandLineArguments::NO_ARGUMENT, \
- CommandLineArguments::type##_TYPE, variable, help); \
+CommandLineArgumentsAddArgumentMacro(BOOL, bool)
+ CommandLineArgumentsAddArgumentMacro(INT, int)
+ CommandLineArgumentsAddArgumentMacro(DOUBLE, double)
+ CommandLineArgumentsAddArgumentMacro(STRING, char*)
+ CommandLineArgumentsAddArgumentMacro(STL_STRING, std::string)
+
+ CommandLineArgumentsAddArgumentMacro(VECTOR_BOOL, std::vector<bool>)
+ CommandLineArgumentsAddArgumentMacro(VECTOR_INT, std::vector<int>)
+ CommandLineArgumentsAddArgumentMacro(VECTOR_DOUBLE,
+ std::vector<double>)
+ CommandLineArgumentsAddArgumentMacro(VECTOR_STRING,
+ std::vector<char*>)
+ CommandLineArgumentsAddArgumentMacro(
+ VECTOR_STL_STRING, std::vector<std::string>)
+
+//----------------------------------------------------------------------------
+#define CommandLineArgumentsAddBooleanArgumentMacro(type, ctype) \
+ void CommandLineArguments::AddBooleanArgument( \
+ const char* argument, ctype* variable, const char* help) \
+ { \
+ this->AddArgument(argument, CommandLineArguments::NO_ARGUMENT, \
+ CommandLineArguments::type##_TYPE, variable, help); \
}
-CommandLineArgumentsAddBooleanArgumentMacro(BOOL, bool)
-CommandLineArgumentsAddBooleanArgumentMacro(INT, int)
-CommandLineArgumentsAddBooleanArgumentMacro(DOUBLE, double)
-CommandLineArgumentsAddBooleanArgumentMacro(STRING, char*)
-CommandLineArgumentsAddBooleanArgumentMacro(STL_STRING, std::string)
+ CommandLineArgumentsAddBooleanArgumentMacro(BOOL, bool)
+ CommandLineArgumentsAddBooleanArgumentMacro(INT, int)
+ CommandLineArgumentsAddBooleanArgumentMacro(DOUBLE,
+ double)
+ CommandLineArgumentsAddBooleanArgumentMacro(STRING,
+ char*)
+ CommandLineArgumentsAddBooleanArgumentMacro(
+ STL_STRING, std::string)
-//----------------------------------------------------------------------------
-void CommandLineArguments::SetClientData(void* client_data)
+ //----------------------------------------------------------------------------
+ void CommandLineArguments::SetClientData(void* client_data)
{
this->Internals->ClientData = client_data;
}
@@ -467,36 +441,32 @@ void CommandLineArguments::SetUnknownArgumentCallback(
//----------------------------------------------------------------------------
const char* CommandLineArguments::GetHelp(const char* arg)
{
- CommandLineArguments::Internal::CallbacksMap::iterator it
- = this->Internals->Callbacks.find(arg);
- if ( it == this->Internals->Callbacks.end() )
- {
+ CommandLineArguments::Internal::CallbacksMap::iterator it =
+ this->Internals->Callbacks.find(arg);
+ if (it == this->Internals->Callbacks.end()) {
return 0;
- }
+ }
// Since several arguments may point to the same argument, find the one this
// 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);
- if ( hit == this->Internals->Callbacks.end() )
- {
+ CommandLineArgumentsCallbackStructure* cs = &(it->second);
+ for (;;) {
+ CommandLineArguments::Internal::CallbacksMap::iterator hit =
+ this->Internals->Callbacks.find(cs->Help);
+ if (hit == this->Internals->Callbacks.end()) {
break;
- }
- cs = &(hit->second);
}
+ cs = &(hit->second);
+ }
return cs->Help;
}
//----------------------------------------------------------------------------
void CommandLineArguments::SetLineLength(unsigned int ll)
{
- if ( ll < 9 || ll > 1000 )
- {
+ if (ll < 9 || ll > 1000) {
return;
- }
+ }
this->LineLength = ll;
this->GenerateHelp();
}
@@ -517,76 +487,68 @@ unsigned int CommandLineArguments::GetLastArgument()
void CommandLineArguments::GenerateHelp()
{
std::ostringstream str;
-
+
// 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;
+ CommandLineArguments::Internal::SetOfStrings>
+ MapArgs;
MapArgs mp;
MapArgs::iterator mpit, smpit;
- for ( it = this->Internals->Callbacks.begin();
- it != this->Internals->Callbacks.end();
- it ++ )
- {
- CommandLineArgumentsCallbackStructure *cs = &(it->second);
+ for (it = this->Internals->Callbacks.begin();
+ it != this->Internals->Callbacks.end(); it++) {
+ CommandLineArgumentsCallbackStructure* cs = &(it->second);
mpit = mp.find(cs->Help);
- if ( mpit != mp.end() )
- {
+ if (mpit != mp.end()) {
mpit->second.insert(it->first);
mp[it->first].insert(it->first);
- }
- else
- {
+ } else {
mp[it->first].insert(it->first);
- }
}
- for ( it = this->Internals->Callbacks.begin();
- it != this->Internals->Callbacks.end();
- it ++ )
- {
- CommandLineArgumentsCallbackStructure *cs = &(it->second);
+ }
+ for (it = this->Internals->Callbacks.begin();
+ it != this->Internals->Callbacks.end(); it++) {
+ CommandLineArgumentsCallbackStructure* cs = &(it->second);
mpit = mp.find(cs->Help);
- if ( mpit != mp.end() )
- {
+ if (mpit != mp.end()) {
mpit->second.insert(it->first);
smpit = mp.find(it->first);
CommandLineArguments::Internal::SetOfStrings::iterator sit;
- for ( sit = smpit->second.begin(); sit != smpit->second.end(); sit++ )
- {
+ for (sit = smpit->second.begin(); sit != smpit->second.end(); sit++) {
mpit->second.insert(*sit);
- }
- mp.erase(smpit);
}
- else
- {
+ mp.erase(smpit);
+ } else {
mp[it->first].insert(it->first);
- }
}
-
+ }
+
// Find the length of the longest string
CommandLineArguments::Internal::String::size_type maxlen = 0;
- for ( mpit = mp.begin();
- mpit != mp.end();
- mpit ++ )
- {
+ for (mpit = mp.begin(); mpit != mp.end(); mpit++) {
CommandLineArguments::Internal::SetOfStrings::iterator sit;
- for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ )
- {
+ for (sit = mpit->second.begin(); sit != mpit->second.end(); sit++) {
CommandLineArguments::Internal::String::size_type clen = sit->size();
- switch ( this->Internals->Callbacks[*sit].ArgumentType )
- {
- case CommandLineArguments::NO_ARGUMENT: clen += 0; break;
- case CommandLineArguments::CONCAT_ARGUMENT: clen += 3; break;
- case CommandLineArguments::SPACE_ARGUMENT: clen += 4; break;
- case CommandLineArguments::EQUAL_ARGUMENT: clen += 4; break;
- }
- if ( clen > maxlen )
- {
+ switch (this->Internals->Callbacks[*sit].ArgumentType) {
+ case CommandLineArguments::NO_ARGUMENT:
+ clen += 0;
+ break;
+ case CommandLineArguments::CONCAT_ARGUMENT:
+ clen += 3;
+ break;
+ case CommandLineArguments::SPACE_ARGUMENT:
+ clen += 4;
+ break;
+ case CommandLineArguments::EQUAL_ARGUMENT:
+ clen += 4;
+ break;
+ }
+ if (clen > maxlen) {
maxlen = clen;
- }
}
}
+ }
// Create format for that string
char format[80];
@@ -595,74 +557,69 @@ void CommandLineArguments::GenerateHelp()
maxlen += 4; // For the space before and after the option
// Print help for each option
- for ( mpit = mp.begin();
- mpit != mp.end();
- mpit ++ )
- {
+ for (mpit = mp.begin(); mpit != mp.end(); mpit++) {
CommandLineArguments::Internal::SetOfStrings::iterator sit;
- for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ )
- {
+ for (sit = mpit->second.begin(); sit != mpit->second.end(); sit++) {
str << std::endl;
char argument[100];
sprintf(argument, "%s", sit->c_str());
- switch ( this->Internals->Callbacks[*sit].ArgumentType )
- {
- case CommandLineArguments::NO_ARGUMENT: break;
- case CommandLineArguments::CONCAT_ARGUMENT: strcat(argument, "opt"); break;
- case CommandLineArguments::SPACE_ARGUMENT: strcat(argument, " opt"); break;
- case CommandLineArguments::EQUAL_ARGUMENT: strcat(argument, "=opt"); break;
- case CommandLineArguments::MULTI_ARGUMENT: strcat(argument, " opt opt ..."); break;
- }
+ switch (this->Internals->Callbacks[*sit].ArgumentType) {
+ case CommandLineArguments::NO_ARGUMENT:
+ break;
+ case CommandLineArguments::CONCAT_ARGUMENT:
+ strcat(argument, "opt");
+ break;
+ case CommandLineArguments::SPACE_ARGUMENT:
+ strcat(argument, " opt");
+ break;
+ case CommandLineArguments::EQUAL_ARGUMENT:
+ strcat(argument, "=opt");
+ break;
+ case CommandLineArguments::MULTI_ARGUMENT:
+ strcat(argument, " opt opt ...");
+ break;
+ }
char buffer[80];
sprintf(buffer, format, argument);
str << buffer;
- }
+ }
const char* ptr = this->Internals->Callbacks[mpit->first].Help;
size_t len = strlen(ptr);
int cnt = 0;
- while ( len > 0)
- {
+ while (len > 0) {
// If argument with help is longer than line length, split it on previous
// space (or tab) and continue on the next line
CommandLineArguments::Internal::String::size_type cc;
- for ( cc = 0; ptr[cc]; cc ++ )
- {
- if ( *ptr == ' ' || *ptr == '\t' )
- {
- ptr ++;
- len --;
- }
+ for (cc = 0; ptr[cc]; cc++) {
+ if (*ptr == ' ' || *ptr == '\t') {
+ ptr++;
+ len--;
}
- if ( cnt > 0 )
- {
- for ( cc = 0; cc < maxlen; cc ++ )
- {
+ }
+ if (cnt > 0) {
+ for (cc = 0; cc < maxlen; cc++) {
str << " ";
- }
}
+ }
CommandLineArguments::Internal::String::size_type skip = len;
- if ( skip > this->LineLength - maxlen )
- {
+ if (skip > this->LineLength - maxlen) {
skip = this->LineLength - maxlen;
- for ( cc = skip-1; cc > 0; cc -- )
- {
- if ( ptr[cc] == ' ' || ptr[cc] == '\t' )
- {
+ for (cc = skip - 1; cc > 0; cc--) {
+ if (ptr[cc] == ' ' || ptr[cc] == '\t') {
break;
- }
}
- if ( cc != 0 )
- {
+ }
+ if (cc != 0) {
skip = cc;
- }
}
+ }
str.write(ptr, static_cast<std::streamsize>(skip));
str << std::endl;
ptr += skip;
len -= skip;
- cnt ++;
- }
+ cnt++;
}
+ }
/*
// This can help debugging help string
str << endl;
@@ -677,181 +634,176 @@ void CommandLineArguments::GenerateHelp()
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- bool* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(bool* variable,
+ const std::string& value)
{
- if ( value == "1" || value == "ON" || value == "on" || value == "On" ||
- value == "TRUE" || value == "true" || value == "True" ||
- value == "yes" || value == "Yes" || value == "YES" )
- {
+ if (value == "1" || value == "ON" || value == "on" || value == "On" ||
+ value == "TRUE" || value == "true" || value == "True" ||
+ value == "yes" || value == "Yes" || value == "YES") {
*variable = true;
- }
- else
- {
+ } else {
*variable = false;
- }
+ }
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- int* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(int* variable,
+ const std::string& value)
{
char* res = 0;
*variable = static_cast<int>(strtol(value.c_str(), &res, 10));
- //if ( res && *res )
+ // if ( res && *res )
// {
// Can handle non-int
// }
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- double* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(double* variable,
+ const std::string& value)
{
char* res = 0;
*variable = strtod(value.c_str(), &res);
- //if ( res && *res )
+ // if ( res && *res )
// {
// Can handle non-double
// }
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- char** variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(char** variable,
+ const std::string& value)
{
- if ( *variable )
- {
- delete [] *variable;
+ if (*variable) {
+ delete[] * variable;
*variable = 0;
- }
- *variable = new char[ value.size() + 1 ];
+ }
+ *variable = new char[value.size() + 1];
strcpy(*variable, value.c_str());
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- std::string* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::string* variable,
+ const std::string& value)
{
*variable = value;
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- std::vector<bool>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<bool>* variable,
+ const std::string& value)
{
bool val = false;
- if ( value == "1" || value == "ON" || value == "on" || value == "On" ||
- value == "TRUE" || value == "true" || value == "True" ||
- value == "yes" || value == "Yes" || value == "YES" )
- {
+ if (value == "1" || value == "ON" || value == "on" || value == "On" ||
+ value == "TRUE" || value == "true" || value == "True" ||
+ value == "yes" || value == "Yes" || value == "YES") {
val = true;
- }
+ }
variable->push_back(val);
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- std::vector<int>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<int>* variable,
+ const std::string& value)
{
char* res = 0;
variable->push_back(static_cast<int>(strtol(value.c_str(), &res, 10)));
- //if ( res && *res )
+ // if ( res && *res )
// {
// Can handle non-int
// }
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- std::vector<double>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<double>* variable,
+ const std::string& value)
{
char* res = 0;
variable->push_back(strtod(value.c_str(), &res));
- //if ( res && *res )
+ // if ( res && *res )
// {
// Can handle non-int
// }
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- std::vector<char*>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<char*>* variable,
+ const std::string& value)
{
- char* var = new char[ value.size() + 1 ];
+ char* var = new char[value.size() + 1];
strcpy(var, value.c_str());
variable->push_back(var);
}
//----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
- std::vector<std::string>* variable,
- const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<std::string>* variable,
+ const std::string& value)
{
variable->push_back(value);
}
//----------------------------------------------------------------------------
-bool CommandLineArguments::PopulateVariable(CommandLineArgumentsCallbackStructure* cs,
- const char* value)
+bool CommandLineArguments::PopulateVariable(
+ CommandLineArgumentsCallbackStructure* cs, const char* value)
{
// Call the callback
- if ( cs->Callback )
- {
- if ( !cs->Callback(cs->Argument, value, cs->CallData) )
- {
- this->Internals->LastArgument --;
+ if (cs->Callback) {
+ if (!cs->Callback(cs->Argument, value, cs->CallData)) {
+ this->Internals->LastArgument--;
return 0;
- }
}
- CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to " << value);
- if ( cs->Variable )
- {
+ }
+ CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to "
+ << value);
+ if (cs->Variable) {
std::string var = "1";
- if ( value )
- {
+ if (value) {
var = value;
- }
- switch ( cs->VariableType )
- {
- case CommandLineArguments::INT_TYPE:
- this->PopulateVariable(static_cast<int*>(cs->Variable), var);
- break;
- case CommandLineArguments::DOUBLE_TYPE:
- this->PopulateVariable(static_cast<double*>(cs->Variable), var);
- break;
- case CommandLineArguments::STRING_TYPE:
- this->PopulateVariable(static_cast<char**>(cs->Variable), var);
- break;
- case CommandLineArguments::STL_STRING_TYPE:
- this->PopulateVariable(static_cast<std::string*>(cs->Variable), var);
- break;
- case CommandLineArguments::BOOL_TYPE:
- this->PopulateVariable(static_cast<bool*>(cs->Variable), var);
- break;
- case CommandLineArguments::VECTOR_BOOL_TYPE:
- this->PopulateVariable(static_cast<std::vector<bool>*>(cs->Variable), var);
- break;
- case CommandLineArguments::VECTOR_INT_TYPE:
- this->PopulateVariable(static_cast<std::vector<int>*>(cs->Variable), var);
- break;
- case CommandLineArguments::VECTOR_DOUBLE_TYPE:
- this->PopulateVariable(static_cast<std::vector<double>*>(cs->Variable), var);
- break;
- case CommandLineArguments::VECTOR_STRING_TYPE:
- this->PopulateVariable(static_cast<std::vector<char*>*>(cs->Variable), var);
- break;
- case CommandLineArguments::VECTOR_STL_STRING_TYPE:
- this->PopulateVariable(static_cast<std::vector<std::string>*>(cs->Variable), var);
- break;
- default:
- std::cerr << "Got unknown variable type: \"" << cs->VariableType << "\"" << std::endl;
- this->Internals->LastArgument --;
- return 0;
- }
}
+ switch (cs->VariableType) {
+ case CommandLineArguments::INT_TYPE:
+ this->PopulateVariable(static_cast<int*>(cs->Variable), var);
+ break;
+ case CommandLineArguments::DOUBLE_TYPE:
+ this->PopulateVariable(static_cast<double*>(cs->Variable), var);
+ break;
+ case CommandLineArguments::STRING_TYPE:
+ this->PopulateVariable(static_cast<char**>(cs->Variable), var);
+ break;
+ case CommandLineArguments::STL_STRING_TYPE:
+ this->PopulateVariable(static_cast<std::string*>(cs->Variable), var);
+ break;
+ case CommandLineArguments::BOOL_TYPE:
+ this->PopulateVariable(static_cast<bool*>(cs->Variable), var);
+ break;
+ case CommandLineArguments::VECTOR_BOOL_TYPE:
+ this->PopulateVariable(static_cast<std::vector<bool>*>(cs->Variable),
+ var);
+ break;
+ case CommandLineArguments::VECTOR_INT_TYPE:
+ this->PopulateVariable(static_cast<std::vector<int>*>(cs->Variable),
+ var);
+ break;
+ case CommandLineArguments::VECTOR_DOUBLE_TYPE:
+ this->PopulateVariable(static_cast<std::vector<double>*>(cs->Variable),
+ var);
+ break;
+ case CommandLineArguments::VECTOR_STRING_TYPE:
+ this->PopulateVariable(static_cast<std::vector<char*>*>(cs->Variable),
+ var);
+ break;
+ case CommandLineArguments::VECTOR_STL_STRING_TYPE:
+ this->PopulateVariable(
+ static_cast<std::vector<std::string>*>(cs->Variable), var);
+ break;
+ default:
+ std::cerr << "Got unknown variable type: \"" << cs->VariableType
+ << "\"" << std::endl;
+ this->Internals->LastArgument--;
+ return 0;
+ }
+ }
return 1;
}
-
} // namespace KWSYS_NAMESPACE
diff --git a/Source/kwsys/CommandLineArguments.hxx.in b/Source/kwsys/CommandLineArguments.hxx.in
index e4f6d02..31115e5 100644
--- a/Source/kwsys/CommandLineArguments.hxx.in
+++ b/Source/kwsys/CommandLineArguments.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_CommandLineArguments_hxx
#define @KWSYS_NAMESPACE@_CommandLineArguments_hxx
@@ -18,8 +9,7 @@
#include <string>
#include <vector>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
class CommandLineArgumentsInternal;
struct CommandLineArgumentsCallbackStructure;
@@ -41,28 +31,29 @@ struct CommandLineArgumentsCallbackStructure;
* the argument is specified, the variable is set to the specified value casted
* to the appropriate type. For boolean (NO_ARGUMENT), the value is "1".
*
- * Both interfaces can be used at the same time.
+ * Both interfaces can be used at the same time.
*
* Possible argument types are:
* NO_ARGUMENT - The argument takes no value : --A
* CONCAT_ARGUMENT - The argument takes value after no space : --Aval
- * SPACE_ARGUMENT - The argument takes value after space : --A val
+ * SPACE_ARGUMENT - The argument takes value after space : --A val
* EQUAL_ARGUMENT - The argument takes value after equal : --A=val
- * MULTI_ARGUMENT - The argument takes values after space : --A val1 val2 val3 ...
+ * MULTI_ARGUMENT - The argument takes values after space : --A val1 val2
+ * val3 ...
*
* Example use:
*
* kwsys::CommandLineArguments arg;
* arg.Initialize(argc, argv);
* typedef kwsys::CommandLineArguments argT;
- * arg.AddArgument("--something", argT::EQUAL_ARGUMENT, &some_variable,
+ * arg.AddArgument("--something", argT::EQUAL_ARGUMENT, &some_variable,
* "This is help string for --something");
* if ( !arg.Parse() )
* {
* std::cerr << "Problem parsing arguments" << std::endl;
* res = 1;
* }
- *
+ *
*/
class @KWSYS_NAMESPACE@_EXPORT CommandLineArguments
@@ -74,7 +65,8 @@ public:
/**
* Various argument types.
*/
- enum ArgumentTypeEnum {
+ enum ArgumentTypeEnum
+ {
NO_ARGUMENT,
CONCAT_ARGUMENT,
SPACE_ARGUMENT,
@@ -86,27 +78,28 @@ public:
* Various variable types. When using the variable interface, this specifies
* what type the variable is.
*/
- enum VariableTypeEnum {
- NO_VARIABLE_TYPE = 0, // The variable is not specified
- INT_TYPE, // The variable is integer (int)
- BOOL_TYPE, // The variable is boolean (bool)
- DOUBLE_TYPE, // The variable is float (double)
- STRING_TYPE, // The variable is string (char*)
- STL_STRING_TYPE, // The variable is string (char*)
- VECTOR_INT_TYPE, // The variable is integer (int)
- VECTOR_BOOL_TYPE, // The variable is boolean (bool)
- VECTOR_DOUBLE_TYPE, // The variable is float (double)
- VECTOR_STRING_TYPE, // The variable is string (char*)
- VECTOR_STL_STRING_TYPE, // The variable is string (char*)
+ enum VariableTypeEnum
+ {
+ NO_VARIABLE_TYPE = 0, // The variable is not specified
+ INT_TYPE, // The variable is integer (int)
+ BOOL_TYPE, // The variable is boolean (bool)
+ DOUBLE_TYPE, // The variable is float (double)
+ STRING_TYPE, // The variable is string (char*)
+ STL_STRING_TYPE, // The variable is string (char*)
+ VECTOR_INT_TYPE, // The variable is integer (int)
+ VECTOR_BOOL_TYPE, // The variable is boolean (bool)
+ VECTOR_DOUBLE_TYPE, // The variable is float (double)
+ VECTOR_STRING_TYPE, // The variable is string (char*)
+ VECTOR_STL_STRING_TYPE, // The variable is string (char*)
LAST_VARIABLE_TYPE
};
/**
* Prototypes for callbacks for callback interface.
*/
- typedef int(*CallbackType)(const char* argument, const char* value,
- void* call_data);
- typedef int(*ErrorCallbackType)(const char* argument, void* client_data);
+ typedef int (*CallbackType)(const char* argument, const char* value,
+ void* call_data);
+ typedef int (*ErrorCallbackType)(const char* argument, void* client_data);
/**
* Initialize internal data structures. This should be called before parsing.
@@ -133,24 +126,24 @@ public:
* argument help specifies the help string used with this option. The
* callback and call_data can be skipped.
*/
- void AddCallback(const char* argument, ArgumentTypeEnum type,
- CallbackType callback, void* call_data, const char* help);
+ void AddCallback(const char* argument, ArgumentTypeEnum type,
+ CallbackType callback, void* call_data, const char* help);
/**
* Add handler for argument which is going to set the variable to the
* specified value. If the argument is specified, the option is casted to the
* appropriate type.
*/
+ void AddArgument(const char* argument, ArgumentTypeEnum type, bool* variable,
+ const char* help);
+ void AddArgument(const char* argument, ArgumentTypeEnum type, int* variable,
+ const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
- bool* variable, const char* help);
+ double* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
- int* variable, const char* help);
- void AddArgument(const char* argument, ArgumentTypeEnum type,
- double* variable, const char* help);
- void AddArgument(const char* argument, ArgumentTypeEnum type,
- char** variable, const char* help);
+ char** variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
- std::string* variable, const char* help);
+ std::string* variable, const char* help);
/**
* Add handler for argument which is going to set the variable to the
@@ -158,31 +151,31 @@ public:
* appropriate type. This will handle the multi argument values.
*/
void AddArgument(const char* argument, ArgumentTypeEnum type,
- std::vector<bool>* variable, const char* help);
+ std::vector<bool>* variable, const char* help);
+ void AddArgument(const char* argument, ArgumentTypeEnum type,
+ std::vector<int>* variable, const char* help);
+ void AddArgument(const char* argument, ArgumentTypeEnum type,
+ std::vector<double>* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
- std::vector<int>* variable, const char* help);
- void AddArgument(const char* argument, ArgumentTypeEnum type,
- std::vector<double>* variable, const char* help);
- void AddArgument(const char* argument, ArgumentTypeEnum type,
- std::vector<char*>* variable, const char* help);
+ std::vector<char*>* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
- std::vector<std::string>* variable, const char* help);
+ std::vector<std::string>* variable, const char* help);
/**
* Add handler for boolean argument. The argument does not take any option
* and if it is specified, the value of the variable is true/1, otherwise it
* is false/0.
*/
- void AddBooleanArgument(const char* argument,
- bool* variable, const char* help);
- void AddBooleanArgument(const char* argument,
- int* variable, const char* help);
- void AddBooleanArgument(const char* argument,
- double* variable, const char* help);
- void AddBooleanArgument(const char* argument,
- char** variable, const char* help);
- void AddBooleanArgument(const char* argument,
- std::string* variable, const char* help);
+ void AddBooleanArgument(const char* argument, bool* variable,
+ const char* help);
+ void AddBooleanArgument(const char* argument, int* variable,
+ const char* help);
+ void AddBooleanArgument(const char* argument, double* variable,
+ const char* help);
+ void AddBooleanArgument(const char* argument, char** variable,
+ const char* help);
+ void AddBooleanArgument(const char* argument, std::string* variable,
+ const char* help);
/**
* Set the callbacks for error handling.
@@ -236,14 +229,14 @@ protected:
//! This is internal method that registers variable with argument
void AddArgument(const char* argument, ArgumentTypeEnum type,
- VariableTypeEnum vtype, void* variable, const char* help);
+ VariableTypeEnum vtype, void* variable, const char* help);
bool GetMatchedArguments(std::vector<std::string>* matches,
- const std::string& arg);
+ const std::string& arg);
//! Populate individual variables
bool PopulateVariable(CommandLineArgumentsCallbackStructure* cs,
- const char* value);
+ const char* value);
//! Populate individual variables of type ...
void PopulateVariable(bool* variable, const std::string& value);
@@ -253,9 +246,12 @@ protected:
void PopulateVariable(std::string* variable, const std::string& value);
void PopulateVariable(std::vector<bool>* variable, const std::string& value);
void PopulateVariable(std::vector<int>* variable, const std::string& value);
- void PopulateVariable(std::vector<double>* variable, const std::string& value);
- void PopulateVariable(std::vector<char*>* variable, const std::string& value);
- void PopulateVariable(std::vector<std::string>* variable, const std::string& value);
+ void PopulateVariable(std::vector<double>* variable,
+ const std::string& value);
+ void PopulateVariable(std::vector<char*>* variable,
+ const std::string& value);
+ void PopulateVariable(std::vector<std::string>* variable,
+ const std::string& value);
typedef CommandLineArgumentsInternal Internal;
Internal* Internals;
@@ -269,8 +265,3 @@ protected:
} // namespace @KWSYS_NAMESPACE@
#endif
-
-
-
-
-
diff --git a/Source/kwsys/Configure.h.in b/Source/kwsys/Configure.h.in
index cd2d965..0afcae7 100644
--- a/Source/kwsys/Configure.h.in
+++ b/Source/kwsys/Configure.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Configure_h
#define @KWSYS_NAMESPACE@_Configure_h
@@ -16,22 +7,22 @@
namespace. When not building a kwsys source file these macros are
temporarily defined inside the headers that use them. */
#if defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
/* Disable some warnings inside kwsys source files. */
#if defined(KWSYS_NAMESPACE)
-# if defined(__BORLANDC__)
-# pragma warn -8027 /* function not inlined. */
-# endif
-# if defined(__INTEL_COMPILER)
-# pragma warning (disable: 1572) /* floating-point equality test */
-# endif
-# if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 3970 /* pointer to int conversion */
-# pragma set woff 3968 /* 64 bit conversion */
-# endif
+#if defined(__BORLANDC__)
+#pragma warn - 8027 /* function not inlined. */
+#endif
+#if defined(__INTEL_COMPILER)
+#pragma warning(disable : 1572) /* floating-point equality test */
+#endif
+#if defined(__sgi) && !defined(__GNUC__)
+#pragma set woff 3970 /* pointer to int conversion */
+#pragma set woff 3968 /* 64 bit conversion */
+#endif
#endif
/* Whether kwsys namespace is "kwsys". */
@@ -42,84 +33,84 @@
/* Whether Large File Support is available. */
#if @KWSYS_NAMESPACE@_LFS_REQUESTED
-# define @KWSYS_NAMESPACE@_LFS_AVAILABLE @KWSYS_LFS_AVAILABLE@
+#define @KWSYS_NAMESPACE@_LFS_AVAILABLE @KWSYS_LFS_AVAILABLE@
#endif
/* Setup Large File Support if requested. */
#if @KWSYS_NAMESPACE@_LFS_REQUESTED
- /* Since LFS is requested this header must be included before system
- headers whether or not LFS is available. */
-# if 0 && (defined(_SYS_TYPES_H) || defined(_SYS_TYPES_INCLUDED))
-# error "@KWSYS_NAMESPACE@/Configure.h must be included before sys/types.h"
-# endif
- /* Enable the large file API if it is available. */
-# if @KWSYS_NAMESPACE@_LFS_AVAILABLE && \
- !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINES)
-# if !defined(_LARGEFILE_SOURCE) && \
- !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGEFILE_SOURCE)
-# define _LARGEFILE_SOURCE
-# endif
-# if !defined(_LARGEFILE64_SOURCE) && \
- !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGEFILE64_SOURCE)
-# define _LARGEFILE64_SOURCE
-# endif
-# if !defined(_LARGE_FILES) && \
- !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGE_FILES)
-# define _LARGE_FILES
-# endif
-# if !defined(_FILE_OFFSET_BITS) && \
- !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_FILE_OFFSET_BITS)
-# define _FILE_OFFSET_BITS 64
-# endif
-# if 0 && (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64)
-# error "_FILE_OFFSET_BITS must be defined to at least 64"
-# endif
-# endif
+/* Since LFS is requested this header must be included before system
+ headers whether or not LFS is available. */
+#if 0 && (defined(_SYS_TYPES_H) || defined(_SYS_TYPES_INCLUDED))
+#error "@KWSYS_NAMESPACE@/Configure.h must be included before sys/types.h"
+#endif
+/* Enable the large file API if it is available. */
+#if @KWSYS_NAMESPACE@_LFS_AVAILABLE && \
+ !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINES)
+#if !defined(_LARGEFILE_SOURCE) && \
+ !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGEFILE_SOURCE)
+#define _LARGEFILE_SOURCE
+#endif
+#if !defined(_LARGEFILE64_SOURCE) && \
+ !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGEFILE64_SOURCE)
+#define _LARGEFILE64_SOURCE
+#endif
+#if !defined(_LARGE_FILES) && \
+ !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGE_FILES)
+#define _LARGE_FILES
+#endif
+#if !defined(_FILE_OFFSET_BITS) && \
+ !defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_FILE_OFFSET_BITS)
+#define _FILE_OFFSET_BITS 64
+#endif
+#if 0 && (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64)
+#error "_FILE_OFFSET_BITS must be defined to at least 64"
+#endif
+#endif
#endif
/* Setup the export macro. */
#if @KWSYS_BUILD_SHARED@
-# if defined(_WIN32) || defined(__CYGWIN__)
-# if defined(@KWSYS_NAMESPACE@_EXPORTS)
-# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllexport)
-# else
-# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllimport)
-# endif
-# elif __GNUC__ >= 4
-# define @KWSYS_NAMESPACE@_EXPORT __attribute__ ((visibility("default")))
-# else
-# define @KWSYS_NAMESPACE@_EXPORT
-# endif
+#if defined(_WIN32) || defined(__CYGWIN__)
+#if defined(@KWSYS_NAMESPACE@_EXPORTS)
+#define @KWSYS_NAMESPACE@_EXPORT __declspec(dllexport)
+#else
+#define @KWSYS_NAMESPACE@_EXPORT __declspec(dllimport)
+#endif
+#elif __GNUC__ >= 4
+#define @KWSYS_NAMESPACE@_EXPORT __attribute__((visibility("default")))
+#else
+#define @KWSYS_NAMESPACE@_EXPORT
+#endif
#else
-# define @KWSYS_NAMESPACE@_EXPORT
+#define @KWSYS_NAMESPACE@_EXPORT
#endif
/* Enable warnings that are off by default but are useful. */
#if !defined(@KWSYS_NAMESPACE@_NO_WARNING_ENABLE)
-# if defined(_MSC_VER)
-# pragma warning ( default : 4263 ) /* no override, call convention differs */
-# endif
+#if defined(_MSC_VER)
+#pragma warning(default : 4263) /* no override, call convention differs */
+#endif
#endif
/* Disable warnings that are on by default but occur in valid code. */
#if !defined(@KWSYS_NAMESPACE@_NO_WARNING_DISABLE)
-# if defined(_MSC_VER)
-# pragma warning (disable: 4097) /* typedef is synonym for class */
-# pragma warning (disable: 4127) /* conditional expression is constant */
-# pragma warning (disable: 4244) /* possible loss in conversion */
-# pragma warning (disable: 4251) /* missing DLL-interface */
-# pragma warning (disable: 4305) /* truncation from type1 to type2 */
-# pragma warning (disable: 4309) /* truncation of constant value */
-# pragma warning (disable: 4514) /* unreferenced inline function */
-# pragma warning (disable: 4706) /* assignment in conditional expression */
-# pragma warning (disable: 4710) /* function not inlined */
-# pragma warning (disable: 4786) /* identifier truncated in debug info */
-# endif
-# if defined(__BORLANDC__) && !defined(__cplusplus)
- /* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
- unused parameter using "(param)" syntax (i.e. no cast to void). */
-# pragma warn -8019
-# endif
+#if defined(_MSC_VER)
+#pragma warning(disable : 4097) /* typedef is synonym for class */
+#pragma warning(disable : 4127) /* conditional expression is constant */
+#pragma warning(disable : 4244) /* possible loss in conversion */
+#pragma warning(disable : 4251) /* missing DLL-interface */
+#pragma warning(disable : 4305) /* truncation from type1 to type2 */
+#pragma warning(disable : 4309) /* truncation of constant value */
+#pragma warning(disable : 4514) /* unreferenced inline function */
+#pragma warning(disable : 4706) /* assignment in conditional expression */
+#pragma warning(disable : 4710) /* function not inlined */
+#pragma warning(disable : 4786) /* identifier truncated in debug info */
+#endif
+#if defined(__BORLANDC__) && !defined(__cplusplus)
+/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
+ unused parameter using "(param)" syntax (i.e. no cast to void). */
+#pragma warn - 8019
+#endif
#endif
/* MSVC 6.0 in release mode will warn about code it produces with its
@@ -127,10 +118,10 @@
configuration. Real warnings will be revealed by a debug build or
by other compilers. */
#if !defined(@KWSYS_NAMESPACE@_NO_WARNING_DISABLE_BOGUS)
-# if defined(_MSC_VER) && (_MSC_VER < 1300) && defined(NDEBUG)
-# pragma warning ( disable : 4701 ) /* Variable may be used uninitialized. */
-# pragma warning ( disable : 4702 ) /* Unreachable code. */
-# endif
+#if defined(_MSC_VER) && (_MSC_VER < 1300) && defined(NDEBUG)
+#pragma warning(disable : 4701) /* Variable may be used uninitialized. */
+#pragma warning(disable : 4702) /* Unreachable code. */
+#endif
#endif
#endif
diff --git a/Source/kwsys/Configure.hxx.in b/Source/kwsys/Configure.hxx.in
index 4ce680d..1c07a4e 100644
--- a/Source/kwsys/Configure.hxx.in
+++ b/Source/kwsys/Configure.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Configure_hxx
#define @KWSYS_NAMESPACE@_Configure_hxx
@@ -18,17 +9,19 @@
/* Whether wstring is available. */
#define @KWSYS_NAMESPACE@_STL_HAS_WSTRING @KWSYS_STL_HAS_WSTRING@
/* Whether <ext/stdio_filebuf.h> is available. */
-#define @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@
+#define @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H \
+ @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@
/* If building a C++ file in kwsys itself, give the source file
access to the macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
-# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsys @KWSYS_NAMESPACE@
-# endif
-# define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define KWSYS_STL_HAS_WSTRING @KWSYS_NAMESPACE@_STL_HAS_WSTRING
-# define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H
+#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#define kwsys @KWSYS_NAMESPACE@
+#endif
+#define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#define KWSYS_STL_HAS_WSTRING @KWSYS_NAMESPACE@_STL_HAS_WSTRING
+#define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H \
+ @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H
#endif
#endif
diff --git a/Source/kwsys/ConsoleBuf.hxx.in b/Source/kwsys/ConsoleBuf.hxx.in
index 2496b45..c45a351 100644
--- a/Source/kwsys/ConsoleBuf.hxx.in
+++ b/Source/kwsys/ConsoleBuf.hxx.in
@@ -1,354 +1,393 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_ConsoleBuf_hxx
#define @KWSYS_NAMESPACE@_ConsoleBuf_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
+
#include <@KWSYS_NAMESPACE@/Encoding.hxx>
-#include <string>
+
#include <cstring>
-#include <sstream>
-#include <streambuf>
#include <iostream>
+#include <sstream>
#include <stdexcept>
+#include <streambuf>
+#include <string>
#if defined(_WIN32)
-# include <windows.h>
-# if __cplusplus >= 201103L
-# include <system_error>
-# endif
+#include <windows.h>
+#if __cplusplus >= 201103L
+#include <system_error>
+#endif
#endif
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
#if defined(_WIN32)
- template<class CharT, class Traits = std::char_traits<CharT> >
- class @KWSYS_NAMESPACE@_EXPORT BasicConsoleBuf :
- public std::basic_streambuf<CharT, Traits> {
- public:
- typedef typename Traits::int_type int_type;
- typedef typename Traits::char_type char_type;
-
- class Manager {
- public:
- Manager(std::basic_ios<CharT, Traits> &ios, const bool err = false)
- : m_consolebuf(0)
- {
- m_ios = &ios;
- try {
- m_consolebuf = new BasicConsoleBuf<CharT, Traits>(err);
- m_streambuf = m_ios->rdbuf(m_consolebuf);
- } catch (const std::runtime_error& ex) {
- std::cerr << "Failed to create ConsoleBuf!" << std::endl
- << ex.what() << std::endl;
- };
- }
-
- ~Manager()
- {
- if (m_consolebuf) {
- delete m_consolebuf;
- m_ios->rdbuf(m_streambuf);
- }
- }
+template <class CharT, class Traits = std::char_traits<CharT> >
+class @KWSYS_NAMESPACE@_EXPORT BasicConsoleBuf
+ : public std::basic_streambuf<CharT, Traits>
+{
+public:
+ typedef typename Traits::int_type int_type;
+ typedef typename Traits::char_type char_type;
- private:
- std::basic_ios<CharT, Traits> *m_ios;
- std::basic_streambuf<CharT, Traits> *m_streambuf;
- BasicConsoleBuf<CharT, Traits> *m_consolebuf;
+ class Manager
+ {
+ public:
+ Manager(std::basic_ios<CharT, Traits>& ios, const bool err = false)
+ : m_consolebuf(0)
+ {
+ m_ios = &ios;
+ try {
+ m_consolebuf = new BasicConsoleBuf<CharT, Traits>(err);
+ m_streambuf = m_ios->rdbuf(m_consolebuf);
+ } catch (const std::runtime_error& ex) {
+ std::cerr << "Failed to create ConsoleBuf!" << std::endl
+ << ex.what() << std::endl;
};
+ }
- BasicConsoleBuf(const bool err = false) :
- flush_on_newline(true),
- input_pipe_codepage(0),
- output_pipe_codepage(0),
- input_file_codepage(CP_UTF8),
- output_file_codepage(CP_UTF8),
- m_consolesCodepage(0)
- {
- m_hInput = ::GetStdHandle(STD_INPUT_HANDLE);
- checkHandle(true, "STD_INPUT_HANDLE");
- if (!setActiveInputCodepage()) {
- throw std::runtime_error("setActiveInputCodepage failed!");
- }
- m_hOutput = err ? ::GetStdHandle(STD_ERROR_HANDLE) :
- ::GetStdHandle(STD_OUTPUT_HANDLE);
- checkHandle(false, err ? "STD_ERROR_HANDLE" : "STD_OUTPUT_HANDLE");
- if (!setActiveOutputCodepage()) {
- throw std::runtime_error("setActiveOutputCodepage failed!");
- }
- _setg();
- _setp();
- }
+ BasicConsoleBuf<CharT, Traits>* GetConsoleBuf() { return m_consolebuf; }
- ~BasicConsoleBuf() throw()
- {
- sync();
+ void SetUTF8Pipes()
+ {
+ if (m_consolebuf) {
+ m_consolebuf->input_pipe_codepage = CP_UTF8;
+ m_consolebuf->output_pipe_codepage = CP_UTF8;
+ m_consolebuf->activateCodepageChange();
}
+ }
- bool activateCodepageChange()
- {
- return setActiveInputCodepage() && setActiveOutputCodepage();
+ ~Manager()
+ {
+ if (m_consolebuf) {
+ delete m_consolebuf;
+ m_ios->rdbuf(m_streambuf);
}
+ }
- protected:
- virtual int sync() {
- bool success = true;
- if (m_hInput && m_isConsoleInput &&
- ::FlushConsoleInputBuffer(m_hInput) == 0) {
- success = false;
- }
- if (m_hOutput && !m_obuffer.empty()) {
- const std::wstring wbuffer = getBuffer(m_obuffer);
- if (m_isConsoleOutput) {
- DWORD charsWritten;
- success = ::WriteConsoleW(m_hOutput, wbuffer.c_str(),
- (DWORD)wbuffer.size(), &charsWritten,
- NULL) == 0 ? false : true;
- } else {
- DWORD bytesWritten;
- std::string buffer;
- success = encodeOutputBuffer(wbuffer, buffer);
- if (success) {
- success = ::WriteFile(m_hOutput, buffer.c_str(),
- (DWORD)buffer.size(), &bytesWritten,
- NULL) == 0 ? false : true;
- }
- }
+ private:
+ std::basic_ios<CharT, Traits>* m_ios;
+ std::basic_streambuf<CharT, Traits>* m_streambuf;
+ BasicConsoleBuf<CharT, Traits>* m_consolebuf;
+ };
+
+ BasicConsoleBuf(const bool err = false)
+ : flush_on_newline(true)
+ , input_pipe_codepage(0)
+ , output_pipe_codepage(0)
+ , input_file_codepage(CP_UTF8)
+ , output_file_codepage(CP_UTF8)
+ , m_consolesCodepage(0)
+ {
+ m_hInput = ::GetStdHandle(STD_INPUT_HANDLE);
+ checkHandle(true, "STD_INPUT_HANDLE");
+ if (!setActiveInputCodepage()) {
+ throw std::runtime_error("setActiveInputCodepage failed!");
+ }
+ m_hOutput = err ? ::GetStdHandle(STD_ERROR_HANDLE)
+ : ::GetStdHandle(STD_OUTPUT_HANDLE);
+ checkHandle(false, err ? "STD_ERROR_HANDLE" : "STD_OUTPUT_HANDLE");
+ if (!setActiveOutputCodepage()) {
+ throw std::runtime_error("setActiveOutputCodepage failed!");
+ }
+ _setg();
+ _setp();
+ }
+
+ ~BasicConsoleBuf() throw() { sync(); }
+
+ bool activateCodepageChange()
+ {
+ return setActiveInputCodepage() && setActiveOutputCodepage();
+ }
+
+protected:
+ virtual int sync()
+ {
+ bool success = true;
+ if (m_hInput && m_isConsoleInput &&
+ ::FlushConsoleInputBuffer(m_hInput) == 0) {
+ success = false;
+ }
+ if (m_hOutput && !m_obuffer.empty()) {
+ const std::wstring wbuffer = getBuffer(m_obuffer);
+ if (m_isConsoleOutput) {
+ DWORD charsWritten;
+ success =
+ ::WriteConsoleW(m_hOutput, wbuffer.c_str(), (DWORD)wbuffer.size(),
+ &charsWritten, NULL) == 0
+ ? false
+ : true;
+ } else {
+ DWORD bytesWritten;
+ std::string buffer;
+ success = encodeOutputBuffer(wbuffer, buffer);
+ if (success) {
+ success = ::WriteFile(m_hOutput, buffer.c_str(),
+ (DWORD)buffer.size(), &bytesWritten, NULL) == 0
+ ? false
+ : true;
}
- m_ibuffer.clear();
- m_obuffer.clear();
- _setg();
- _setp();
- return success ? 0 : -1;
}
+ }
+ m_ibuffer.clear();
+ m_obuffer.clear();
+ _setg();
+ _setp();
+ return success ? 0 : -1;
+ }
- virtual int_type underflow() {
- if (this->gptr() >= this->egptr()) {
- if (!m_hInput) {
- _setg(true);
- return Traits::eof();
- }
- if (m_isConsoleInput) {
- wchar_t wbuffer[128];
- DWORD charsRead;
- if (::ReadConsoleW(m_hInput, wbuffer, (sizeof(wbuffer) / sizeof(wbuffer[0])) - 1,
- &charsRead, NULL) == 0 || charsRead == 0) {
- _setg(true);
- return Traits::eof();
- }
- wbuffer[charsRead] = L'\0';
- setBuffer(wbuffer, m_ibuffer);
- } else {
- std::wstring totalBuffer;
- std::wstring wbuffer;
- char buffer[128];
- DWORD bytesRead;
- while (::ReadFile(m_hInput, buffer, (sizeof(buffer) / sizeof(buffer[0])) - 1,
- &bytesRead, NULL) == 0) {
- if (::GetLastError() == ERROR_MORE_DATA) {
- buffer[bytesRead] = '\0';
- if (decodeInputBuffer(buffer, wbuffer)) {
- totalBuffer += wbuffer;
- continue;
- }
- }
- _setg(true);
- return Traits::eof();
- }
- buffer[bytesRead] = '\0';
- if (!decodeInputBuffer(buffer, wbuffer)) {
- _setg(true);
- return Traits::eof();
- }
- totalBuffer += wbuffer;
- setBuffer(totalBuffer, m_ibuffer);
+ virtual int_type underflow()
+ {
+ if (this->gptr() >= this->egptr()) {
+ if (!m_hInput) {
+ _setg(true);
+ return Traits::eof();
+ }
+ if (m_isConsoleInput) {
+ // ReadConsole doesn't tell if there's more input available
+ // don't support reading more characters than this
+ wchar_t wbuffer[8192];
+ DWORD charsRead;
+ if (ReadConsoleW(m_hInput, wbuffer,
+ (sizeof(wbuffer) / sizeof(wbuffer[0])), &charsRead,
+ NULL) == 0 ||
+ charsRead == 0) {
+ _setg(true);
+ return Traits::eof();
+ }
+ setBuffer(std::wstring(wbuffer, charsRead), m_ibuffer);
+ } else {
+ std::wstring wbuffer;
+ std::string strbuffer;
+ DWORD bytesRead;
+ LARGE_INTEGER size;
+ if (GetFileSizeEx(m_hInput, &size) == 0) {
+ _setg(true);
+ return Traits::eof();
+ }
+ char* buffer = new char[size.LowPart];
+ while (ReadFile(m_hInput, buffer, size.LowPart, &bytesRead, NULL) ==
+ 0) {
+ if (GetLastError() == ERROR_MORE_DATA) {
+ strbuffer += std::string(buffer, bytesRead);
+ continue;
}
- _setg();
+ _setg(true);
+ delete[] buffer;
+ return Traits::eof();
+ }
+ if (bytesRead > 0) {
+ strbuffer += std::string(buffer, bytesRead);
+ }
+ delete[] buffer;
+ if (!decodeInputBuffer(strbuffer, wbuffer)) {
+ _setg(true);
+ return Traits::eof();
}
- return Traits::to_int_type(*this->gptr());
+ setBuffer(wbuffer, m_ibuffer);
}
+ _setg();
+ }
+ return Traits::to_int_type(*this->gptr());
+ }
- virtual int_type overflow(int_type ch = Traits::eof()) {
- if (!Traits::eq_int_type(ch, Traits::eof())) {
- char_type chr = Traits::to_char_type(ch);
- m_obuffer += chr;
- if ((flush_on_newline && Traits::eq(chr, '\n')) ||
- Traits::eq_int_type(ch, 0x00)) {
- sync();
- }
- return ch;
- }
+ virtual int_type overflow(int_type ch = Traits::eof())
+ {
+ if (!Traits::eq_int_type(ch, Traits::eof())) {
+ char_type chr = Traits::to_char_type(ch);
+ m_obuffer += chr;
+ if ((flush_on_newline && Traits::eq(chr, '\n')) ||
+ Traits::eq_int_type(ch, 0x00)) {
sync();
- return Traits::eof();
}
+ return ch;
+ }
+ sync();
+ return Traits::eof();
+ }
- public:
- bool flush_on_newline;
- UINT input_pipe_codepage;
- UINT output_pipe_codepage;
- UINT input_file_codepage;
- UINT output_file_codepage;
+public:
+ bool flush_on_newline;
+ UINT input_pipe_codepage;
+ UINT output_pipe_codepage;
+ UINT input_file_codepage;
+ UINT output_file_codepage;
- private:
- HANDLE m_hInput;
- HANDLE m_hOutput;
- std::basic_string<char_type> m_ibuffer;
- std::basic_string<char_type> m_obuffer;
- bool m_isConsoleInput;
- bool m_isConsoleOutput;
- UINT m_activeInputCodepage;
- UINT m_activeOutputCodepage;
- UINT m_consolesCodepage;
- void checkHandle(bool input, std::string handleName) {
- if ((input && m_hInput == INVALID_HANDLE_VALUE) ||
- (!input && m_hOutput == INVALID_HANDLE_VALUE)) {
- std::string errmsg = "GetStdHandle(" + handleName +
- ") returned INVALID_HANDLE_VALUE";
+private:
+ HANDLE m_hInput;
+ HANDLE m_hOutput;
+ std::basic_string<char_type> m_ibuffer;
+ std::basic_string<char_type> m_obuffer;
+ bool m_isConsoleInput;
+ bool m_isConsoleOutput;
+ UINT m_activeInputCodepage;
+ UINT m_activeOutputCodepage;
+ UINT m_consolesCodepage;
+ void checkHandle(bool input, std::string handleName)
+ {
+ if ((input && m_hInput == INVALID_HANDLE_VALUE) ||
+ (!input && m_hOutput == INVALID_HANDLE_VALUE)) {
+ std::string errmsg =
+ "GetStdHandle(" + handleName + ") returned INVALID_HANDLE_VALUE";
#if __cplusplus >= 201103L
- throw std::system_error(::GetLastError(),
- std::system_category(), errmsg);
+ throw std::system_error(::GetLastError(), std::system_category(),
+ errmsg);
#else
- throw std::runtime_error(errmsg);
+ throw std::runtime_error(errmsg);
#endif
- }
- }
- UINT getConsolesCodepage() {
- if (!m_consolesCodepage) {
- m_consolesCodepage = GetConsoleCP();
- if (!m_consolesCodepage) {
- m_consolesCodepage = GetACP();
- }
- }
- return m_consolesCodepage;
+ }
+ }
+ UINT getConsolesCodepage()
+ {
+ if (!m_consolesCodepage) {
+ m_consolesCodepage = GetConsoleCP();
+ if (!m_consolesCodepage) {
+ m_consolesCodepage = GetACP();
}
- bool setActiveInputCodepage() {
- m_isConsoleInput = false;
- switch (GetFileType(m_hInput)) {
- case FILE_TYPE_DISK:
- m_activeInputCodepage = input_file_codepage;
- break;
- case FILE_TYPE_CHAR:
- // Check for actual console.
- DWORD consoleMode;
- m_isConsoleInput = GetConsoleMode(m_hInput, &consoleMode) == 0 ? false : true;
- if (m_isConsoleInput) {
- break;
- }
- case FILE_TYPE_PIPE:
- m_activeInputCodepage = input_pipe_codepage;
- break;
- default:
- return false;
+ }
+ return m_consolesCodepage;
+ }
+ bool setActiveInputCodepage()
+ {
+ m_isConsoleInput = false;
+ switch (GetFileType(m_hInput)) {
+ case FILE_TYPE_DISK:
+ m_activeInputCodepage = input_file_codepage;
+ break;
+ case FILE_TYPE_CHAR:
+ // Check for actual console.
+ DWORD consoleMode;
+ m_isConsoleInput =
+ GetConsoleMode(m_hInput, &consoleMode) == 0 ? false : true;
+ if (m_isConsoleInput) {
+ break;
}
- if (!m_isConsoleInput && m_activeInputCodepage == 0) {
- m_activeInputCodepage = getConsolesCodepage();
+ case FILE_TYPE_PIPE:
+ m_activeInputCodepage = input_pipe_codepage;
+ break;
+ default:
+ return false;
+ }
+ if (!m_isConsoleInput && m_activeInputCodepage == 0) {
+ m_activeInputCodepage = getConsolesCodepage();
+ }
+ return true;
+ }
+ bool setActiveOutputCodepage()
+ {
+ m_isConsoleOutput = false;
+ switch (GetFileType(m_hOutput)) {
+ case FILE_TYPE_DISK:
+ m_activeOutputCodepage = output_file_codepage;
+ break;
+ case FILE_TYPE_CHAR:
+ // Check for actual console.
+ DWORD consoleMode;
+ m_isConsoleOutput =
+ GetConsoleMode(m_hOutput, &consoleMode) == 0 ? false : true;
+ if (m_isConsoleOutput) {
+ break;
}
- return true;
- }
- bool setActiveOutputCodepage() {
- m_isConsoleOutput = false;
- switch (GetFileType(m_hOutput)) {
- case FILE_TYPE_DISK:
- m_activeOutputCodepage = output_file_codepage;
- break;
- case FILE_TYPE_CHAR:
- // Check for actual console.
- DWORD consoleMode;
- m_isConsoleOutput = GetConsoleMode(m_hOutput, &consoleMode) == 0 ? false : true;
- if (m_isConsoleOutput) {
- break;
- }
- case FILE_TYPE_PIPE:
- m_activeOutputCodepage = output_pipe_codepage;
- break;
- default:
- return false;
- }
- if (!m_isConsoleOutput && m_activeOutputCodepage == 0) {
- m_activeOutputCodepage = getConsolesCodepage();
- }
- return true;
- }
- void _setg(bool empty = false) {
- if (!empty) {
- this->setg((char_type *)m_ibuffer.data(),
- (char_type *)m_ibuffer.data(),
- (char_type *)m_ibuffer.data() + m_ibuffer.size());
- } else {
- this->setg((char_type *)m_ibuffer.data(),
- (char_type *)m_ibuffer.data() + m_ibuffer.size(),
- (char_type *)m_ibuffer.data() + m_ibuffer.size());
- }
- }
- void _setp() {
- this->setp((char_type *)m_obuffer.data(),
- (char_type *)m_obuffer.data() + m_obuffer.size());
- }
- bool encodeOutputBuffer(const std::wstring wbuffer,
- std::string &buffer) {
- const int length = WideCharToMultiByte(m_activeOutputCodepage, 0,
- wbuffer.c_str(),
- (int)wbuffer.size(), NULL, 0,
- NULL, NULL);
- char *buf = new char[length + 1];
- const bool success = WideCharToMultiByte(m_activeOutputCodepage, 0,
- wbuffer.c_str(),
- (int)wbuffer.size(), buf,
- length, NULL, NULL) > 0
- ? true : false;
- buf[length] = '\0';
- buffer = buf;
- delete[] buf;
- return success;
- }
- bool decodeInputBuffer(const char *buffer, std::wstring &wbuffer) {
- int actualCodepage = m_activeInputCodepage;
- const char BOM_UTF8[] = { char(0xEF), char(0xBB), char(0xBF) };
- if (std::memcmp(buffer, BOM_UTF8, sizeof(BOM_UTF8)) == 0) {
- // PowerShell uses UTF-8 with BOM for pipes
- actualCodepage = CP_UTF8;
- buffer += sizeof(BOM_UTF8);
- }
- const int wlength = MultiByteToWideChar(actualCodepage, 0, buffer,
- -1, NULL, 0);
- wchar_t *wbuf = new wchar_t[wlength];
- const bool success = MultiByteToWideChar(actualCodepage, 0, buffer,
- -1, wbuf, wlength) > 0
- ? true : false;
- wbuffer = wbuf;
- delete[] wbuf;
- return success;
- }
- std::wstring getBuffer(const std::basic_string<char> buffer) {
- return Encoding::ToWide(buffer);
- }
- std::wstring getBuffer(const std::basic_string<wchar_t> buffer) {
- return buffer;
- }
- void setBuffer(const std::wstring wbuffer,
- std::basic_string<char> &target) {
- target = Encoding::ToNarrow(wbuffer);
- }
- void setBuffer(const std::wstring wbuffer,
- std::basic_string<wchar_t> &target) {
- target = wbuffer;
- }
+ case FILE_TYPE_PIPE:
+ m_activeOutputCodepage = output_pipe_codepage;
+ break;
+ default:
+ return false;
+ }
+ if (!m_isConsoleOutput && m_activeOutputCodepage == 0) {
+ m_activeOutputCodepage = getConsolesCodepage();
+ }
+ return true;
+ }
+ void _setg(bool empty = false)
+ {
+ if (!empty) {
+ this->setg((char_type*)m_ibuffer.data(), (char_type*)m_ibuffer.data(),
+ (char_type*)m_ibuffer.data() + m_ibuffer.size());
+ } else {
+ this->setg((char_type*)m_ibuffer.data(),
+ (char_type*)m_ibuffer.data() + m_ibuffer.size(),
+ (char_type*)m_ibuffer.data() + m_ibuffer.size());
+ }
+ }
+ void _setp()
+ {
+ this->setp((char_type*)m_obuffer.data(),
+ (char_type*)m_obuffer.data() + m_obuffer.size());
+ }
+ bool encodeOutputBuffer(const std::wstring wbuffer, std::string& buffer)
+ {
+ if (wbuffer.size() == 0) {
+ buffer = std::string();
+ return true;
+ }
+ const int length =
+ WideCharToMultiByte(m_activeOutputCodepage, 0, wbuffer.c_str(),
+ (int)wbuffer.size(), NULL, 0, NULL, NULL);
+ char* buf = new char[length + 1];
+ const bool success =
+ WideCharToMultiByte(m_activeOutputCodepage, 0, wbuffer.c_str(),
+ (int)wbuffer.size(), buf, length, NULL, NULL) > 0
+ ? true
+ : false;
+ buf[length] = '\0';
+ buffer = buf;
+ delete[] buf;
+ return success;
+ }
+ bool decodeInputBuffer(const std::string buffer, std::wstring& wbuffer)
+ {
+ int length = int(buffer.length());
+ if (length == 0) {
+ wbuffer = std::wstring();
+ return true;
+ }
+ int actualCodepage = m_activeInputCodepage;
+ const char BOM_UTF8[] = { char(0xEF), char(0xBB), char(0xBF) };
+ const char* data = buffer.data();
+ const size_t BOMsize = sizeof(BOM_UTF8);
+ if (length >= BOMsize && std::memcmp(data, BOM_UTF8, BOMsize) == 0) {
+ // PowerShell uses UTF-8 with BOM for pipes
+ actualCodepage = CP_UTF8;
+ data += BOMsize;
+ length -= BOMsize;
+ }
+ const int wlength =
+ MultiByteToWideChar(actualCodepage, 0, data, length, NULL, 0);
+ wchar_t* wbuf = new wchar_t[wlength];
+ const bool success =
+ MultiByteToWideChar(actualCodepage, 0, data, length, wbuf, wlength) > 0
+ ? true
+ : false;
+ wbuffer = std::wstring(wbuf, wlength);
+ delete[] wbuf;
+ return success;
+ }
+ std::wstring getBuffer(const std::basic_string<char> buffer)
+ {
+ return Encoding::ToWide(buffer);
+ }
+ std::wstring getBuffer(const std::basic_string<wchar_t> buffer)
+ {
+ return buffer;
+ }
+ void setBuffer(const std::wstring wbuffer, std::basic_string<char>& target)
+ {
+ target = Encoding::ToNarrow(wbuffer);
+ }
+ void setBuffer(const std::wstring wbuffer,
+ std::basic_string<wchar_t>& target)
+ {
+ target = wbuffer;
+ }
- }; // BasicConsoleBuf class
+}; // BasicConsoleBuf class
- typedef BasicConsoleBuf<char> ConsoleBuf;
- typedef BasicConsoleBuf<wchar_t> WConsoleBuf;
+typedef BasicConsoleBuf<char> ConsoleBuf;
+typedef BasicConsoleBuf<wchar_t> WConsoleBuf;
#endif
} // KWSYS_NAMESPACE
diff --git a/Source/kwsys/Copyright.txt b/Source/kwsys/Copyright.txt
index 1549a7d..33d7fb4 100644
--- a/Source/kwsys/Copyright.txt
+++ b/Source/kwsys/Copyright.txt
@@ -1,5 +1,5 @@
KWSys - Kitware System Library
-Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+Copyright 2000-2016 Kitware, Inc. and Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -13,10 +13,9 @@ are met:
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
-* Neither the names of Kitware, Inc., the Insight Software Consortium,
- nor the names of their contributors may be used to endorse or promote
- products derived from this software without specific prior written
- permission.
+* Neither the name of Kitware, Inc. nor the names of Contributors
+ may be used to endorse or promote products derived from this
+ software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -29,3 +28,11 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+
+The following individuals and institutions are among the Contributors:
+
+* Insight Software Consortium <insightsoftwareconsortium.org>
+
+See version control history for details of individual contributions.
diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx
index 15480e1..3c31b49 100644
--- a/Source/kwsys/Directory.cxx
+++ b/Source/kwsys/Directory.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Directory.hxx)
@@ -19,16 +10,15 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Directory.hxx.in"
-# include "Configure.hxx.in"
-# include "Encoding.hxx.in"
+#include "Configure.hxx.in"
+#include "Directory.hxx.in"
+#include "Encoding.hxx.in"
#endif
#include <string>
#include <vector>
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
class DirectoryInternals
@@ -62,10 +52,9 @@ unsigned long Directory::GetNumberOfFiles() const
//----------------------------------------------------------------------------
const char* Directory::GetFile(unsigned long dindex) const
{
- if ( dindex >= this->Internal->Files.size() )
- {
+ if (dindex >= this->Internal->Files.size()) {
return 0;
- }
+ }
return this->Internal->Files[dindex].c_str();
}
@@ -88,9 +77,10 @@ void Directory::Clear()
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <windows.h>
-#include <io.h>
+
#include <ctype.h>
#include <fcntl.h>
+#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -99,15 +89,14 @@ void Directory::Clear()
// Wide function names can vary depending on compiler:
#ifdef __BORLANDC__
-# define _wfindfirst_func __wfindfirst
-# define _wfindnext_func __wfindnext
+#define _wfindfirst_func __wfindfirst
+#define _wfindnext_func __wfindnext
#else
-# define _wfindfirst_func _wfindfirst
-# define _wfindnext_func _wfindnext
+#define _wfindfirst_func _wfindfirst
+#define _wfindnext_func _wfindnext
#endif
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
bool Directory::Load(const std::string& name)
{
@@ -120,42 +109,34 @@ bool Directory::Load(const std::string& name)
#endif
char* buf;
size_t n = name.size();
- if ( *name.rbegin() == '/' || *name.rbegin() == '\\' )
- {
+ if (*name.rbegin() == '/' || *name.rbegin() == '\\') {
buf = new char[n + 1 + 1];
sprintf(buf, "%s*", name.c_str());
- }
- else
- {
+ } else {
// Make sure the slashes in the wildcard suffix are consistent with the
// rest of the path
buf = new char[n + 2 + 1];
- if ( name.find('\\') != name.npos )
- {
+ if (name.find('\\') != name.npos) {
sprintf(buf, "%s\\*", name.c_str());
- }
- else
- {
+ } else {
sprintf(buf, "%s/*", name.c_str());
- }
}
- struct _wfinddata_t data; // data of current file
+ }
+ struct _wfinddata_t data; // data of current file
// Now put them into the file array
- srchHandle = _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
- delete [] buf;
+ srchHandle =
+ _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+ delete[] buf;
- if ( srchHandle == -1 )
- {
+ if (srchHandle == -1) {
return 0;
- }
+ }
// Loop through names
- do
- {
+ do {
this->Internal->Files.push_back(Encoding::ToNarrow(data.name));
- }
- while ( _wfindnext_func(srchHandle, &data) != -1 );
+ } while (_wfindnext_func(srchHandle, &data) != -1);
this->Internal->Path = name;
return _findclose(srchHandle) != -1;
}
@@ -170,34 +151,29 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
#endif
char* buf;
size_t n = name.size();
- if ( *name.rbegin() == '/' )
- {
+ if (*name.rbegin() == '/') {
buf = new char[n + 1 + 1];
sprintf(buf, "%s*", name.c_str());
- }
- else
- {
+ } else {
buf = new char[n + 2 + 1];
sprintf(buf, "%s/*", name.c_str());
- }
- struct _wfinddata_t data; // data of current file
+ }
+ struct _wfinddata_t data; // data of current file
// Now put them into the file array
- srchHandle = _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
- delete [] buf;
+ srchHandle =
+ _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+ delete[] buf;
- if ( srchHandle == -1 )
- {
+ if (srchHandle == -1) {
return 0;
- }
+ }
// Loop through names
unsigned long count = 0;
- do
- {
+ do {
count++;
- }
- while ( _wfindnext_func(srchHandle, &data) != -1 );
+ } while (_wfindnext_func(srchHandle, &data) != -1);
_findclose(srchHandle);
return count;
}
@@ -209,6 +185,7 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
// Now the POSIX style directory access
#include <sys/types.h>
+
#include <dirent.h>
// PGI with glibc has trouble with dirent and large file support:
@@ -216,33 +193,30 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
// p=1992&sid=f16167f51964f1a68fe5041b8eb213b6
// Work around the problem by mapping dirent the same way as readdir.
#if defined(__PGI) && defined(__GLIBC__)
-# define kwsys_dirent_readdir dirent
-# define kwsys_dirent_readdir64 dirent64
-# define kwsys_dirent kwsys_dirent_lookup(readdir)
-# define kwsys_dirent_lookup(x) kwsys_dirent_lookup_delay(x)
-# define kwsys_dirent_lookup_delay(x) kwsys_dirent_##x
+#define kwsys_dirent_readdir dirent
+#define kwsys_dirent_readdir64 dirent64
+#define kwsys_dirent kwsys_dirent_lookup(readdir)
+#define kwsys_dirent_lookup(x) kwsys_dirent_lookup_delay(x)
+#define kwsys_dirent_lookup_delay(x) kwsys_dirent_##x
#else
-# define kwsys_dirent dirent
+#define kwsys_dirent dirent
#endif
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
bool Directory::Load(const std::string& name)
{
this->Clear();
-
+
DIR* dir = opendir(name.c_str());
- if (!dir)
- {
+ if (!dir) {
return 0;
- }
+ }
- for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir) )
- {
+ for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) {
this->Internal->Files.push_back(d->d_name);
- }
+ }
this->Internal->Path = name;
closedir(dir);
return 1;
@@ -252,16 +226,14 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
{
DIR* dir = opendir(name.c_str());
- if (!dir)
- {
+ if (!dir) {
return 0;
- }
+ }
unsigned long count = 0;
- for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir) )
- {
+ for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) {
count++;
- }
+ }
closedir(dir);
return count;
}
diff --git a/Source/kwsys/Directory.hxx.in b/Source/kwsys/Directory.hxx.in
index e68f337..ad8c51b 100644
--- a/Source/kwsys/Directory.hxx.in
+++ b/Source/kwsys/Directory.hxx.in
@@ -1,22 +1,13 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Directory_hxx
#define @KWSYS_NAMESPACE@_Directory_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
+
#include <string>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
class DirectoryInternals;
@@ -72,9 +63,9 @@ private:
// Private implementation details.
DirectoryInternals* Internal;
- Directory(const Directory&); // Not implemented.
- void operator=(const Directory&); // Not implemented.
-}; // End Class: Directory
+ Directory(const Directory&); // Not implemented.
+ void operator=(const Directory&); // Not implemented.
+}; // End Class: Directory
} // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/DynamicLoader.cxx b/Source/kwsys/DynamicLoader.cxx
index 1941d96..e0268c0 100644
--- a/Source/kwsys/DynamicLoader.cxx
+++ b/Source/kwsys/DynamicLoader.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
@@ -17,8 +8,8 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "DynamicLoader.hxx.in"
-# include "Configure.hxx.in"
+#include "Configure.hxx.in"
+#include "DynamicLoader.hxx.in"
#endif
// This file is actually 3 different implementations.
@@ -32,15 +23,15 @@
// ---------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
-#include <errno.h>
#include <dl.h>
+#include <errno.h>
#define DYNAMICLOADER_DEFINED 1
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
return shl_load(libname.c_str(), BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
@@ -48,25 +39,25 @@ DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libna
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
- if (!lib)
- {
+ if (!lib) {
return 0;
- }
+ }
return !shl_unload(lib);
}
//----------------------------------------------------------------------------
-DynamicLoader::SymbolPointer
-DynamicLoader::GetSymbolAddress(DynamicLoader::LibraryHandle lib, const std::string& sym)
+DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
+ DynamicLoader::LibraryHandle lib, const std::string& sym)
{
void* addr;
int status;
/* TYPE_PROCEDURE Look for a function or procedure. (This used to be default)
- * TYPE_DATA Look for a symbol in the data segment (for example, variables).
+ * TYPE_DATA Look for a symbol in the data segment (for example,
+ * variables).
* TYPE_UNDEFINED Look for any symbol.
*/
- status = shl_findsym (&lib, sym.c_str(), TYPE_UNDEFINED, &addr);
+ status = shl_findsym(&lib, sym.c_str(), TYPE_UNDEFINED, &addr);
void* result = (status < 0) ? (void*)0 : addr;
// Hack to cast pointer-to-data to pointer-to-function.
@@ -88,12 +79,9 @@ const char* DynamicLoader::LastError()
* The specified handle is invalid.
*/
- if( errno == ENOEXEC
- || errno == ENOSYM
- || errno == EINVAL )
- {
+ if (errno == ENOEXEC || errno == ENOSYM || errno == EINVAL) {
return strerror(errno);
- }
+ }
// else
return 0;
}
@@ -102,38 +90,37 @@ const char* DynamicLoader::LastError()
#endif //__hpux
-
// ---------------------------------------------------------------
// 2. Implementation for Mac OS X 10.2.x and earlier
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
-#include <string.h> // for strlen
#include <mach-o/dyld.h>
+#include <string.h> // for strlen
#define DYNAMICLOADER_DEFINED 1
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
NSObjectFileImageReturnCode rc;
NSObjectFileImage image = 0;
rc = NSCreateObjectFileImageFromFile(libname.c_str(), &image);
// rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
- if( rc != NSObjectFileImageSuccess )
- {
+ if (rc != NSObjectFileImageSuccess) {
return 0;
- }
- NSModule handle = NSLinkModule(image, libname.c_str(),
- NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
+ }
+ NSModule handle =
+ NSLinkModule(image, libname.c_str(), NSLINKMODULE_OPTION_BINDNOW |
+ NSLINKMODULE_OPTION_RETURN_ON_ERROR);
NSDestroyObjectFileImage(image);
return handle;
}
//----------------------------------------------------------------------------
-int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
+int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
// NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
// With this option the memory for the module is not deallocated
@@ -148,18 +135,17 @@ int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const std::string& sym)
{
- void *result=0;
+ void* result = 0;
// Need to prepend symbols with '_' on Apple-gcc compilers
size_t len = sym.size();
- char *rsym = new char[len + 1 + 1];
+ char* rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
- strcat(rsym+1, sym.c_str());
+ strcat(rsym + 1, sym.c_str());
NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
- if(symbol)
- {
+ if (symbol) {
result = NSAddressOfSymbol(symbol);
- }
+ }
delete[] rsym;
// Hack to cast pointer-to-data to pointer-to-function.
@@ -183,19 +169,19 @@ const char* DynamicLoader::LastError()
#include <windows.h>
#define DYNAMICLOADER_DEFINED 1
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname)
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
DynamicLoader::LibraryHandle lh;
int length = MultiByteToWideChar(CP_UTF8, 0, libname.c_str(), -1, NULL, 0);
- wchar_t* wchars = new wchar_t[length+1];
+ wchar_t* wchars = new wchar_t[length + 1];
wchars[0] = '\0';
MultiByteToWideChar(CP_UTF8, 0, libname.c_str(), -1, wchars, length);
lh = LoadLibraryW(wchars);
- delete [] wchars;
+ delete[] wchars;
return lh;
}
@@ -231,21 +217,21 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
//
// Note that the "@X" part of the name above is the total size (in
// bytes) of the arguments on the stack.
- void *result;
+ void* result;
#if defined(__BORLANDC__) || defined(__WATCOMC__)
// Need to prepend symbols with '_'
size_t len = sym.size();
- char *rsym = new char[len + 1 + 1];
+ char* rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym, sym.c_str());
#else
- const char *rsym = sym.c_str();
+ const char* rsym = sym.c_str();
#endif
result = (void*)GetProcAddress(lib, rsym);
#if defined(__BORLANDC__) || defined(__WATCOMC__)
delete[] rsym;
#endif
- // Hack to cast pointer-to-data to pointer-to-function.
+// Hack to cast pointer-to-data to pointer-to-function.
#ifdef __WATCOMC__
return *(DynamicLoader::SymbolPointer*)(&result);
#else
@@ -256,28 +242,22 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
- LPVOID lpMsgBuf=NULL;
-
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- GetLastError(),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL
- );
-
- if(!lpMsgBuf)
- {
+ LPVOID lpMsgBuf = NULL;
+
+ FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL, GetLastError(),
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
+ (LPTSTR)&lpMsgBuf, 0, NULL);
+
+ if (!lpMsgBuf) {
return NULL;
- }
+ }
static char* str = 0;
- delete [] str;
- str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
+ delete[] str;
+ str = strcpy(new char[strlen((char*)lpMsgBuf) + 1], (char*)lpMsgBuf);
// Free the buffer.
- LocalFree( lpMsgBuf );
+ LocalFree(lpMsgBuf);
return str;
}
@@ -296,44 +276,39 @@ const char* DynamicLoader::LastError()
#define DYNAMICLOADER_DEFINED 1
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
static image_id last_dynamic_err = B_OK;
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
// image_id's are integers, errors are negative. Add one just in case we
// get a valid image_id of zero (is that even possible?).
image_id rc = load_add_on(libname.c_str());
- if (rc < 0)
- {
+ if (rc < 0) {
last_dynamic_err = rc;
return 0;
- }
+ }
- return rc+1;
+ return rc + 1;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
- if (!lib)
- {
- last_dynamic_err = B_BAD_VALUE;
- return 0;
- }
- else
- {
+ if (!lib) {
+ last_dynamic_err = B_BAD_VALUE;
+ return 0;
+ } else {
// The function dlclose() returns 0 on success, and non-zero on error.
- status_t rc = unload_add_on(lib-1);
- if (rc != B_OK)
- {
+ status_t rc = unload_add_on(lib - 1);
+ if (rc != B_OK) {
last_dynamic_err = rc;
return 0;
- }
}
+ }
return 1;
}
@@ -343,7 +318,7 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const std::string& sym)
{
// Hack to cast pointer-to-data to pointer-to-function.
- union
+ union
{
void* pvoid;
DynamicLoader::SymbolPointer psym;
@@ -351,29 +326,26 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
result.psym = NULL;
- if (!lib)
- {
- last_dynamic_err = B_BAD_VALUE;
- }
- else
- {
+ if (!lib) {
+ last_dynamic_err = B_BAD_VALUE;
+ } else {
// !!! FIXME: BeOS can do function-only lookups...does this ever
// !!! FIXME: actually _want_ a data symbol lookup, or was this union
// !!! FIXME: a leftover of dlsym()? (s/ANY/TEXT for functions only).
- status_t rc = get_image_symbol(lib-1,sym.c_str(),B_SYMBOL_TYPE_ANY,&result.pvoid);
- if (rc != B_OK)
- {
+ status_t rc =
+ get_image_symbol(lib - 1, sym.c_str(), B_SYMBOL_TYPE_ANY, &result.pvoid);
+ if (rc != B_OK) {
last_dynamic_err = rc;
result.psym = NULL;
- }
}
+ }
return result.psym;
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
- const char *retval = strerror(last_dynamic_err);
+ const char* retval = strerror(last_dynamic_err);
last_dynamic_err = B_OK;
return retval;
}
@@ -385,15 +357,16 @@ const char* DynamicLoader::LastError()
// 5. Implementation for systems without dynamic libs
// __gnu_blrts__ is IBM BlueGene/L
// __LIBCATAMOUNT__ is defined on Catamount on Cray compute nodes
-#if defined(__gnu_blrts__) || defined(__LIBCATAMOUNT__) || defined(__CRAYXT_COMPUTE_LINUX_TARGET)
+#if defined(__gnu_blrts__) || defined(__LIBCATAMOUNT__) || \
+ defined(__CRAYXT_COMPUTE_LINUX_TARGET)
#include <string.h> // for strerror()
#define DYNAMICLOADER_DEFINED 1
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
return 0;
}
@@ -401,26 +374,25 @@ DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libna
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
- if (!lib)
- {
+ if (!lib) {
return 0;
- }
+ }
return 1;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
- DynamicLoader::LibraryHandle lib, const std::string& sym)
+ DynamicLoader::LibraryHandle lib, const std::string& sym)
{
return 0;
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
- {
+{
return "General error";
- }
+}
} // namespace KWSYS_NAMESPACE
#endif
@@ -428,28 +400,28 @@ const char* DynamicLoader::LastError()
#ifdef __MINT__
#define DYNAMICLOADER_DEFINED 1
#define _GNU_SOURCE /* for program_invocation_name */
-#include <string.h>
-#include <malloc.h>
-#include <errno.h>
#include <dld.h>
+#include <errno.h>
+#include <malloc.h>
+#include <string.h>
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
- char *name = (char *)calloc(1, libname.size() + 1);
+ char* name = (char*)calloc(1, libname.size() + 1);
dld_init(program_invocation_name);
strncpy(name, libname.c_str(), libname.size());
dld_link(libname.c_str());
- return (void *)name;
+ return (void*)name;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
- dld_unlink_by_file((char *)lib, 0);
+ dld_unlink_by_file((char*)lib, 0);
free(lib);
return 0;
}
@@ -485,11 +457,11 @@ const char* DynamicLoader::LastError()
// Setup for most unix machines
#include <dlfcn.h>
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+ const std::string& libname)
{
return dlopen(libname.c_str(), RTLD_LAZY);
}
@@ -497,11 +469,10 @@ DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libna
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
- if (lib)
- {
+ if (lib) {
// The function dlclose() returns 0 on success, and non-zero on error.
return !dlclose(lib);
- }
+ }
// else
return 0;
}
@@ -511,7 +482,7 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const std::string& sym)
{
// Hack to cast pointer-to-data to pointer-to-function.
- union
+ union
{
void* pvoid;
DynamicLoader::SymbolPointer psym;
diff --git a/Source/kwsys/DynamicLoader.hxx.in b/Source/kwsys/DynamicLoader.hxx.in
index 1e4a912..7e71a45 100644
--- a/Source/kwsys/DynamicLoader.hxx.in
+++ b/Source/kwsys/DynamicLoader.hxx.in
@@ -1,35 +1,26 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_DynamicLoader_hxx
#define @KWSYS_NAMESPACE@_DynamicLoader_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
+
#include <string>
#if defined(__hpux)
- #include <dl.h>
+#include <dl.h>
#elif defined(_WIN32) && !defined(__CYGWIN__)
- #include <windows.h>
+#include <windows.h>
#elif defined(__APPLE__)
- #include <AvailabilityMacros.h>
- #if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
- #include <mach-o/dyld.h>
- #endif
+#include <AvailabilityMacros.h>
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
+#include <mach-o/dyld.h>
+#endif
#elif defined(__BEOS__)
- #include <be/kernel/image.h>
+#include <be/kernel/image.h>
#endif
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
/** \class DynamicLoader
* \brief Portable loading of dynamic libraries or dll's.
*
@@ -61,14 +52,14 @@ public:
#elif defined(_WIN32) && !defined(__CYGWIN__)
typedef HMODULE LibraryHandle;
#elif defined(__APPLE__)
- #if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
- typedef NSModule LibraryHandle;
- #else
- typedef void* LibraryHandle;
- #endif
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
+ typedef NSModule LibraryHandle;
+#else
+ typedef void* LibraryHandle;
+#endif
#elif defined(__BEOS__)
typedef image_id LibraryHandle;
-#else // POSIX
+#else // POSIX
typedef void* LibraryHandle;
#endif
diff --git a/Source/kwsys/Encoding.h.in b/Source/kwsys/Encoding.h.in
index 591c5a8..7b6ed10 100644
--- a/Source/kwsys/Encoding.h.in
+++ b/Source/kwsys/Encoding.h.in
@@ -1,18 +1,10 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Encoding_h
#define @KWSYS_NAMESPACE@_Encoding_h
#include <@KWSYS_NAMESPACE@/Configure.h>
+
#include <wchar.h>
/* Redefine all public interface symbol names to be in the proper
@@ -20,44 +12,42 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysEncoding kwsys_ns(Encoding)
-# define kwsysEncoding_mbstowcs kwsys_ns(Encoding_mbstowcs)
-# define kwsysEncoding_DupToWide kwsys_ns(Encoding_DupToWide)
-# define kwsysEncoding_wcstombs kwsys_ns(Encoding_wcstombs)
-# define kwsysEncoding_DupToNarrow kwsys_ns(Encoding_DupToNarrow)
+#define kwsysEncoding kwsys_ns(Encoding)
+#define kwsysEncoding_mbstowcs kwsys_ns(Encoding_mbstowcs)
+#define kwsysEncoding_DupToWide kwsys_ns(Encoding_DupToWide)
+#define kwsysEncoding_wcstombs kwsys_ns(Encoding_wcstombs)
+#define kwsysEncoding_DupToNarrow kwsys_ns(Encoding_DupToNarrow)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
-
/* Convert a narrow string to a wide string.
On Windows, UTF-8 is assumed, and on other platforms,
the current locale is assumed.
*/
-kwsysEXPORT size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* src, size_t n);
+kwsysEXPORT size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* src,
+ size_t n);
/* Convert a narrow string to a wide string.
This can return NULL if the conversion fails. */
kwsysEXPORT wchar_t* kwsysEncoding_DupToWide(const char* src);
-
/* Convert a wide string to a narrow string.
On Windows, UTF-8 is assumed, and on other platforms,
the current locale is assumed. */
-kwsysEXPORT size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* src, size_t n);
+kwsysEXPORT size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* src,
+ size_t n);
/* Convert a wide string to a narrow string.
This can return NULL if the conversion fails. */
kwsysEXPORT char* kwsysEncoding_DupToNarrow(const wchar_t* str);
-
#if defined(__cplusplus)
} /* extern "C" */
#endif
@@ -65,15 +55,15 @@ kwsysEXPORT char* kwsysEncoding_DupToNarrow(const wchar_t* str);
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysEncoding
-# undef kwsysEncoding_mbstowcs
-# undef kwsysEncoding_DupToWide
-# undef kwsysEncoding_wcstombs
-# undef kwsysEncoding_DupToNarrow
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysEncoding
+#undef kwsysEncoding_mbstowcs
+#undef kwsysEncoding_DupToWide
+#undef kwsysEncoding_wcstombs
+#undef kwsysEncoding_DupToNarrow
+#endif
#endif
#endif
diff --git a/Source/kwsys/Encoding.hxx.in b/Source/kwsys/Encoding.hxx.in
index 87b1c21..6639efd 100644
--- a/Source/kwsys/Encoding.hxx.in
+++ b/Source/kwsys/Encoding.hxx.in
@@ -1,59 +1,49 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Encoding_hxx
#define @KWSYS_NAMESPACE@_Encoding_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
+
#include <string>
#include <vector>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
class @KWSYS_NAMESPACE@_EXPORT Encoding
{
public:
-
// Container class for argc/argv.
class CommandLineArguments
{
- public:
- // On Windows, get the program command line arguments
- // in this Encoding module's 8 bit encoding.
- // On other platforms the given argc/argv is used, and
- // to be consistent, should be the argc/argv from main().
- static CommandLineArguments Main(int argc, char const* const* argv);
-
- // Construct CommandLineArguments with the given
- // argc/argv. It is assumed that the string is already
- // in the encoding used by this module.
- CommandLineArguments(int argc, char const* const* argv);
-
- // Construct CommandLineArguments with the given
- // argc and wide argv. This is useful if wmain() is used.
- CommandLineArguments(int argc, wchar_t const* const* argv);
- ~CommandLineArguments();
- CommandLineArguments(const CommandLineArguments&);
- CommandLineArguments& operator=(const CommandLineArguments&);
-
- int argc() const;
- char const* const* argv() const;
-
- protected:
- std::vector<char*> argv_;
+ public:
+ // On Windows, get the program command line arguments
+ // in this Encoding module's 8 bit encoding.
+ // On other platforms the given argc/argv is used, and
+ // to be consistent, should be the argc/argv from main().
+ static CommandLineArguments Main(int argc, char const* const* argv);
+
+ // Construct CommandLineArguments with the given
+ // argc/argv. It is assumed that the string is already
+ // in the encoding used by this module.
+ CommandLineArguments(int argc, char const* const* argv);
+
+ // Construct CommandLineArguments with the given
+ // argc and wide argv. This is useful if wmain() is used.
+ CommandLineArguments(int argc, wchar_t const* const* argv);
+ ~CommandLineArguments();
+ CommandLineArguments(const CommandLineArguments&);
+ CommandLineArguments& operator=(const CommandLineArguments&);
+
+ int argc() const;
+ char const* const* argv() const;
+
+ protected:
+ std::vector<char*> argv_;
};
- /**
- * Convert between char and wchar_t
- */
+/**
+ * Convert between char and wchar_t
+ */
#if @KWSYS_NAMESPACE@_STL_HAS_WSTRING
diff --git a/Source/kwsys/EncodingC.c b/Source/kwsys/EncodingC.c
index 32b9bff..c1315b2 100644
--- a/Source/kwsys/EncodingC.c
+++ b/Source/kwsys/EncodingC.c
@@ -1,21 +1,12 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Encoding.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Encoding.h.in"
+#include "Encoding.h.in"
#endif
#include <stdlib.h>
@@ -26,13 +17,13 @@
size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* str, size_t n)
{
- if(str == 0)
- {
+ if (str == 0) {
return (size_t)-1;
- }
+ }
#ifdef _WIN32
- return MultiByteToWideChar(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0,
- str, -1, dest, (int)n) - 1;
+ return MultiByteToWideChar(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1, dest,
+ (int)n) -
+ 1;
#else
return mbstowcs(dest, str, n);
#endif
@@ -42,27 +33,25 @@ wchar_t* kwsysEncoding_DupToWide(const char* str)
{
wchar_t* ret = NULL;
size_t length = kwsysEncoding_mbstowcs(NULL, str, 0) + 1;
- if(length > 0)
- {
- ret = (wchar_t*)malloc((length)*sizeof(wchar_t));
- if(ret)
- {
+ if (length > 0) {
+ ret = (wchar_t*)malloc((length) * sizeof(wchar_t));
+ if (ret) {
ret[0] = 0;
kwsysEncoding_mbstowcs(ret, str, length);
- }
}
+ }
return ret;
}
size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* str, size_t n)
{
- if(str == 0)
- {
+ if (str == 0) {
return (size_t)-1;
- }
+ }
#ifdef _WIN32
- return WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1,
- dest, (int)n, NULL, NULL) - 1;
+ return WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1, dest,
+ (int)n, NULL, NULL) -
+ 1;
#else
return wcstombs(dest, str, n);
#endif
@@ -72,14 +61,12 @@ char* kwsysEncoding_DupToNarrow(const wchar_t* str)
{
char* ret = NULL;
size_t length = kwsysEncoding_wcstombs(0, str, 0) + 1;
- if(length > 0)
- {
+ if (length > 0) {
ret = (char*)malloc(length);
- if(ret)
- {
+ if (ret) {
ret[0] = 0;
kwsysEncoding_wcstombs(ret, str, length);
- }
}
+ }
return ret;
}
diff --git a/Source/kwsys/EncodingCXX.cxx b/Source/kwsys/EncodingCXX.cxx
index 597d4bd..5c58bcb 100644
--- a/Source/kwsys/EncodingCXX.cxx
+++ b/Source/kwsys/EncodingCXX.cxx
@@ -1,19 +1,9 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifdef __osf__
-# define _OSF_SOURCE
-# define _POSIX_C_SOURCE 199506L
-# define _XOPEN_SOURCE_EXTENDED
+#define _OSF_SOURCE
+#define _POSIX_C_SOURCE 199506L
+#define _XOPEN_SOURCE_EXTENDED
#endif
#include "kwsysPrivate.h"
@@ -23,44 +13,43 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Encoding.hxx.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Encoding.hxx.in"
#endif
-#include <vector>
#include <stdlib.h>
#include <string.h>
+#include <vector>
#ifdef _MSC_VER
-# pragma warning (disable: 4786)
+#pragma warning(disable : 4786)
#endif
// Windows API.
#if defined(_WIN32)
-# include <windows.h>
-# include <shellapi.h>
+#include <windows.h>
+
+#include <shellapi.h>
#endif
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
-Encoding::CommandLineArguments
-Encoding::CommandLineArguments::Main(int argc, char const* const* argv)
+Encoding::CommandLineArguments Encoding::CommandLineArguments::Main(
+ int argc, char const* const* argv)
{
#ifdef _WIN32
- (void) argc;
- (void) argv;
+ (void)argc;
+ (void)argv;
int ac;
LPWSTR* w_av = CommandLineToArgvW(GetCommandLineW(), &ac);
std::vector<std::string> av1(ac);
std::vector<char const*> av2(ac);
- for(int i=0; i<ac; i++)
- {
+ for (int i = 0; i < ac; i++) {
av1[i] = ToNarrow(w_av[i]);
av2[i] = av1[i].c_str();
- }
+ }
LocalFree(w_av);
return CommandLineArguments(ac, &av2[0]);
#else
@@ -71,60 +60,53 @@ Encoding::CommandLineArguments::Main(int argc, char const* const* argv)
Encoding::CommandLineArguments::CommandLineArguments(int ac,
char const* const* av)
{
- this->argv_.resize(ac+1);
- for(int i=0; i<ac; i++)
- {
+ this->argv_.resize(ac + 1);
+ for (int i = 0; i < ac; i++) {
this->argv_[i] = strdup(av[i]);
- }
+ }
this->argv_[ac] = 0;
}
Encoding::CommandLineArguments::CommandLineArguments(int ac,
wchar_t const* const* av)
{
- this->argv_.resize(ac+1);
- for(int i=0; i<ac; i++)
- {
+ this->argv_.resize(ac + 1);
+ for (int i = 0; i < ac; i++) {
this->argv_[i] = kwsysEncoding_DupToNarrow(av[i]);
- }
+ }
this->argv_[ac] = 0;
}
Encoding::CommandLineArguments::~CommandLineArguments()
{
- for(size_t i=0; i<this->argv_.size(); i++)
- {
+ for (size_t i = 0; i < this->argv_.size(); i++) {
free(argv_[i]);
- }
+ }
}
-Encoding::CommandLineArguments::
- CommandLineArguments(const CommandLineArguments& other)
+Encoding::CommandLineArguments::CommandLineArguments(
+ const CommandLineArguments& other)
{
this->argv_.resize(other.argv_.size());
- for(size_t i=0; i<this->argv_.size(); i++)
- {
+ for (size_t i = 0; i < this->argv_.size(); i++) {
this->argv_[i] = other.argv_[i] ? strdup(other.argv_[i]) : 0;
- }
+ }
}
-Encoding::CommandLineArguments&
-Encoding::CommandLineArguments::operator=(const CommandLineArguments& other)
+Encoding::CommandLineArguments& Encoding::CommandLineArguments::operator=(
+ const CommandLineArguments& other)
{
- if(this != &other)
- {
+ if (this != &other) {
size_t i;
- for(i=0; i<this->argv_.size(); i++)
- {
+ for (i = 0; i < this->argv_.size(); i++) {
free(this->argv_[i]);
- }
+ }
this->argv_.resize(other.argv_.size());
- for(i=0; i<this->argv_.size(); i++)
- {
+ for (i = 0; i < this->argv_.size(); i++) {
this->argv_[i] = other.argv_[i] ? strdup(other.argv_[i]) : 0;
- }
}
+ }
return *this;
}
@@ -155,14 +137,12 @@ std::wstring Encoding::ToWide(const char* cstr)
{
std::wstring wstr;
size_t length = kwsysEncoding_mbstowcs(0, cstr, 0) + 1;
- if(length > 0)
- {
+ if (length > 0) {
std::vector<wchar_t> wchars(length);
- if(kwsysEncoding_mbstowcs(&wchars[0], cstr, length) > 0)
- {
+ if (kwsysEncoding_mbstowcs(&wchars[0], cstr, length) > 0) {
wstr = &wchars[0];
- }
}
+ }
return wstr;
}
@@ -170,14 +150,12 @@ std::string Encoding::ToNarrow(const wchar_t* wcstr)
{
std::string str;
size_t length = kwsysEncoding_wcstombs(0, wcstr, 0) + 1;
- if(length > 0)
- {
+ if (length > 0) {
std::vector<char> chars(length);
- if(kwsysEncoding_wcstombs(&chars[0], wcstr, length) > 0)
- {
+ if (kwsysEncoding_wcstombs(&chars[0], wcstr, length) > 0) {
str = &chars[0];
- }
}
+ }
return str;
}
#endif // KWSYS_STL_HAS_WSTRING
diff --git a/Source/kwsys/FStream.cxx b/Source/kwsys/FStream.cxx
index 5a30997..3c44a6f 100644
--- a/Source/kwsys/FStream.cxx
+++ b/Source/kwsys/FStream.cxx
@@ -1,78 +1,55 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(FStream.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "FStream.hxx.in"
+#include "FStream.hxx.in"
#endif
-namespace KWSYS_NAMESPACE
-{
-namespace FStream
-{
+namespace KWSYS_NAMESPACE {
+namespace FStream {
BOM ReadBOM(std::istream& in)
{
- if(!in.good())
- {
+ if (!in.good()) {
return BOM_None;
- }
+ }
unsigned long orig = in.tellg();
unsigned char bom[4];
in.read(reinterpret_cast<char*>(bom), 2);
- if(!in.good())
- {
+ if (!in.good()) {
in.clear();
in.seekg(orig);
return BOM_None;
- }
- if(bom[0] == 0xEF && bom[1] == 0xBB)
- {
- in.read(reinterpret_cast<char*>(bom+2), 1);
- if(in.good() && bom[2] == 0xBF)
- {
+ }
+ if (bom[0] == 0xEF && bom[1] == 0xBB) {
+ in.read(reinterpret_cast<char*>(bom + 2), 1);
+ if (in.good() && bom[2] == 0xBF) {
return BOM_UTF8;
- }
}
- else if(bom[0] == 0xFE && bom[1] == 0xFF)
- {
+ } else if (bom[0] == 0xFE && bom[1] == 0xFF) {
return BOM_UTF16BE;
- }
- else if(bom[0] == 0x00 && bom[1] == 0x00)
- {
- in.read(reinterpret_cast<char*>(bom+2), 2);
- if(in.good() && bom[2] == 0xFE && bom[3] == 0xFF)
- {
+ } else if (bom[0] == 0x00 && bom[1] == 0x00) {
+ in.read(reinterpret_cast<char*>(bom + 2), 2);
+ if (in.good() && bom[2] == 0xFE && bom[3] == 0xFF) {
return BOM_UTF32BE;
- }
}
- else if(bom[0] == 0xFF && bom[1] == 0xFE)
- {
+ } else if (bom[0] == 0xFF && bom[1] == 0xFE) {
unsigned long p = in.tellg();
- in.read(reinterpret_cast<char*>(bom+2), 2);
- if(in.good() && bom[2] == 0x00 && bom[3] == 0x00)
- {
+ in.read(reinterpret_cast<char*>(bom + 2), 2);
+ if (in.good() && bom[2] == 0x00 && bom[3] == 0x00) {
return BOM_UTF32LE;
- }
+ }
in.seekg(p);
return BOM_UTF16LE;
- }
+ }
in.clear();
in.seekg(orig);
return BOM_None;
}
} // FStream namespace
-} //KWSYS_NAMESPACE
+} // KWSYS_NAMESPACE
diff --git a/Source/kwsys/FStream.hxx.in b/Source/kwsys/FStream.hxx.in
index 5471247..736214f 100644
--- a/Source/kwsys/FStream.hxx.in
+++ b/Source/kwsys/FStream.hxx.in
@@ -1,288 +1,276 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_FStream_hxx
#define @KWSYS_NAMESPACE@_FStream_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
+
#include <@KWSYS_NAMESPACE@/Encoding.hxx>
+
#include <fstream>
#if defined(_WIN32)
-# if !defined(_MSC_VER) && @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H
-# include <ext/stdio_filebuf.h>
-# endif
+#if !defined(_MSC_VER) && @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H
+#include <ext/stdio_filebuf.h>
+#endif
#endif
-namespace @KWSYS_NAMESPACE@
-{
-#if defined(_WIN32) && (defined(_MSC_VER) || @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H)
-# if defined(_NOEXCEPT)
-# define @KWSYS_NAMESPACE@_FStream_NOEXCEPT _NOEXCEPT
-# else
-# define @KWSYS_NAMESPACE@_FStream_NOEXCEPT
-# endif
+namespace @KWSYS_NAMESPACE@ {
+#if defined(_WIN32) && \
+ (defined(_MSC_VER) || @KWSYS_NAMESPACE@_CXX_HAS_EXT_STDIO_FILEBUF_H)
+#if defined(_NOEXCEPT)
+#define @KWSYS_NAMESPACE@_FStream_NOEXCEPT _NOEXCEPT
+#else
+#define @KWSYS_NAMESPACE@_FStream_NOEXCEPT
+#endif
#if defined(_MSC_VER)
- template<typename CharType,typename Traits>
- class basic_filebuf : public std::basic_filebuf<CharType,Traits>
+template <typename CharType, typename Traits>
+class basic_filebuf : public std::basic_filebuf<CharType, Traits>
+{
+#if _MSC_VER >= 1400
+public:
+ typedef std::basic_filebuf<CharType, Traits> my_base_type;
+ basic_filebuf* open(char const* s, std::ios_base::openmode mode)
{
-# if _MSC_VER >= 1400
- public:
- typedef std::basic_filebuf<CharType,Traits> my_base_type;
- basic_filebuf *open(char const *s,std::ios_base::openmode mode)
- {
- const std::wstring wstr = Encoding::ToWide(s);
- return static_cast<basic_filebuf*>(
- my_base_type::open(wstr.c_str(), mode)
- );
- }
-# endif
- };
+ const std::wstring wstr = Encoding::ToWide(s);
+ return static_cast<basic_filebuf*>(my_base_type::open(wstr.c_str(), mode));
+ }
+#endif
+};
#else
- inline std::wstring getcmode(const std::ios_base::openmode mode) {
- std::wstring cmode;
- bool plus = false;
- if (mode & std::ios_base::app) {
- cmode += L"a";
- plus = mode & std::ios_base::in ? true : false;
- } else if (mode & std::ios_base::trunc ||
- (mode & std::ios_base::out && (mode & std::ios_base::in) == 0)) {
- cmode += L"w";
- plus = mode & std::ios_base::in ? true : false;
- } else {
- cmode += L"r";
- plus = mode & std::ios_base::out ? true : false;
- }
- if (plus) {
- cmode += L"+";
- }
- if (mode & std::ios_base::binary) {
- cmode += L"b";
- } else {
- cmode += L"t";
- }
- return cmode;
- };
+inline std::wstring getcmode(const std::ios_base::openmode mode)
+{
+ std::wstring cmode;
+ bool plus = false;
+ if (mode & std::ios_base::app) {
+ cmode += L"a";
+ plus = mode & std::ios_base::in ? true : false;
+ } else if (mode & std::ios_base::trunc ||
+ (mode & std::ios_base::out && (mode & std::ios_base::in) == 0)) {
+ cmode += L"w";
+ plus = mode & std::ios_base::in ? true : false;
+ } else {
+ cmode += L"r";
+ plus = mode & std::ios_base::out ? true : false;
+ }
+ if (plus) {
+ cmode += L"+";
+ }
+ if (mode & std::ios_base::binary) {
+ cmode += L"b";
+ } else {
+ cmode += L"t";
+ }
+ return cmode;
+};
#endif
- template<typename CharType,typename Traits = std::char_traits<CharType> >
- class basic_efilebuf
- {
- public:
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_efilebuf
+{
+public:
#if defined(_MSC_VER)
- typedef basic_filebuf<CharType,Traits> internal_buffer_type;
+ typedef basic_filebuf<CharType, Traits> internal_buffer_type;
#else
- typedef __gnu_cxx::stdio_filebuf<CharType,Traits> internal_buffer_type;
+ typedef __gnu_cxx::stdio_filebuf<CharType, Traits> internal_buffer_type;
#endif
- basic_efilebuf() : file_(0)
- {
- buf_ = 0;
- }
+ basic_efilebuf()
+ : file_(0)
+ {
+ buf_ = 0;
+ }
- bool _open(char const *file_name,std::ios_base::openmode mode)
- {
- if (is_open() || file_) {
- return false;
- }
+ bool _open(char const* file_name, std::ios_base::openmode mode)
+ {
+ if (is_open() || file_) {
+ return false;
+ }
#if defined(_MSC_VER)
- const bool success = buf_->open(file_name,mode) != 0;
+ const bool success = buf_->open(file_name, mode) != 0;
#else
- const std::wstring wstr = Encoding::ToWide(file_name);
- bool success = false;
- std::wstring cmode = getcmode(mode);
- file_ = _wfopen(wstr.c_str(), cmode.c_str());
- if (file_) {
- if (buf_) {
- delete buf_;
- }
- buf_ = new internal_buffer_type(file_, mode);
- success = true;
- }
-#endif
- return success;
+ const std::wstring wstr = Encoding::ToWide(file_name);
+ bool success = false;
+ std::wstring cmode = getcmode(mode);
+ file_ = _wfopen(wstr.c_str(), cmode.c_str());
+ if (file_) {
+ if (buf_) {
+ delete buf_;
}
+ buf_ = new internal_buffer_type(file_, mode);
+ success = true;
+ }
+#endif
+ return success;
+ }
- bool is_open()
- {
- if (!buf_) {
- return false;
- }
- return buf_->is_open();
- }
+ bool is_open()
+ {
+ if (!buf_) {
+ return false;
+ }
+ return buf_->is_open();
+ }
- bool is_open() const
- {
- if (!buf_) {
- return false;
- }
- return buf_->is_open();
- }
+ bool is_open() const
+ {
+ if (!buf_) {
+ return false;
+ }
+ return buf_->is_open();
+ }
- bool _close()
- {
- bool success = false;
- if (buf_) {
- success = buf_->close() != 0;
+ bool _close()
+ {
+ bool success = false;
+ if (buf_) {
+ success = buf_->close() != 0;
#if !defined(_MSC_VER)
- if (file_) {
- success = fclose(file_) == 0 ? success : false;
- file_ = 0;
- }
-#endif
- }
- return success;
+ if (file_) {
+ success = fclose(file_) == 0 ? success : false;
+ file_ = 0;
}
+#endif
+ }
+ return success;
+ }
- static void _set_state(bool success, std::basic_ios<CharType,Traits> *ios, basic_efilebuf* efilebuf)
- {
+ static void _set_state(bool success, std::basic_ios<CharType, Traits>* ios,
+ basic_efilebuf* efilebuf)
+ {
#if !defined(_MSC_VER)
- ios->rdbuf(efilebuf->buf_);
+ ios->rdbuf(efilebuf->buf_);
+#else
+ static_cast<void>(efilebuf);
#endif
- if (!success) {
- ios->setstate(std::ios_base::failbit);
- } else {
- ios->clear();
- }
- }
+ if (!success) {
+ ios->setstate(std::ios_base::failbit);
+ } else {
+ ios->clear();
+ }
+ }
- ~basic_efilebuf()
- {
- if (buf_) {
- delete buf_;
- }
- }
-
- protected:
- internal_buffer_type* buf_;
- FILE *file_;
- };
-
-template<typename CharType,typename Traits = std::char_traits<CharType> >
-class basic_ifstream : public std::basic_istream<CharType,Traits>,
- public basic_efilebuf<CharType,Traits>
+ ~basic_efilebuf()
+ {
+ if (buf_) {
+ delete buf_;
+ }
+ }
+
+protected:
+ internal_buffer_type* buf_;
+ FILE* file_;
+};
+
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_ifstream : public std::basic_istream<CharType, Traits>,
+ public basic_efilebuf<CharType, Traits>
{
- using basic_efilebuf<CharType,Traits>::is_open;
+ using basic_efilebuf<CharType, Traits>::is_open;
- public:
- typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type internal_buffer_type;
- typedef std::basic_istream<CharType,Traits> internal_stream_type;
+public:
+ typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type
+ internal_buffer_type;
+ typedef std::basic_istream<CharType, Traits> internal_stream_type;
- basic_ifstream() : internal_stream_type(new internal_buffer_type())
- {
- this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
- }
- explicit basic_ifstream(char const *file_name,
- std::ios_base::openmode mode = std::ios_base::in)
- : internal_stream_type(new internal_buffer_type())
- {
- this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
- open(file_name,mode);
- }
+ basic_ifstream()
+ : internal_stream_type(new internal_buffer_type())
+ {
+ this->buf_ =
+ static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+ }
+ explicit basic_ifstream(char const* file_name,
+ std::ios_base::openmode mode = std::ios_base::in)
+ : internal_stream_type(new internal_buffer_type())
+ {
+ this->buf_ =
+ static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+ open(file_name, mode);
+ }
- void open(char const *file_name,std::ios_base::openmode mode = std::ios_base::in)
- {
- mode = mode | std::ios_base::in;
- this->_set_state(this->_open(file_name, mode), this, this);
- }
+ void open(char const* file_name,
+ std::ios_base::openmode mode = std::ios_base::in)
+ {
+ mode = mode | std::ios_base::in;
+ this->_set_state(this->_open(file_name, mode), this, this);
+ }
- void close()
- {
- this->_set_state(this->_close(), this, this);
- }
+ void close() { this->_set_state(this->_close(), this, this); }
- internal_buffer_type *rdbuf() const
- {
- return this->buf_;
- }
+ internal_buffer_type* rdbuf() const { return this->buf_; }
- ~basic_ifstream() @KWSYS_NAMESPACE@_FStream_NOEXCEPT
- {
- close();
- }
+ ~basic_ifstream() @KWSYS_NAMESPACE@_FStream_NOEXCEPT { close(); }
};
-template<typename CharType,typename Traits = std::char_traits<CharType> >
-class basic_ofstream : public std::basic_ostream<CharType,Traits>,
- public basic_efilebuf<CharType,Traits>
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_ofstream : public std::basic_ostream<CharType, Traits>,
+ public basic_efilebuf<CharType, Traits>
{
- using basic_efilebuf<CharType,Traits>::is_open;
+ using basic_efilebuf<CharType, Traits>::is_open;
- public:
- typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type internal_buffer_type;
- typedef std::basic_ostream<CharType,Traits> internal_stream_type;
+public:
+ typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type
+ internal_buffer_type;
+ typedef std::basic_ostream<CharType, Traits> internal_stream_type;
- basic_ofstream() : internal_stream_type(new internal_buffer_type())
+ basic_ofstream()
+ : internal_stream_type(new internal_buffer_type())
{
- this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
+ this->buf_ =
+ static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
}
- explicit basic_ofstream(char const *file_name,std::ios_base::openmode mode = std::ios_base::out) :
- internal_stream_type(new internal_buffer_type())
+ explicit basic_ofstream(char const* file_name,
+ std::ios_base::openmode mode = std::ios_base::out)
+ : internal_stream_type(new internal_buffer_type())
{
- this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
- open(file_name,mode);
+ this->buf_ =
+ static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+ open(file_name, mode);
}
- void open(char const *file_name,std::ios_base::openmode mode = std::ios_base::out)
+ void open(char const* file_name,
+ std::ios_base::openmode mode = std::ios_base::out)
{
mode = mode | std::ios_base::out;
this->_set_state(this->_open(file_name, mode), this, this);
}
- void close()
- {
- this->_set_state(this->_close(), this, this);
- }
+ void close() { this->_set_state(this->_close(), this, this); }
- internal_buffer_type *rdbuf() const
- {
- return this->buf_;
- }
+ internal_buffer_type* rdbuf() const { return this->buf_; }
- ~basic_ofstream() @KWSYS_NAMESPACE@_FStream_NOEXCEPT
- {
- close();
- }
+ ~basic_ofstream() @KWSYS_NAMESPACE@_FStream_NOEXCEPT { close(); }
};
- typedef basic_ifstream<char> ifstream;
- typedef basic_ofstream<char> ofstream;
+typedef basic_ifstream<char> ifstream;
+typedef basic_ofstream<char> ofstream;
-# undef @KWSYS_NAMESPACE@_FStream_NOEXCEPT
+#undef @KWSYS_NAMESPACE@_FStream_NOEXCEPT
#else
- using std::ofstream;
- using std::ifstream;
+using std::ofstream;
+using std::ifstream;
#endif
- namespace FStream
- {
- enum BOM
- {
- BOM_None,
- BOM_UTF8,
- BOM_UTF16BE,
- BOM_UTF16LE,
- BOM_UTF32BE,
- BOM_UTF32LE
- };
-
- // Read a BOM, if one exists.
- // If a BOM exists, the stream is advanced to after the BOM.
- // This function requires a seekable stream (but not a relative
- // seekable stream).
- BOM ReadBOM(std::istream& in);
- }
+namespace FStream {
+enum BOM
+{
+ BOM_None,
+ BOM_UTF8,
+ BOM_UTF16BE,
+ BOM_UTF16LE,
+ BOM_UTF32BE,
+ BOM_UTF32LE
+};
+
+// Read a BOM, if one exists.
+// If a BOM exists, the stream is advanced to after the BOM.
+// This function requires a seekable stream (but not a relative
+// seekable stream).
+BOM ReadBOM(std::istream& in);
+}
}
#endif
diff --git a/Source/kwsys/Glob.cxx b/Source/kwsys/Glob.cxx
index 9d63459..fa8760d 100644
--- a/Source/kwsys/Glob.cxx
+++ b/Source/kwsys/Glob.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Glob.hxx)
@@ -21,30 +12,29 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Glob.hxx.in"
-# include "Directory.hxx.in"
-# include "Configure.hxx.in"
-# include "RegularExpression.hxx.in"
-# include "SystemTools.hxx.in"
+#include "Configure.hxx.in"
+#include "Directory.hxx.in"
+#include "Glob.hxx.in"
+#include "RegularExpression.hxx.in"
+#include "SystemTools.hxx.in"
#endif
+#include <algorithm>
#include <string>
#include <vector>
-#include <algorithm>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
#if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
// On Windows and apple, no difference between lower and upper case
-# define KWSYS_GLOB_CASE_INDEPENDENT
+#define KWSYS_GLOB_CASE_INDEPENDENT
#endif
#if defined(_WIN32) || defined(__CYGWIN__)
// Handle network paths
-# define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
+#define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
#endif
//----------------------------------------------------------------------------
@@ -63,8 +53,8 @@ Glob::Glob()
this->Relative = "";
this->RecurseThroughSymlinks = true;
- // RecurseThroughSymlinks is true by default for backwards compatibility,
- // not because it's a good idea...
+ // RecurseThroughSymlinks is true by default for backwards compatibility,
+ // not because it's a good idea...
this->FollowedSymlinkCount = 0;
// Keep separate variables for directory listing for back compatibility
@@ -86,69 +76,55 @@ std::vector<std::string>& Glob::GetFiles()
//----------------------------------------------------------------------------
std::string Glob::PatternToRegex(const std::string& pattern,
- bool require_whole_string,
- bool preserve_case)
+ bool require_whole_string, bool preserve_case)
{
// Incrementally build the regular expression from the pattern.
- std::string regex = require_whole_string? "^" : "";
+ std::string regex = require_whole_string ? "^" : "";
std::string::const_iterator pattern_first = pattern.begin();
std::string::const_iterator pattern_last = pattern.end();
- for(std::string::const_iterator i = pattern_first;
- i != pattern_last; ++i)
- {
+ for (std::string::const_iterator i = pattern_first; i != pattern_last; ++i) {
int c = *i;
- if(c == '*')
- {
+ if (c == '*') {
// A '*' (not between brackets) matches any string.
// We modify this to not match slashes since the orignal glob
// pattern documentation was meant for matching file name
// components separated by slashes.
regex += "[^/]*";
- }
- else if(c == '?')
- {
+ } else if (c == '?') {
// A '?' (not between brackets) matches any single character.
// We modify this to not match slashes since the orignal glob
// pattern documentation was meant for matching file name
// components separated by slashes.
regex += "[^/]";
- }
- else if(c == '[')
- {
+ } else if (c == '[') {
// Parse out the bracket expression. It begins just after the
// opening character.
- std::string::const_iterator bracket_first = i+1;
+ std::string::const_iterator bracket_first = i + 1;
std::string::const_iterator bracket_last = bracket_first;
// The first character may be complementation '!' or '^'.
- if(bracket_last != pattern_last &&
- (*bracket_last == '!' || *bracket_last == '^'))
- {
+ if (bracket_last != pattern_last &&
+ (*bracket_last == '!' || *bracket_last == '^')) {
++bracket_last;
- }
+ }
// If the next character is a ']' it is included in the brackets
// because the bracket string may not be empty.
- if(bracket_last != pattern_last && *bracket_last == ']')
- {
+ if (bracket_last != pattern_last && *bracket_last == ']') {
++bracket_last;
- }
+ }
// Search for the closing ']'.
- while(bracket_last != pattern_last && *bracket_last != ']')
- {
+ while (bracket_last != pattern_last && *bracket_last != ']') {
++bracket_last;
- }
+ }
// Check whether we have a complete bracket string.
- if(bracket_last == pattern_last)
- {
+ if (bracket_last == pattern_last) {
// The bracket string did not end, so it was opened simply by
// a '[' that is supposed to be matched literally.
regex += "\\[";
- }
- else
- {
+ } else {
// Convert the bracket string to its regex equivalent.
std::string::const_iterator k = bracket_first;
@@ -156,97 +132,81 @@ std::string Glob::PatternToRegex(const std::string& pattern,
regex += "[";
// A regex range complement uses '^' instead of '!'.
- if(k != bracket_last && *k == '!')
- {
+ if (k != bracket_last && *k == '!') {
regex += "^";
++k;
- }
+ }
// Convert the remaining characters.
- for(; k != bracket_last; ++k)
- {
+ for (; k != bracket_last; ++k) {
// Backslashes must be escaped.
- if(*k == '\\')
- {
+ if (*k == '\\') {
regex += "\\";
- }
+ }
// Store this character.
regex += *k;
- }
+ }
// Close the regex block.
regex += "]";
// Jump to the end of the bracket string.
i = bracket_last;
- }
}
- else
- {
+ } else {
// A single character matches itself.
int ch = c;
- if(!(('a' <= ch && ch <= 'z') ||
- ('A' <= ch && ch <= 'Z') ||
- ('0' <= ch && ch <= '9')))
- {
+ if (!(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
+ ('0' <= ch && ch <= '9'))) {
// Escape the non-alphanumeric character.
regex += "\\";
- }
+ }
#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
- else
- {
+ else {
// On case-insensitive systems file names are converted to lower
// case before matching.
- if(!preserve_case)
- {
+ if (!preserve_case) {
ch = tolower(ch);
- }
}
+ }
#endif
(void)preserve_case;
// Store the character.
regex.append(1, static_cast<char>(ch));
- }
}
+ }
- if(require_whole_string)
- {
+ if (require_whole_string) {
regex += "$";
- }
+ }
return regex;
}
//----------------------------------------------------------------------------
bool Glob::RecurseDirectory(std::string::size_type start,
- const std::string& dir, GlobMessages* messages)
+ const std::string& dir, GlobMessages* messages)
{
kwsys::Directory d;
- if ( !d.Load(dir) )
- {
+ if (!d.Load(dir)) {
return true;
- }
+ }
unsigned long cc;
std::string realname;
std::string fname;
- for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
- {
+ for (cc = 0; cc < d.GetNumberOfFiles(); cc++) {
fname = d.GetFile(cc);
- if ( fname == "." || fname == ".." )
- {
+ if (fname == "." || fname == "..") {
continue;
- }
+ }
- if ( start == 0 )
- {
+ if (start == 0) {
realname = dir + fname;
- }
- else
- {
+ } else {
realname = dir + "/" + fname;
- }
+ }
-#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
+#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
// On Windows and apple, no difference between lower and upper case
fname = kwsys::SystemTools::LowerCase(fname);
#endif
@@ -254,157 +214,127 @@ bool Glob::RecurseDirectory(std::string::size_type start,
bool isDir = kwsys::SystemTools::FileIsDirectory(realname);
bool isSymLink = kwsys::SystemTools::FileIsSymlink(realname);
- if ( isDir && (!isSymLink || this->RecurseThroughSymlinks) )
- {
- if (isSymLink)
- {
+ if (isDir && (!isSymLink || this->RecurseThroughSymlinks)) {
+ if (isSymLink) {
++this->FollowedSymlinkCount;
std::string realPathErrorMessage;
- std::string canonicalPath(SystemTools::GetRealPath(dir,
- &realPathErrorMessage));
+ std::string canonicalPath(
+ SystemTools::GetRealPath(dir, &realPathErrorMessage));
- if(!realPathErrorMessage.empty())
- {
- if(messages)
- {
+ if (!realPathErrorMessage.empty()) {
+ if (messages) {
messages->push_back(Message(
- Glob::error, "Canonical path generation from path '"
- + dir + "' failed! Reason: '" + realPathErrorMessage + "'"));
- }
- return false;
+ Glob::error, "Canonical path generation from path '" + dir +
+ "' failed! Reason: '" + realPathErrorMessage + "'"));
}
+ return false;
+ }
- if(std::find(this->VisitedSymlinks.begin(),
- this->VisitedSymlinks.end(),
- canonicalPath) == this->VisitedSymlinks.end())
- {
- if(this->RecurseListDirs)
- {
+ if (std::find(this->VisitedSymlinks.begin(),
+ this->VisitedSymlinks.end(),
+ canonicalPath) == this->VisitedSymlinks.end()) {
+ if (this->RecurseListDirs) {
// symlinks are treated as directories
this->AddFile(this->Internals->Files, realname);
- }
+ }
this->VisitedSymlinks.push_back(canonicalPath);
- if(!this->RecurseDirectory(start+1, realname, messages))
- {
+ if (!this->RecurseDirectory(start + 1, realname, messages)) {
this->VisitedSymlinks.pop_back();
return false;
- }
- this->VisitedSymlinks.pop_back();
}
+ this->VisitedSymlinks.pop_back();
+ }
// else we have already visited this symlink - prevent cyclic recursion
- else if(messages)
- {
+ else if (messages) {
std::string message;
- for(std::vector<std::string>::const_iterator
- pathIt = std::find(this->VisitedSymlinks.begin(),
- this->VisitedSymlinks.end(),
- canonicalPath);
- pathIt != this->VisitedSymlinks.end(); ++pathIt)
- {
+ for (std::vector<std::string>::const_iterator pathIt =
+ std::find(this->VisitedSymlinks.begin(),
+ this->VisitedSymlinks.end(), canonicalPath);
+ pathIt != this->VisitedSymlinks.end(); ++pathIt) {
message += *pathIt + "\n";
- }
+ }
message += canonicalPath + "/" + fname;
messages->push_back(Message(Glob::cyclicRecursion, message));
- }
}
- else
- {
- if(this->RecurseListDirs)
- {
+ } else {
+ if (this->RecurseListDirs) {
this->AddFile(this->Internals->Files, realname);
- }
- if(!this->RecurseDirectory(start+1, realname, messages))
- {
+ }
+ if (!this->RecurseDirectory(start + 1, realname, messages)) {
return false;
- }
}
}
- else
- {
- if ( !this->Internals->Expressions.empty() &&
- this->Internals->Expressions.rbegin()->find(fname) )
- {
+ } else {
+ if (!this->Internals->Expressions.empty() &&
+ this->Internals->Expressions.rbegin()->find(fname)) {
this->AddFile(this->Internals->Files, realname);
- }
}
}
+ }
return true;
}
//----------------------------------------------------------------------------
void Glob::ProcessDirectory(std::string::size_type start,
- const std::string& dir, GlobMessages* messages)
+ const std::string& dir, GlobMessages* messages)
{
- //std::cout << "ProcessDirectory: " << dir << std::endl;
- bool last = ( start == this->Internals->Expressions.size()-1 );
- if ( last && this->Recurse )
- {
+ // std::cout << "ProcessDirectory: " << dir << std::endl;
+ bool last = (start == this->Internals->Expressions.size() - 1);
+ if (last && this->Recurse) {
this->RecurseDirectory(start, dir, messages);
return;
- }
+ }
- if ( start >= this->Internals->Expressions.size() )
- {
+ if (start >= this->Internals->Expressions.size()) {
return;
- }
+ }
kwsys::Directory d;
- if ( !d.Load(dir) )
- {
+ if (!d.Load(dir)) {
return;
- }
+ }
unsigned long cc;
std::string realname;
std::string fname;
- for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
- {
+ for (cc = 0; cc < d.GetNumberOfFiles(); cc++) {
fname = d.GetFile(cc);
- if ( fname == "." || fname == ".." )
- {
+ if (fname == "." || fname == "..") {
continue;
- }
+ }
- if ( start == 0 )
- {
+ if (start == 0) {
realname = dir + fname;
- }
- else
- {
+ } else {
realname = dir + "/" + fname;
- }
+ }
#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
// On case-insensitive file systems convert to lower case for matching.
fname = kwsys::SystemTools::LowerCase(fname);
#endif
- //std::cout << "Look at file: " << fname << std::endl;
- //std::cout << "Match: "
+ // std::cout << "Look at file: " << fname << std::endl;
+ // std::cout << "Match: "
// << this->Internals->TextExpressions[start].c_str() << std::endl;
- //std::cout << "Real name: " << realname << std::endl;
+ // std::cout << "Real name: " << realname << std::endl;
- if( (!last && !kwsys::SystemTools::FileIsDirectory(realname))
- || (!this->ListDirs && last &&
- kwsys::SystemTools::FileIsDirectory(realname)) )
- {
+ if ((!last && !kwsys::SystemTools::FileIsDirectory(realname)) ||
+ (!this->ListDirs && last &&
+ kwsys::SystemTools::FileIsDirectory(realname))) {
continue;
- }
+ }
- if ( this->Internals->Expressions[start].find(fname) )
- {
- if ( last )
- {
+ if (this->Internals->Expressions[start].find(fname)) {
+ if (last) {
this->AddFile(this->Internals->Files, realname);
- }
- else
- {
- this->ProcessDirectory(start+1, realname, messages);
- }
+ } else {
+ this->ProcessDirectory(start + 1, realname, messages);
}
}
+ }
}
//----------------------------------------------------------------------------
@@ -417,99 +347,76 @@ bool Glob::FindFiles(const std::string& inexpr, GlobMessages* messages)
this->Internals->Expressions.clear();
this->Internals->Files.clear();
- if ( !kwsys::SystemTools::FileIsFullPath(expr) )
- {
+ if (!kwsys::SystemTools::FileIsFullPath(expr)) {
expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
expr += "/" + inexpr;
- }
+ }
std::string fexpr = expr;
std::string::size_type skip = 0;
std::string::size_type last_slash = 0;
- for ( cc = 0; cc < expr.size(); cc ++ )
- {
- if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
- {
+ for (cc = 0; cc < expr.size(); cc++) {
+ if (cc > 0 && expr[cc] == '/' && expr[cc - 1] != '\\') {
last_slash = cc;
- }
- if ( cc > 0 &&
- (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
- expr[cc-1] != '\\' )
- {
+ }
+ if (cc > 0 && (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
+ expr[cc - 1] != '\\') {
break;
- }
}
- if ( last_slash > 0 )
- {
- //std::cout << "I can skip: " << fexpr.substr(0, last_slash)
+ }
+ if (last_slash > 0) {
+ // std::cout << "I can skip: " << fexpr.substr(0, last_slash)
// << std::endl;
skip = last_slash;
- }
- if ( skip == 0 )
- {
-#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
+ }
+ if (skip == 0) {
+#if defined(KWSYS_GLOB_SUPPORT_NETWORK_PATHS)
// Handle network paths
- if ( expr[0] == '/' && expr[1] == '/' )
- {
+ if (expr[0] == '/' && expr[1] == '/') {
int cnt = 0;
- for ( cc = 2; cc < expr.size(); cc ++ )
- {
- if ( expr[cc] == '/' )
- {
- cnt ++;
- if ( cnt == 2 )
- {
+ for (cc = 2; cc < expr.size(); cc++) {
+ if (expr[cc] == '/') {
+ cnt++;
+ if (cnt == 2) {
break;
- }
}
}
- skip = int(cc + 1);
}
- else
+ skip = int(cc + 1);
+ } else
#endif
// Handle drive letters on Windows
- if ( expr[1] == ':' && expr[0] != '/' )
- {
- skip = 2;
- }
+ if (expr[1] == ':' && expr[0] != '/') {
+ skip = 2;
}
+ }
- if ( skip > 0 )
- {
+ if (skip > 0) {
expr = expr.substr(skip);
- }
+ }
cexpr = "";
- for ( cc = 0; cc < expr.size(); cc ++ )
- {
+ for (cc = 0; cc < expr.size(); cc++) {
int ch = expr[cc];
- if ( ch == '/' )
- {
- if ( !cexpr.empty() )
- {
+ if (ch == '/') {
+ if (!cexpr.empty()) {
this->AddExpression(cexpr);
- }
- cexpr = "";
}
- else
- {
+ cexpr = "";
+ } else {
cexpr.append(1, static_cast<char>(ch));
- }
}
- if ( !cexpr.empty() )
- {
+ }
+ if (!cexpr.empty()) {
this->AddExpression(cexpr);
- }
+ }
// Handle network paths
- if ( skip > 0 )
- {
+ if (skip > 0) {
this->ProcessDirectory(0, fexpr.substr(0, skip) + "/", messages);
- }
- else
- {
+ } else {
this->ProcessDirectory(0, "/", messages);
- }
+ }
return true;
}
@@ -517,43 +424,36 @@ 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)));
+ kwsys::RegularExpression(this->PatternToRegex(expr)));
}
//----------------------------------------------------------------------------
void Glob::SetRelative(const char* dir)
{
- if ( !dir )
- {
+ if (!dir) {
this->Relative = "";
return;
- }
+ }
this->Relative = dir;
}
//----------------------------------------------------------------------------
const char* Glob::GetRelative()
{
- if ( this->Relative.empty() )
- {
+ if (this->Relative.empty()) {
return 0;
- }
+ }
return this->Relative.c_str();
}
//----------------------------------------------------------------------------
void Glob::AddFile(std::vector<std::string>& files, const std::string& file)
{
- if ( !this->Relative.empty() )
- {
+ if (!this->Relative.empty()) {
files.push_back(kwsys::SystemTools::RelativePath(this->Relative, file));
- }
- else
- {
+ } else {
files.push_back(file);
- }
+ }
}
} // namespace KWSYS_NAMESPACE
-
diff --git a/Source/kwsys/Glob.hxx.in b/Source/kwsys/Glob.hxx.in
index ffee9ca..bd4a176 100644
--- a/Source/kwsys/Glob.hxx.in
+++ b/Source/kwsys/Glob.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Glob_hxx
#define @KWSYS_NAMESPACE@_Glob_hxx
@@ -18,8 +9,7 @@
#include <string>
#include <vector>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
class GlobInternals;
@@ -46,31 +36,33 @@ public:
MessageType type;
std::string content;
- Message(MessageType t, const std::string& c) :
- type(t),
- content(c)
- {}
- Message(const Message& msg) :
- type(msg.type),
- content(msg.content)
- {}
+ Message(MessageType t, const std::string& c)
+ : type(t)
+ , content(c)
+ {
+ }
+ Message(const Message& msg)
+ : type(msg.type)
+ , content(msg.content)
+ {
+ }
Message& operator=(Message const& msg)
- {
+ {
this->type = msg.type;
this->content = msg.content;
return *this;
- }
+ }
};
typedef std::vector<Message> GlobMessages;
typedef std::vector<Message>::iterator GlobMessagesIterator;
+
public:
Glob();
~Glob();
//! Find all files that match the pattern.
- bool FindFiles(const std::string& inexpr,
- GlobMessages* messages = 0);
+ bool FindFiles(const std::string& inexpr, GlobMessages* messages = 0);
//! Return the list of files that matched.
std::vector<std::string>& GetFiles();
@@ -103,29 +95,27 @@ public:
whole strings, but may be disabled to support concatenating
expressions more easily (regex1|regex2|etc). */
static std::string PatternToRegex(const std::string& pattern,
- bool require_whole_string = true,
- bool preserve_case = false);
+ bool require_whole_string = true,
+ bool preserve_case = false);
/** Getters and setters for enabling and disabling directory
listing in recursive and non recursive globbing mode.
If listing is enabled in recursive mode it also lists
directory symbolic links even if follow symlinks is enabled. */
- void SetListDirs(bool list) { this->ListDirs=list; }
+ void SetListDirs(bool list) { this->ListDirs = list; }
bool GetListDirs() const { return this->ListDirs; }
- void SetRecurseListDirs(bool list) { this->RecurseListDirs=list; }
+ void SetRecurseListDirs(bool list) { this->RecurseListDirs = list; }
bool GetRecurseListDirs() const { return this->RecurseListDirs; }
protected:
//! Process directory
- void ProcessDirectory(std::string::size_type start,
- const std::string& dir,
- GlobMessages* messages);
+ void ProcessDirectory(std::string::size_type start, const std::string& dir,
+ GlobMessages* messages);
//! Process last directory, but only when recurse flags is on. That is
// effectively like saying: /path/to/file/**/file
- bool RecurseDirectory(std::string::size_type start,
- const std::string& dir,
- GlobMessages* messages);
+ bool RecurseDirectory(std::string::size_type start, const std::string& dir,
+ GlobMessages* messages);
//! Add regular expression
void AddExpression(const std::string& expr);
@@ -143,8 +133,8 @@ protected:
bool RecurseListDirs;
private:
- Glob(const Glob&); // Not implemented.
- void operator=(const Glob&); // Not implemented.
+ Glob(const Glob&); // Not implemented.
+ void operator=(const Glob&); // Not implemented.
};
} // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/IOStream.cxx b/Source/kwsys/IOStream.cxx
index 81c6a73..01ada1f 100644
--- a/Source/kwsys/IOStream.cxx
+++ b/Source/kwsys/IOStream.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Configure.hxx)
@@ -19,24 +10,23 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Configure.hxx.in"
-# include "IOStream.hxx.in"
+#include "Configure.hxx.in"
+#include "IOStream.hxx.in"
#endif
// Implement the rest of this file only if it is needed.
#if KWSYS_IOS_NEED_OPERATORS_LL
-# include <stdio.h> // sscanf, sprintf
-# include <string.h> // memchr
+#include <stdio.h> // sscanf, sprintf
+#include <string.h> // memchr
-# if defined(_MAX_INT_DIG)
-# define KWSYS_IOS_INT64_MAX_DIG _MAX_INT_DIG
-# else
-# define KWSYS_IOS_INT64_MAX_DIG 32
-# endif
+#if defined(_MAX_INT_DIG)
+#define KWSYS_IOS_INT64_MAX_DIG _MAX_INT_DIG
+#else
+#define KWSYS_IOS_INT64_MAX_DIG 32
+#endif
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
// Scan an input stream for an integer value.
static int IOStreamScanStream(std::istream& is, char* buffer)
@@ -46,74 +36,68 @@ static int IOStreamScanStream(std::istream& is, char* buffer)
char* end = buffer + KWSYS_IOS_INT64_MAX_DIG - 1;
// Look for leading sign.
- if(is.peek() == '+') { *out++ = '+'; is.ignore(); }
- else if(is.peek() == '-') { *out++ = '-'; is.ignore(); }
+ if (is.peek() == '+') {
+ *out++ = '+';
+ is.ignore();
+ } else if (is.peek() == '-') {
+ *out++ = '-';
+ is.ignore();
+ }
// Determine the base. If not specified in the stream, try to
// detect it from the input. A leading 0x means hex, and a leading
// 0 alone means octal.
int base = 0;
int flags = is.flags() & std::ios_base::basefield;
- if(flags == std::ios_base::oct) { base = 8; }
- else if(flags == std::ios_base::dec) { base = 10; }
- else if(flags == std::ios_base::hex) { base = 16; }
+ if (flags == std::ios_base::oct) {
+ base = 8;
+ } else if (flags == std::ios_base::dec) {
+ base = 10;
+ } else if (flags == std::ios_base::hex) {
+ base = 16;
+ }
bool foundDigit = false;
bool foundNonZero = false;
- if(is.peek() == '0')
- {
+ if (is.peek() == '0') {
foundDigit = true;
is.ignore();
- if((is.peek() == 'x' || is.peek() == 'X') && (base == 0 || base == 16))
- {
+ if ((is.peek() == 'x' || is.peek() == 'X') && (base == 0 || base == 16)) {
base = 16;
foundDigit = false;
is.ignore();
- }
- else if (base == 0)
- {
+ } else if (base == 0) {
base = 8;
- }
}
+ }
// Determine the range of digits allowed for this number.
const char* digits = "0123456789abcdefABCDEF";
int maxDigitIndex = 10;
- if(base == 8)
- {
+ if (base == 8) {
maxDigitIndex = 8;
- }
- else if(base == 16)
- {
- maxDigitIndex = 10+6+6;
- }
+ } else if (base == 16) {
+ maxDigitIndex = 10 + 6 + 6;
+ }
// Scan until an invalid digit is found.
- for(;is.peek() != EOF; is.ignore())
- {
- if(memchr(digits, *out = (char)is.peek(), maxDigitIndex) != 0)
- {
- if((foundNonZero || *out != '0') && out < end)
- {
+ for (; is.peek() != EOF; is.ignore()) {
+ if (memchr(digits, *out = (char)is.peek(), maxDigitIndex) != 0) {
+ if ((foundNonZero || *out != '0') && out < end) {
++out;
foundNonZero = true;
- }
- foundDigit = true;
}
- else
- {
+ foundDigit = true;
+ } else {
break;
- }
}
+ }
// Correct the buffer contents for degenerate cases.
- if(foundDigit && !foundNonZero)
- {
+ if (foundDigit && !foundNonZero) {
*out++ = '0';
- }
- else if (!foundDigit)
- {
+ } else if (!foundDigit) {
out = buffer;
- }
+ }
// Terminate the string in the buffer.
*out = '\0';
@@ -123,44 +107,54 @@ static int IOStreamScanStream(std::istream& is, char* buffer)
// Read an integer value from an input stream.
template <class T>
-std::istream&
-IOStreamScanTemplate(std::istream& is, T& value, char type)
+std::istream& IOStreamScanTemplate(std::istream& is, T& value, char type)
{
int state = std::ios_base::goodbit;
// Skip leading whitespace.
std::istream::sentry okay(is);
- if(okay)
- {
+ if (okay) {
try {
- // Copy the string to a buffer and construct the format string.
- char buffer[KWSYS_IOS_INT64_MAX_DIG];
-# if defined(_MSC_VER)
- char format[] = "%I64_";
- const int typeIndex = 4;
-# else
- char format[] = "%ll_";
- const int typeIndex = 3;
-# endif
- switch(IOStreamScanStream(is, buffer))
- {
- case 8: format[typeIndex] = 'o'; break;
- case 0: // Default to decimal if not told otherwise.
- case 10: format[typeIndex] = type; break;
- case 16: format[typeIndex] = 'x'; break;
+ // Copy the string to a buffer and construct the format string.
+ char buffer[KWSYS_IOS_INT64_MAX_DIG];
+#if defined(_MSC_VER)
+ char format[] = "%I64_";
+ const int typeIndex = 4;
+#else
+ char format[] = "%ll_";
+ const int typeIndex = 3;
+#endif
+ switch (IOStreamScanStream(is, buffer)) {
+ case 8:
+ format[typeIndex] = 'o';
+ break;
+ case 0: // Default to decimal if not told otherwise.
+ case 10:
+ format[typeIndex] = type;
+ break;
+ case 16:
+ format[typeIndex] = 'x';
+ break;
};
- // Use sscanf to parse the number from the buffer.
- T result;
- int success = (sscanf(buffer, format, &result) == 1)?1:0;
+ // Use sscanf to parse the number from the buffer.
+ T result;
+ int success = (sscanf(buffer, format, &result) == 1) ? 1 : 0;
- // Set flags for resulting state.
- if(is.peek() == EOF) { state |= std::ios_base::eofbit; }
- if(!success) { state |= std::ios_base::failbit; }
- else { value = result; }
- } catch(...) { state |= std::ios_base::badbit; }
+ // Set flags for resulting state.
+ if (is.peek() == EOF) {
+ state |= std::ios_base::eofbit;
+ }
+ if (!success) {
+ state |= std::ios_base::failbit;
+ } else {
+ value = result;
+ }
+ } catch (...) {
+ state |= std::ios_base::badbit;
}
+ }
is.setstate(std::ios_base::iostate(state));
return is;
@@ -168,42 +162,54 @@ IOStreamScanTemplate(std::istream& is, T& value, char type)
// Print an integer value to an output stream.
template <class T>
-std::ostream&
-IOStreamPrintTemplate(std::ostream& os, T value, char type)
+std::ostream& IOStreamPrintTemplate(std::ostream& os, T value, char type)
{
std::ostream::sentry okay(os);
- if(okay)
- {
+ if (okay) {
try {
- // Construct the format string.
- char format[8];
- char* f = format;
- *f++ = '%';
- if(os.flags() & std::ios_base::showpos) { *f++ = '+'; }
- if(os.flags() & std::ios_base::showbase) { *f++ = '#'; }
-# if defined(_MSC_VER)
- *f++ = 'I'; *f++ = '6'; *f++ = '4';
-# else
- *f++ = 'l'; *f++ = 'l';
-# endif
- long bflags = os.flags() & std::ios_base::basefield;
- if(bflags == std::ios_base::oct) { *f++ = 'o'; }
- else if(bflags != std::ios_base::hex) { *f++ = type; }
- else if(os.flags() & std::ios_base::uppercase) { *f++ = 'X'; }
- else { *f++ = 'x'; }
- *f = '\0';
-
- // Use sprintf to print to a buffer and then write the
- // buffer to the stream.
- char buffer[2*KWSYS_IOS_INT64_MAX_DIG];
- sprintf(buffer, format, value);
- os << buffer;
- } catch(...) { os.clear(os.rdstate() | std::ios_base::badbit); }
+ // Construct the format string.
+ char format[8];
+ char* f = format;
+ *f++ = '%';
+ if (os.flags() & std::ios_base::showpos) {
+ *f++ = '+';
+ }
+ if (os.flags() & std::ios_base::showbase) {
+ *f++ = '#';
+ }
+#if defined(_MSC_VER)
+ *f++ = 'I';
+ *f++ = '6';
+ *f++ = '4';
+#else
+ *f++ = 'l';
+ *f++ = 'l';
+#endif
+ long bflags = os.flags() & std::ios_base::basefield;
+ if (bflags == std::ios_base::oct) {
+ *f++ = 'o';
+ } else if (bflags != std::ios_base::hex) {
+ *f++ = type;
+ } else if (os.flags() & std::ios_base::uppercase) {
+ *f++ = 'X';
+ } else {
+ *f++ = 'x';
+ }
+ *f = '\0';
+
+ // Use sprintf to print to a buffer and then write the
+ // buffer to the stream.
+ char buffer[2 * KWSYS_IOS_INT64_MAX_DIG];
+ sprintf(buffer, format, value);
+ os << buffer;
+ } catch (...) {
+ os.clear(os.rdstate() | std::ios_base::badbit);
}
+ }
return os;
}
-# if !KWSYS_IOS_HAS_ISTREAM_LONG_LONG
+#if !KWSYS_IOS_HAS_ISTREAM_LONG_LONG
// Implement input stream operator for IOStreamSLL.
std::istream& IOStreamScan(std::istream& is, IOStreamSLL& value)
{
@@ -215,9 +221,9 @@ std::istream& IOStreamScan(std::istream& is, IOStreamULL& value)
{
return IOStreamScanTemplate(is, value, 'u');
}
-# endif
+#endif
-# if !KWSYS_IOS_HAS_OSTREAM_LONG_LONG
+#if !KWSYS_IOS_HAS_OSTREAM_LONG_LONG
// Implement output stream operator for IOStreamSLL.
std::ostream& IOStreamPrint(std::ostream& os, IOStreamSLL value)
{
@@ -229,14 +235,13 @@ std::ostream& IOStreamPrint(std::ostream& os, IOStreamULL value)
{
return IOStreamPrintTemplate(os, value, 'u');
}
-# endif
+#endif
} // namespace KWSYS_NAMESPACE
#else
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
// Create one public symbol in this object file to avoid warnings from
// archivers.
diff --git a/Source/kwsys/IOStream.hxx.in b/Source/kwsys/IOStream.hxx.in
index c101909..de3a2e6 100644
--- a/Source/kwsys/IOStream.hxx.in
+++ b/Source/kwsys/IOStream.hxx.in
@@ -1,136 +1,126 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_IOStream_hxx
#define @KWSYS_NAMESPACE@_IOStream_hxx
#include <iosfwd>
/* Define these macros temporarily to keep the code readable. */
-#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
/* Whether istream supports long long. */
-#define @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG @KWSYS_IOS_HAS_ISTREAM_LONG_LONG@
+#define @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG \
+ @KWSYS_IOS_HAS_ISTREAM_LONG_LONG@
/* Whether ostream supports long long. */
-#define @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG @KWSYS_IOS_HAS_OSTREAM_LONG_LONG@
+#define @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG \
+ @KWSYS_IOS_HAS_OSTREAM_LONG_LONG@
/* Determine whether we need to define the streaming operators for
long long or __int64. */
#if @KWSYS_USE_LONG_LONG@
-# if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG || \
- !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
-# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
- namespace @KWSYS_NAMESPACE@
- {
- typedef long long IOStreamSLL;
- typedef unsigned long long IOStreamULL;
- }
-# endif
+#if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG || \
+ !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
+#define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
+namespace @KWSYS_NAMESPACE@ {
+typedef long long IOStreamSLL;
+typedef unsigned long long IOStreamULL;
+}
+#endif
#elif defined(_MSC_VER) && _MSC_VER < 1300
-# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
- namespace @KWSYS_NAMESPACE@
- {
- typedef __int64 IOStreamSLL;
- typedef unsigned __int64 IOStreamULL;
- }
+#define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
+namespace @KWSYS_NAMESPACE@ {
+typedef __int64 IOStreamSLL;
+typedef unsigned __int64 IOStreamULL;
+}
#endif
#if !defined(@KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL)
-# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 0
+#define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 0
#endif
#if @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
-# if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
+#if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
/* Input stream operator implementation functions. */
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
kwsysEXPORT std::istream& IOStreamScan(std::istream&, IOStreamSLL&);
kwsysEXPORT std::istream& IOStreamScan(std::istream&, IOStreamULL&);
}
/* Provide input stream operator for long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_LONG_LONG) && \
- !defined(KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED)
-# define KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_ISTREAM_LONG_LONG_DEFINED
-inline std::istream&
-operator>>(std::istream& is, @KWSYS_NAMESPACE@::IOStreamSLL& value)
+#if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_LONG_LONG) && \
+ !defined(KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED)
+#define KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE@_IOS_ISTREAM_LONG_LONG_DEFINED
+inline std::istream& operator>>(std::istream& is,
+ @KWSYS_NAMESPACE@::IOStreamSLL& value)
{
return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
}
-# endif
+#endif
/* Provide input stream operator for unsigned long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_UNSIGNED_LONG_LONG) && \
- !defined(KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED)
-# define KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
-inline std::istream&
-operator>>(std::istream& is, @KWSYS_NAMESPACE@::IOStreamULL& value)
+#if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_UNSIGNED_LONG_LONG) && \
+ !defined(KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED)
+#define KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE@_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
+inline std::istream& operator>>(std::istream& is,
+ @KWSYS_NAMESPACE@::IOStreamULL& value)
{
return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
}
-# endif
-# endif /* !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG */
+#endif
+#endif /* !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG */
-# if !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
+#if !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
/* Output stream operator implementation functions. */
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
kwsysEXPORT std::ostream& IOStreamPrint(std::ostream&, IOStreamSLL);
kwsysEXPORT std::ostream& IOStreamPrint(std::ostream&, IOStreamULL);
}
/* Provide output stream operator for long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_LONG_LONG) && \
- !defined(KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED)
-# define KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_OSTREAM_LONG_LONG_DEFINED
-inline std::ostream&
-operator<<(std::ostream& os, @KWSYS_NAMESPACE@::IOStreamSLL value)
+#if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_LONG_LONG) && \
+ !defined(KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED)
+#define KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE@_IOS_OSTREAM_LONG_LONG_DEFINED
+inline std::ostream& operator<<(std::ostream& os,
+ @KWSYS_NAMESPACE@::IOStreamSLL value)
{
return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
}
-# endif
+#endif
/* Provide output stream operator for unsigned long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_UNSIGNED_LONG_LONG) && \
- !defined(KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED)
-# define KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
-inline std::ostream&
-operator<<(std::ostream& os, @KWSYS_NAMESPACE@::IOStreamULL value)
+#if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_UNSIGNED_LONG_LONG) && \
+ !defined(KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED)
+#define KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE@_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
+inline std::ostream& operator<<(std::ostream& os,
+ @KWSYS_NAMESPACE@::IOStreamULL value)
{
return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
}
-# endif
-# endif /* !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG */
+#endif
+#endif /* !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG */
#endif /* @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL */
/* Undefine temporary macros. */
-#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysEXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysEXPORT
#endif
/* If building a C++ file in kwsys itself, give the source file
access to the macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
-# define KWSYS_IOS_HAS_ISTREAM_LONG_LONG @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
-# define KWSYS_IOS_HAS_OSTREAM_LONG_LONG @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
-# define KWSYS_IOS_NEED_OPERATORS_LL @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
+#define KWSYS_IOS_HAS_ISTREAM_LONG_LONG \
+ @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
+#define KWSYS_IOS_HAS_OSTREAM_LONG_LONG \
+ @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
+#define KWSYS_IOS_NEED_OPERATORS_LL @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
#endif
#endif
-
diff --git a/Source/kwsys/MD5.c b/Source/kwsys/MD5.c
index b75acb2..1310c64 100644
--- a/Source/kwsys/MD5.c
+++ b/Source/kwsys/MD5.c
@@ -1,26 +1,17 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(MD5.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "MD5.h.in"
+#include "MD5.h.in"
#endif
-#include <stddef.h> /* size_t */
-#include <stdlib.h> /* malloc, free */
-#include <string.h> /* memcpy, strlen */
+#include <stddef.h> /* size_t */
+#include <stdlib.h> /* malloc, free */
+#include <string.h> /* memcpy, strlen */
/*--------------------------------------------------------------------------*/
@@ -30,8 +21,8 @@
implementation file. */
#if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wcast-align"
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wcast-align"
#endif
/*
@@ -97,344 +88,341 @@
*/
typedef unsigned char md5_byte_t; /* 8-bit byte */
-typedef unsigned int md5_word_t; /* 32-bit word */
+typedef unsigned int md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
-typedef struct md5_state_s {
- md5_word_t count[2]; /* message length in bits, lsw first */
- md5_word_t abcd[4]; /* digest buffer */
- md5_byte_t buf[64]; /* accumulate block */
+typedef struct md5_state_s
+{
+ md5_word_t count[2]; /* message length in bits, lsw first */
+ md5_word_t abcd[4]; /* digest buffer */
+ md5_byte_t buf[64]; /* accumulate block */
} md5_state_t;
-#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
+#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
-# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
+#define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
-# define BYTE_ORDER 0
+#define BYTE_ORDER 0
#endif
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
-#define T3 0x242070db
+#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
-#define T6 0x4787c62a
+#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
-#define T9 0x698098d8
+#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
-#define T13 0x6b901122
+#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
-#define T16 0x49b40821
+#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
-#define T19 0x265e5a51
+#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
-#define T22 0x02441453
+#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
-#define T25 0x21e1cde6
+#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
-#define T28 0x455a14ed
+#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
-#define T31 0x676f02d9
+#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
-#define T35 0x6d9d6122
+#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
-#define T38 0x4bdecfa9
+#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
-#define T41 0x289b7ec6
+#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
-#define T44 0x04881d05
+#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
-#define T47 0x1fa27cf8
+#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
-#define T50 0x432aff97
+#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
-#define T53 0x655b59c3
+#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
-#define T57 0x6fa87e4f
+#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
-#define T60 0x4e0811a1
+#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
-#define T63 0x2ad7d2bb
+#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
-
-static void
-md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
+static void md5_process(md5_state_t* pms, const md5_byte_t* data /*[64]*/)
{
- md5_word_t
- a = pms->abcd[0], b = pms->abcd[1],
- c = pms->abcd[2], d = pms->abcd[3];
- md5_word_t t;
+ md5_word_t a = pms->abcd[0], b = pms->abcd[1], c = pms->abcd[2],
+ d = pms->abcd[3];
+ md5_word_t t;
#if BYTE_ORDER > 0
- /* Define storage only for big-endian CPUs. */
- md5_word_t X[16];
+ /* Define storage only for big-endian CPUs. */
+ md5_word_t X[16];
#else
- /* Define storage for little-endian or both types of CPUs. */
- md5_word_t xbuf[16];
- const md5_word_t *X;
+ /* Define storage for little-endian or both types of CPUs. */
+ md5_word_t xbuf[16];
+ const md5_word_t* X;
#endif
- {
+ {
#if BYTE_ORDER == 0
- /*
- * Determine dynamically whether this is a big-endian or
- * little-endian machine, since we can use a more efficient
- * algorithm on the latter.
- */
- static const int w = 1;
-
- if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
+ /*
+ * Determine dynamically whether this is a big-endian or
+ * little-endian machine, since we can use a more efficient
+ * algorithm on the latter.
+ */
+ static const int w = 1;
+
+ if (*((const md5_byte_t*)&w)) /* dynamic little-endian */
#endif
-#if BYTE_ORDER <= 0 /* little-endian */
- {
- /*
- * On little-endian machines, we can process properly aligned
- * data without copying it.
- */
- if (!((data - (const md5_byte_t *)0) & 3)) {
- /* data are properly aligned */
- X = (const md5_word_t *)data;
- } else {
- /* not aligned */
- memcpy(xbuf, data, 64);
- X = xbuf;
- }
- }
+#if BYTE_ORDER <= 0 /* little-endian */
+ {
+ /*
+ * On little-endian machines, we can process properly aligned
+ * data without copying it.
+ */
+ if (!((data - (const md5_byte_t*)0) & 3)) {
+ /* data are properly aligned */
+ X = (const md5_word_t*)data;
+ } else {
+ /* not aligned */
+ memcpy(xbuf, data, 64);
+ X = xbuf;
+ }
+ }
#endif
#if BYTE_ORDER == 0
- else /* dynamic big-endian */
+ else /* dynamic big-endian */
#endif
-#if BYTE_ORDER >= 0 /* big-endian */
- {
- /*
- * On big-endian machines, we must arrange the bytes in the
- * right order.
- */
- const md5_byte_t *xp = data;
- int i;
-
-# if BYTE_ORDER == 0
- X = xbuf; /* (dynamic only) */
-# else
-# define xbuf X /* (static only) */
-# endif
- for (i = 0; i < 16; ++i, xp += 4)
- xbuf[i] = (md5_word_t)(xp[0] + (xp[1] << 8) +
- (xp[2] << 16) + (xp[3] << 24));
- }
+#if BYTE_ORDER >= 0 /* big-endian */
+ {
+ /*
+ * On big-endian machines, we must arrange the bytes in the
+ * right order.
+ */
+ const md5_byte_t* xp = data;
+ int i;
+
+#if BYTE_ORDER == 0
+ X = xbuf; /* (dynamic only) */
+#else
+#define xbuf X /* (static only) */
#endif
+ for (i = 0; i < 16; ++i, xp += 4)
+ xbuf[i] =
+ (md5_word_t)(xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24));
}
+#endif
+ }
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
- /* Round 1. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 1. */
+/* Let [abcd k s i] denote the operation
+ a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + F(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti) \
+ t = a + F(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 0, 7, T1);
- SET(d, a, b, c, 1, 12, T2);
- SET(c, d, a, b, 2, 17, T3);
- SET(b, c, d, a, 3, 22, T4);
- SET(a, b, c, d, 4, 7, T5);
- SET(d, a, b, c, 5, 12, T6);
- SET(c, d, a, b, 6, 17, T7);
- SET(b, c, d, a, 7, 22, T8);
- SET(a, b, c, d, 8, 7, T9);
- SET(d, a, b, c, 9, 12, T10);
- SET(c, d, a, b, 10, 17, T11);
- SET(b, c, d, a, 11, 22, T12);
- SET(a, b, c, d, 12, 7, T13);
- SET(d, a, b, c, 13, 12, T14);
- SET(c, d, a, b, 14, 17, T15);
- SET(b, c, d, a, 15, 22, T16);
+ /* Do the following 16 operations. */
+ SET(a, b, c, d, 0, 7, T1);
+ SET(d, a, b, c, 1, 12, T2);
+ SET(c, d, a, b, 2, 17, T3);
+ SET(b, c, d, a, 3, 22, T4);
+ SET(a, b, c, d, 4, 7, T5);
+ SET(d, a, b, c, 5, 12, T6);
+ SET(c, d, a, b, 6, 17, T7);
+ SET(b, c, d, a, 7, 22, T8);
+ SET(a, b, c, d, 8, 7, T9);
+ SET(d, a, b, c, 9, 12, T10);
+ SET(c, d, a, b, 10, 17, T11);
+ SET(b, c, d, a, 11, 22, T12);
+ SET(a, b, c, d, 12, 7, T13);
+ SET(d, a, b, c, 13, 12, T14);
+ SET(c, d, a, b, 14, 17, T15);
+ SET(b, c, d, a, 15, 22, T16);
#undef SET
- /* Round 2. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 2. */
+/* Let [abcd k s i] denote the operation
+ a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + G(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti) \
+ t = a + G(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 1, 5, T17);
- SET(d, a, b, c, 6, 9, T18);
- SET(c, d, a, b, 11, 14, T19);
- SET(b, c, d, a, 0, 20, T20);
- SET(a, b, c, d, 5, 5, T21);
- SET(d, a, b, c, 10, 9, T22);
- SET(c, d, a, b, 15, 14, T23);
- SET(b, c, d, a, 4, 20, T24);
- SET(a, b, c, d, 9, 5, T25);
- SET(d, a, b, c, 14, 9, T26);
- SET(c, d, a, b, 3, 14, T27);
- SET(b, c, d, a, 8, 20, T28);
- SET(a, b, c, d, 13, 5, T29);
- SET(d, a, b, c, 2, 9, T30);
- SET(c, d, a, b, 7, 14, T31);
- SET(b, c, d, a, 12, 20, T32);
+ /* Do the following 16 operations. */
+ SET(a, b, c, d, 1, 5, T17);
+ SET(d, a, b, c, 6, 9, T18);
+ SET(c, d, a, b, 11, 14, T19);
+ SET(b, c, d, a, 0, 20, T20);
+ SET(a, b, c, d, 5, 5, T21);
+ SET(d, a, b, c, 10, 9, T22);
+ SET(c, d, a, b, 15, 14, T23);
+ SET(b, c, d, a, 4, 20, T24);
+ SET(a, b, c, d, 9, 5, T25);
+ SET(d, a, b, c, 14, 9, T26);
+ SET(c, d, a, b, 3, 14, T27);
+ SET(b, c, d, a, 8, 20, T28);
+ SET(a, b, c, d, 13, 5, T29);
+ SET(d, a, b, c, 2, 9, T30);
+ SET(c, d, a, b, 7, 14, T31);
+ SET(b, c, d, a, 12, 20, T32);
#undef SET
- /* Round 3. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 3. */
+/* Let [abcd k s t] denote the operation
+ a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + H(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti) \
+ t = a + H(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 5, 4, T33);
- SET(d, a, b, c, 8, 11, T34);
- SET(c, d, a, b, 11, 16, T35);
- SET(b, c, d, a, 14, 23, T36);
- SET(a, b, c, d, 1, 4, T37);
- SET(d, a, b, c, 4, 11, T38);
- SET(c, d, a, b, 7, 16, T39);
- SET(b, c, d, a, 10, 23, T40);
- SET(a, b, c, d, 13, 4, T41);
- SET(d, a, b, c, 0, 11, T42);
- SET(c, d, a, b, 3, 16, T43);
- SET(b, c, d, a, 6, 23, T44);
- SET(a, b, c, d, 9, 4, T45);
- SET(d, a, b, c, 12, 11, T46);
- SET(c, d, a, b, 15, 16, T47);
- SET(b, c, d, a, 2, 23, T48);
+ /* Do the following 16 operations. */
+ SET(a, b, c, d, 5, 4, T33);
+ SET(d, a, b, c, 8, 11, T34);
+ SET(c, d, a, b, 11, 16, T35);
+ SET(b, c, d, a, 14, 23, T36);
+ SET(a, b, c, d, 1, 4, T37);
+ SET(d, a, b, c, 4, 11, T38);
+ SET(c, d, a, b, 7, 16, T39);
+ SET(b, c, d, a, 10, 23, T40);
+ SET(a, b, c, d, 13, 4, T41);
+ SET(d, a, b, c, 0, 11, T42);
+ SET(c, d, a, b, 3, 16, T43);
+ SET(b, c, d, a, 6, 23, T44);
+ SET(a, b, c, d, 9, 4, T45);
+ SET(d, a, b, c, 12, 11, T46);
+ SET(c, d, a, b, 15, 16, T47);
+ SET(b, c, d, a, 2, 23, T48);
#undef SET
- /* Round 4. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 4. */
+/* Let [abcd k s t] denote the operation
+ a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
- t = a + I(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti) \
+ t = a + I(b, c, d) + X[k] + (Ti); \
a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
- SET(a, b, c, d, 0, 6, T49);
- SET(d, a, b, c, 7, 10, T50);
- SET(c, d, a, b, 14, 15, T51);
- SET(b, c, d, a, 5, 21, T52);
- SET(a, b, c, d, 12, 6, T53);
- SET(d, a, b, c, 3, 10, T54);
- SET(c, d, a, b, 10, 15, T55);
- SET(b, c, d, a, 1, 21, T56);
- SET(a, b, c, d, 8, 6, T57);
- SET(d, a, b, c, 15, 10, T58);
- SET(c, d, a, b, 6, 15, T59);
- SET(b, c, d, a, 13, 21, T60);
- SET(a, b, c, d, 4, 6, T61);
- SET(d, a, b, c, 11, 10, T62);
- SET(c, d, a, b, 2, 15, T63);
- SET(b, c, d, a, 9, 21, T64);
+ /* Do the following 16 operations. */
+ SET(a, b, c, d, 0, 6, T49);
+ SET(d, a, b, c, 7, 10, T50);
+ SET(c, d, a, b, 14, 15, T51);
+ SET(b, c, d, a, 5, 21, T52);
+ SET(a, b, c, d, 12, 6, T53);
+ SET(d, a, b, c, 3, 10, T54);
+ SET(c, d, a, b, 10, 15, T55);
+ SET(b, c, d, a, 1, 21, T56);
+ SET(a, b, c, d, 8, 6, T57);
+ SET(d, a, b, c, 15, 10, T58);
+ SET(c, d, a, b, 6, 15, T59);
+ SET(b, c, d, a, 13, 21, T60);
+ SET(a, b, c, d, 4, 6, T61);
+ SET(d, a, b, c, 11, 10, T62);
+ SET(c, d, a, b, 2, 15, T63);
+ SET(b, c, d, a, 9, 21, T64);
#undef SET
- /* Then perform the following additions. (That is increment each
- of the four registers by the value it had before this block
- was started.) */
- pms->abcd[0] += a;
- pms->abcd[1] += b;
- pms->abcd[2] += c;
- pms->abcd[3] += d;
+ /* Then perform the following additions. (That is increment each
+ of the four registers by the value it had before this block
+ was started.) */
+ pms->abcd[0] += a;
+ pms->abcd[1] += b;
+ pms->abcd[2] += c;
+ pms->abcd[3] += d;
}
/* Initialize the algorithm. */
-static void md5_init(md5_state_t *pms)
+static void md5_init(md5_state_t* pms)
{
- pms->count[0] = pms->count[1] = 0;
- pms->abcd[0] = 0x67452301;
- pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
- pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
- pms->abcd[3] = 0x10325476;
+ pms->count[0] = pms->count[1] = 0;
+ pms->abcd[0] = 0x67452301;
+ pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
+ pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
+ pms->abcd[3] = 0x10325476;
}
/* Append a string to the message. */
-static void md5_append(md5_state_t *pms, const md5_byte_t *data, size_t nbytes)
+static void md5_append(md5_state_t* pms, const md5_byte_t* data, size_t nbytes)
{
- const md5_byte_t *p = data;
- size_t left = nbytes;
- size_t offset = (pms->count[0] >> 3) & 63;
- md5_word_t nbits = (md5_word_t)(nbytes << 3);
-
- if (nbytes <= 0)
- return;
-
- /* Update the message length. */
- pms->count[1] += (md5_word_t)(nbytes >> 29);
- pms->count[0] += nbits;
- if (pms->count[0] < nbits)
- pms->count[1]++;
-
- /* Process an initial partial block. */
- if (offset) {
- size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
- memcpy(pms->buf + offset, p, copy);
- if (offset + copy < 64)
- return;
- p += copy;
- left -= copy;
- md5_process(pms, pms->buf);
- }
+ const md5_byte_t* p = data;
+ size_t left = nbytes;
+ size_t offset = (pms->count[0] >> 3) & 63;
+ md5_word_t nbits = (md5_word_t)(nbytes << 3);
- /* Process full blocks. */
- for (; left >= 64; p += 64, left -= 64)
- md5_process(pms, p);
+ if (nbytes <= 0)
+ return;
- /* Process a final partial block. */
- if (left)
- memcpy(pms->buf, p, left);
+ /* Update the message length. */
+ pms->count[1] += (md5_word_t)(nbytes >> 29);
+ pms->count[0] += nbits;
+ if (pms->count[0] < nbits)
+ pms->count[1]++;
+
+ /* Process an initial partial block. */
+ if (offset) {
+ size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+ memcpy(pms->buf + offset, p, copy);
+ if (offset + copy < 64)
+ return;
+ p += copy;
+ left -= copy;
+ md5_process(pms, pms->buf);
+ }
+
+ /* Process full blocks. */
+ for (; left >= 64; p += 64, left -= 64)
+ md5_process(pms, p);
+
+ /* Process a final partial block. */
+ if (left)
+ memcpy(pms->buf, p, left);
}
/* Finish the message and return the digest. */
-static void md5_finish(md5_state_t *pms, md5_byte_t digest[16])
+static void md5_finish(md5_state_t* pms, md5_byte_t digest[16])
{
- static const md5_byte_t pad[64] = {
- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
- };
- md5_byte_t data[8];
- int i;
-
- /* Save the length before padding. */
- for (i = 0; i < 8; ++i)
- data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
- /* Pad to 56 bytes mod 64. */
- md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
- /* Append the length. */
- md5_append(pms, data, 8);
- for (i = 0; i < 16; ++i)
- digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+ static const md5_byte_t pad[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ md5_byte_t data[8];
+ int i;
+
+ /* Save the length before padding. */
+ for (i = 0; i < 8; ++i)
+ data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+ /* Pad to 56 bytes mod 64. */
+ md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
+ /* Append the length. */
+ md5_append(pms, data, 8);
+ for (i = 0; i < 16; ++i)
+ digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
#if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic pop
+#pragma clang diagnostic pop
#endif
/*--------------------------------------------------------------------------*/
@@ -449,10 +437,9 @@ kwsysMD5* kwsysMD5_New(void)
{
/* Allocate a process control structure. */
kwsysMD5* md5 = (kwsysMD5*)malloc(sizeof(kwsysMD5));
- if(!md5)
- {
+ if (!md5) {
return 0;
- }
+ }
return md5;
}
@@ -460,10 +447,9 @@ kwsysMD5* kwsysMD5_New(void)
void kwsysMD5_Delete(kwsysMD5* md5)
{
/* Make sure we have an instance. */
- if(!md5)
- {
+ if (!md5) {
return;
- }
+ }
/* Free memory. */
free(md5);
@@ -479,14 +465,11 @@ void kwsysMD5_Initialize(kwsysMD5* md5)
void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data, int length)
{
size_t dlen;
- if(length < 0)
- {
+ if (length < 0) {
dlen = strlen((char const*)data);
- }
- else
- {
+ } else {
dlen = (size_t)length;
- }
+ }
md5_append(&md5->md5_state, (md5_byte_t const*)data, dlen);
}
@@ -508,16 +491,14 @@ void kwsysMD5_FinalizeHex(kwsysMD5* md5, char buffer[32])
void kwsysMD5_DigestToHex(unsigned char const digest[16], char buffer[32])
{
/* Map from 4-bit index to hexadecimal representation. */
- static char const hex[16] =
- {'0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+ static char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/* Map each 4-bit block separately. */
char* out = buffer;
int i;
- for(i=0; i < 16; ++i)
- {
+ for (i = 0; i < 16; ++i) {
*out++ = hex[digest[i] >> 4];
*out++ = hex[digest[i] & 0xF];
- }
+ }
}
diff --git a/Source/kwsys/MD5.h.in b/Source/kwsys/MD5.h.in
index 3334431..c257f7f 100644
--- a/Source/kwsys/MD5.h.in
+++ b/Source/kwsys/MD5.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_MD5_h
#define @KWSYS_NAMESPACE@_MD5_h
@@ -19,24 +10,23 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysMD5 kwsys_ns(MD5)
-# define kwsysMD5_s kwsys_ns(MD5_s)
-# define kwsysMD5_New kwsys_ns(MD5_New)
-# define kwsysMD5_Delete kwsys_ns(MD5_Delete)
-# define kwsysMD5_Initialize kwsys_ns(MD5_Initialize)
-# define kwsysMD5_Append kwsys_ns(MD5_Append)
-# define kwsysMD5_Finalize kwsys_ns(MD5_Finalize)
-# define kwsysMD5_FinalizeHex kwsys_ns(MD5_FinalizeHex)
-# define kwsysMD5_DigestToHex kwsys_ns(MD5_DigestToHex)
+#define kwsysMD5 kwsys_ns(MD5)
+#define kwsysMD5_s kwsys_ns(MD5_s)
+#define kwsysMD5_New kwsys_ns(MD5_New)
+#define kwsysMD5_Delete kwsys_ns(MD5_Delete)
+#define kwsysMD5_Initialize kwsys_ns(MD5_Initialize)
+#define kwsysMD5_Append kwsys_ns(MD5_Append)
+#define kwsysMD5_Finalize kwsys_ns(MD5_Finalize)
+#define kwsysMD5_FinalizeHex kwsys_ns(MD5_FinalizeHex)
+#define kwsysMD5_DigestToHex kwsys_ns(MD5_DigestToHex)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
/**
@@ -89,19 +79,19 @@ kwsysEXPORT void kwsysMD5_DigestToHex(unsigned char const digest[16],
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysMD5
-# undef kwsysMD5_s
-# undef kwsysMD5_New
-# undef kwsysMD5_Delete
-# undef kwsysMD5_Initialize
-# undef kwsysMD5_Append
-# undef kwsysMD5_Finalize
-# undef kwsysMD5_FinalizeHex
-# undef kwsysMD5_DigestToHex
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysMD5
+#undef kwsysMD5_s
+#undef kwsysMD5_New
+#undef kwsysMD5_Delete
+#undef kwsysMD5_Initialize
+#undef kwsysMD5_Append
+#undef kwsysMD5_Finalize
+#undef kwsysMD5_FinalizeHex
+#undef kwsysMD5_DigestToHex
+#endif
#endif
#endif
diff --git a/Source/kwsys/Process.h.in b/Source/kwsys/Process.h.in
index 96563a2..b8349a6 100644
--- a/Source/kwsys/Process.h.in
+++ b/Source/kwsys/Process.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Process_h
#define @KWSYS_NAMESPACE@_Process_h
@@ -19,70 +10,70 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysProcess kwsys_ns(Process)
-# define kwsysProcess_s kwsys_ns(Process_s)
-# define kwsysProcess_New kwsys_ns(Process_New)
-# define kwsysProcess_Delete kwsys_ns(Process_Delete)
-# define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand)
-# define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand)
-# define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout)
-# define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory)
-# define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile)
-# define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative)
-# define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared)
-# define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach)
-# define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow)
-# define kwsysProcess_Option_MergeOutput kwsys_ns(Process_Option_MergeOutput)
-# define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim)
-# define kwsysProcess_Option_CreateProcessGroup kwsys_ns(Process_Option_CreateProcessGroup)
-# define kwsysProcess_GetOption kwsys_ns(Process_GetOption)
-# define kwsysProcess_SetOption kwsys_ns(Process_SetOption)
-# define kwsysProcess_Option_e kwsys_ns(Process_Option_e)
-# define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting)
-# define kwsysProcess_State_Error kwsys_ns(Process_State_Error)
-# define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception)
-# define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing)
-# define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited)
-# define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired)
-# define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed)
-# define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned)
-# define kwsysProcess_GetState kwsys_ns(Process_GetState)
-# define kwsysProcess_State_e kwsys_ns(Process_State_e)
-# define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None)
-# define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault)
-# define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal)
-# define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt)
-# define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical)
-# define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other)
-# define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException)
-# define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e)
-# define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode)
-# define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue)
-# define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString)
-# define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString)
-# define kwsysProcess_Execute kwsys_ns(Process_Execute)
-# define kwsysProcess_Disown kwsys_ns(Process_Disown)
-# define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData)
-# define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e)
-# define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None)
-# define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN)
-# define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT)
-# define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR)
-# define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout)
-# define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle)
-# define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit)
-# define kwsysProcess_Interrupt kwsys_ns(Process_Interrupt)
-# define kwsysProcess_Kill kwsys_ns(Process_Kill)
-# define kwsysProcess_ResetStartTime kwsys_ns(Process_ResetStartTime)
+#define kwsysProcess kwsys_ns(Process)
+#define kwsysProcess_s kwsys_ns(Process_s)
+#define kwsysProcess_New kwsys_ns(Process_New)
+#define kwsysProcess_Delete kwsys_ns(Process_Delete)
+#define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand)
+#define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand)
+#define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout)
+#define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory)
+#define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile)
+#define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative)
+#define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared)
+#define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach)
+#define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow)
+#define kwsysProcess_Option_MergeOutput kwsys_ns(Process_Option_MergeOutput)
+#define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim)
+#define kwsysProcess_Option_CreateProcessGroup \
+ kwsys_ns(Process_Option_CreateProcessGroup)
+#define kwsysProcess_GetOption kwsys_ns(Process_GetOption)
+#define kwsysProcess_SetOption kwsys_ns(Process_SetOption)
+#define kwsysProcess_Option_e kwsys_ns(Process_Option_e)
+#define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting)
+#define kwsysProcess_State_Error kwsys_ns(Process_State_Error)
+#define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception)
+#define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing)
+#define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited)
+#define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired)
+#define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed)
+#define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned)
+#define kwsysProcess_GetState kwsys_ns(Process_GetState)
+#define kwsysProcess_State_e kwsys_ns(Process_State_e)
+#define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None)
+#define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault)
+#define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal)
+#define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt)
+#define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical)
+#define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other)
+#define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException)
+#define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e)
+#define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode)
+#define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue)
+#define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString)
+#define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString)
+#define kwsysProcess_Execute kwsys_ns(Process_Execute)
+#define kwsysProcess_Disown kwsys_ns(Process_Disown)
+#define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData)
+#define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e)
+#define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None)
+#define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN)
+#define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT)
+#define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR)
+#define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout)
+#define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle)
+#define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit)
+#define kwsysProcess_Interrupt kwsys_ns(Process_Interrupt)
+#define kwsysProcess_Kill kwsys_ns(Process_Kill)
+#define kwsysProcess_ResetStartTime kwsys_ns(Process_ResetStartTime)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
/**
@@ -256,9 +247,12 @@ enum kwsysProcess_State_e
*
* kwsysProcess_Exception_None = No exceptional behavior occurred.
* kwsysProcess_Exception_Fault = Child crashed with a memory fault.
- * kwsysProcess_Exception_Illegal = Child crashed with an illegal instruction.
- * kwsysProcess_Exception_Interrupt = Child was interrupted by user (Cntl-C/Break).
- * kwsysProcess_Exception_Numerical = Child crashed with a numerical exception.
+ * kwsysProcess_Exception_Illegal = Child crashed with an illegal
+ * instruction.
+ * kwsysProcess_Exception_Interrupt = Child was interrupted by user
+ * (Cntl-C/Break).
+ * kwsysProcess_Exception_Numerical = Child crashed with a numerical
+ * exception.
* kwsysProcess_Exception_Other = Child terminated for another reason.
*/
kwsysEXPORT int kwsysProcess_GetExitException(kwsysProcess* cp);
@@ -352,7 +346,7 @@ enum kwsysProcess_Pipes_e
kwsysProcess_Pipe_STDIN,
kwsysProcess_Pipe_STDOUT,
kwsysProcess_Pipe_STDERR,
- kwsysProcess_Pipe_Timeout=255
+ kwsysProcess_Pipe_Timeout = 255
};
/**
@@ -405,65 +399,65 @@ kwsysEXPORT void kwsysProcess_ResetStartTime(kwsysProcess* cp);
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysProcess
-# undef kwsysProcess_s
-# undef kwsysProcess_New
-# undef kwsysProcess_Delete
-# undef kwsysProcess_SetCommand
-# undef kwsysProcess_AddCommand
-# undef kwsysProcess_SetTimeout
-# undef kwsysProcess_SetWorkingDirectory
-# undef kwsysProcess_SetPipeFile
-# undef kwsysProcess_SetPipeNative
-# undef kwsysProcess_SetPipeShared
-# undef kwsysProcess_Option_Detach
-# undef kwsysProcess_Option_HideWindow
-# undef kwsysProcess_Option_MergeOutput
-# undef kwsysProcess_Option_Verbatim
-# undef kwsysProcess_Option_CreateProcessGroup
-# undef kwsysProcess_GetOption
-# undef kwsysProcess_SetOption
-# undef kwsysProcess_Option_e
-# undef kwsysProcess_State_Starting
-# undef kwsysProcess_State_Error
-# undef kwsysProcess_State_Exception
-# undef kwsysProcess_State_Executing
-# undef kwsysProcess_State_Exited
-# undef kwsysProcess_State_Expired
-# undef kwsysProcess_State_Killed
-# undef kwsysProcess_State_Disowned
-# undef kwsysProcess_GetState
-# undef kwsysProcess_State_e
-# undef kwsysProcess_Exception_None
-# undef kwsysProcess_Exception_Fault
-# undef kwsysProcess_Exception_Illegal
-# undef kwsysProcess_Exception_Interrupt
-# undef kwsysProcess_Exception_Numerical
-# undef kwsysProcess_Exception_Other
-# undef kwsysProcess_GetExitException
-# undef kwsysProcess_Exception_e
-# undef kwsysProcess_GetExitCode
-# undef kwsysProcess_GetExitValue
-# undef kwsysProcess_GetErrorString
-# undef kwsysProcess_GetExceptionString
-# undef kwsysProcess_Execute
-# undef kwsysProcess_Disown
-# undef kwsysProcess_WaitForData
-# undef kwsysProcess_Pipes_e
-# undef kwsysProcess_Pipe_None
-# undef kwsysProcess_Pipe_STDIN
-# undef kwsysProcess_Pipe_STDOUT
-# undef kwsysProcess_Pipe_STDERR
-# undef kwsysProcess_Pipe_Timeout
-# undef kwsysProcess_Pipe_Handle
-# undef kwsysProcess_WaitForExit
-# undef kwsysProcess_Interrupt
-# undef kwsysProcess_Kill
-# undef kwsysProcess_ResetStartTime
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysProcess
+#undef kwsysProcess_s
+#undef kwsysProcess_New
+#undef kwsysProcess_Delete
+#undef kwsysProcess_SetCommand
+#undef kwsysProcess_AddCommand
+#undef kwsysProcess_SetTimeout
+#undef kwsysProcess_SetWorkingDirectory
+#undef kwsysProcess_SetPipeFile
+#undef kwsysProcess_SetPipeNative
+#undef kwsysProcess_SetPipeShared
+#undef kwsysProcess_Option_Detach
+#undef kwsysProcess_Option_HideWindow
+#undef kwsysProcess_Option_MergeOutput
+#undef kwsysProcess_Option_Verbatim
+#undef kwsysProcess_Option_CreateProcessGroup
+#undef kwsysProcess_GetOption
+#undef kwsysProcess_SetOption
+#undef kwsysProcess_Option_e
+#undef kwsysProcess_State_Starting
+#undef kwsysProcess_State_Error
+#undef kwsysProcess_State_Exception
+#undef kwsysProcess_State_Executing
+#undef kwsysProcess_State_Exited
+#undef kwsysProcess_State_Expired
+#undef kwsysProcess_State_Killed
+#undef kwsysProcess_State_Disowned
+#undef kwsysProcess_GetState
+#undef kwsysProcess_State_e
+#undef kwsysProcess_Exception_None
+#undef kwsysProcess_Exception_Fault
+#undef kwsysProcess_Exception_Illegal
+#undef kwsysProcess_Exception_Interrupt
+#undef kwsysProcess_Exception_Numerical
+#undef kwsysProcess_Exception_Other
+#undef kwsysProcess_GetExitException
+#undef kwsysProcess_Exception_e
+#undef kwsysProcess_GetExitCode
+#undef kwsysProcess_GetExitValue
+#undef kwsysProcess_GetErrorString
+#undef kwsysProcess_GetExceptionString
+#undef kwsysProcess_Execute
+#undef kwsysProcess_Disown
+#undef kwsysProcess_WaitForData
+#undef kwsysProcess_Pipes_e
+#undef kwsysProcess_Pipe_None
+#undef kwsysProcess_Pipe_STDIN
+#undef kwsysProcess_Pipe_STDOUT
+#undef kwsysProcess_Pipe_STDERR
+#undef kwsysProcess_Pipe_Timeout
+#undef kwsysProcess_Pipe_Handle
+#undef kwsysProcess_WaitForExit
+#undef kwsysProcess_Interrupt
+#undef kwsysProcess_Kill
+#undef kwsysProcess_ResetStartTime
+#endif
#endif
#endif
diff --git a/Source/kwsys/ProcessUNIX.c b/Source/kwsys/ProcessUNIX.c
index b577982..ed09095 100644
--- a/Source/kwsys/ProcessUNIX.c
+++ b/Source/kwsys/ProcessUNIX.c
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
#include KWSYS_HEADER(System.h)
@@ -16,8 +7,8 @@
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Process.h.in"
-# include "System.h.in"
+#include "Process.h.in"
+#include "System.h.in"
#endif
/*
@@ -35,7 +26,6 @@ races.
*/
-
/*
TODO:
@@ -50,30 +40,30 @@ do.
#if defined(__CYGWIN__)
/* Increase the file descriptor limit for select() before including
related system headers. (Default: 64) */
-# define FD_SETSIZE 16384
+#define FD_SETSIZE 16384
#endif
+#include <assert.h> /* assert */
+#include <ctype.h> /* isspace */
+#include <dirent.h> /* DIR, dirent */
+#include <errno.h> /* errno */
+#include <fcntl.h> /* fcntl */
+#include <signal.h> /* sigaction */
#include <stddef.h> /* ptrdiff_t */
#include <stdio.h> /* snprintf */
#include <stdlib.h> /* malloc, free */
#include <string.h> /* strdup, strerror, memset */
+#include <sys/stat.h> /* open mode */
#include <sys/time.h> /* struct timeval */
#include <sys/types.h> /* pid_t, fd_set */
#include <sys/wait.h> /* waitpid */
-#include <sys/stat.h> /* open mode */
-#include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
-#include <fcntl.h> /* fcntl */
-#include <errno.h> /* errno */
#include <time.h> /* gettimeofday */
-#include <signal.h> /* sigaction */
-#include <dirent.h> /* DIR, dirent */
-#include <ctype.h> /* isspace */
-#include <assert.h> /* assert */
+#include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
#if defined(__VMS)
-# define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
+#define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
#else
-# define KWSYSPE_VMS_NONBLOCK
+#define KWSYSPE_VMS_NONBLOCK
#endif
#if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
@@ -90,13 +80,13 @@ typedef int kwsysProcess_ssize_t;
#if defined(__BEOS__) && !defined(__ZETA__)
/* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
-# include <be/kernel/OS.h>
+#include <be/kernel/OS.h>
static inline void kwsysProcess_usleep(unsigned int msec)
{
snooze(msec);
}
#else
-# define kwsysProcess_usleep usleep
+#define kwsysProcess_usleep usleep
#endif
/*
@@ -110,12 +100,12 @@ static inline void kwsysProcess_usleep(unsigned int msec)
* without select().
*/
#if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__)
-# define KWSYSPE_USE_SELECT 1
+#define KWSYSPE_USE_SELECT 1
#endif
/* Some platforms do not have siginfo on their signal handlers. */
#if defined(SA_SIGINFO) && !defined(__BEOS__)
-# define KWSYSPE_USE_SIGINFO 1
+#define KWSYSPE_USE_SIGINFO 1
#endif
/* The number of pipes for the child's output. The standard stdout
@@ -172,8 +162,10 @@ static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
static double kwsysProcessTimeToDouble(kwsysProcessTime t);
static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+ kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+ kwsysProcessTime in2);
static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
static void kwsysProcessChildErrorExit(int errorPipe);
static void kwsysProcessRestoreDefaultSignalHandlers(void);
@@ -281,10 +273,10 @@ struct kwsysProcess_s
volatile sig_atomic_t Killed;
/* Buffer for error message in case of failure. */
- char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
+ char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
/* Description for the ExitException. */
- char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
+ char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
/* The exit codes of each child process in the pipeline. */
int* CommandExitCodes;
@@ -314,10 +306,9 @@ kwsysProcess* kwsysProcess_New(void)
{
/* Allocate a process control structure. */
kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
+ }
memset(cp, 0, sizeof(kwsysProcess));
/* Share stdin with the parent process by default. */
@@ -341,23 +332,18 @@ kwsysProcess* kwsysProcess_New(void)
void kwsysProcess_Delete(kwsysProcess* cp)
{
/* Make sure we have an instance. */
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
/* If the process is executing, wait for it to finish. */
- if(cp->State == kwsysProcess_State_Executing)
- {
- if(cp->Detached)
- {
+ if (cp->State == kwsysProcess_State_Executing) {
+ if (cp->Detached) {
kwsysProcess_Disown(cp);
- }
- else
- {
+ } else {
kwsysProcess_WaitForExit(cp, 0);
- }
}
+ }
/* Free memory. */
kwsysProcess_SetCommand(cp, 0);
@@ -365,10 +351,9 @@ void kwsysProcess_Delete(kwsysProcess* cp)
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
- if(cp->CommandExitCodes)
- {
+ if (cp->CommandExitCodes) {
free(cp->CommandExitCodes);
- }
+ }
free(cp);
}
@@ -376,29 +361,24 @@ void kwsysProcess_Delete(kwsysProcess* cp)
int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
{
int i;
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ }
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
char** c = cp->Commands[i];
- while(*c)
- {
+ while (*c) {
free(*c++);
- }
- free(cp->Commands[i]);
}
+ free(cp->Commands[i]);
+ }
cp->NumberOfCommands = 0;
- if(cp->Commands)
- {
+ if (cp->Commands) {
free(cp->Commands);
cp->Commands = 0;
- }
- if(command)
- {
+ }
+ if (command) {
return kwsysProcess_AddCommand(cp, command);
- }
+ }
return 1;
}
@@ -409,81 +389,70 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
char*** newCommands;
/* Make sure we have a command to add. */
- if(!cp || !command || !*command)
- {
+ if (!cp || !command || !*command) {
return 0;
- }
+ }
/* Allocate a new array for command pointers. */
newNumberOfCommands = cp->NumberOfCommands + 1;
- if(!(newCommands =
- (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands))))
- {
+ if (!(newCommands =
+ (char***)malloc(sizeof(char**) * (size_t)(newNumberOfCommands)))) {
/* Out of memory. */
return 0;
- }
+ }
/* Copy any existing commands into the new array. */
{
- int i;
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- newCommands[i] = cp->Commands[i];
+ int i;
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ newCommands[i] = cp->Commands[i];
}
}
/* Add the new command. */
- if(cp->Verbatim)
- {
+ if (cp->Verbatim) {
/* In order to run the given command line verbatim we need to
parse it. */
newCommands[cp->NumberOfCommands] =
kwsysSystem_Parse_CommandForUnix(*command, 0);
- if(!newCommands[cp->NumberOfCommands] ||
- !newCommands[cp->NumberOfCommands][0])
- {
+ if (!newCommands[cp->NumberOfCommands] ||
+ !newCommands[cp->NumberOfCommands][0]) {
/* Out of memory or no command parsed. */
free(newCommands);
return 0;
- }
}
- else
- {
+ } else {
/* Copy each argument string individually. */
char const* const* c = command;
kwsysProcess_ptrdiff_t n = 0;
kwsysProcess_ptrdiff_t i = 0;
- while(*c++);
+ while (*c++)
+ ;
n = c - command - 1;
newCommands[cp->NumberOfCommands] =
- (char**)malloc((size_t)(n+1)*sizeof(char*));
- if(!newCommands[cp->NumberOfCommands])
- {
+ (char**)malloc((size_t)(n + 1) * sizeof(char*));
+ if (!newCommands[cp->NumberOfCommands]) {
/* Out of memory. */
free(newCommands);
return 0;
- }
- for(i=0; i < n; ++i)
- {
+ }
+ for (i = 0; i < n; ++i) {
assert(command[i]); /* Quiet Clang scan-build. */
newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
- if(!newCommands[cp->NumberOfCommands][i])
- {
+ if (!newCommands[cp->NumberOfCommands][i]) {
break;
- }
}
- if(i < n)
- {
+ }
+ if (i < n) {
/* Out of memory. */
- for(;i > 0; --i)
- {
- free(newCommands[cp->NumberOfCommands][i-1]);
- }
+ for (; i > 0; --i) {
+ free(newCommands[cp->NumberOfCommands][i - 1]);
+ }
free(newCommands);
return 0;
- }
- newCommands[cp->NumberOfCommands][n] = 0;
}
+ newCommands[cp->NumberOfCommands][n] = 0;
+ }
/* Successfully allocated new command array. Free the old array. */
free(cp->Commands);
@@ -496,15 +465,13 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
/*--------------------------------------------------------------------------*/
void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
cp->Timeout = timeout;
- if(cp->Timeout < 0)
- {
+ if (cp->Timeout < 0) {
cp->Timeout = 0;
- }
+ }
// Force recomputation of TimeoutTime.
cp->TimeoutTime.tv_sec = -1;
}
@@ -512,32 +479,26 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
/*--------------------------------------------------------------------------*/
int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
{
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
- if(cp->WorkingDirectory == dir)
- {
+ }
+ if (cp->WorkingDirectory == dir) {
return 1;
- }
- if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
- {
+ }
+ if (cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0) {
return 1;
- }
- if(cp->WorkingDirectory)
- {
+ }
+ if (cp->WorkingDirectory) {
free(cp->WorkingDirectory);
cp->WorkingDirectory = 0;
- }
- if(dir)
- {
+ }
+ if (dir) {
cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
- if(!cp->WorkingDirectory)
- {
+ if (!cp->WorkingDirectory) {
return 0;
- }
- strcpy(cp->WorkingDirectory, dir);
}
+ strcpy(cp->WorkingDirectory, dir);
+ }
return 1;
}
@@ -545,65 +506,70 @@ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
{
char** pfile;
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
- switch(prPipe)
- {
- case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
- case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
- case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
- default: return 0;
- }
- if(*pfile)
- {
+ }
+ switch (prPipe) {
+ case kwsysProcess_Pipe_STDIN:
+ pfile = &cp->PipeFileSTDIN;
+ break;
+ case kwsysProcess_Pipe_STDOUT:
+ pfile = &cp->PipeFileSTDOUT;
+ break;
+ case kwsysProcess_Pipe_STDERR:
+ pfile = &cp->PipeFileSTDERR;
+ break;
+ default:
+ return 0;
+ }
+ if (*pfile) {
free(*pfile);
*pfile = 0;
- }
- if(file)
- {
- *pfile = (char*)malloc(strlen(file)+1);
- if(!*pfile)
- {
+ }
+ if (file) {
+ *pfile = (char*)malloc(strlen(file) + 1);
+ if (!*pfile) {
return 0;
- }
- strcpy(*pfile, file);
}
+ strcpy(*pfile, file);
+ }
/* If we are redirecting the pipe, do not share it or use a native
pipe. */
- if(*pfile)
- {
+ if (*pfile) {
kwsysProcess_SetPipeNative(cp, prPipe, 0);
kwsysProcess_SetPipeShared(cp, prPipe, 0);
- }
+ }
return 1;
}
/*--------------------------------------------------------------------------*/
void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
- switch(prPipe)
- {
- case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
- case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
- case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
- default: return;
- }
+ switch (prPipe) {
+ case kwsysProcess_Pipe_STDIN:
+ cp->PipeSharedSTDIN = shared ? 1 : 0;
+ break;
+ case kwsysProcess_Pipe_STDOUT:
+ cp->PipeSharedSTDOUT = shared ? 1 : 0;
+ break;
+ case kwsysProcess_Pipe_STDERR:
+ cp->PipeSharedSTDERR = shared ? 1 : 0;
+ break;
+ default:
+ return;
+ }
/* If we are sharing the pipe, do not redirect it to a file or use a
native pipe. */
- if(shared)
- {
+ if (shared) {
kwsysProcess_SetPipeFile(cp, prPipe, 0);
kwsysProcess_SetPipeNative(cp, prPipe, 0);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -611,127 +577,130 @@ void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
{
int* pPipeNative = 0;
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
- switch(prPipe)
- {
- case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
- case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
- case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
- default: return;
- }
+ switch (prPipe) {
+ case kwsysProcess_Pipe_STDIN:
+ pPipeNative = cp->PipeNativeSTDIN;
+ break;
+ case kwsysProcess_Pipe_STDOUT:
+ pPipeNative = cp->PipeNativeSTDOUT;
+ break;
+ case kwsysProcess_Pipe_STDERR:
+ pPipeNative = cp->PipeNativeSTDERR;
+ break;
+ default:
+ return;
+ }
/* Copy the native pipe descriptors provided. */
- if(p)
- {
+ if (p) {
pPipeNative[0] = p[0];
pPipeNative[1] = p[1];
- }
- else
- {
+ } else {
pPipeNative[0] = -1;
pPipeNative[1] = -1;
- }
+ }
/* If we are using a native pipe, do not share it or redirect it to
a file. */
- if(p)
- {
+ if (p) {
kwsysProcess_SetPipeFile(cp, prPipe, 0);
kwsysProcess_SetPipeShared(cp, prPipe, 0);
- }
+ }
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
{
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
+ }
- switch(optionId)
- {
- case kwsysProcess_Option_Detach: return cp->OptionDetach;
- case kwsysProcess_Option_MergeOutput: return cp->MergeOutput;
- case kwsysProcess_Option_Verbatim: return cp->Verbatim;
+ switch (optionId) {
+ case kwsysProcess_Option_Detach:
+ return cp->OptionDetach;
+ case kwsysProcess_Option_MergeOutput:
+ return cp->MergeOutput;
+ case kwsysProcess_Option_Verbatim:
+ return cp->Verbatim;
case kwsysProcess_Option_CreateProcessGroup:
return cp->CreateProcessGroup;
- default: return 0;
- }
+ default:
+ return 0;
+ }
}
/*--------------------------------------------------------------------------*/
void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
- switch(optionId)
- {
- case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
- case kwsysProcess_Option_MergeOutput: cp->MergeOutput = value; break;
- case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
+ switch (optionId) {
+ case kwsysProcess_Option_Detach:
+ cp->OptionDetach = value;
+ break;
+ case kwsysProcess_Option_MergeOutput:
+ cp->MergeOutput = value;
+ break;
+ case kwsysProcess_Option_Verbatim:
+ cp->Verbatim = value;
+ break;
case kwsysProcess_Option_CreateProcessGroup:
- cp->CreateProcessGroup = value; break;
- default: break;
- }
+ cp->CreateProcessGroup = value;
+ break;
+ default:
+ break;
+ }
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetState(kwsysProcess* cp)
{
- return cp? cp->State : kwsysProcess_State_Error;
+ return cp ? cp->State : kwsysProcess_State_Error;
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitException(kwsysProcess* cp)
{
- return cp? cp->ExitException : kwsysProcess_Exception_Other;
+ return cp ? cp->ExitException : kwsysProcess_Exception_Other;
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitCode(kwsysProcess* cp)
{
- return cp? cp->ExitCode : 0;
+ return cp ? cp->ExitCode : 0;
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitValue(kwsysProcess* cp)
{
- return cp? cp->ExitValue : -1;
+ return cp ? cp->ExitValue : -1;
}
/*--------------------------------------------------------------------------*/
const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
{
- if(!cp)
- {
+ if (!cp) {
return "Process management structure could not be allocated";
- }
- else if(cp->State == kwsysProcess_State_Error)
- {
+ } else if (cp->State == kwsysProcess_State_Error) {
return cp->ErrorMessage;
- }
+ }
return "Success";
}
/*--------------------------------------------------------------------------*/
const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
{
- if(!cp)
- {
+ if (!cp) {
return "GetExceptionString called with NULL process management structure";
- }
- else if(cp->State == kwsysProcess_State_Exception)
- {
+ } else if (cp->State == kwsysProcess_State_Exception) {
return cp->ExitExceptionString;
- }
+ }
return "No exception";
}
@@ -741,231 +710,193 @@ void kwsysProcess_Execute(kwsysProcess* cp)
int i;
/* Do not execute a second copy simultaneously. */
- if(!cp || cp->State == kwsysProcess_State_Executing)
- {
+ if (!cp || cp->State == kwsysProcess_State_Executing) {
return;
- }
+ }
/* Make sure we have something to run. */
- if(cp->NumberOfCommands < 1)
- {
+ if (cp->NumberOfCommands < 1) {
strcpy(cp->ErrorMessage, "No command");
cp->State = kwsysProcess_State_Error;
return;
- }
+ }
/* Initialize the control structure for a new process. */
- if(!kwsysProcessInitialize(cp))
- {
+ if (!kwsysProcessInitialize(cp)) {
strcpy(cp->ErrorMessage, "Out of memory");
cp->State = kwsysProcess_State_Error;
return;
- }
+ }
#if defined(__VMS)
/* Make sure pipes behave like streams on VMS. */
- if(!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1))
- {
+ if (!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1)) {
kwsysProcessCleanup(cp, 1);
return;
- }
+ }
#endif
/* Save the real working directory of this process and change to
the working directory for the child processes. This is needed
to make pipe file paths evaluate correctly. */
- if(cp->WorkingDirectory)
- {
+ if (cp->WorkingDirectory) {
int r;
- if(!getcwd(cp->RealWorkingDirectory,
- (size_t)(cp->RealWorkingDirectoryLength)))
- {
+ if (!getcwd(cp->RealWorkingDirectory,
+ (size_t)(cp->RealWorkingDirectoryLength))) {
kwsysProcessCleanup(cp, 1);
return;
- }
+ }
/* Some platforms specify that the chdir call may be
interrupted. Repeat the call until it finishes. */
- while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
- if(r < 0)
- {
+ while (((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR))
+ ;
+ if (r < 0) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
+ }
/* If not running a detached child, add this object to the global
set of process objects that wish to be notified when a child
exits. */
- if(!cp->OptionDetach)
- {
- if(!kwsysProcessesAdd(cp))
- {
+ if (!cp->OptionDetach) {
+ if (!kwsysProcessesAdd(cp)) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
+ }
/* Setup the stdin pipe for the first process. */
- if(cp->PipeFileSTDIN)
- {
+ if (cp->PipeFileSTDIN) {
/* Open a file for the child's stdin to read. */
cp->PipeChildStd[0] = open(cp->PipeFileSTDIN, O_RDONLY);
- if(cp->PipeChildStd[0] < 0)
- {
+ if (cp->PipeChildStd[0] < 0) {
kwsysProcessCleanup(cp, 1);
return;
- }
+ }
/* Set close-on-exec flag on the pipe's end. */
- if(fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0)
- {
+ if (fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
- else if(cp->PipeSharedSTDIN)
- {
+ } else if (cp->PipeSharedSTDIN) {
cp->PipeChildStd[0] = 0;
- }
- else if(cp->PipeNativeSTDIN[0] >= 0)
- {
+ } else if (cp->PipeNativeSTDIN[0] >= 0) {
cp->PipeChildStd[0] = cp->PipeNativeSTDIN[0];
/* Set close-on-exec flag on the pipe's ends. The read end will
be dup2-ed into the stdin descriptor after the fork but before
the exec. */
- if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
- {
+ if ((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0)) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
- else
- {
+ } else {
cp->PipeChildStd[0] = -1;
- }
+ }
/* Create the output pipe for the last process.
We always create this so the pipe can be passed to select even if
it will report closed immediately. */
{
- /* Create the pipe. */
- int p[2];
- if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
- {
- kwsysProcessCleanup(cp, 1);
- return;
+ /* Create the pipe. */
+ int p[2];
+ if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- /* Store the pipe. */
- cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
- cp->PipeChildStd[1] = p[1];
+ /* Store the pipe. */
+ cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
+ cp->PipeChildStd[1] = p[1];
- /* Set close-on-exec flag on the pipe's ends. */
- if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
- {
- kwsysProcessCleanup(cp, 1);
- return;
+ /* Set close-on-exec flag on the pipe's ends. */
+ if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- /* Set to non-blocking in case select lies, or for the polling
- implementation. */
- if(!kwsysProcessSetNonBlocking(p[0]))
- {
- kwsysProcessCleanup(cp, 1);
- return;
+ /* Set to non-blocking in case select lies, or for the polling
+ implementation. */
+ if (!kwsysProcessSetNonBlocking(p[0])) {
+ kwsysProcessCleanup(cp, 1);
+ return;
}
}
- if (cp->PipeFileSTDOUT)
- {
+ if (cp->PipeFileSTDOUT) {
/* Use a file for stdout. */
- if(!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
- cp->PipeFileSTDOUT))
- {
+ if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
+ cp->PipeFileSTDOUT)) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
- else if (cp->PipeSharedSTDOUT)
- {
+ } else if (cp->PipeSharedSTDOUT) {
/* Use the parent stdout. */
kwsysProcessCleanupDescriptor(&cp->PipeChildStd[1]);
cp->PipeChildStd[1] = 1;
- }
- else if (cp->PipeNativeSTDOUT[1] >= 0)
- {
+ } else if (cp->PipeNativeSTDOUT[1] >= 0) {
/* Use the given descriptor for stdout. */
- if(!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
- cp->PipeNativeSTDOUT))
- {
+ if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
+ cp->PipeNativeSTDOUT)) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
+ }
/* Create stderr pipe to be shared by all processes in the pipeline.
We always create this so the pipe can be passed to select even if
it will report closed immediately. */
{
- /* Create the pipe. */
- int p[2];
- if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
- {
- kwsysProcessCleanup(cp, 1);
- return;
+ /* Create the pipe. */
+ int p[2];
+ if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- /* Store the pipe. */
- cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
- cp->PipeChildStd[2] = p[1];
+ /* Store the pipe. */
+ cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
+ cp->PipeChildStd[2] = p[1];
- /* Set close-on-exec flag on the pipe's ends. */
- if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
- {
- kwsysProcessCleanup(cp, 1);
- return;
+ /* Set close-on-exec flag on the pipe's ends. */
+ if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- /* Set to non-blocking in case select lies, or for the polling
- implementation. */
- if(!kwsysProcessSetNonBlocking(p[0]))
- {
- kwsysProcessCleanup(cp, 1);
- return;
+ /* Set to non-blocking in case select lies, or for the polling
+ implementation. */
+ if (!kwsysProcessSetNonBlocking(p[0])) {
+ kwsysProcessCleanup(cp, 1);
+ return;
}
}
- if (cp->PipeFileSTDERR)
- {
+ if (cp->PipeFileSTDERR) {
/* Use a file for stderr. */
- if(!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
- cp->PipeFileSTDERR))
- {
+ if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
+ cp->PipeFileSTDERR)) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
- else if (cp->PipeSharedSTDERR)
- {
+ } else if (cp->PipeSharedSTDERR) {
/* Use the parent stderr. */
kwsysProcessCleanupDescriptor(&cp->PipeChildStd[2]);
cp->PipeChildStd[2] = 2;
- }
- else if (cp->PipeNativeSTDERR[1] >= 0)
- {
+ } else if (cp->PipeNativeSTDERR[1] >= 0) {
/* Use the given handle for stderr. */
- if(!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
- cp->PipeNativeSTDERR))
- {
+ if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
+ cp->PipeNativeSTDERR)) {
kwsysProcessCleanup(cp, 1);
return;
- }
}
+ }
/* The timeout period starts now. */
cp->StartTime = kwsysProcessTimeGetCurrent();
@@ -974,96 +905,82 @@ void kwsysProcess_Execute(kwsysProcess* cp)
/* Create the pipeline of processes. */
{
- kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
- int nextStdIn = cp->PipeChildStd[0];
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- /* Setup the process's pipes. */
- si.StdIn = nextStdIn;
- if (i == cp->NumberOfCommands-1)
- {
- nextStdIn = -1;
- si.StdOut = cp->PipeChildStd[1];
- }
- else
- {
- /* Create a pipe to sit between the children. */
- int p[2] = {-1,-1};
- if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
- {
- if (nextStdIn != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupDescriptor(&nextStdIn);
+ kwsysProcessCreateInformation si = { -1, -1, -1, { -1, -1 } };
+ int nextStdIn = cp->PipeChildStd[0];
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ /* Setup the process's pipes. */
+ si.StdIn = nextStdIn;
+ if (i == cp->NumberOfCommands - 1) {
+ nextStdIn = -1;
+ si.StdOut = cp->PipeChildStd[1];
+ } else {
+ /* Create a pipe to sit between the children. */
+ int p[2] = { -1, -1 };
+ if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+ if (nextStdIn != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupDescriptor(&nextStdIn);
}
- kwsysProcessCleanup(cp, 1);
- return;
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- /* Set close-on-exec flag on the pipe's ends. */
- if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
- {
- close(p[0]);
- close(p[1]);
- if (nextStdIn != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupDescriptor(&nextStdIn);
+ /* Set close-on-exec flag on the pipe's ends. */
+ if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+ close(p[0]);
+ close(p[1]);
+ if (nextStdIn != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupDescriptor(&nextStdIn);
}
- kwsysProcessCleanup(cp, 1);
- return;
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- nextStdIn = p[0];
- si.StdOut = p[1];
+ nextStdIn = p[0];
+ si.StdOut = p[1];
}
- si.StdErr = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2];
+ si.StdErr = cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2];
- {
- int res = kwsysProcessCreate(cp, i, &si);
-
- /* Close our copies of pipes used between children. */
- if (si.StdIn != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupDescriptor(&si.StdIn);
- }
- if (si.StdOut != cp->PipeChildStd[1])
- {
- kwsysProcessCleanupDescriptor(&si.StdOut);
- }
- if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput)
{
- kwsysProcessCleanupDescriptor(&si.StdErr);
- }
+ int res = kwsysProcessCreate(cp, i, &si);
- if(!res)
- {
- kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
- kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
- if (nextStdIn != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupDescriptor(&nextStdIn);
+ /* Close our copies of pipes used between children. */
+ if (si.StdIn != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupDescriptor(&si.StdIn);
+ }
+ if (si.StdOut != cp->PipeChildStd[1]) {
+ kwsysProcessCleanupDescriptor(&si.StdOut);
+ }
+ if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput) {
+ kwsysProcessCleanupDescriptor(&si.StdErr);
+ }
+
+ if (!res) {
+ kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
+ kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
+ if (nextStdIn != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupDescriptor(&nextStdIn);
+ }
+ kwsysProcessCleanup(cp, 1);
+ return;
}
- kwsysProcessCleanup(cp, 1);
- return;
}
}
- }
}
/* The parent process does not need the child's pipe ends. */
- for (i=0; i < 3; ++i)
- {
+ for (i = 0; i < 3; ++i) {
kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
- }
+ }
/* Restore the working directory. */
- if(cp->RealWorkingDirectory)
- {
+ if (cp->RealWorkingDirectory) {
/* Some platforms specify that the chdir call may be
interrupted. Repeat the call until it finishes. */
- while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
+ while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
+ ;
free(cp->RealWorkingDirectory);
cp->RealWorkingDirectory = 0;
- }
+ }
/* All the pipes are now open. */
cp->PipesLeft = KWSYSPE_PIPE_COUNT;
@@ -1077,11 +994,10 @@ void kwsysProcess_Execute(kwsysProcess* cp)
kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
{
/* Make sure a detached child process is running. */
- if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
- cp->TimeoutExpired || cp->Killed)
- {
+ if (!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
+ cp->TimeoutExpired || cp->Killed) {
return;
- }
+ }
/* Close all the pipes safely. */
kwsysProcessClosePipes(cp);
@@ -1109,81 +1025,62 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
double* userTimeout)
{
- kwsysProcessTime userStartTime = {0, 0};
- kwsysProcessWaitData wd =
- {
- 0,
- kwsysProcess_Pipe_None,
- 0,
- 0,
- {0, 0}
- };
+ kwsysProcessTime userStartTime = { 0, 0 };
+ kwsysProcessWaitData wd = { 0, kwsysProcess_Pipe_None, 0, 0, { 0, 0 } };
wd.UserTimeout = userTimeout;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
- cp->TimeoutExpired)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
+ cp->TimeoutExpired) {
return kwsysProcess_Pipe_None;
- }
+ }
/* Record the time at which user timeout period starts. */
- if(userTimeout)
- {
+ if (userTimeout) {
userStartTime = kwsysProcessTimeGetCurrent();
- }
+ }
/* Calculate the time at which a timeout will expire, and whether it
is the user or process timeout. */
- wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
- &wd.TimeoutTime);
+ wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout, &wd.TimeoutTime);
/* Data can only be available when pipes are open. If the process
is not running, cp->PipesLeft will be 0. */
- while(cp->PipesLeft > 0 &&
- !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
+ while (cp->PipesLeft > 0 &&
+ !kwsysProcessWaitForPipe(cp, data, length, &wd)) {
+ }
/* Update the user timeout. */
- if(userTimeout)
- {
+ if (userTimeout) {
kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
- kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
- userStartTime);
+ kwsysProcessTime difference =
+ kwsysProcessTimeSubtract(userEndTime, userStartTime);
double d = kwsysProcessTimeToDouble(difference);
*userTimeout -= d;
- if(*userTimeout < 0)
- {
+ if (*userTimeout < 0) {
*userTimeout = 0;
- }
}
+ }
/* Check what happened. */
- if(wd.PipeId)
- {
+ if (wd.PipeId) {
/* Data are ready on a pipe. */
return wd.PipeId;
- }
- else if(wd.Expired)
- {
+ } else if (wd.Expired) {
/* A timeout has expired. */
- if(wd.User)
- {
+ if (wd.User) {
/* The user timeout has expired. It has no time left. */
return kwsysProcess_Pipe_Timeout;
- }
- else
- {
+ } else {
/* The process timeout has expired. Kill the children now. */
kwsysProcess_Kill(cp);
cp->Killed = 0;
cp->TimeoutExpired = 1;
return kwsysProcess_Pipe_None;
- }
}
- else
- {
+ } else {
/* No pipes are left open. */
return kwsysProcess_Pipe_None;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1202,11 +1099,9 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
call to select. According to "man select_tut" we must deal
with all descriptors reported by a call to select before
passing them to another select call. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
- if(cp->PipeReadEnds[i] >= 0 &&
- FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+ if (cp->PipeReadEnds[i] >= 0 &&
+ FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet)) {
kwsysProcess_ssize_t n;
/* We are handling this pipe now. Remove it from the set. */
@@ -1214,108 +1109,91 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
/* The pipe is ready to read without blocking. Keep trying to
read until the operation is not interrupted. */
- while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
- KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
- if(n > 0)
- {
+ while (((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
+ KWSYSPE_PIPE_BUFFER_SIZE)) < 0) &&
+ (errno == EINTR))
+ ;
+ if (n > 0) {
/* We have data on this pipe. */
- if(i == KWSYSPE_PIPE_SIGNAL)
- {
+ if (i == KWSYSPE_PIPE_SIGNAL) {
/* A child process has terminated. */
kwsysProcessDestroy(cp);
- }
- else if(data && length)
- {
+ } else if (data && length) {
/* Report this data. */
*data = cp->PipeBuffer;
*length = (int)(n);
- switch(i)
- {
+ switch (i) {
case KWSYSPE_PIPE_STDOUT:
- wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
+ wd->PipeId = kwsysProcess_Pipe_STDOUT;
+ break;
case KWSYSPE_PIPE_STDERR:
- wd->PipeId = kwsysProcess_Pipe_STDERR; break;
- };
+ wd->PipeId = kwsysProcess_Pipe_STDERR;
+ break;
+ };
return 1;
- }
}
- else if(n < 0 && errno == EAGAIN)
- {
+ } else if (n < 0 && errno == EAGAIN) {
/* No data are really ready. The select call lied. See the
"man select" page on Linux for cases when this occurs. */
- }
- else
- {
+ } else {
/* We are done reading from this pipe. */
kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
--cp->PipesLeft;
- }
}
}
+ }
/* If we have data, break early. */
- if(wd->PipeId)
- {
+ if (wd->PipeId) {
return 1;
- }
+ }
/* Make sure the set is empty (it should always be empty here
anyway). */
FD_ZERO(&cp->PipeSet);
/* Setup a timeout if required. */
- if(wd->TimeoutTime.tv_sec < 0)
- {
+ if (wd->TimeoutTime.tv_sec < 0) {
timeout = 0;
- }
- else
- {
+ } else {
timeout = &timeoutLength;
- }
- if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
- wd->User?wd->UserTimeout:0,
- &timeoutLength, 0))
- {
+ }
+ if (kwsysProcessGetTimeoutLeft(
+ &wd->TimeoutTime, wd->User ? wd->UserTimeout : 0, &timeoutLength, 0)) {
/* Timeout has already expired. */
wd->Expired = 1;
return 1;
- }
+ }
/* Add the pipe reading ends that are still open. */
max = -1;
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
- if(cp->PipeReadEnds[i] >= 0)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+ if (cp->PipeReadEnds[i] >= 0) {
FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
- if(cp->PipeReadEnds[i] > max)
- {
+ if (cp->PipeReadEnds[i] > max) {
max = cp->PipeReadEnds[i];
- }
}
}
+ }
/* Make sure we have a non-empty set. */
- if(max < 0)
- {
+ if (max < 0) {
/* All pipes have closed. Child has terminated. */
return 1;
- }
+ }
/* Run select to block until data are available. Repeat call
until it is not interrupted. */
- while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
- (errno == EINTR));
+ while (((numReady = select(max + 1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
+ (errno == EINTR))
+ ;
/* Check result of select. */
- if(numReady == 0)
- {
+ if (numReady == 0) {
/* Select's timeout expired. */
wd->Expired = 1;
return 1;
- }
- else if(numReady < 0)
- {
+ } else if (numReady < 0) {
/* Select returned an error. Leave the error description in the
pipe buffer. */
strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
@@ -1324,98 +1202,84 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
kwsysProcess_Kill(cp);
cp->Killed = 0;
cp->SelectError = 1;
- }
+ }
return 0;
#else
/* Poll pipes for data since we do not have select. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
- if(cp->PipeReadEnds[i] >= 0)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+ if (cp->PipeReadEnds[i] >= 0) {
const int fd = cp->PipeReadEnds[i];
int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
- if(n > 0)
- {
+ if (n > 0) {
/* We have data on this pipe. */
- if(i == KWSYSPE_PIPE_SIGNAL)
- {
+ if (i == KWSYSPE_PIPE_SIGNAL) {
/* A child process has terminated. */
kwsysProcessDestroy(cp);
- }
- else if(data && length)
- {
+ } else if (data && length) {
/* Report this data. */
*data = cp->PipeBuffer;
*length = n;
- switch(i)
- {
+ switch (i) {
case KWSYSPE_PIPE_STDOUT:
- wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
+ wd->PipeId = kwsysProcess_Pipe_STDOUT;
+ break;
case KWSYSPE_PIPE_STDERR:
- wd->PipeId = kwsysProcess_Pipe_STDERR; break;
- };
- }
- return 1;
+ wd->PipeId = kwsysProcess_Pipe_STDERR;
+ break;
+ };
}
- else if (n == 0) /* EOF */
- {
- /* We are done reading from this pipe. */
+ return 1;
+ } else if (n == 0) /* EOF */
+ {
+/* We are done reading from this pipe. */
#if defined(__VMS)
- if(!cp->CommandsLeft)
+ if (!cp->CommandsLeft)
#endif
- {
+ {
kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
--cp->PipesLeft;
- }
}
- else if (n < 0) /* error */
- {
+ } else if (n < 0) /* error */
+ {
#if defined(__VMS)
- if(!cp->CommandsLeft)
- {
+ if (!cp->CommandsLeft) {
kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
--cp->PipesLeft;
- }
- else
+ } else
#endif
- if((errno != EINTR) && (errno != EAGAIN))
- {
- strncpy(cp->ErrorMessage,strerror(errno),
- KWSYSPE_PIPE_BUFFER_SIZE);
+ if ((errno != EINTR) && (errno != EAGAIN)) {
+ strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
/* Kill the children now. */
kwsysProcess_Kill(cp);
cp->Killed = 0;
cp->SelectError = 1;
return 1;
- }
}
}
}
+ }
/* If we have data, break early. */
- if(wd->PipeId)
- {
+ if (wd->PipeId) {
return 1;
- }
+ }
- if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
- &timeoutLength, 1))
- {
+ if (kwsysProcessGetTimeoutLeft(
+ &wd->TimeoutTime, wd->User ? wd->UserTimeout : 0, &timeoutLength, 1)) {
/* Timeout has already expired. */
wd->Expired = 1;
return 1;
- }
+ }
/* Sleep a little, try again. */
{
- unsigned int msec = ((timeoutLength.tv_sec * 1000) +
- (timeoutLength.tv_usec / 1000));
- if (msec > 100000)
- {
- msec = 100000; /* do not sleep more than 100 milliseconds at a time */
+ unsigned int msec =
+ ((timeoutLength.tv_sec * 1000) + (timeoutLength.tv_usec / 1000));
+ if (msec > 100000) {
+ msec = 100000; /* do not sleep more than 100 milliseconds at a time */
}
- kwsysProcess_usleep(msec);
+ kwsysProcess_usleep(msec);
}
return 0;
#endif
@@ -1428,74 +1292,60 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
int prPipe = 0;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing) {
return 1;
- }
+ }
/* Wait for all the pipes to close. Ignore all data. */
- while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
- {
- if(prPipe == kwsysProcess_Pipe_Timeout)
- {
+ while ((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) {
+ if (prPipe == kwsysProcess_Pipe_Timeout) {
return 0;
- }
}
+ }
/* Check if there was an error in one of the waitpid calls. */
- if(cp->State == kwsysProcess_State_Error)
- {
+ if (cp->State == kwsysProcess_State_Error) {
/* The error message is already in its buffer. Tell
kwsysProcessCleanup to not create it. */
kwsysProcessCleanup(cp, 0);
return 1;
- }
+ }
/* Check whether the child reported an error invoking the process. */
- if(cp->SelectError)
- {
+ if (cp->SelectError) {
/* The error message is already in its buffer. Tell
kwsysProcessCleanup to not create it. */
kwsysProcessCleanup(cp, 0);
cp->State = kwsysProcess_State_Error;
return 1;
- }
+ }
/* Use the status of the last process in the pipeline. */
- status = cp->CommandExitCodes[cp->NumberOfCommands-1];
+ status = cp->CommandExitCodes[cp->NumberOfCommands - 1];
/* Determine the outcome. */
- if(cp->Killed)
- {
+ if (cp->Killed) {
/* We killed the child. */
cp->State = kwsysProcess_State_Killed;
- }
- else if(cp->TimeoutExpired)
- {
+ } else if (cp->TimeoutExpired) {
/* The timeout expired. */
cp->State = kwsysProcess_State_Expired;
- }
- else if(WIFEXITED(status))
- {
+ } else if (WIFEXITED(status)) {
/* The child exited normally. */
cp->State = kwsysProcess_State_Exited;
cp->ExitException = kwsysProcess_Exception_None;
cp->ExitCode = status;
cp->ExitValue = (int)WEXITSTATUS(status);
- }
- else if(WIFSIGNALED(status))
- {
+ } else if (WIFSIGNALED(status)) {
/* The child received an unhandled signal. */
cp->State = kwsysProcess_State_Exception;
cp->ExitCode = status;
kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
- }
- else
- {
+ } else {
/* Error getting the child return code. */
strcpy(cp->ErrorMessage, "Error getting child return code.");
cp->State = kwsysProcess_State_Error;
- }
+ }
/* Normal cleanup. */
kwsysProcessCleanup(cp, 0);
@@ -1507,38 +1357,31 @@ void kwsysProcess_Interrupt(kwsysProcess* cp)
{
int i;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
- cp->Killed)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
+ cp->Killed) {
return;
- }
+ }
/* Interrupt the children. */
- if (cp->CreateProcessGroup)
- {
- if(cp->ForkPIDs)
- {
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ if (cp->CreateProcessGroup) {
+ if (cp->ForkPIDs) {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
/* Make sure the PID is still valid. */
- if(cp->ForkPIDs[i])
- {
+ if (cp->ForkPIDs[i]) {
/* The user created a process group for this process. The group ID
is the process ID for the original process in the group. */
kill(-cp->ForkPIDs[i], SIGINT);
- }
}
}
}
- else
- {
+ } else {
/* No process group was created. Kill our own process group.
NOTE: While one could argue that we could call kill(cp->ForkPIDs[i],
SIGINT) as a way to still interrupt the process even though it's not in
a special group, this is not an option on Windows. Therefore, we kill
the current process group for consistency with Windows. */
kill(0, SIGINT);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1547,10 +1390,9 @@ void kwsysProcess_Kill(kwsysProcess* cp)
int i;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing) {
return;
- }
+ }
/* First close the child exit report pipe write end to avoid causing a
SIGPIPE when the child terminates and our signal handler tries to
@@ -1566,19 +1408,18 @@ void kwsysProcess_Kill(kwsysProcess* cp)
/* Kill the children. */
cp->Killed = 1;
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
int status;
- if(cp->ForkPIDs[i])
- {
+ if (cp->ForkPIDs[i]) {
/* Kill the child. */
kwsysProcessKill(cp->ForkPIDs[i]);
/* Reap the child. Keep trying until the call is not
interrupted. */
- while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
- }
+ while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR))
+ ;
}
+ }
#if defined(__APPLE__)
/* Close all the pipe read ends. Do this after killing the
@@ -1595,15 +1436,15 @@ void kwsysProcess_Kill(kwsysProcess* cp)
compiler warnings. */
static void kwsysProcessVolatileFree(volatile void* p)
{
- /* clang has made it impossible to free memory that points to volatile
- without first using special pragmas to disable a warning... */
+/* clang has made it impossible to free memory that points to volatile
+ without first using special pragmas to disable a warning... */
#if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wcast-qual"
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wcast-qual"
#endif
free((void*)p); /* The cast will silence most compilers, but not clang. */
#if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic pop
+#pragma clang diagnostic pop
#endif
}
@@ -1613,14 +1454,12 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
{
int i;
volatile pid_t* oldForkPIDs;
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
cp->PipeReadEnds[i] = -1;
- }
- for(i=0; i < 3; ++i)
- {
+ }
+ for (i = 0; i < 3; ++i) {
cp->PipeChildStd[i] = -1;
- }
+ }
cp->SignalPipe = -1;
cp->SelectError = 0;
cp->StartTime.tv_sec = -1;
@@ -1642,36 +1481,31 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
strcpy(cp->ExitExceptionString, "No exception");
oldForkPIDs = cp->ForkPIDs;
- cp->ForkPIDs = (volatile pid_t*)malloc(
- sizeof(volatile pid_t)*(size_t)(cp->NumberOfCommands));
- if(oldForkPIDs)
- {
+ cp->ForkPIDs = (volatile pid_t*)malloc(sizeof(volatile pid_t) *
+ (size_t)(cp->NumberOfCommands));
+ if (oldForkPIDs) {
kwsysProcessVolatileFree(oldForkPIDs);
- }
- if(!cp->ForkPIDs)
- {
+ }
+ if (!cp->ForkPIDs) {
return 0;
- }
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ }
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
cp->ForkPIDs[i] = 0; /* can't use memset due to volatile */
- }
+ }
- if(cp->CommandExitCodes)
- {
+ if (cp->CommandExitCodes) {
free(cp->CommandExitCodes);
- }
- cp->CommandExitCodes = (int*)malloc(sizeof(int)*
- (size_t)(cp->NumberOfCommands));
- if(!cp->CommandExitCodes)
- {
+ }
+ cp->CommandExitCodes =
+ (int*)malloc(sizeof(int) * (size_t)(cp->NumberOfCommands));
+ if (!cp->CommandExitCodes) {
return 0;
- }
- memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands));
+ }
+ memset(cp->CommandExitCodes, 0,
+ sizeof(int) * (size_t)(cp->NumberOfCommands));
/* Allocate memory to save the real working directory. */
- if ( cp->WorkingDirectory )
- {
+ if (cp->WorkingDirectory) {
#if defined(MAXPATHLEN)
cp->RealWorkingDirectoryLength = MAXPATHLEN;
#elif defined(PATH_MAX)
@@ -1681,11 +1515,10 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
#endif
cp->RealWorkingDirectory =
(char*)malloc((size_t)(cp->RealWorkingDirectoryLength));
- if(!cp->RealWorkingDirectory)
- {
+ if (!cp->RealWorkingDirectory) {
return 0;
- }
}
+ }
return 1;
}
@@ -1697,86 +1530,77 @@ static void kwsysProcessCleanup(kwsysProcess* cp, int error)
{
int i;
- if(error)
- {
+ if (error) {
/* We are cleaning up due to an error. Report the error message
if one has not been provided already. */
- if(cp->ErrorMessage[0] == 0)
- {
+ if (cp->ErrorMessage[0] == 0) {
strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
- }
+ }
/* Set the error state. */
cp->State = kwsysProcess_State_Error;
/* Kill any children already started. */
- if(cp->ForkPIDs)
- {
+ if (cp->ForkPIDs) {
int status;
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- if(cp->ForkPIDs[i])
- {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ if (cp->ForkPIDs[i]) {
/* Kill the child. */
kwsysProcessKill(cp->ForkPIDs[i]);
/* Reap the child. Keep trying until the call is not
interrupted. */
- while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
- (errno == EINTR));
- }
+ while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
+ (errno == EINTR))
+ ;
}
}
+ }
/* Restore the working directory. */
- if(cp->RealWorkingDirectory)
- {
- while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
- }
+ if (cp->RealWorkingDirectory) {
+ while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
+ ;
}
+ }
/* If not creating a detached child, remove this object from the
global set of process objects that wish to be notified when a
child exits. */
- if(!cp->OptionDetach)
- {
+ if (!cp->OptionDetach) {
kwsysProcessesRemove(cp);
- }
+ }
/* Free memory. */
- if(cp->ForkPIDs)
- {
+ if (cp->ForkPIDs) {
kwsysProcessVolatileFree(cp->ForkPIDs);
cp->ForkPIDs = 0;
- }
- if(cp->RealWorkingDirectory)
- {
+ }
+ if (cp->RealWorkingDirectory) {
free(cp->RealWorkingDirectory);
cp->RealWorkingDirectory = 0;
- }
+ }
/* Close pipe handles. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
- }
- for(i=0; i < 3; ++i)
- {
+ }
+ for (i = 0; i < 3; ++i) {
kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
- }
+ }
}
/*--------------------------------------------------------------------------*/
/* Close the given file descriptor if it is open. Reset its value to -1. */
static void kwsysProcessCleanupDescriptor(int* pfd)
{
- if(pfd && *pfd > 2)
- {
+ if (pfd && *pfd > 2) {
/* Keep trying to close until it is not interrupted by a
* signal. */
- while((close(*pfd) < 0) && (errno == EINTR));
+ while ((close(*pfd) < 0) && (errno == EINTR))
+ ;
*pfd = -1;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1785,42 +1609,40 @@ static void kwsysProcessClosePipes(kwsysProcess* cp)
int i;
/* Close any pipes that are still open. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
- if(cp->PipeReadEnds[i] >= 0)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+ if (cp->PipeReadEnds[i] >= 0) {
#if KWSYSPE_USE_SELECT
/* If the pipe was reported by the last call to select, we must
read from it. This is needed to satisfy the suggestions from
"man select_tut" and is not needed for the polling
implementation. Ignore the data. */
- if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
- {
+ if (FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet)) {
/* We are handling this pipe now. Remove it from the set. */
FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
/* The pipe is ready to read without blocking. Keep trying to
read until the operation is not interrupted. */
- while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
- KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
- }
+ while ((read(cp->PipeReadEnds[i], cp->PipeBuffer,
+ KWSYSPE_PIPE_BUFFER_SIZE) < 0) &&
+ (errno == EINTR))
+ ;
+ }
#endif
/* We are done reading from this pipe. */
kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
--cp->PipesLeft;
- }
}
+ }
}
/*--------------------------------------------------------------------------*/
static int kwsysProcessSetNonBlocking(int fd)
{
int flags = fcntl(fd, F_GETFL);
- if(flags >= 0)
- {
+ if (flags >= 0) {
flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
- }
+ }
return flags >= 0;
}
@@ -1839,30 +1661,27 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
ssize_t readRes;
/* Create the error reporting pipe. */
- if(pipe(si->ErrorPipe) < 0)
- {
+ if (pipe(si->ErrorPipe) < 0) {
return 0;
- }
+ }
/* Create a pipe for detecting that the child process has created a process
group and session. */
- if(pipe(pgidPipe) < 0)
- {
+ if (pipe(pgidPipe) < 0) {
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
return 0;
- }
+ }
/* Set close-on-exec flag on the pipe's write end. */
- if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0 ||
- fcntl(pgidPipe[1], F_SETFD, FD_CLOEXEC) < 0)
- {
+ if (fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0 ||
+ fcntl(pgidPipe[1], F_SETFD, FD_CLOEXEC) < 0) {
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
kwsysProcessCleanupDescriptor(&pgidPipe[0]);
kwsysProcessCleanupDescriptor(&pgidPipe[1]);
return 0;
- }
+ }
/* Block SIGINT / SIGTERM while we start. The purpose is so that our signal
handler doesn't get called from the child process after the fork and
@@ -1870,16 +1689,15 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
- if(sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0)
- {
+ if (sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0) {
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
kwsysProcessCleanupDescriptor(&pgidPipe[0]);
kwsysProcessCleanupDescriptor(&pgidPipe[1]);
return 0;
- }
+ }
- /* Fork off a child process. */
+/* Fork off a child process. */
#if defined(__VMS)
/* VMS needs vfork and execvp to be in the same function because
they use setjmp/longjmp to run the child startup code in the
@@ -1889,18 +1707,16 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
#else
cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
#endif
- if(cp->ForkPIDs[prIndex] < 0)
- {
+ if (cp->ForkPIDs[prIndex] < 0) {
sigprocmask(SIG_SETMASK, &old_mask, 0);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
kwsysProcessCleanupDescriptor(&pgidPipe[0]);
kwsysProcessCleanupDescriptor(&pgidPipe[1]);
return 0;
- }
+ }
- if(cp->ForkPIDs[prIndex] == 0)
- {
+ if (cp->ForkPIDs[prIndex] == 0) {
#if defined(__VMS)
/* Specify standard pipes for child process. */
decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
@@ -1911,22 +1727,17 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
close(pgidPipe[0]);
/* Setup the stdin, stdout, and stderr pipes. */
- if(si->StdIn > 0)
- {
+ if (si->StdIn > 0) {
dup2(si->StdIn, 0);
- }
- else if(si->StdIn < 0)
- {
+ } else if (si->StdIn < 0) {
close(0);
- }
- if(si->StdOut != 1)
- {
+ }
+ if (si->StdOut != 1) {
dup2(si->StdOut, 1);
- }
- if(si->StdErr != 2)
- {
+ }
+ if (si->StdErr != 2) {
dup2(si->StdErr, 2);
- }
+ }
/* Clear the close-on-exec flag for stdin, stdout, and stderr.
All other pipe handles will be closed when exec succeeds. */
@@ -1945,10 +1756,9 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
the child getting hung up on signals like SIGTTOU. (In the real world,
this has been observed where "git svn" ends up calling the "resize"
program which opens /dev/tty. */
- if(cp->CreateProcessGroup && setsid() < 0)
- {
+ if (cp->CreateProcessGroup && setsid() < 0) {
kwsysProcessChildErrorExit(si->ErrorPipe[1]);
- }
+ }
#endif
/* Execute the real process. If successful, this does not return. */
@@ -1958,7 +1768,7 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
/* Failure. Report error to parent and terminate. */
kwsysProcessChildErrorExit(si->ErrorPipe[1]);
- }
+ }
#if defined(__VMS)
/* Restore the standard pipes of this process. */
@@ -1973,22 +1783,21 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
/* Make sure the child is in the process group before we proceed. This
avoids race conditions with calls to the kill function that we make for
signalling process groups. */
- while((readRes = read(pgidPipe[0], &tmp, 1)) > 0);
- if(readRes < 0)
- {
+ while ((readRes = read(pgidPipe[0], &tmp, 1)) > 0)
+ ;
+ if (readRes < 0) {
sigprocmask(SIG_SETMASK, &old_mask, 0);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
kwsysProcessCleanupDescriptor(&pgidPipe[0]);
return 0;
- }
+ }
kwsysProcessCleanupDescriptor(&pgidPipe[0]);
/* Unmask signals. */
- if(sigprocmask(SIG_SETMASK, &old_mask, 0) < 0)
- {
+ if (sigprocmask(SIG_SETMASK, &old_mask, 0) < 0) {
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
return 0;
- }
+ }
/* A child has been created. */
++cp->CommandsLeft;
@@ -1996,28 +1805,26 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
/* Block until the child's exec call succeeds and closes the error
pipe or writes data to the pipe to report an error. */
{
- kwsysProcess_ssize_t total = 0;
- kwsysProcess_ssize_t n = 1;
- /* Read the entire error message up to the length of our buffer. */
- while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
- {
- /* Keep trying to read until the operation is not interrupted. */
- while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
- (size_t)(KWSYSPE_PIPE_BUFFER_SIZE-total))) < 0) &&
- (errno == EINTR));
- if(n > 0)
- {
- total += n;
+ kwsysProcess_ssize_t total = 0;
+ kwsysProcess_ssize_t n = 1;
+ /* Read the entire error message up to the length of our buffer. */
+ while (total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0) {
+ /* Keep trying to read until the operation is not interrupted. */
+ while (((n = read(si->ErrorPipe[0], cp->ErrorMessage + total,
+ (size_t)(KWSYSPE_PIPE_BUFFER_SIZE - total))) < 0) &&
+ (errno == EINTR))
+ ;
+ if (n > 0) {
+ total += n;
}
}
- /* We are done with the error reporting pipe read end. */
- kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+ /* We are done with the error reporting pipe read end. */
+ kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
- if(total > 0)
- {
- /* The child failed to execute the process. */
- return 0;
+ if (total > 0) {
+ /* The child failed to execute the process. */
+ return 0;
}
}
@@ -2036,25 +1843,21 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
- if(sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0)
- {
+ if (sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0) {
return;
- }
+ }
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- if(cp->ForkPIDs[i])
- {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ if (cp->ForkPIDs[i]) {
int result;
- while(((result = waitpid(cp->ForkPIDs[i],
- &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
- (errno == EINTR));
- if(result > 0)
- {
+ while (((result = waitpid(cp->ForkPIDs[i], &cp->CommandExitCodes[i],
+ WNOHANG)) < 0) &&
+ (errno == EINTR))
+ ;
+ if (result > 0) {
/* This child has termianted. */
cp->ForkPIDs[i] = 0;
- if(--cp->CommandsLeft == 0)
- {
+ if (--cp->CommandsLeft == 0) {
/* All children have terminated. Close the signal pipe
write end so that no more notifications are sent to this
object. */
@@ -2064,16 +1867,14 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
WaitForData to use a non-blocking read to get the
rest of the data from the pipe. This is needed when
grandchildren keep the output pipes open. */
- }
}
- else if(result < 0 && cp->State != kwsysProcess_State_Error)
- {
+ } else if (result < 0 && cp->State != kwsysProcess_State_Error) {
/* Unexpected error. Report the first time this happens. */
strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
cp->State = kwsysProcess_State_Error;
- }
}
}
+ }
/* Re-enable signals. */
sigprocmask(SIG_SETMASK, &old_mask, 0);
@@ -2083,25 +1884,22 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
{
int fout;
- if(!name)
- {
+ if (!name) {
return 1;
- }
+ }
/* Close the existing descriptor. */
kwsysProcessCleanupDescriptor(p);
/* Open a file for the pipe to write. */
- if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
- {
+ if ((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
return 0;
- }
+ }
/* Set close-on-exec flag on the pipe's end. */
- if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
- {
+ if (fcntl(fout, F_SETFD, FD_CLOEXEC) < 0) {
return 0;
- }
+ }
/* Assign the replacement descriptor. */
*p = fout;
@@ -2117,11 +1915,10 @@ static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
/* Set close-on-exec flag on the pipe's ends. The proper end will
be dup2-ed into the standard descriptor number after fork but
before exec. */
- if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
- {
+ if ((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0)) {
return 0;
- }
+ }
/* Assign the replacement descriptor. */
*p = des[1];
@@ -2136,29 +1933,27 @@ static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
{
/* The first time this is called, we need to calculate the time at
which the child will timeout. */
- if(cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0)
- {
+ if (cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0) {
kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
- }
+ }
/* Start with process timeout. */
*timeoutTime = cp->TimeoutTime;
/* Check if the user timeout is earlier. */
- if(userTimeout)
- {
+ if (userTimeout) {
kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
- kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
- kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
- userTimeoutLength);
- if(timeoutTime->tv_sec < 0 ||
- kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
- {
+ kwsysProcessTime userTimeoutLength =
+ kwsysProcessTimeFromDouble(*userTimeout);
+ kwsysProcessTime userTimeoutTime =
+ kwsysProcessTimeAdd(currentTime, userTimeoutLength);
+ if (timeoutTime->tv_sec < 0 ||
+ kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) {
*timeoutTime = userTimeoutTime;
return 1;
- }
}
+ }
return 0;
}
@@ -2170,38 +1965,31 @@ static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
kwsysProcessTimeNative* timeoutLength,
int zeroIsExpired)
{
- if(timeoutTime->tv_sec < 0)
- {
+ if (timeoutTime->tv_sec < 0) {
/* No timeout time has been requested. */
return 0;
- }
- else
- {
+ } else {
/* Calculate the remaining time. */
kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
- kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
- currentTime);
- if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
- {
+ kwsysProcessTime timeLeft =
+ kwsysProcessTimeSubtract(*timeoutTime, currentTime);
+ if (timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0) {
/* Caller has explicitly requested a zero timeout. */
timeLeft.tv_sec = 0;
timeLeft.tv_usec = 0;
- }
+ }
- if(timeLeft.tv_sec < 0 ||
- (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired))
- {
+ if (timeLeft.tv_sec < 0 ||
+ (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired)) {
/* Timeout has already expired. */
return 1;
- }
- else
- {
+ } else {
/* There is some time left. */
timeoutLength->tv_sec = timeLeft.tv_sec;
timeoutLength->tv_usec = timeLeft.tv_usec;
return 0;
- }
}
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2218,7 +2006,7 @@ static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
/*--------------------------------------------------------------------------*/
static double kwsysProcessTimeToDouble(kwsysProcessTime t)
{
- return (double)t.tv_sec + (double)(t.tv_usec)*0.000001;
+ return (double)t.tv_sec + (double)(t.tv_usec) * 0.000001;
}
/*--------------------------------------------------------------------------*/
@@ -2226,7 +2014,7 @@ static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
{
kwsysProcessTime t;
t.tv_sec = (long)d;
- t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000);
+ t.tv_usec = (long)((d - (double)(t.tv_sec)) * 1000000);
return t;
}
@@ -2238,158 +2026,227 @@ static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
}
/*--------------------------------------------------------------------------*/
-static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
+static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+ kwsysProcessTime in2)
{
kwsysProcessTime out;
out.tv_sec = in1.tv_sec + in2.tv_sec;
out.tv_usec = in1.tv_usec + in2.tv_usec;
- if(out.tv_usec >= 1000000)
- {
+ if (out.tv_usec >= 1000000) {
out.tv_usec -= 1000000;
out.tv_sec += 1;
- }
+ }
return out;
}
/*--------------------------------------------------------------------------*/
-static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
+static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+ kwsysProcessTime in2)
{
kwsysProcessTime out;
out.tv_sec = in1.tv_sec - in2.tv_sec;
out.tv_usec = in1.tv_usec - in2.tv_usec;
- if(out.tv_usec < 0)
- {
+ if (out.tv_usec < 0) {
out.tv_usec += 1000000;
out.tv_sec -= 1;
- }
+ }
return out;
}
/*--------------------------------------------------------------------------*/
-#define KWSYSPE_CASE(type, str) \
- cp->ExitException = kwsysProcess_Exception_##type; \
+#define KWSYSPE_CASE(type, str) \
+ cp->ExitException = kwsysProcess_Exception_##type; \
strcpy(cp->ExitExceptionString, str)
static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
{
- switch (sig)
- {
+ switch (sig) {
#ifdef SIGSEGV
- case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
+ case SIGSEGV:
+ KWSYSPE_CASE(Fault, "Segmentation fault");
+ break;
#endif
#ifdef SIGBUS
-# if !defined(SIGSEGV) || SIGBUS != SIGSEGV
- case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
-# endif
+#if !defined(SIGSEGV) || SIGBUS != SIGSEGV
+ case SIGBUS:
+ KWSYSPE_CASE(Fault, "Bus error");
+ break;
+#endif
#endif
#ifdef SIGFPE
- case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
+ case SIGFPE:
+ KWSYSPE_CASE(Numerical, "Floating-point exception");
+ break;
#endif
#ifdef SIGILL
- case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
+ case SIGILL:
+ KWSYSPE_CASE(Illegal, "Illegal instruction");
+ break;
#endif
#ifdef SIGINT
- case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
+ case SIGINT:
+ KWSYSPE_CASE(Interrupt, "User interrupt");
+ break;
#endif
#ifdef SIGABRT
- case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
+ case SIGABRT:
+ KWSYSPE_CASE(Other, "Child aborted");
+ break;
#endif
#ifdef SIGKILL
- case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
+ case SIGKILL:
+ KWSYSPE_CASE(Other, "Child killed");
+ break;
#endif
#ifdef SIGTERM
- case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
+ case SIGTERM:
+ KWSYSPE_CASE(Other, "Child terminated");
+ break;
#endif
#ifdef SIGHUP
- case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
+ case SIGHUP:
+ KWSYSPE_CASE(Other, "SIGHUP");
+ break;
#endif
#ifdef SIGQUIT
- case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
+ case SIGQUIT:
+ KWSYSPE_CASE(Other, "SIGQUIT");
+ break;
#endif
#ifdef SIGTRAP
- case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
+ case SIGTRAP:
+ KWSYSPE_CASE(Other, "SIGTRAP");
+ break;
#endif
#ifdef SIGIOT
-# if !defined(SIGABRT) || SIGIOT != SIGABRT
- case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
-# endif
+#if !defined(SIGABRT) || SIGIOT != SIGABRT
+ case SIGIOT:
+ KWSYSPE_CASE(Other, "SIGIOT");
+ break;
+#endif
#endif
#ifdef SIGUSR1
- case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
+ case SIGUSR1:
+ KWSYSPE_CASE(Other, "SIGUSR1");
+ break;
#endif
#ifdef SIGUSR2
- case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
+ case SIGUSR2:
+ KWSYSPE_CASE(Other, "SIGUSR2");
+ break;
#endif
#ifdef SIGPIPE
- case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
+ case SIGPIPE:
+ KWSYSPE_CASE(Other, "SIGPIPE");
+ break;
#endif
#ifdef SIGALRM
- case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
+ case SIGALRM:
+ KWSYSPE_CASE(Other, "SIGALRM");
+ break;
#endif
#ifdef SIGSTKFLT
- case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
+ case SIGSTKFLT:
+ KWSYSPE_CASE(Other, "SIGSTKFLT");
+ break;
#endif
#ifdef SIGCHLD
- case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
+ case SIGCHLD:
+ KWSYSPE_CASE(Other, "SIGCHLD");
+ break;
#elif defined(SIGCLD)
- case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
+ case SIGCLD:
+ KWSYSPE_CASE(Other, "SIGCLD");
+ break;
#endif
#ifdef SIGCONT
- case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
+ case SIGCONT:
+ KWSYSPE_CASE(Other, "SIGCONT");
+ break;
#endif
#ifdef SIGSTOP
- case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
+ case SIGSTOP:
+ KWSYSPE_CASE(Other, "SIGSTOP");
+ break;
#endif
#ifdef SIGTSTP
- case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
+ case SIGTSTP:
+ KWSYSPE_CASE(Other, "SIGTSTP");
+ break;
#endif
#ifdef SIGTTIN
- case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
+ case SIGTTIN:
+ KWSYSPE_CASE(Other, "SIGTTIN");
+ break;
#endif
#ifdef SIGTTOU
- case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
+ case SIGTTOU:
+ KWSYSPE_CASE(Other, "SIGTTOU");
+ break;
#endif
#ifdef SIGURG
- case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
+ case SIGURG:
+ KWSYSPE_CASE(Other, "SIGURG");
+ break;
#endif
#ifdef SIGXCPU
- case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
+ case SIGXCPU:
+ KWSYSPE_CASE(Other, "SIGXCPU");
+ break;
#endif
#ifdef SIGXFSZ
- case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
+ case SIGXFSZ:
+ KWSYSPE_CASE(Other, "SIGXFSZ");
+ break;
#endif
#ifdef SIGVTALRM
- case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
+ case SIGVTALRM:
+ KWSYSPE_CASE(Other, "SIGVTALRM");
+ break;
#endif
#ifdef SIGPROF
- case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
+ case SIGPROF:
+ KWSYSPE_CASE(Other, "SIGPROF");
+ break;
#endif
#ifdef SIGWINCH
- case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
+ case SIGWINCH:
+ KWSYSPE_CASE(Other, "SIGWINCH");
+ break;
#endif
#ifdef SIGPOLL
- case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
+ case SIGPOLL:
+ KWSYSPE_CASE(Other, "SIGPOLL");
+ break;
#endif
#ifdef SIGIO
-# if !defined(SIGPOLL) || SIGIO != SIGPOLL
- case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
-# endif
+#if !defined(SIGPOLL) || SIGIO != SIGPOLL
+ case SIGIO:
+ KWSYSPE_CASE(Other, "SIGIO");
+ break;
+#endif
#endif
#ifdef SIGPWR
- case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
+ case SIGPWR:
+ KWSYSPE_CASE(Other, "SIGPWR");
+ break;
#endif
#ifdef SIGSYS
- case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
+ case SIGSYS:
+ KWSYSPE_CASE(Other, "SIGSYS");
+ break;
#endif
#ifdef SIGUNUSED
-# if !defined(SIGSYS) || SIGUNUSED != SIGSYS
- case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
-# endif
+#if !defined(SIGSYS) || SIGUNUSED != SIGSYS
+ case SIGUNUSED:
+ KWSYSPE_CASE(Other, "SIGUNUSED");
+ break;
+#endif
#endif
default:
cp->ExitException = kwsysProcess_Exception_Other;
sprintf(cp->ExitExceptionString, "Signal %d", sig);
break;
- }
+ }
}
#undef KWSYSPE_CASE
@@ -2405,7 +2262,7 @@ static void kwsysProcessChildErrorExit(int errorPipe)
strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
/* Report the error to the parent through the special pipe. */
- result=write(errorPipe, buffer, strlen(buffer));
+ result = write(errorPipe, buffer, strlen(buffer));
(void)result;
/* Terminate without cleanup. */
@@ -2532,55 +2389,47 @@ static pid_t kwsysProcessFork(kwsysProcess* cp,
kwsysProcessCreateInformation* si)
{
/* Create a detached process if requested. */
- if(cp->OptionDetach)
- {
+ if (cp->OptionDetach) {
/* Create an intermediate process. */
pid_t middle_pid = fork();
- if(middle_pid < 0)
- {
+ if (middle_pid < 0) {
/* Fork failed. Return as if we were not detaching. */
return middle_pid;
- }
- else if(middle_pid == 0)
- {
+ } else if (middle_pid == 0) {
/* This is the intermediate process. Create the real child. */
pid_t child_pid = fork();
- if(child_pid == 0)
- {
+ if (child_pid == 0) {
/* This is the real child process. There is nothing to do here. */
return 0;
- }
- else
- {
+ } else {
/* Use the error pipe to report the pid to the real parent. */
- while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
- (errno == EINTR));
+ while ((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
+ (errno == EINTR))
+ ;
/* Exit without cleanup. The parent holds all resources. */
kwsysProcessExit();
return 0; /* Never reached, but avoids SunCC warning. */
- }
}
- else
- {
+ } else {
/* This is the original parent process. The intermediate
process will use the error pipe to report the pid of the
detached child. */
pid_t child_pid;
int status;
- while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
- (errno == EINTR));
+ while ((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
+ (errno == EINTR))
+ ;
/* Wait for the intermediate process to exit and clean it up. */
- while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
+ while ((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR))
+ ;
return child_pid;
- }
}
- else
- {
+ } else {
/* Not creating a detached process. Use normal fork. */
return fork();
- }
+ }
}
#endif
@@ -2589,23 +2438,23 @@ static pid_t kwsysProcessFork(kwsysProcess* cp,
Here we define the command to call on each platform and the
corresponding parsing format string. The parsing format should
have two integers to store: the pid and then the ppid. */
-#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) \
- || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
-# define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
-# define KWSYSPE_PS_FORMAT "%d %d\n"
+#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
+ defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
+#define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
+#define KWSYSPE_PS_FORMAT "%d %d\n"
#elif defined(__sun) && (defined(__SVR4) || defined(__svr4__)) /* Solaris */
-# define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
-# define KWSYSPE_PS_FORMAT "%d %d\n"
-#elif defined(__hpux) || defined(__sun__) || defined(__sgi) || defined(_AIX) \
- || defined(__sparc)
-# define KWSYSPE_PS_COMMAND "ps -ef"
-# define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
+#define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
+#define KWSYSPE_PS_FORMAT "%d %d\n"
+#elif defined(__hpux) || defined(__sun__) || defined(__sgi) || \
+ defined(_AIX) || defined(__sparc)
+#define KWSYSPE_PS_COMMAND "ps -ef"
+#define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
#elif defined(__QNX__)
-# define KWSYSPE_PS_COMMAND "ps -Af"
-# define KWSYSPE_PS_FORMAT "%*d %d %d %*[^\n]\n"
+#define KWSYSPE_PS_COMMAND "ps -Af"
+#define KWSYSPE_PS_FORMAT "%*d %d %d %*[^\n]\n"
#elif defined(__CYGWIN__)
-# define KWSYSPE_PS_COMMAND "ps aux"
-# define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
+#define KWSYSPE_PS_COMMAND "ps aux"
+#define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
#endif
/*--------------------------------------------------------------------------*/
@@ -2624,11 +2473,10 @@ static void kwsysProcessKill(pid_t process_id)
usleep(1);
#endif
- /* Kill all children if we can find them. */
+/* Kill all children if we can find them. */
#if defined(__linux__) || defined(__CYGWIN__)
/* First try using the /proc filesystem. */
- if((procdir = opendir("/proc")) != NULL)
- {
+ if ((procdir = opendir("/proc")) != NULL) {
#if defined(MAXPATHLEN)
char fname[MAXPATHLEN];
#elif defined(PATH_MAX)
@@ -2636,7 +2484,7 @@ static void kwsysProcessKill(pid_t process_id)
#else
char fname[4096];
#endif
- char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
+ char buffer[KWSYSPE_PIPE_BUFFER_SIZE + 1];
struct dirent* d;
/* Each process has a directory in /proc whose name is the pid.
@@ -2647,69 +2495,57 @@ static void kwsysProcessKill(pid_t process_id)
We want to get the ppid for all processes. Those that have
process_id as their parent should be recursively killed. */
- for(d = readdir(procdir); d; d = readdir(procdir))
- {
+ for (d = readdir(procdir); d; d = readdir(procdir)) {
int pid;
- if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
- {
+ if (sscanf(d->d_name, "%d", &pid) == 1 && pid != 0) {
struct stat finfo;
sprintf(fname, "/proc/%d/stat", pid);
- if(stat(fname, &finfo) == 0)
- {
+ if (stat(fname, &finfo) == 0) {
FILE* f = fopen(fname, "r");
- if(f)
- {
+ if (f) {
size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
fclose(f);
buffer[nread] = '\0';
- if(nread > 0)
- {
+ if (nread > 0) {
const char* rparen = strrchr(buffer, ')');
int ppid;
- if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
- {
- if(ppid == process_id)
- {
+ if (rparen && (sscanf(rparen + 1, "%*s %d", &ppid) == 1)) {
+ if (ppid == process_id) {
/* Recursively kill this child and its children. */
kwsysProcessKill(pid);
- }
}
}
}
}
}
}
- closedir(procdir);
}
- else
+ closedir(procdir);
+ } else
#endif
- {
+ {
#if defined(KWSYSPE_PS_COMMAND)
/* Try running "ps" to get the process information. */
FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
/* Make sure the process started and provided a valid header. */
- if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
- {
+ if (ps && fscanf(ps, "%*[^\n]\n") != EOF) {
/* Look for processes whose parent is the process being killed. */
int pid, ppid;
- while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
- {
- if(ppid == process_id)
- {
+ while (fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2) {
+ if (ppid == process_id) {
/* Recursively kill this child and its children. */
kwsysProcessKill(pid);
- }
}
}
+ }
/* We are done with the ps process. */
- if(ps)
- {
+ if (ps) {
pclose(ps);
- }
-#endif
}
+#endif
+ }
/* Kill the process. */
kill(process_id, SIGKILL);
@@ -2781,112 +2617,104 @@ static int kwsysProcessesAdd(kwsysProcess* cp)
/* Create a pipe through which the signal handler can notify the
given process object that a child has exited. */
{
- /* Create the pipe. */
- int p[2];
- if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
- {
- return 0;
+ /* Create the pipe. */
+ int p[2];
+ if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+ return 0;
}
- /* Store the pipes now to be sure they are cleaned up later. */
- cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
- cp->SignalPipe = p[1];
+ /* Store the pipes now to be sure they are cleaned up later. */
+ cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
+ cp->SignalPipe = p[1];
- /* Switch the pipe to non-blocking mode so that reading a byte can
- be an atomic test-and-set. */
- if(!kwsysProcessSetNonBlocking(p[0]) ||
- !kwsysProcessSetNonBlocking(p[1]))
- {
- return 0;
+ /* Switch the pipe to non-blocking mode so that reading a byte can
+ be an atomic test-and-set. */
+ if (!kwsysProcessSetNonBlocking(p[0]) ||
+ !kwsysProcessSetNonBlocking(p[1])) {
+ return 0;
}
- /* The children do not need this pipe. Set close-on-exec flag on
- the pipe's ends. */
- if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
- (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
- {
- return 0;
+ /* The children do not need this pipe. Set close-on-exec flag on
+ the pipe's ends. */
+ if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+ (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+ return 0;
}
}
/* Attempt to add the given signal pipe to the signal handler set. */
{
- /* Make sure there is enough space for the new signal pipe. */
- kwsysProcessInstances oldProcesses = kwsysProcesses;
- kwsysProcessInstances newProcesses = oldProcesses;
- if(oldProcesses.Count == oldProcesses.Size)
- {
- /* Start with enough space for a small number of process instances
- and double the size each time more is needed. */
- newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
-
- /* Try allocating the new block of memory. */
- if((newProcesses.Processes = ((kwsysProcess**)
- malloc((size_t)(newProcesses.Size)*
- sizeof(kwsysProcess*)))))
- {
- /* Copy the old pipe set to the new memory. */
- if(oldProcesses.Count > 0)
- {
- memcpy(newProcesses.Processes, oldProcesses.Processes,
- ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
+ /* Make sure there is enough space for the new signal pipe. */
+ kwsysProcessInstances oldProcesses = kwsysProcesses;
+ kwsysProcessInstances newProcesses = oldProcesses;
+ if (oldProcesses.Count == oldProcesses.Size) {
+ /* Start with enough space for a small number of process instances
+ and double the size each time more is needed. */
+ newProcesses.Size = oldProcesses.Size ? oldProcesses.Size * 2 : 4;
+
+ /* Try allocating the new block of memory. */
+ if ((newProcesses.Processes = ((kwsysProcess**)malloc(
+ (size_t)(newProcesses.Size) * sizeof(kwsysProcess*))))) {
+ /* Copy the old pipe set to the new memory. */
+ if (oldProcesses.Count > 0) {
+ memcpy(newProcesses.Processes, oldProcesses.Processes,
+ ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
}
- }
- else
- {
- /* Failed to allocate memory for the new signal pipe set. */
- return 0;
+ } else {
+ /* Failed to allocate memory for the new signal pipe set. */
+ return 0;
}
}
- /* Append the new signal pipe to the set. */
- newProcesses.Processes[newProcesses.Count++] = cp;
+ /* Append the new signal pipe to the set. */
+ newProcesses.Processes[newProcesses.Count++] = cp;
- /* Store the new set in that seen by the signal handler. */
- kwsysProcessesUpdate(&newProcesses);
+ /* Store the new set in that seen by the signal handler. */
+ kwsysProcessesUpdate(&newProcesses);
- /* Free the original pipes if new ones were allocated. */
- if(newProcesses.Processes != oldProcesses.Processes)
- {
- free(oldProcesses.Processes);
+ /* Free the original pipes if new ones were allocated. */
+ if (newProcesses.Processes != oldProcesses.Processes) {
+ free(oldProcesses.Processes);
}
- /* If this is the first process, enable the signal handler. */
- if(newProcesses.Count == 1)
- {
- /* Install our handler for SIGCHLD. Repeat call until it is not
- interrupted. */
- struct sigaction newSigAction;
- memset(&newSigAction, 0, sizeof(struct sigaction));
+ /* If this is the first process, enable the signal handler. */
+ if (newProcesses.Count == 1) {
+ /* Install our handler for SIGCHLD. Repeat call until it is not
+ interrupted. */
+ struct sigaction newSigAction;
+ memset(&newSigAction, 0, sizeof(struct sigaction));
#if KWSYSPE_USE_SIGINFO
- newSigAction.sa_sigaction = kwsysProcessesSignalHandler;
- newSigAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
-# ifdef SA_RESTART
- newSigAction.sa_flags |= SA_RESTART;
-# endif
-#else
- newSigAction.sa_handler = kwsysProcessesSignalHandler;
- newSigAction.sa_flags = SA_NOCLDSTOP;
+ newSigAction.sa_sigaction = kwsysProcessesSignalHandler;
+ newSigAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
+#ifdef SA_RESTART
+ newSigAction.sa_flags |= SA_RESTART;
#endif
- sigemptyset(&newSigAction.sa_mask);
- while((sigaction(SIGCHLD, &newSigAction,
- &kwsysProcessesOldSigChldAction) < 0) &&
- (errno == EINTR));
-
- /* Install our handler for SIGINT / SIGTERM. Repeat call until
- it is not interrupted. */
- sigemptyset(&newSigAction.sa_mask);
- sigaddset(&newSigAction.sa_mask, SIGTERM);
- while((sigaction(SIGINT, &newSigAction,
- &kwsysProcessesOldSigIntAction) < 0) &&
- (errno == EINTR));
+#else
+ newSigAction.sa_handler = kwsysProcessesSignalHandler;
+ newSigAction.sa_flags = SA_NOCLDSTOP;
+#endif
+ sigemptyset(&newSigAction.sa_mask);
+ while ((sigaction(SIGCHLD, &newSigAction,
+ &kwsysProcessesOldSigChldAction) < 0) &&
+ (errno == EINTR))
+ ;
+
+ /* Install our handler for SIGINT / SIGTERM. Repeat call until
+ it is not interrupted. */
+ sigemptyset(&newSigAction.sa_mask);
+ sigaddset(&newSigAction.sa_mask, SIGTERM);
+ while ((sigaction(SIGINT, &newSigAction,
+ &kwsysProcessesOldSigIntAction) < 0) &&
+ (errno == EINTR))
+ ;
- sigemptyset(&newSigAction.sa_mask);
- sigaddset(&newSigAction.sa_mask, SIGINT);
- while((sigaction(SIGTERM, &newSigAction,
- &kwsysProcessesOldSigIntAction) < 0) &&
- (errno == EINTR));
+ sigemptyset(&newSigAction.sa_mask);
+ sigaddset(&newSigAction.sa_mask, SIGINT);
+ while ((sigaction(SIGTERM, &newSigAction,
+ &kwsysProcessesOldSigIntAction) < 0) &&
+ (errno == EINTR))
+ ;
}
}
@@ -2898,46 +2726,44 @@ static void kwsysProcessesRemove(kwsysProcess* cp)
{
/* Attempt to remove the given signal pipe from the signal handler set. */
{
- /* Find the given process in the set. */
- kwsysProcessInstances newProcesses = kwsysProcesses;
- int i;
- for(i=0; i < newProcesses.Count; ++i)
- {
- if(newProcesses.Processes[i] == cp)
- {
- break;
+ /* Find the given process in the set. */
+ kwsysProcessInstances newProcesses = kwsysProcesses;
+ int i;
+ for (i = 0; i < newProcesses.Count; ++i) {
+ if (newProcesses.Processes[i] == cp) {
+ break;
}
}
- if(i < newProcesses.Count)
- {
- /* Remove the process from the set. */
- --newProcesses.Count;
- for(; i < newProcesses.Count; ++i)
- {
- newProcesses.Processes[i] = newProcesses.Processes[i+1];
+ if (i < newProcesses.Count) {
+ /* Remove the process from the set. */
+ --newProcesses.Count;
+ for (; i < newProcesses.Count; ++i) {
+ newProcesses.Processes[i] = newProcesses.Processes[i + 1];
}
- /* If this was the last process, disable the signal handler. */
- if(newProcesses.Count == 0)
- {
- /* Restore the signal handlers. Repeat call until it is not
- interrupted. */
- while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
- (errno == EINTR));
- while((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
- (errno == EINTR));
- while((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
- (errno == EINTR));
-
- /* Free the table of process pointers since it is now empty.
- This is safe because the signal handler has been removed. */
- newProcesses.Size = 0;
- free(newProcesses.Processes);
- newProcesses.Processes = 0;
+ /* If this was the last process, disable the signal handler. */
+ if (newProcesses.Count == 0) {
+ /* Restore the signal handlers. Repeat call until it is not
+ interrupted. */
+ while ((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
+ (errno == EINTR))
+ ;
+ while ((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
+ (errno == EINTR))
+ ;
+ while ((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
+ (errno == EINTR))
+ ;
+
+ /* Free the table of process pointers since it is now empty.
+ This is safe because the signal handler has been removed. */
+ newProcesses.Size = 0;
+ free(newProcesses.Processes);
+ newProcesses.Processes = 0;
}
- /* Store the new set in that seen by the signal handler. */
- kwsysProcessesUpdate(&newProcesses);
+ /* Store the new set in that seen by the signal handler. */
+ kwsysProcessesUpdate(&newProcesses);
}
}
@@ -2949,9 +2775,10 @@ static void kwsysProcessesRemove(kwsysProcess* cp)
/*--------------------------------------------------------------------------*/
static void kwsysProcessesSignalHandler(int signum
#if KWSYSPE_USE_SIGINFO
- , siginfo_t* info, void* ucontext
+ ,
+ siginfo_t* info, void* ucontext
#endif
- )
+ )
{
int i, j, procStatus, old_errno = errno;
#if KWSYSPE_USE_SIGINFO
@@ -2960,99 +2787,97 @@ static void kwsysProcessesSignalHandler(int signum
#endif
/* Signal all process objects that a child has terminated. */
- switch(signum)
- {
+ switch (signum) {
case SIGCHLD:
- for(i=0; i < kwsysProcesses.Count; ++i)
- {
+ for (i = 0; i < kwsysProcesses.Count; ++i) {
/* Set the pipe in a signalled state. */
char buf = 1;
kwsysProcess* cp = kwsysProcesses.Processes[i];
- kwsysProcess_ssize_t pipeStatus=
+ kwsysProcess_ssize_t pipeStatus =
read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
(void)pipeStatus;
- pipeStatus=write(cp->SignalPipe, &buf, 1);
+ pipeStatus = write(cp->SignalPipe, &buf, 1);
(void)pipeStatus;
- }
+ }
break;
case SIGINT:
case SIGTERM:
/* Signal child processes that are running in new process groups. */
- for(i=0; i < kwsysProcesses.Count; ++i)
- {
+ for (i = 0; i < kwsysProcesses.Count; ++i) {
kwsysProcess* cp = kwsysProcesses.Processes[i];
/* Check Killed to avoid data race condition when killing.
Check State to avoid data race condition in kwsysProcessCleanup
when there is an error (it leaves a reaped PID). */
- if(cp->CreateProcessGroup && !cp->Killed &&
- cp->State != kwsysProcess_State_Error && cp->ForkPIDs)
- {
- for(j=0; j < cp->NumberOfCommands; ++j)
- {
+ if (cp->CreateProcessGroup && !cp->Killed &&
+ cp->State != kwsysProcess_State_Error && cp->ForkPIDs) {
+ for (j = 0; j < cp->NumberOfCommands; ++j) {
/* Make sure the PID is still valid. */
- if(cp->ForkPIDs[j])
- {
- /* The user created a process group for this process. The group ID
+ if (cp->ForkPIDs[j]) {
+ /* The user created a process group for this process. The group
+ ID
is the process ID for the original process in the group. */
kill(-cp->ForkPIDs[j], SIGINT);
- }
}
}
}
+ }
/* Wait for all processes to terminate. */
- while(wait(&procStatus) >= 0 || errno != ECHILD)
- {
- }
+ while (wait(&procStatus) >= 0 || errno != ECHILD) {
+ }
/* Terminate the process, which is now in an inconsistent state
because we reaped all the PIDs that it may have been reaping
or may have reaped in the future. Reraise the signal so that
the proper exit code is returned. */
{
- /* Install default signal handler. */
- struct sigaction defSigAction;
- sigset_t unblockSet;
- memset(&defSigAction, 0, sizeof(defSigAction));
- defSigAction.sa_handler = SIG_DFL;
- sigemptyset(&defSigAction.sa_mask);
- while((sigaction(signum, &defSigAction, 0) < 0) &&
- (errno == EINTR));
- /* Unmask the signal. */
- sigemptyset(&unblockSet);
- sigaddset(&unblockSet, signum);
- sigprocmask(SIG_UNBLOCK, &unblockSet, 0);
- /* Raise the signal again. */
- raise(signum);
- /* We shouldn't get here... but if we do... */
- _exit(1);
+ /* Install default signal handler. */
+ struct sigaction defSigAction;
+ sigset_t unblockSet;
+ memset(&defSigAction, 0, sizeof(defSigAction));
+ defSigAction.sa_handler = SIG_DFL;
+ sigemptyset(&defSigAction.sa_mask);
+ while ((sigaction(signum, &defSigAction, 0) < 0) && (errno == EINTR))
+ ;
+ /* Unmask the signal. */
+ sigemptyset(&unblockSet);
+ sigaddset(&unblockSet, signum);
+ sigprocmask(SIG_UNBLOCK, &unblockSet, 0);
+ /* Raise the signal again. */
+ raise(signum);
+ /* We shouldn't get here... but if we do... */
+ _exit(1);
}
/* break omitted to silence unreachable code clang compiler warning. */
- }
+ }
#if !KWSYSPE_USE_SIGINFO
/* Re-Install our handler. Repeat call until it is not interrupted. */
{
- struct sigaction newSigAction;
- struct sigaction &oldSigAction;
- memset(&newSigAction, 0, sizeof(struct sigaction));
- newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
- newSigChldAction.sa_flags = SA_NOCLDSTOP;
- sigemptyset(&newSigAction.sa_mask);
- switch(signum)
- {
- case SIGCHLD: oldSigAction = &kwsysProcessesOldSigChldAction; break;
- case SIGINT:
- sigaddset(&newSigAction.sa_mask, SIGTERM);
- oldSigAction = &kwsysProcessesOldSigIntAction; break;
- case SIGTERM:
- sigaddset(&newSigAction.sa_mask, SIGINT);
- oldSigAction = &kwsysProcessesOldSigTermAction; break;
- default: return 0;
+ struct sigaction newSigAction;
+ struct sigaction& oldSigAction;
+ memset(&newSigAction, 0, sizeof(struct sigaction));
+ newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
+ newSigChldAction.sa_flags = SA_NOCLDSTOP;
+ sigemptyset(&newSigAction.sa_mask);
+ switch (signum) {
+ case SIGCHLD:
+ oldSigAction = &kwsysProcessesOldSigChldAction;
+ break;
+ case SIGINT:
+ sigaddset(&newSigAction.sa_mask, SIGTERM);
+ oldSigAction = &kwsysProcessesOldSigIntAction;
+ break;
+ case SIGTERM:
+ sigaddset(&newSigAction.sa_mask, SIGINT);
+ oldSigAction = &kwsysProcessesOldSigTermAction;
+ break;
+ default:
+ return 0;
}
- while((sigaction(signum, &newSigAction,
- oldSigAction) < 0) &&
- (errno == EINTR));
+ while ((sigaction(signum, &newSigAction, oldSigAction) < 0) &&
+ (errno == EINTR))
+ ;
}
#endif
@@ -3062,10 +2887,9 @@ static void kwsysProcessesSignalHandler(int signum
/*--------------------------------------------------------------------------*/
void kwsysProcess_ResetStartTime(kwsysProcess* cp)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
/* Reset start time. */
cp->StartTime = kwsysProcessTimeGetCurrent();
}
diff --git a/Source/kwsys/ProcessWin32.c b/Source/kwsys/ProcessWin32.c
index 2b93e69..d10c733 100644
--- a/Source/kwsys/ProcessWin32.c
+++ b/Source/kwsys/ProcessWin32.c
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
#include KWSYS_HEADER(Encoding.h)
@@ -16,8 +7,8 @@
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Process.h.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Process.h.in"
#endif
/*
@@ -31,15 +22,15 @@ a UNIX-style select system call.
*/
#ifdef _MSC_VER
-#pragma warning (push, 1)
+#pragma warning(push, 1)
#endif
#include <windows.h> /* Windows API */
#if defined(_MSC_VER) && _MSC_VER >= 1800
-# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+#define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
#endif
-#include <string.h> /* strlen, strdup */
-#include <stdio.h> /* sprintf */
-#include <io.h> /* _unlink */
+#include <io.h> /* _unlink */
+#include <stdio.h> /* sprintf */
+#include <string.h> /* strlen, strdup */
#ifdef __WATCOMC__
#define _unlink unlink
#endif
@@ -52,14 +43,14 @@ a UNIX-style select system call.
#endif
#ifdef _MSC_VER
-#pragma warning (pop)
-#pragma warning (disable: 4514)
-#pragma warning (disable: 4706)
+#pragma warning(pop)
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4706)
#endif
#if defined(__BORLANDC__)
-# pragma warn -8004 /* assigned a value that is never used */
-# pragma warn -8060 /* Assignment inside if() condition. */
+#pragma warn - 8004 /* assigned a value that is never used */
+#pragma warn - 8060 /* Assignment inside if() condition. */
#endif
/* There are pipes for the process pipeline's stdout and stderr. */
@@ -72,18 +63,14 @@ a UNIX-style select system call.
/* Debug output macro. */
#if 0
-# define KWSYSPE_DEBUG(x) \
-( \
- (void*)cp == (void*)0x00226DE0? \
- ( \
- fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp, __LINE__), \
- fprintf x, \
- fflush(stderr), \
- 1 \
- ) : (1) \
-)
+#define KWSYSPE_DEBUG(x) \
+ ((void*)cp == (void*)0x00226DE0 \
+ ? (fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp, \
+ __LINE__), \
+ fprintf x, fflush(stderr), 1) \
+ : (1))
#else
-# define KWSYSPE_DEBUG(x) (void)1
+#define KWSYSPE_DEBUG(x) (void)1
#endif
typedef LARGE_INTEGER kwsysProcessTime;
@@ -99,7 +86,6 @@ typedef struct kwsysProcessCreateInformation_s
HANDLE hStdError;
} kwsysProcessCreateInformation;
-
/*--------------------------------------------------------------------------*/
typedef struct kwsysProcessPipeData_s kwsysProcessPipeData;
static DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd);
@@ -112,8 +98,7 @@ static int kwsysProcessInitialize(kwsysProcess* cp);
static DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
kwsysProcessCreateInformation* si);
static void kwsysProcessDestroy(kwsysProcess* cp, int event);
-static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle,
- const char* name);
+static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle, const char* name);
static void kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle);
static void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle);
static void kwsysProcessCleanupHandle(PHANDLE h);
@@ -129,8 +114,10 @@ static DWORD kwsysProcessTimeToDWORD(kwsysProcessTime t);
static double kwsysProcessTimeToDouble(kwsysProcessTime t);
static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+ kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+ kwsysProcessTime in2);
static void kwsysProcessSetExitException(kwsysProcess* cp, int code);
static void kwsysProcessKillTree(int pid);
static void kwsysProcessDisablePipeThreads(kwsysProcess* cp);
@@ -300,10 +287,10 @@ struct kwsysProcess_s
int PipesLeft;
/* Buffer for error messages. */
- char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
+ char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
/* Description for the ExitException. */
- char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
+ char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
/* Windows process information data. */
PROCESS_INFORMATION* ProcessInformation;
@@ -337,18 +324,16 @@ kwsysProcess* kwsysProcess_New(void)
first process. This prevents the risk of an orphaned process being
started by the main thread while the default Ctrl handler is in
progress. */
- if(!kwsysProcessesInitialize())
- {
+ if (!kwsysProcessesInitialize()) {
return 0;
- }
+ }
/* Allocate a process control structure. */
cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
- if(!cp)
- {
+ if (!cp) {
/* Could not allocate memory for the control structure. */
return 0;
- }
+ }
ZeroMemory(cp, sizeof(*cp));
/* Share stdin with the parent process by default. */
@@ -362,42 +347,38 @@ kwsysProcess* kwsysProcess_New(void)
ZeroMemory(&osv, sizeof(osv));
osv.dwOSVersionInfoSize = sizeof(osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-# pragma warning (disable:1478)
-# else
-# pragma warning (disable:4996)
-# endif
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
#endif
GetVersionEx(&osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
#endif
- if(osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
- {
+ if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
/* Win9x no longer supported. */
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* Initially no thread owns the mutex. Initialize semaphore to 1. */
- if(!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0)))
- {
+ if (!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* Initially no data are available. Initialize semaphore to 0. */
- if(!(cp->Full = CreateSemaphore(0, 0, 1, 0)))
- {
+ if (!(cp->Full = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* Create the thread to read each pipe. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
- DWORD dummy=0;
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+ DWORD dummy = 0;
/* Assign the thread its index. */
cp->Pipe[i].Index = i;
@@ -406,73 +387,62 @@ kwsysProcess* kwsysProcess_New(void)
cp->Pipe[i].Process = cp;
/* No process is yet running. Initialize semaphore to 0. */
- if(!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0)))
- {
+ if (!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* The pipe is not yet reset. Initialize semaphore to 0. */
- if(!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0)))
- {
+ if (!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* The thread's buffer is initially empty. Initialize semaphore to 1. */
- if(!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0)))
- {
+ if (!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* Create the reading thread. It will block immediately. The
thread will not make deeply nested calls, so we need only a
small stack. */
- if(!(cp->Pipe[i].Reader.Thread = CreateThread(0, 1024,
- kwsysProcessPipeThreadRead,
- &cp->Pipe[i], 0, &dummy)))
- {
+ if (!(cp->Pipe[i].Reader.Thread = CreateThread(
+ 0, 1024, kwsysProcessPipeThreadRead, &cp->Pipe[i], 0, &dummy))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* No process is yet running. Initialize semaphore to 0. */
- if(!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0)))
- {
+ if (!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* The pipe is not yet reset. Initialize semaphore to 0. */
- if(!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0)))
- {
+ if (!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* The waker should not wake immediately. Initialize semaphore to 0. */
- if(!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0)))
- {
+ if (!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
- }
+ }
/* Create the waking thread. It will block immediately. The
thread will not make deeply nested calls, so we need only a
small stack. */
- if(!(cp->Pipe[i].Waker.Thread = CreateThread(0, 1024,
- kwsysProcessPipeThreadWake,
- &cp->Pipe[i], 0, &dummy)))
- {
+ if (!(cp->Pipe[i].Waker.Thread = CreateThread(
+ 0, 1024, kwsysProcessPipeThreadWake, &cp->Pipe[i], 0, &dummy))) {
kwsysProcess_Delete(cp);
return 0;
- }
}
- for(i=0; i < 3; ++i)
- {
+ }
+ for (i = 0; i < 3; ++i) {
cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
- }
+ }
return cp;
}
@@ -483,33 +453,26 @@ void kwsysProcess_Delete(kwsysProcess* cp)
int i;
/* Make sure we have an instance. */
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
/* If the process is executing, wait for it to finish. */
- if(cp->State == kwsysProcess_State_Executing)
- {
- if(cp->Detached)
- {
+ if (cp->State == kwsysProcess_State_Executing) {
+ if (cp->Detached) {
kwsysProcess_Disown(cp);
- }
- else
- {
+ } else {
kwsysProcess_WaitForExit(cp, 0);
- }
}
+ }
/* We are deleting the kwsysProcess instance. */
cp->Deleting = 1;
/* Terminate each of the threads. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
/* Terminate this reading thread. */
- if(cp->Pipe[i].Reader.Thread)
- {
+ if (cp->Pipe[i].Reader.Thread) {
/* Signal the thread we are ready for it. It will terminate
immediately since Deleting is set. */
ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0);
@@ -519,11 +482,10 @@ void kwsysProcess_Delete(kwsysProcess* cp)
/* Close the handle to the thread. */
kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Thread);
- }
+ }
/* Terminate this waking thread. */
- if(cp->Pipe[i].Waker.Thread)
- {
+ if (cp->Pipe[i].Waker.Thread) {
/* Signal the thread we are ready for it. It will terminate
immediately since Deleting is set. */
ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0);
@@ -533,7 +495,7 @@ void kwsysProcess_Delete(kwsysProcess* cp)
/* Close the handle to the thread. */
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Thread);
- }
+ }
/* Cleanup the pipe's semaphores. */
kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Ready);
@@ -542,7 +504,7 @@ void kwsysProcess_Delete(kwsysProcess* cp)
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Ready);
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Go);
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Reset);
- }
+ }
/* Close the shared semaphores. */
kwsysProcessCleanupHandle(&cp->SharedIndexMutex);
@@ -554,10 +516,9 @@ void kwsysProcess_Delete(kwsysProcess* cp)
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
- if(cp->CommandExitCodes)
- {
+ if (cp->CommandExitCodes) {
free(cp->CommandExitCodes);
- }
+ }
free(cp);
}
@@ -565,24 +526,20 @@ void kwsysProcess_Delete(kwsysProcess* cp)
int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
{
int i;
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ }
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
free(cp->Commands[i]);
- }
+ }
cp->NumberOfCommands = 0;
- if(cp->Commands)
- {
+ if (cp->Commands) {
free(cp->Commands);
cp->Commands = 0;
- }
- if(command)
- {
+ }
+ if (command) {
return kwsysProcess_AddCommand(cp, command);
- }
+ }
return 1;
}
@@ -593,91 +550,87 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
wchar_t** newCommands;
/* Make sure we have a command to add. */
- if(!cp || !command || !*command)
- {
+ if (!cp || !command || !*command) {
return 0;
- }
-
+ }
/* Allocate a new array for command pointers. */
newNumberOfCommands = cp->NumberOfCommands + 1;
- if(!(newCommands = (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands)))
- {
+ if (!(newCommands =
+ (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands))) {
/* Out of memory. */
return 0;
- }
+ }
/* Copy any existing commands into the new array. */
{
- int i;
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- newCommands[i] = cp->Commands[i];
+ int i;
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ newCommands[i] = cp->Commands[i];
}
}
- if (cp->Verbatim)
- {
+ if (cp->Verbatim) {
/* Copy the verbatim command line into the buffer. */
newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(*command);
- }
- else
- {
+ } else {
/* Encode the arguments so CommandLineToArgvW can decode
them from the command line string in the child. */
char buffer[32768]; /* CreateProcess max command-line length. */
char* end = buffer + sizeof(buffer);
char* out = buffer;
char const* const* a;
- for (a = command; *a; ++a)
- {
+ for (a = command; *a; ++a) {
int quote = !**a; /* Quote the empty string. */
int slashes = 0;
char const* c;
- if (a != command && out != end) { *out++ = ' '; }
- for (c = *a; !quote && *c; ++c)
- { quote = (*c == ' ' || *c == '\t'); }
- if (quote && out != end) { *out++ = '"'; }
- for (c = *a; *c; ++c)
- {
- if (*c == '\\')
- {
+ if (a != command && out != end) {
+ *out++ = ' ';
+ }
+ for (c = *a; !quote && *c; ++c) {
+ quote = (*c == ' ' || *c == '\t');
+ }
+ if (quote && out != end) {
+ *out++ = '"';
+ }
+ for (c = *a; *c; ++c) {
+ if (*c == '\\') {
++slashes;
- }
- else
- {
- if (*c == '"')
- {
+ } else {
+ if (*c == '"') {
// Add n+1 backslashes to total 2n+1 before internal '"'.
- while(slashes-- >= 0 && out != end) { *out++ = '\\'; }
+ while (slashes-- >= 0 && out != end) {
+ *out++ = '\\';
}
- slashes = 0;
}
- if (out != end) { *out++ = *c; }
+ slashes = 0;
}
- if (quote)
- {
+ if (out != end) {
+ *out++ = *c;
+ }
+ }
+ if (quote) {
// Add n backslashes to total 2n before ending '"'.
- while (slashes-- > 0 && out != end) { *out++ = '\\'; }
- if (out != end) { *out++ = '"'; }
+ while (slashes-- > 0 && out != end) {
+ *out++ = '\\';
+ }
+ if (out != end) {
+ *out++ = '"';
}
}
- if(out != end)
- {
+ }
+ if (out != end) {
*out = '\0';
newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(buffer);
- }
- else
- {
+ } else {
newCommands[cp->NumberOfCommands] = 0;
- }
}
- if (!newCommands[cp->NumberOfCommands])
- {
+ }
+ if (!newCommands[cp->NumberOfCommands]) {
/* Out of memory or command line too long. */
free(newCommands);
return 0;
- }
+ }
/* Save the new array of commands. */
free(cp->Commands);
@@ -689,15 +642,13 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
/*--------------------------------------------------------------------------*/
void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
cp->Timeout = timeout;
- if(cp->Timeout < 0)
- {
+ if (cp->Timeout < 0) {
cp->Timeout = 0;
- }
+ }
// Force recomputation of TimeoutTime.
cp->TimeoutTime.QuadPart = -1;
}
@@ -705,38 +656,32 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
/*--------------------------------------------------------------------------*/
int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
{
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
- if(cp->WorkingDirectory)
- {
+ }
+ if (cp->WorkingDirectory) {
free(cp->WorkingDirectory);
cp->WorkingDirectory = 0;
- }
- if(dir && dir[0])
- {
+ }
+ if (dir && dir[0]) {
wchar_t* wdir = kwsysEncoding_DupToWide(dir);
/* We must convert the working directory to a full path. */
DWORD length = GetFullPathNameW(wdir, 0, 0, 0);
- if(length > 0)
- {
- wchar_t* work_dir = malloc(length*sizeof(wchar_t));
- if(!work_dir)
- {
+ if (length > 0) {
+ wchar_t* work_dir = malloc(length * sizeof(wchar_t));
+ if (!work_dir) {
free(wdir);
return 0;
- }
- if(!GetFullPathNameW(wdir, length, work_dir, 0))
- {
+ }
+ if (!GetFullPathNameW(wdir, length, work_dir, 0)) {
free(work_dir);
free(wdir);
return 0;
- }
- cp->WorkingDirectory = work_dir;
}
- free(wdir);
+ cp->WorkingDirectory = work_dir;
}
+ free(wdir);
+ }
return 1;
}
@@ -744,39 +689,40 @@ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file)
{
char** pfile;
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
- switch(pipe)
- {
- case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
- case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
- case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
- default: return 0;
- }
- if(*pfile)
- {
+ }
+ switch (pipe) {
+ case kwsysProcess_Pipe_STDIN:
+ pfile = &cp->PipeFileSTDIN;
+ break;
+ case kwsysProcess_Pipe_STDOUT:
+ pfile = &cp->PipeFileSTDOUT;
+ break;
+ case kwsysProcess_Pipe_STDERR:
+ pfile = &cp->PipeFileSTDERR;
+ break;
+ default:
+ return 0;
+ }
+ if (*pfile) {
free(*pfile);
*pfile = 0;
- }
- if(file)
- {
- *pfile = (char*)malloc(strlen(file)+1);
- if(!*pfile)
- {
+ }
+ if (file) {
+ *pfile = (char*)malloc(strlen(file) + 1);
+ if (!*pfile) {
return 0;
- }
- strcpy(*pfile, file);
}
+ strcpy(*pfile, file);
+ }
/* If we are redirecting the pipe, do not share it or use a native
pipe. */
- if(*pfile)
- {
+ if (*pfile) {
kwsysProcess_SetPipeNative(cp, pipe, 0);
kwsysProcess_SetPipeShared(cp, pipe, 0);
- }
+ }
return 1;
}
@@ -784,26 +730,30 @@ int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file)
/*--------------------------------------------------------------------------*/
void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, int shared)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
- switch(pipe)
- {
- case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
- case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
- case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
- default: return;
- }
+ switch (pipe) {
+ case kwsysProcess_Pipe_STDIN:
+ cp->PipeSharedSTDIN = shared ? 1 : 0;
+ break;
+ case kwsysProcess_Pipe_STDOUT:
+ cp->PipeSharedSTDOUT = shared ? 1 : 0;
+ break;
+ case kwsysProcess_Pipe_STDERR:
+ cp->PipeSharedSTDERR = shared ? 1 : 0;
+ break;
+ default:
+ return;
+ }
/* If we are sharing the pipe, do not redirect it to a file or use a
native pipe. */
- if(shared)
- {
+ if (shared) {
kwsysProcess_SetPipeFile(cp, pipe, 0);
kwsysProcess_SetPipeNative(cp, pipe, 0);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -811,129 +761,135 @@ void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, HANDLE p[2])
{
HANDLE* pPipeNative = 0;
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
- switch(pipe)
- {
- case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
- case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
- case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
- default: return;
- }
+ switch (pipe) {
+ case kwsysProcess_Pipe_STDIN:
+ pPipeNative = cp->PipeNativeSTDIN;
+ break;
+ case kwsysProcess_Pipe_STDOUT:
+ pPipeNative = cp->PipeNativeSTDOUT;
+ break;
+ case kwsysProcess_Pipe_STDERR:
+ pPipeNative = cp->PipeNativeSTDERR;
+ break;
+ default:
+ return;
+ }
/* Copy the native pipe handles provided. */
- if(p)
- {
+ if (p) {
pPipeNative[0] = p[0];
pPipeNative[1] = p[1];
- }
- else
- {
+ } else {
pPipeNative[0] = 0;
pPipeNative[1] = 0;
- }
+ }
/* If we are using a native pipe, do not share it or redirect it to
a file. */
- if(p)
- {
+ if (p) {
kwsysProcess_SetPipeFile(cp, pipe, 0);
kwsysProcess_SetPipeShared(cp, pipe, 0);
- }
+ }
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
{
- if(!cp)
- {
+ if (!cp) {
return 0;
- }
+ }
- switch(optionId)
- {
- case kwsysProcess_Option_Detach: return cp->OptionDetach;
- case kwsysProcess_Option_HideWindow: return cp->HideWindow;
- case kwsysProcess_Option_MergeOutput: return cp->MergeOutput;
- case kwsysProcess_Option_Verbatim: return cp->Verbatim;
+ switch (optionId) {
+ case kwsysProcess_Option_Detach:
+ return cp->OptionDetach;
+ case kwsysProcess_Option_HideWindow:
+ return cp->HideWindow;
+ case kwsysProcess_Option_MergeOutput:
+ return cp->MergeOutput;
+ case kwsysProcess_Option_Verbatim:
+ return cp->Verbatim;
case kwsysProcess_Option_CreateProcessGroup:
return cp->CreateProcessGroup;
- default: return 0;
- }
+ default:
+ return 0;
+ }
}
/*--------------------------------------------------------------------------*/
void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
- switch(optionId)
- {
- case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
- case kwsysProcess_Option_HideWindow: cp->HideWindow = value; break;
- case kwsysProcess_Option_MergeOutput: cp->MergeOutput = value; break;
- case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
+ switch (optionId) {
+ case kwsysProcess_Option_Detach:
+ cp->OptionDetach = value;
+ break;
+ case kwsysProcess_Option_HideWindow:
+ cp->HideWindow = value;
+ break;
+ case kwsysProcess_Option_MergeOutput:
+ cp->MergeOutput = value;
+ break;
+ case kwsysProcess_Option_Verbatim:
+ cp->Verbatim = value;
+ break;
case kwsysProcess_Option_CreateProcessGroup:
- cp->CreateProcessGroup = value; break;
- default: break;
- }
+ cp->CreateProcessGroup = value;
+ break;
+ default:
+ break;
+ }
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetState(kwsysProcess* cp)
{
- return cp? cp->State : kwsysProcess_State_Error;
+ return cp ? cp->State : kwsysProcess_State_Error;
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitException(kwsysProcess* cp)
{
- return cp? cp->ExitException : kwsysProcess_Exception_Other;
+ return cp ? cp->ExitException : kwsysProcess_Exception_Other;
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitValue(kwsysProcess* cp)
{
- return cp? cp->ExitValue : -1;
+ return cp ? cp->ExitValue : -1;
}
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitCode(kwsysProcess* cp)
{
- return cp? cp->ExitCode : 0;
+ return cp ? cp->ExitCode : 0;
}
/*--------------------------------------------------------------------------*/
const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
{
- if(!cp)
- {
+ if (!cp) {
return "Process management structure could not be allocated";
- }
- else if(cp->State == kwsysProcess_State_Error)
- {
+ } else if (cp->State == kwsysProcess_State_Error) {
return cp->ErrorMessage;
- }
+ }
return "Success";
}
/*--------------------------------------------------------------------------*/
const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
{
- if(!cp)
- {
+ if (!cp) {
return "GetExceptionString called with NULL process management structure";
- }
- else if(cp->State == kwsysProcess_State_Exception)
- {
+ } else if (cp->State == kwsysProcess_State_Exception) {
return cp->ExitExceptionString;
- }
+ }
return "No exception";
}
@@ -943,259 +899,210 @@ void kwsysProcess_Execute(kwsysProcess* cp)
int i;
/* Do not execute a second time. */
- if(!cp || cp->State == kwsysProcess_State_Executing)
- {
+ if (!cp || cp->State == kwsysProcess_State_Executing) {
return;
- }
+ }
/* Make sure we have something to run. */
- if(cp->NumberOfCommands < 1)
- {
+ if (cp->NumberOfCommands < 1) {
strcpy(cp->ErrorMessage, "No command");
cp->State = kwsysProcess_State_Error;
return;
- }
+ }
/* Initialize the control structure for a new process. */
- if(!kwsysProcessInitialize(cp))
- {
+ if (!kwsysProcessInitialize(cp)) {
strcpy(cp->ErrorMessage, "Out of memory");
cp->State = kwsysProcess_State_Error;
return;
- }
+ }
/* Save the real working directory of this process and change to
the working directory for the child processes. This is needed
to make pipe file paths evaluate correctly. */
- if(cp->WorkingDirectory)
- {
- if(!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
- cp->RealWorkingDirectory))
- {
+ if (cp->WorkingDirectory) {
+ if (!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
+ cp->RealWorkingDirectory)) {
kwsysProcessCleanup(cp, GetLastError());
return;
- }
- SetCurrentDirectoryW(cp->WorkingDirectory);
}
-
+ SetCurrentDirectoryW(cp->WorkingDirectory);
+ }
/* Setup the stdin pipe for the first process. */
- if(cp->PipeFileSTDIN)
- {
+ if (cp->PipeFileSTDIN) {
/* Create a handle to read a file for stdin. */
wchar_t* wstdin = kwsysEncoding_DupToWide(cp->PipeFileSTDIN);
DWORD error;
cp->PipeChildStd[0] =
- CreateFileW(wstdin, GENERIC_READ|GENERIC_WRITE,
- FILE_SHARE_READ|FILE_SHARE_WRITE,
- 0, OPEN_EXISTING, 0, 0);
+ CreateFileW(wstdin, GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
error = GetLastError(); /* Check now in case free changes this. */
free(wstdin);
- if(cp->PipeChildStd[0] == INVALID_HANDLE_VALUE)
- {
+ if (cp->PipeChildStd[0] == INVALID_HANDLE_VALUE) {
kwsysProcessCleanup(cp, error);
return;
- }
}
- else if(cp->PipeSharedSTDIN)
- {
+ } else if (cp->PipeSharedSTDIN) {
/* Share this process's stdin with the child. */
kwsysProcessSetupSharedPipe(STD_INPUT_HANDLE, &cp->PipeChildStd[0]);
- }
- else if(cp->PipeNativeSTDIN[0])
- {
+ } else if (cp->PipeNativeSTDIN[0]) {
/* Use the provided native pipe. */
kwsysProcessSetupPipeNative(cp->PipeNativeSTDIN[0], &cp->PipeChildStd[0]);
- }
- else
- {
+ } else {
/* Explicitly give the child no stdin. */
cp->PipeChildStd[0] = INVALID_HANDLE_VALUE;
- }
+ }
/* Create the output pipe for the last process.
We always create this so the pipe thread can run even if we
do not end up giving the write end to the child below. */
- if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read,
- &cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0))
- {
+ if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read,
+ &cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0)) {
kwsysProcessCleanup(cp, GetLastError());
return;
- }
+ }
- if(cp->PipeFileSTDOUT)
- {
+ if (cp->PipeFileSTDOUT) {
/* Use a file for stdout. */
DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
cp->PipeFileSTDOUT);
- if(error)
- {
+ if (error) {
kwsysProcessCleanup(cp, error);
return;
- }
}
- else if(cp->PipeSharedSTDOUT)
- {
+ } else if (cp->PipeSharedSTDOUT) {
/* Use the parent stdout. */
kwsysProcessSetupSharedPipe(STD_OUTPUT_HANDLE, &cp->PipeChildStd[1]);
- }
- else if(cp->PipeNativeSTDOUT[1])
- {
+ } else if (cp->PipeNativeSTDOUT[1]) {
/* Use the given handle for stdout. */
kwsysProcessSetupPipeNative(cp->PipeNativeSTDOUT[1], &cp->PipeChildStd[1]);
- }
- else
- {
+ } else {
/* Use our pipe for stdout. Duplicate the handle since our waker
thread will use the original. Do not make it inherited yet. */
- if(!DuplicateHandle(GetCurrentProcess(),
- cp->Pipe[KWSYSPE_PIPE_STDOUT].Write,
- GetCurrentProcess(), &cp->PipeChildStd[1],
- 0, FALSE, DUPLICATE_SAME_ACCESS))
- {
+ if (!DuplicateHandle(GetCurrentProcess(),
+ cp->Pipe[KWSYSPE_PIPE_STDOUT].Write,
+ GetCurrentProcess(), &cp->PipeChildStd[1], 0, FALSE,
+ DUPLICATE_SAME_ACCESS)) {
kwsysProcessCleanup(cp, GetLastError());
return;
- }
}
+ }
/* Create stderr pipe to be shared by all processes in the pipeline.
We always create this so the pipe thread can run even if we do not
end up giving the write end to the child below. */
- if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read,
- &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0))
- {
+ if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read,
+ &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0)) {
kwsysProcessCleanup(cp, GetLastError());
return;
- }
+ }
- if(cp->PipeFileSTDERR)
- {
+ if (cp->PipeFileSTDERR) {
/* Use a file for stderr. */
DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
cp->PipeFileSTDERR);
- if(error)
- {
+ if (error) {
kwsysProcessCleanup(cp, error);
return;
- }
}
- else if(cp->PipeSharedSTDERR)
- {
+ } else if (cp->PipeSharedSTDERR) {
/* Use the parent stderr. */
kwsysProcessSetupSharedPipe(STD_ERROR_HANDLE, &cp->PipeChildStd[2]);
- }
- else if(cp->PipeNativeSTDERR[1])
- {
+ } else if (cp->PipeNativeSTDERR[1]) {
/* Use the given handle for stderr. */
kwsysProcessSetupPipeNative(cp->PipeNativeSTDERR[1], &cp->PipeChildStd[2]);
- }
- else
- {
+ } else {
/* Use our pipe for stderr. Duplicate the handle since our waker
thread will use the original. Do not make it inherited yet. */
- if(!DuplicateHandle(GetCurrentProcess(),
- cp->Pipe[KWSYSPE_PIPE_STDERR].Write,
- GetCurrentProcess(), &cp->PipeChildStd[2],
- 0, FALSE, DUPLICATE_SAME_ACCESS))
- {
+ if (!DuplicateHandle(GetCurrentProcess(),
+ cp->Pipe[KWSYSPE_PIPE_STDERR].Write,
+ GetCurrentProcess(), &cp->PipeChildStd[2], 0, FALSE,
+ DUPLICATE_SAME_ACCESS)) {
kwsysProcessCleanup(cp, GetLastError());
return;
- }
}
+ }
/* Create the pipeline of processes. */
{
- /* Child startup control data. */
- kwsysProcessCreateInformation si;
- HANDLE nextStdInput = cp->PipeChildStd[0];
-
- /* Initialize startup info data. */
- ZeroMemory(&si, sizeof(si));
- si.StartupInfo.cb = sizeof(si.StartupInfo);
-
- /* Decide whether a child window should be shown. */
- si.StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
- si.StartupInfo.wShowWindow =
- (unsigned short)(cp->HideWindow?SW_HIDE:SW_SHOWDEFAULT);
-
- /* Connect the child's output pipes to the threads. */
- si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
-
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- /* Setup the process's pipes. */
- si.hStdInput = nextStdInput;
- if (i == cp->NumberOfCommands-1)
- {
- /* The last child gets the overall stdout. */
- nextStdInput = INVALID_HANDLE_VALUE;
- si.hStdOutput = cp->PipeChildStd[1];
- }
- else
- {
- /* Create a pipe to sit between the children. */
- HANDLE p[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
- if (!CreatePipe(&p[0], &p[1], 0, 0))
- {
- DWORD error = GetLastError();
- if (nextStdInput != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupHandle(&nextStdInput);
+ /* Child startup control data. */
+ kwsysProcessCreateInformation si;
+ HANDLE nextStdInput = cp->PipeChildStd[0];
+
+ /* Initialize startup info data. */
+ ZeroMemory(&si, sizeof(si));
+ si.StartupInfo.cb = sizeof(si.StartupInfo);
+
+ /* Decide whether a child window should be shown. */
+ si.StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
+ si.StartupInfo.wShowWindow =
+ (unsigned short)(cp->HideWindow ? SW_HIDE : SW_SHOWDEFAULT);
+
+ /* Connect the child's output pipes to the threads. */
+ si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
+
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ /* Setup the process's pipes. */
+ si.hStdInput = nextStdInput;
+ if (i == cp->NumberOfCommands - 1) {
+ /* The last child gets the overall stdout. */
+ nextStdInput = INVALID_HANDLE_VALUE;
+ si.hStdOutput = cp->PipeChildStd[1];
+ } else {
+ /* Create a pipe to sit between the children. */
+ HANDLE p[2] = { INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE };
+ if (!CreatePipe(&p[0], &p[1], 0, 0)) {
+ DWORD error = GetLastError();
+ if (nextStdInput != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupHandle(&nextStdInput);
}
- kwsysProcessCleanup(cp, error);
- return;
+ kwsysProcessCleanup(cp, error);
+ return;
}
- nextStdInput = p[0];
- si.hStdOutput = p[1];
+ nextStdInput = p[0];
+ si.hStdOutput = p[1];
}
- si.hStdError = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2];
-
- {
- DWORD error = kwsysProcessCreate(cp, i, &si);
+ si.hStdError =
+ cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2];
- /* Close our copies of pipes used between children. */
- if (si.hStdInput != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupHandle(&si.hStdInput);
- }
- if (si.hStdOutput != cp->PipeChildStd[1])
- {
- kwsysProcessCleanupHandle(&si.hStdOutput);
- }
- if (si.hStdError != cp->PipeChildStd[2] && !cp->MergeOutput)
{
- kwsysProcessCleanupHandle(&si.hStdError);
- }
- if (!error)
- {
- cp->ProcessEvents[i+1] = cp->ProcessInformation[i].hProcess;
- }
- else
- {
- if (nextStdInput != cp->PipeChildStd[0])
- {
- kwsysProcessCleanupHandle(&nextStdInput);
+ DWORD error = kwsysProcessCreate(cp, i, &si);
+
+ /* Close our copies of pipes used between children. */
+ if (si.hStdInput != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupHandle(&si.hStdInput);
+ }
+ if (si.hStdOutput != cp->PipeChildStd[1]) {
+ kwsysProcessCleanupHandle(&si.hStdOutput);
+ }
+ if (si.hStdError != cp->PipeChildStd[2] && !cp->MergeOutput) {
+ kwsysProcessCleanupHandle(&si.hStdError);
+ }
+ if (!error) {
+ cp->ProcessEvents[i + 1] = cp->ProcessInformation[i].hProcess;
+ } else {
+ if (nextStdInput != cp->PipeChildStd[0]) {
+ kwsysProcessCleanupHandle(&nextStdInput);
+ }
+ kwsysProcessCleanup(cp, error);
+ return;
}
- kwsysProcessCleanup(cp, error);
- return;
}
}
- }
}
/* The parent process does not need the child's pipe ends. */
- for (i=0; i < 3; ++i)
- {
+ for (i = 0; i < 3; ++i) {
kwsysProcessCleanupHandle(&cp->PipeChildStd[i]);
- }
+ }
/* Restore the working directory. */
- if(cp->RealWorkingDirectory)
- {
+ if (cp->RealWorkingDirectory) {
SetCurrentDirectoryW(cp->RealWorkingDirectory);
free(cp->RealWorkingDirectory);
cp->RealWorkingDirectory = 0;
- }
+ }
/* The timeout period starts now. */
cp->StartTime = kwsysProcessTimeGetCurrent();
@@ -1203,24 +1110,21 @@ void kwsysProcess_Execute(kwsysProcess* cp)
/* All processes in the pipeline have been started in suspended
mode. Resume them all now. */
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
ResumeThread(cp->ProcessInformation[i].hThread);
- }
+ }
/* ---- It is no longer safe to call kwsysProcessCleanup. ----- */
/* Tell the pipe threads that a process has started. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0);
ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0);
- }
+ }
/* We don't care about the children's main threads. */
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
- }
+ }
/* No pipe has reported data. */
cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
@@ -1237,21 +1141,19 @@ void kwsysProcess_Disown(kwsysProcess* cp)
int i;
/* Make sure we are executing a detached process. */
- if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
- cp->TimeoutExpired || cp->Killed || cp->Terminated)
- {
+ if (!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
+ cp->TimeoutExpired || cp->Killed || cp->Terminated) {
return;
- }
+ }
/* Disable the reading threads. */
kwsysProcessDisablePipeThreads(cp);
/* Wait for all pipe threads to reset. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
WaitForSingleObject(cp->Pipe[i].Reader.Reset, INFINITE);
WaitForSingleObject(cp->Pipe[i].Waker.Reset, INFINITE);
- }
+ }
/* We will not wait for exit, so cleanup now. */
kwsysProcessCleanup(cp, 0);
@@ -1276,11 +1178,10 @@ int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
DWORD w;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
- cp->TimeoutExpired)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
+ cp->TimeoutExpired) {
return kwsysProcess_Pipe_None;
- }
+ }
/* Record the time at which user timeout period starts. */
userStartTime = kwsysProcessTimeGetCurrent();
@@ -1290,125 +1191,102 @@ int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime);
/* Loop until we have a reason to return. */
- while(!done && cp->PipesLeft > 0)
- {
+ while (!done && cp->PipesLeft > 0) {
/* If we previously got data from a thread, let it know we are
done with the data. */
- if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT)
- {
+ if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) {
KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex));
ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
- }
+ }
/* Setup a timeout if required. */
- if(kwsysProcessGetTimeoutLeft(&timeoutTime, user?userTimeout:0,
- &timeoutLength))
- {
+ if (kwsysProcessGetTimeoutLeft(&timeoutTime, user ? userTimeout : 0,
+ &timeoutLength)) {
/* Timeout has already expired. */
expired = 1;
break;
- }
- if(timeoutTime.QuadPart < 0)
- {
+ }
+ if (timeoutTime.QuadPart < 0) {
timeout = INFINITE;
- }
- else
- {
+ } else {
timeout = kwsysProcessTimeToDWORD(timeoutLength);
- }
+ }
/* Wait for a pipe's thread to signal or a process to terminate. */
- w = WaitForMultipleObjects(cp->ProcessEventsLength, cp->ProcessEvents,
- 0, timeout);
- if(w == WAIT_TIMEOUT)
- {
+ w = WaitForMultipleObjects(cp->ProcessEventsLength, cp->ProcessEvents, 0,
+ timeout);
+ if (w == WAIT_TIMEOUT) {
/* Timeout has expired. */
expired = 1;
done = 1;
- }
- else if(w == WAIT_OBJECT_0)
- {
+ } else if (w == WAIT_OBJECT_0) {
/* Save the index of the reporting thread and release the mutex.
The thread will block until we signal its Empty mutex. */
cp->CurrentIndex = cp->SharedIndex;
ReleaseSemaphore(cp->SharedIndexMutex, 1, 0);
/* Data are available or a pipe closed. */
- if(cp->Pipe[cp->CurrentIndex].Closed)
- {
+ if (cp->Pipe[cp->CurrentIndex].Closed) {
/* The pipe closed at the write end. Close the read end and
inform the wakeup thread it is done with this process. */
kwsysProcessCleanupHandle(&cp->Pipe[cp->CurrentIndex].Read);
ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Waker.Go, 1, 0);
KWSYSPE_DEBUG((stderr, "wakeup %d\n", cp->CurrentIndex));
--cp->PipesLeft;
- }
- else if(data && length)
- {
+ } else if (data && length) {
/* Report this data. */
*data = cp->Pipe[cp->CurrentIndex].DataBuffer;
*length = cp->Pipe[cp->CurrentIndex].DataLength;
- switch(cp->CurrentIndex)
- {
+ switch (cp->CurrentIndex) {
case KWSYSPE_PIPE_STDOUT:
- pipeId = kwsysProcess_Pipe_STDOUT; break;
+ pipeId = kwsysProcess_Pipe_STDOUT;
+ break;
case KWSYSPE_PIPE_STDERR:
- pipeId = kwsysProcess_Pipe_STDERR; break;
- }
- done = 1;
+ pipeId = kwsysProcess_Pipe_STDERR;
+ break;
}
+ done = 1;
}
- else
- {
+ } else {
/* A process has terminated. */
- kwsysProcessDestroy(cp, w-WAIT_OBJECT_0);
- }
+ kwsysProcessDestroy(cp, w - WAIT_OBJECT_0);
}
+ }
/* Update the user timeout. */
- if(userTimeout)
- {
+ if (userTimeout) {
kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
- kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
- userStartTime);
+ kwsysProcessTime difference =
+ kwsysProcessTimeSubtract(userEndTime, userStartTime);
double d = kwsysProcessTimeToDouble(difference);
*userTimeout -= d;
- if(*userTimeout < 0)
- {
+ if (*userTimeout < 0) {
*userTimeout = 0;
- }
}
+ }
/* Check what happened. */
- if(pipeId)
- {
+ if (pipeId) {
/* Data are ready on a pipe. */
return pipeId;
- }
- else if(expired)
- {
+ } else if (expired) {
/* A timeout has expired. */
- if(user)
- {
+ if (user) {
/* The user timeout has expired. It has no time left. */
return kwsysProcess_Pipe_Timeout;
- }
- else
- {
+ } else {
/* The process timeout has expired. Kill the child now. */
KWSYSPE_DEBUG((stderr, "killing child because timeout expired\n"));
kwsysProcess_Kill(cp);
cp->TimeoutExpired = 1;
cp->Killed = 0;
return kwsysProcess_Pipe_None;
- }
}
- else
- {
+ } else {
/* The children have terminated and no more data are available. */
return kwsysProcess_Pipe_None;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1418,75 +1296,62 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
int pipe;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing) {
return 1;
- }
+ }
/* Wait for the process to terminate. Ignore all data. */
- while((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
- {
- if(pipe == kwsysProcess_Pipe_Timeout)
- {
+ while ((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) {
+ if (pipe == kwsysProcess_Pipe_Timeout) {
/* The user timeout has expired. */
return 0;
- }
}
+ }
KWSYSPE_DEBUG((stderr, "no more data\n"));
/* When the last pipe closes in WaitForData, the loop terminates
without releasing the pipe's thread. Release it now. */
- if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT)
- {
+ if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) {
KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex));
ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
- }
+ }
/* Wait for all pipe threads to reset. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
KWSYSPE_DEBUG((stderr, "waiting reader reset %d\n", i));
WaitForSingleObject(cp->Pipe[i].Reader.Reset, INFINITE);
KWSYSPE_DEBUG((stderr, "waiting waker reset %d\n", i));
WaitForSingleObject(cp->Pipe[i].Waker.Reset, INFINITE);
- }
+ }
/* ---- It is now safe again to call kwsysProcessCleanup. ----- */
/* Close all the pipes. */
kwsysProcessCleanup(cp, 0);
/* Determine the outcome. */
- if(cp->Killed)
- {
+ if (cp->Killed) {
/* We killed the child. */
cp->State = kwsysProcess_State_Killed;
- }
- else if(cp->TimeoutExpired)
- {
+ } else if (cp->TimeoutExpired) {
/* The timeout expired. */
cp->State = kwsysProcess_State_Expired;
- }
- else
- {
+ } else {
/* The children exited. Report the outcome of the last process. */
- cp->ExitCode = cp->CommandExitCodes[cp->NumberOfCommands-1];
- if((cp->ExitCode & 0xF0000000) == 0xC0000000)
- {
+ cp->ExitCode = cp->CommandExitCodes[cp->NumberOfCommands - 1];
+ if ((cp->ExitCode & 0xF0000000) == 0xC0000000) {
/* Child terminated due to exceptional behavior. */
cp->State = kwsysProcess_State_Exception;
cp->ExitValue = 1;
kwsysProcessSetExitException(cp, cp->ExitCode);
- }
- else
- {
+ } else {
/* Child exited without exception. */
cp->State = kwsysProcess_State_Exited;
cp->ExitException = kwsysProcess_Exception_None;
cp->ExitValue = cp->ExitCode;
- }
}
+ }
return 1;
}
@@ -1496,45 +1361,37 @@ void kwsysProcess_Interrupt(kwsysProcess* cp)
{
int i;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
- cp->Killed)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
+ cp->Killed) {
KWSYSPE_DEBUG((stderr, "interrupt: child not executing\n"));
return;
- }
+ }
/* Skip actually interrupting the child if it has already terminated. */
- if(cp->Terminated)
- {
+ if (cp->Terminated) {
KWSYSPE_DEBUG((stderr, "interrupt: child already terminated\n"));
return;
- }
+ }
/* Interrupt the children. */
- if (cp->CreateProcessGroup)
- {
- if(cp->ProcessInformation)
- {
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ if (cp->CreateProcessGroup) {
+ if (cp->ProcessInformation) {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
/* Make sure the process handle isn't closed (e.g. from disowning). */
- if(cp->ProcessInformation[i].hProcess)
- {
+ if (cp->ProcessInformation[i].hProcess) {
/* The user created a process group for this process. The group ID
is the process ID for the original process in the group. Note
that we have to use Ctrl+Break: Ctrl+C is not allowed for process
groups. */
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT,
cp->ProcessInformation[i].dwProcessId);
- }
}
}
}
- else
- {
+ } else {
/* No process group was created. Kill our own process group... */
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1542,34 +1399,31 @@ void kwsysProcess_Kill(kwsysProcess* cp)
{
int i;
/* Make sure we are executing a process. */
- if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
- cp->Killed)
- {
+ if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
+ cp->Killed) {
KWSYSPE_DEBUG((stderr, "kill: child not executing\n"));
return;
- }
+ }
/* Disable the reading threads. */
KWSYSPE_DEBUG((stderr, "kill: disabling pipe threads\n"));
kwsysProcessDisablePipeThreads(cp);
/* Skip actually killing the child if it has already terminated. */
- if(cp->Terminated)
- {
+ if (cp->Terminated) {
KWSYSPE_DEBUG((stderr, "kill: child already terminated\n"));
return;
- }
+ }
/* Kill the children. */
cp->Killed = 1;
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
kwsysProcessKillTree(cp->ProcessInformation[i].dwProcessId);
/* Remove from global list of processes and close handles. */
kwsysProcessesRemove(cp->ProcessInformation[i].hProcess);
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess);
- }
+ }
/* We are killing the children and ignoring all data. Do not wait
for them to exit. */
@@ -1587,14 +1441,13 @@ DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd)
kwsysProcess* cp = td->Process;
/* Wait for a process to be ready. */
- while((WaitForSingleObject(td->Reader.Ready, INFINITE), !cp->Deleting))
- {
+ while ((WaitForSingleObject(td->Reader.Ready, INFINITE), !cp->Deleting)) {
/* Read output from the process for this thread's pipe. */
kwsysProcessPipeThreadReadPipe(cp, td);
/* Signal the main thread we have reset for a new process. */
ReleaseSemaphore(td->Reader.Reset, 1, 0);
- }
+ }
return 0;
}
@@ -1607,24 +1460,21 @@ DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd)
void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp, kwsysProcessPipeData* td)
{
/* Wait for space in the thread's buffer. */
- while((KWSYSPE_DEBUG((stderr, "wait for read %d\n", td->Index)),
- WaitForSingleObject(td->Reader.Go, INFINITE), !td->Closed))
- {
+ while ((KWSYSPE_DEBUG((stderr, "wait for read %d\n", td->Index)),
+ WaitForSingleObject(td->Reader.Go, INFINITE), !td->Closed)) {
KWSYSPE_DEBUG((stderr, "reading %d\n", td->Index));
/* Read data from the pipe. This may block until data are available. */
- if(!ReadFile(td->Read, td->DataBuffer, KWSYSPE_PIPE_BUFFER_SIZE,
- &td->DataLength, 0))
- {
- if(GetLastError() != ERROR_BROKEN_PIPE)
- {
+ if (!ReadFile(td->Read, td->DataBuffer, KWSYSPE_PIPE_BUFFER_SIZE,
+ &td->DataLength, 0)) {
+ if (GetLastError() != ERROR_BROKEN_PIPE) {
/* UNEXPECTED failure to read the pipe. */
- }
+ }
/* The pipe closed. There are no more data to read. */
td->Closed = 1;
KWSYSPE_DEBUG((stderr, "read closed %d\n", td->Index));
- }
+ }
KWSYSPE_DEBUG((stderr, "read %d\n", td->Index));
@@ -1636,7 +1486,7 @@ void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp, kwsysProcessPipeData* td)
/* Tell the main thread we have something to report. */
cp->SharedIndex = td->Index;
ReleaseSemaphore(cp->Full, 1, 0);
- }
+ }
/* We were signalled to exit with our buffer empty. Reset the
mutex for a new process. */
@@ -1656,14 +1506,13 @@ DWORD WINAPI kwsysProcessPipeThreadWake(LPVOID ptd)
kwsysProcess* cp = td->Process;
/* Wait for a process to be ready. */
- while((WaitForSingleObject(td->Waker.Ready, INFINITE), !cp->Deleting))
- {
+ while ((WaitForSingleObject(td->Waker.Ready, INFINITE), !cp->Deleting)) {
/* Wait for a possible wakeup. */
kwsysProcessPipeThreadWakePipe(cp, td);
/* Signal the main thread we have reset for a new process. */
ReleaseSemaphore(td->Waker.Reset, 1, 0);
- }
+ }
return 0;
}
@@ -1683,13 +1532,12 @@ void kwsysProcessPipeThreadWakePipe(kwsysProcess* cp, kwsysProcessPipeData* td)
KWSYSPE_DEBUG((stderr, "waking %d\n", td->Index));
/* If the pipe is not closed, we need to wake up the reading thread. */
- if(!td->Closed)
- {
+ if (!td->Closed) {
DWORD dummy;
KWSYSPE_DEBUG((stderr, "waker %d writing byte\n", td->Index));
WriteFile(td->Write, "", 1, &dummy, 0);
KWSYSPE_DEBUG((stderr, "waker %d wrote byte\n", td->Index));
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1709,55 +1557,48 @@ int kwsysProcessInitialize(kwsysProcess* cp)
strcpy(cp->ExitExceptionString, "No exception");
/* Allocate process information for each process. */
- cp->ProcessInformation =
- (PROCESS_INFORMATION*)malloc(sizeof(PROCESS_INFORMATION) *
- cp->NumberOfCommands);
- if(!cp->ProcessInformation)
- {
+ cp->ProcessInformation = (PROCESS_INFORMATION*)malloc(
+ sizeof(PROCESS_INFORMATION) * cp->NumberOfCommands);
+ if (!cp->ProcessInformation) {
return 0;
- }
+ }
ZeroMemory(cp->ProcessInformation,
sizeof(PROCESS_INFORMATION) * cp->NumberOfCommands);
- if(cp->CommandExitCodes)
- {
+ if (cp->CommandExitCodes) {
free(cp->CommandExitCodes);
- }
- cp->CommandExitCodes = (DWORD*)malloc(sizeof(DWORD)*cp->NumberOfCommands);
- if(!cp->CommandExitCodes)
- {
+ }
+ cp->CommandExitCodes = (DWORD*)malloc(sizeof(DWORD) * cp->NumberOfCommands);
+ if (!cp->CommandExitCodes) {
return 0;
- }
- ZeroMemory(cp->CommandExitCodes, sizeof(DWORD)*cp->NumberOfCommands);
+ }
+ ZeroMemory(cp->CommandExitCodes, sizeof(DWORD) * cp->NumberOfCommands);
/* Allocate event wait array. The first event is cp->Full, the rest
are the process termination events. */
- cp->ProcessEvents = (PHANDLE)malloc(sizeof(HANDLE)*(cp->NumberOfCommands+1));
- if(!cp->ProcessEvents)
- {
+ cp->ProcessEvents =
+ (PHANDLE)malloc(sizeof(HANDLE) * (cp->NumberOfCommands + 1));
+ if (!cp->ProcessEvents) {
return 0;
- }
- ZeroMemory(cp->ProcessEvents, sizeof(HANDLE) * (cp->NumberOfCommands+1));
+ }
+ ZeroMemory(cp->ProcessEvents, sizeof(HANDLE) * (cp->NumberOfCommands + 1));
cp->ProcessEvents[0] = cp->Full;
- cp->ProcessEventsLength = cp->NumberOfCommands+1;
+ cp->ProcessEventsLength = cp->NumberOfCommands + 1;
/* Allocate space to save the real working directory of this process. */
- if(cp->WorkingDirectory)
- {
+ if (cp->WorkingDirectory) {
cp->RealWorkingDirectoryLength = GetCurrentDirectoryW(0, 0);
- if(cp->RealWorkingDirectoryLength > 0)
- {
- cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t));
- if(!cp->RealWorkingDirectory)
- {
+ if (cp->RealWorkingDirectoryLength > 0) {
+ cp->RealWorkingDirectory =
+ malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t));
+ if (!cp->RealWorkingDirectory) {
return 0;
- }
}
}
+ }
{
- int i;
- for (i=0; i < 3; ++i)
- {
- cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
+ int i;
+ for (i = 0; i < 3; ++i) {
+ cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
}
}
@@ -1770,28 +1611,21 @@ static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn)
DWORD flags;
/* Check whether the handle is valid for this process. */
- if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags))
- {
+ if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags)) {
/* Use the handle as-is if it is already inherited. */
- if (flags & HANDLE_FLAG_INHERIT)
- {
+ if (flags & HANDLE_FLAG_INHERIT) {
*out = in;
return ERROR_SUCCESS;
- }
+ }
/* Create an inherited copy of this handle. */
- if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out,
- 0, TRUE, DUPLICATE_SAME_ACCESS))
- {
+ if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out, 0,
+ TRUE, DUPLICATE_SAME_ACCESS)) {
return ERROR_SUCCESS;
- }
- else
- {
+ } else {
return GetLastError();
- }
}
- else
- {
+ } else {
/* The given handle is not valid for this process. Some child
processes may break if they do not have a valid standard handle,
so open NUL to give to the child. */
@@ -1799,13 +1633,12 @@ static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn)
ZeroMemory(&sa, sizeof(sa));
sa.nLength = (DWORD)sizeof(sa);
sa.bInheritHandle = 1;
- *out = CreateFileW(L"NUL",
- (isStdIn ? GENERIC_READ :
- (GENERIC_WRITE | FILE_READ_ATTRIBUTES)),
- FILE_SHARE_READ|FILE_SHARE_WRITE,
- &sa, OPEN_EXISTING, 0, 0);
+ *out = CreateFileW(
+ L"NUL",
+ (isStdIn ? GENERIC_READ : (GENERIC_WRITE | FILE_READ_ATTRIBUTES)),
+ FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0);
return (*out != INVALID_HANDLE_VALUE) ? ERROR_SUCCESS : GetLastError();
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1816,54 +1649,49 @@ DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
DWORD error = ERROR_SUCCESS;
/* Check if we are currently exiting. */
- if (!kwsysTryEnterCreateProcessSection())
- {
+ if (!kwsysTryEnterCreateProcessSection()) {
/* The Ctrl handler is currently working on exiting our process. Rather
than return an error code, which could cause incorrect conclusions to be
reached by the caller, we simply hang. (For example, a CMake try_run
configure step might cause the project to configure wrong.) */
Sleep(INFINITE);
- }
+ }
/* Create the child in a suspended state so we can wait until all
children have been created before running any one. */
creationFlags = CREATE_SUSPENDED;
- if (cp->CreateProcessGroup)
- {
+ if (cp->CreateProcessGroup) {
creationFlags |= CREATE_NEW_PROCESS_GROUP;
- }
+ }
/* Create inherited copies of the handles. */
(error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdInput,
- si->hStdInput, 1)) ||
- (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdOutput,
- si->hStdOutput, 0)) ||
- (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdError,
- si->hStdError, 0)) ||
- /* Create the process. */
- (!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, creationFlags, 0,
- 0, &si->StartupInfo, &cp->ProcessInformation[index]) &&
- (error = GetLastError()));
+ si->hStdInput, 1)) ||
+ (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdOutput,
+ si->hStdOutput, 0)) ||
+ (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdError,
+ si->hStdError, 0)) ||
+ /* Create the process. */
+ (!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, creationFlags, 0, 0,
+ &si->StartupInfo, &cp->ProcessInformation[index]) &&
+ (error = GetLastError()));
/* Close the inherited copies of the handles. */
- if (si->StartupInfo.hStdInput != si->hStdInput)
- {
+ if (si->StartupInfo.hStdInput != si->hStdInput) {
kwsysProcessCleanupHandle(&si->StartupInfo.hStdInput);
- }
- if (si->StartupInfo.hStdOutput != si->hStdOutput)
- {
+ }
+ if (si->StartupInfo.hStdOutput != si->hStdOutput) {
kwsysProcessCleanupHandle(&si->StartupInfo.hStdOutput);
- }
- if (si->StartupInfo.hStdError != si->hStdError)
- {
+ }
+ if (si->StartupInfo.hStdError != si->hStdError) {
kwsysProcessCleanupHandle(&si->StartupInfo.hStdError);
- }
+ }
/* Add the process to the global list of processes. */
if (!error &&
!kwsysProcessesAdd(cp->ProcessInformation[index].hProcess,
- cp->ProcessInformation[index].dwProcessId, cp->CreateProcessGroup))
- {
+ cp->ProcessInformation[index].dwProcessId,
+ cp->CreateProcessGroup)) {
/* This failed for some reason. Kill the suspended process. */
TerminateProcess(cp->ProcessInformation[index].hProcess, 1);
/* And clean up... */
@@ -1871,7 +1699,7 @@ DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
kwsysProcessCleanupHandle(&cp->ProcessInformation[index].hThread);
strcpy(cp->ErrorMessage, "kwsysProcessesAdd function failed");
error = ERROR_NOT_ENOUGH_MEMORY; /* Most likely reason. */
- }
+ }
/* If the console Ctrl handler is waiting for us, this will release it... */
kwsysLeaveCreateProcessSection();
@@ -1885,13 +1713,11 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
int index;
/* Find the process index for the termination event. */
- for(index=0; index < cp->NumberOfCommands; ++index)
- {
- if(cp->ProcessInformation[index].hProcess == cp->ProcessEvents[event])
- {
+ for (index = 0; index < cp->NumberOfCommands; ++index) {
+ if (cp->ProcessInformation[index].hProcess == cp->ProcessEvents[event]) {
break;
- }
}
+ }
/* Check the exit code of the process. */
GetExitCodeProcess(cp->ProcessInformation[index].hProcess,
@@ -1905,20 +1731,17 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
/* Remove the process from the available events. */
cp->ProcessEventsLength -= 1;
- for(i=event; i < cp->ProcessEventsLength; ++i)
- {
- cp->ProcessEvents[i] = cp->ProcessEvents[i+1];
- }
+ for (i = event; i < cp->ProcessEventsLength; ++i) {
+ cp->ProcessEvents[i] = cp->ProcessEvents[i + 1];
+ }
/* Check if all processes have terminated. */
- if(cp->ProcessEventsLength == 1)
- {
+ if (cp->ProcessEventsLength == 1) {
cp->Terminated = 1;
/* Close our copies of the pipe write handles so the pipe threads
can detect end-of-data. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
/* TODO: If the child created its own child (our grandchild)
which inherited a copy of the pipe write-end then the pipe
may not close and we will still need the waker write pipe.
@@ -1929,8 +1752,8 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
read on posix. */
KWSYSPE_DEBUG((stderr, "closing wakeup write %d\n", i));
kwsysProcessCleanupHandle(&cp->Pipe[i].Write);
- }
}
+ }
}
/*--------------------------------------------------------------------------*/
@@ -1939,24 +1762,22 @@ DWORD kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name)
HANDLE fout;
wchar_t* wname;
DWORD error;
- if(!name)
- {
+ if (!name) {
return ERROR_INVALID_PARAMETER;
- }
+ }
/* Close the existing handle. */
kwsysProcessCleanupHandle(phandle);
/* Create a handle to write a file for the pipe. */
wname = kwsysEncoding_DupToWide(name);
- fout = CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0,
- CREATE_ALWAYS, 0, 0);
+ fout =
+ CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
error = GetLastError();
free(wname);
- if(fout == INVALID_HANDLE_VALUE)
- {
+ if (fout == INVALID_HANDLE_VALUE) {
return error;
- }
+ }
/* Assign the replacement handle. */
*phandle = fout;
@@ -1986,14 +1807,13 @@ void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle)
/* Close the given handle if it is open. Reset its value to 0. */
void kwsysProcessCleanupHandle(PHANDLE h)
{
- if(h && *h && *h != INVALID_HANDLE_VALUE &&
- *h != GetStdHandle(STD_INPUT_HANDLE) &&
- *h != GetStdHandle(STD_OUTPUT_HANDLE) &&
- *h != GetStdHandle(STD_ERROR_HANDLE))
- {
+ if (h && *h && *h != INVALID_HANDLE_VALUE &&
+ *h != GetStdHandle(STD_INPUT_HANDLE) &&
+ *h != GetStdHandle(STD_OUTPUT_HANDLE) &&
+ *h != GetStdHandle(STD_ERROR_HANDLE)) {
CloseHandle(*h);
*h = INVALID_HANDLE_VALUE;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2003,35 +1823,31 @@ void kwsysProcessCleanup(kwsysProcess* cp, DWORD error)
{
int i;
/* If this is an error case, report the error. */
- if(error)
- {
+ if (error) {
/* Construct an error message if one has not been provided already. */
- if(cp->ErrorMessage[0] == 0)
- {
+ if (cp->ErrorMessage[0] == 0) {
/* Format the error message. */
wchar_t err_msg[KWSYSPE_PIPE_BUFFER_SIZE];
- DWORD length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS, 0, error,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- err_msg, KWSYSPE_PIPE_BUFFER_SIZE, 0);
- if(length < 1)
- {
+ DWORD length = FormatMessageW(
+ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_msg,
+ KWSYSPE_PIPE_BUFFER_SIZE, 0);
+ if (length < 1) {
/* FormatMessage failed. Use a default message. */
_snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE,
"Process execution failed with error 0x%X. "
"FormatMessage failed with error 0x%X",
error, GetLastError());
- }
- if(!WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage,
- KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL))
- {
+ }
+ if (!WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage,
+ KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL)) {
/* WideCharToMultiByte failed. Use a default message. */
_snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE,
"Process execution failed with error 0x%X. "
"WideCharToMultiByte failed with error 0x%X",
error, GetLastError());
- }
}
+ }
/* Remove trailing period and newline, if any. */
kwsysProcessCleanErrorMessage(cp);
@@ -2040,60 +1856,50 @@ void kwsysProcessCleanup(kwsysProcess* cp, DWORD error)
cp->State = kwsysProcess_State_Error;
/* Cleanup any processes already started in a suspended state. */
- if(cp->ProcessInformation)
- {
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
- if(cp->ProcessInformation[i].hProcess)
- {
+ if (cp->ProcessInformation) {
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
+ if (cp->ProcessInformation[i].hProcess) {
TerminateProcess(cp->ProcessInformation[i].hProcess, 255);
WaitForSingleObject(cp->ProcessInformation[i].hProcess, INFINITE);
- }
}
- for(i=0; i < cp->NumberOfCommands; ++i)
- {
+ }
+ for (i = 0; i < cp->NumberOfCommands; ++i) {
/* Remove from global list of processes and close handles. */
kwsysProcessesRemove(cp->ProcessInformation[i].hProcess);
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess);
- }
}
+ }
/* Restore the working directory. */
- if(cp->RealWorkingDirectory)
- {
+ if (cp->RealWorkingDirectory) {
SetCurrentDirectoryW(cp->RealWorkingDirectory);
- }
}
+ }
/* Free memory. */
- if(cp->ProcessInformation)
- {
+ if (cp->ProcessInformation) {
free(cp->ProcessInformation);
cp->ProcessInformation = 0;
- }
- if(cp->ProcessEvents)
- {
+ }
+ if (cp->ProcessEvents) {
free(cp->ProcessEvents);
cp->ProcessEvents = 0;
- }
- if(cp->RealWorkingDirectory)
- {
+ }
+ if (cp->RealWorkingDirectory) {
free(cp->RealWorkingDirectory);
cp->RealWorkingDirectory = 0;
- }
+ }
/* Close each pipe. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
kwsysProcessCleanupHandle(&cp->Pipe[i].Write);
kwsysProcessCleanupHandle(&cp->Pipe[i].Read);
cp->Pipe[i].Closed = 0;
- }
- for(i=0; i < 3; ++i)
- {
+ }
+ for (i = 0; i < 3; ++i) {
kwsysProcessCleanupHandle(&cp->PipeChildStd[i]);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2101,20 +1907,17 @@ void kwsysProcessCleanErrorMessage(kwsysProcess* cp)
{
/* Remove trailing period and newline, if any. */
size_t length = strlen(cp->ErrorMessage);
- if(cp->ErrorMessage[length-1] == '\n')
- {
- cp->ErrorMessage[length-1] = 0;
+ if (cp->ErrorMessage[length - 1] == '\n') {
+ cp->ErrorMessage[length - 1] = 0;
--length;
- if(length > 0 && cp->ErrorMessage[length-1] == '\r')
- {
- cp->ErrorMessage[length-1] = 0;
+ if (length > 0 && cp->ErrorMessage[length - 1] == '\r') {
+ cp->ErrorMessage[length - 1] = 0;
--length;
- }
- }
- if(length > 0 && cp->ErrorMessage[length-1] == '.')
- {
- cp->ErrorMessage[length-1] = 0;
}
+ }
+ if (length > 0 && cp->ErrorMessage[length - 1] == '.') {
+ cp->ErrorMessage[length - 1] = 0;
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2125,29 +1928,27 @@ int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
{
/* The first time this is called, we need to calculate the time at
which the child will timeout. */
- if(cp->Timeout && cp->TimeoutTime.QuadPart < 0)
- {
+ if (cp->Timeout && cp->TimeoutTime.QuadPart < 0) {
kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
- }
+ }
/* Start with process timeout. */
*timeoutTime = cp->TimeoutTime;
/* Check if the user timeout is earlier. */
- if(userTimeout)
- {
+ if (userTimeout) {
kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
- kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
- kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
- userTimeoutLength);
- if(timeoutTime->QuadPart < 0 ||
- kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
- {
+ kwsysProcessTime userTimeoutLength =
+ kwsysProcessTimeFromDouble(*userTimeout);
+ kwsysProcessTime userTimeoutTime =
+ kwsysProcessTimeAdd(currentTime, userTimeoutLength);
+ if (timeoutTime->QuadPart < 0 ||
+ kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) {
*timeoutTime = userTimeoutTime;
return 1;
- }
}
+ }
return 0;
}
@@ -2158,34 +1959,27 @@ int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
double* userTimeout,
kwsysProcessTime* timeoutLength)
{
- if(timeoutTime->QuadPart < 0)
- {
+ if (timeoutTime->QuadPart < 0) {
/* No timeout time has been requested. */
return 0;
- }
- else
- {
+ } else {
/* Calculate the remaining time. */
kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
*timeoutLength = kwsysProcessTimeSubtract(*timeoutTime, currentTime);
- if(timeoutLength->QuadPart < 0 && userTimeout && *userTimeout <= 0)
- {
+ if (timeoutLength->QuadPart < 0 && userTimeout && *userTimeout <= 0) {
/* Caller has explicitly requested a zero timeout. */
timeoutLength->QuadPart = 0;
- }
+ }
- if(timeoutLength->QuadPart < 0)
- {
+ if (timeoutLength->QuadPart < 0) {
/* Timeout has already expired. */
return 1;
- }
- else
- {
+ } else {
/* There is some time left. */
return 0;
- }
}
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2215,7 +2009,7 @@ double kwsysProcessTimeToDouble(kwsysProcessTime t)
kwsysProcessTime kwsysProcessTimeFromDouble(double d)
{
kwsysProcessTime t;
- t.QuadPart = (LONGLONG)(d*10000000);
+ t.QuadPart = (LONGLONG)(d * 10000000);
return t;
}
@@ -2226,7 +2020,8 @@ int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
}
/*--------------------------------------------------------------------------*/
-kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
+kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+ kwsysProcessTime in2)
{
kwsysProcessTime out;
out.QuadPart = in1.QuadPart + in2.QuadPart;
@@ -2234,7 +2029,8 @@ kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
}
/*--------------------------------------------------------------------------*/
-kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
+kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+ kwsysProcessTime in2)
{
kwsysProcessTime out;
out.QuadPart = in1.QuadPart - in2.QuadPart;
@@ -2242,71 +2038,93 @@ kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime
}
/*--------------------------------------------------------------------------*/
-#define KWSYSPE_CASE(type, str) \
- cp->ExitException = kwsysProcess_Exception_##type; \
+#define KWSYSPE_CASE(type, str) \
+ cp->ExitException = kwsysProcess_Exception_##type; \
strcpy(cp->ExitExceptionString, str)
static void kwsysProcessSetExitException(kwsysProcess* cp, int code)
{
- switch (code)
- {
+ switch (code) {
case STATUS_CONTROL_C_EXIT:
- KWSYSPE_CASE(Interrupt, "User interrupt"); break;
+ KWSYSPE_CASE(Interrupt, "User interrupt");
+ break;
case STATUS_FLOAT_DENORMAL_OPERAND:
- KWSYSPE_CASE(Numerical, "Floating-point exception (denormal operand)"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point exception (denormal operand)");
+ break;
case STATUS_FLOAT_DIVIDE_BY_ZERO:
- KWSYSPE_CASE(Numerical, "Divide-by-zero"); break;
+ KWSYSPE_CASE(Numerical, "Divide-by-zero");
+ break;
case STATUS_FLOAT_INEXACT_RESULT:
- KWSYSPE_CASE(Numerical, "Floating-point exception (inexact result)"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point exception (inexact result)");
+ break;
case STATUS_FLOAT_INVALID_OPERATION:
- KWSYSPE_CASE(Numerical, "Invalid floating-point operation"); break;
+ KWSYSPE_CASE(Numerical, "Invalid floating-point operation");
+ break;
case STATUS_FLOAT_OVERFLOW:
- KWSYSPE_CASE(Numerical, "Floating-point overflow"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point overflow");
+ break;
case STATUS_FLOAT_STACK_CHECK:
- KWSYSPE_CASE(Numerical, "Floating-point stack check failed"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point stack check failed");
+ break;
case STATUS_FLOAT_UNDERFLOW:
- KWSYSPE_CASE(Numerical, "Floating-point underflow"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point underflow");
+ break;
#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
case STATUS_FLOAT_MULTIPLE_FAULTS:
- KWSYSPE_CASE(Numerical, "Floating-point exception (multiple faults)"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point exception (multiple faults)");
+ break;
#endif
#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
case STATUS_FLOAT_MULTIPLE_TRAPS:
- KWSYSPE_CASE(Numerical, "Floating-point exception (multiple traps)"); break;
+ KWSYSPE_CASE(Numerical, "Floating-point exception (multiple traps)");
+ break;
#endif
case STATUS_INTEGER_DIVIDE_BY_ZERO:
- KWSYSPE_CASE(Numerical, "Integer divide-by-zero"); break;
+ KWSYSPE_CASE(Numerical, "Integer divide-by-zero");
+ break;
case STATUS_INTEGER_OVERFLOW:
- KWSYSPE_CASE(Numerical, "Integer overflow"); break;
+ KWSYSPE_CASE(Numerical, "Integer overflow");
+ break;
case STATUS_DATATYPE_MISALIGNMENT:
- KWSYSPE_CASE(Fault, "Datatype misalignment"); break;
+ KWSYSPE_CASE(Fault, "Datatype misalignment");
+ break;
case STATUS_ACCESS_VIOLATION:
- KWSYSPE_CASE(Fault, "Access violation"); break;
+ KWSYSPE_CASE(Fault, "Access violation");
+ break;
case STATUS_IN_PAGE_ERROR:
- KWSYSPE_CASE(Fault, "In-page error"); break;
+ KWSYSPE_CASE(Fault, "In-page error");
+ break;
case STATUS_INVALID_HANDLE:
- KWSYSPE_CASE(Fault, "Invalid hanlde"); break;
+ KWSYSPE_CASE(Fault, "Invalid hanlde");
+ break;
case STATUS_NONCONTINUABLE_EXCEPTION:
- KWSYSPE_CASE(Fault, "Noncontinuable exception"); break;
+ KWSYSPE_CASE(Fault, "Noncontinuable exception");
+ break;
case STATUS_INVALID_DISPOSITION:
- KWSYSPE_CASE(Fault, "Invalid disposition"); break;
+ KWSYSPE_CASE(Fault, "Invalid disposition");
+ break;
case STATUS_ARRAY_BOUNDS_EXCEEDED:
- KWSYSPE_CASE(Fault, "Array bounds exceeded"); break;
+ KWSYSPE_CASE(Fault, "Array bounds exceeded");
+ break;
case STATUS_STACK_OVERFLOW:
- KWSYSPE_CASE(Fault, "Stack overflow"); break;
+ KWSYSPE_CASE(Fault, "Stack overflow");
+ break;
case STATUS_ILLEGAL_INSTRUCTION:
- KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
+ KWSYSPE_CASE(Illegal, "Illegal instruction");
+ break;
case STATUS_PRIVILEGED_INSTRUCTION:
- KWSYSPE_CASE(Illegal, "Privileged instruction"); break;
+ KWSYSPE_CASE(Illegal, "Privileged instruction");
+ break;
case STATUS_NO_MEMORY:
default:
cp->ExitException = kwsysProcess_Exception_Other;
- _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE, "Exit code 0x%x\n", code);
+ _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE,
+ "Exit code 0x%x\n", code);
break;
- }
+ }
}
#undef KWSYSPE_CASE
@@ -2338,21 +2156,21 @@ typedef struct _SYSTEM_PROCESS_INFORMATION SYSTEM_PROCESS_INFORMATION;
typedef SYSTEM_PROCESS_INFORMATION* PSYSTEM_PROCESS_INFORMATION;
struct _SYSTEM_PROCESS_INFORMATION
{
- ULONG NextEntryDelta;
- ULONG ThreadCount;
- ULONG Reserved1[6];
- LARGE_INTEGER CreateTime;
- LARGE_INTEGER UserTime;
- LARGE_INTEGER KernelTime;
+ ULONG NextEntryDelta;
+ ULONG ThreadCount;
+ ULONG Reserved1[6];
+ LARGE_INTEGER CreateTime;
+ LARGE_INTEGER UserTime;
+ LARGE_INTEGER KernelTime;
UNICODE_STRING ProcessName;
- KPRIORITY BasePriority;
- ULONG ProcessId;
- ULONG InheritedFromProcessId;
+ KPRIORITY BasePriority;
+ ULONG ProcessId;
+ ULONG InheritedFromProcessId;
};
/*--------------------------------------------------------------------------*/
/* Toolhelp32 API definitions. */
-#define TH32CS_SNAPPROCESS 0x00000002
+#define TH32CS_SNAPPROCESS 0x00000002
#if defined(_WIN64)
typedef unsigned __int64 ProcessULONG_PTR;
#else
@@ -2369,19 +2187,18 @@ struct tagPROCESSENTRY32
DWORD th32ModuleID;
DWORD cntThreads;
DWORD th32ParentProcessID;
- LONG pcPriClassBase;
+ LONG pcPriClassBase;
DWORD dwFlags;
char szExeFile[MAX_PATH];
};
/*--------------------------------------------------------------------------*/
/* Windows API function types. */
-typedef HANDLE (WINAPI* CreateToolhelp32SnapshotType)(DWORD, DWORD);
-typedef BOOL (WINAPI* Process32FirstType)(HANDLE, LPPROCESSENTRY32);
-typedef BOOL (WINAPI* Process32NextType)(HANDLE, LPPROCESSENTRY32);
-typedef NTSTATUS (WINAPI* ZwQuerySystemInformationType)(ULONG, PVOID,
- ULONG, PULONG);
-
+typedef HANDLE(WINAPI* CreateToolhelp32SnapshotType)(DWORD, DWORD);
+typedef BOOL(WINAPI* Process32FirstType)(HANDLE, LPPROCESSENTRY32);
+typedef BOOL(WINAPI* Process32NextType)(HANDLE, LPPROCESSENTRY32);
+typedef NTSTATUS(WINAPI* ZwQuerySystemInformationType)(ULONG, PVOID, ULONG,
+ PULONG);
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__New_NT4(kwsysProcess_List* self);
@@ -2423,97 +2240,88 @@ static kwsysProcess_List* kwsysProcess_List_New(void)
kwsysProcess_List* self;
/* Allocate and initialize the list object. */
- if(!(self = (kwsysProcess_List*)malloc(sizeof(kwsysProcess_List))))
- {
+ if (!(self = (kwsysProcess_List*)malloc(sizeof(kwsysProcess_List)))) {
return 0;
- }
+ }
memset(self, 0, sizeof(*self));
/* Select an implementation. */
ZeroMemory(&osv, sizeof(osv));
osv.dwOSVersionInfoSize = sizeof(osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-# pragma warning (disable:1478)
-# else
-# pragma warning (disable:4996)
-# endif
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
#endif
GetVersionEx(&osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
#endif
- self->NT4 = (osv.dwPlatformId == VER_PLATFORM_WIN32_NT &&
- osv.dwMajorVersion < 5)? 1:0;
+ self->NT4 =
+ (osv.dwPlatformId == VER_PLATFORM_WIN32_NT && osv.dwMajorVersion < 5) ? 1
+ : 0;
/* Initialize the selected implementation. */
- if(!(self->NT4?
- kwsysProcess_List__New_NT4(self) :
- kwsysProcess_List__New_Snapshot(self)))
- {
+ if (!(self->NT4 ? kwsysProcess_List__New_NT4(self)
+ : kwsysProcess_List__New_Snapshot(self))) {
kwsysProcess_List_Delete(self);
return 0;
- }
+ }
/* Update to the current set of processes. */
- if(!kwsysProcess_List_Update(self))
- {
+ if (!kwsysProcess_List_Update(self)) {
kwsysProcess_List_Delete(self);
return 0;
- }
+ }
return self;
}
/*--------------------------------------------------------------------------*/
static void kwsysProcess_List_Delete(kwsysProcess_List* self)
{
- if(self)
- {
- if(self->NT4)
- {
+ if (self) {
+ if (self->NT4) {
kwsysProcess_List__Delete_NT4(self);
- }
- else
- {
+ } else {
kwsysProcess_List__Delete_Snapshot(self);
- }
- free(self);
}
+ free(self);
+ }
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List_Update(kwsysProcess_List* self)
{
- return self? (self->NT4?
- kwsysProcess_List__Update_NT4(self) :
- kwsysProcess_List__Update_Snapshot(self)) : 0;
+ return self ? (self->NT4 ? kwsysProcess_List__Update_NT4(self)
+ : kwsysProcess_List__Update_Snapshot(self))
+ : 0;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List_GetCurrentProcessId(kwsysProcess_List* self)
{
- return self? (self->NT4?
- kwsysProcess_List__GetProcessId_NT4(self) :
- kwsysProcess_List__GetProcessId_Snapshot(self)) : -1;
-
+ return self ? (self->NT4 ? kwsysProcess_List__GetProcessId_NT4(self)
+ : kwsysProcess_List__GetProcessId_Snapshot(self))
+ : -1;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List_GetCurrentParentId(kwsysProcess_List* self)
{
- return self? (self->NT4?
- kwsysProcess_List__GetParentId_NT4(self) :
- kwsysProcess_List__GetParentId_Snapshot(self)) : -1;
-
+ return self ? (self->NT4 ? kwsysProcess_List__GetParentId_NT4(self)
+ : kwsysProcess_List__GetParentId_Snapshot(self))
+ : -1;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List_NextProcess(kwsysProcess_List* self)
{
- return (self? (self->NT4?
- kwsysProcess_List__Next_NT4(self) :
- kwsysProcess_List__Next_Snapshot(self)) : 0);
+ return (self ? (self->NT4 ? kwsysProcess_List__Next_NT4(self)
+ : kwsysProcess_List__Next_Snapshot(self))
+ : 0);
}
/*--------------------------------------------------------------------------*/
@@ -2524,100 +2332,85 @@ static int kwsysProcess_List__New_NT4(kwsysProcess_List* self)
reference count to the module so we do not need to close the
handle. */
HMODULE hNT = GetModuleHandleW(L"ntdll.dll");
- if(hNT)
- {
+ if (hNT) {
/* Get pointers to the needed API functions. */
self->P_ZwQuerySystemInformation =
- ((ZwQuerySystemInformationType)
- GetProcAddress(hNT, "ZwQuerySystemInformation"));
- }
- if(!self->P_ZwQuerySystemInformation)
- {
+ ((ZwQuerySystemInformationType)GetProcAddress(
+ hNT, "ZwQuerySystemInformation"));
+ }
+ if (!self->P_ZwQuerySystemInformation) {
return 0;
- }
+ }
/* Allocate an initial process information buffer. */
self->BufferSize = 32768;
self->Buffer = (char*)malloc(self->BufferSize);
- return self->Buffer? 1:0;
+ return self->Buffer ? 1 : 0;
}
/*--------------------------------------------------------------------------*/
static void kwsysProcess_List__Delete_NT4(kwsysProcess_List* self)
{
/* Free the process information buffer. */
- if(self->Buffer)
- {
+ if (self->Buffer) {
free(self->Buffer);
- }
+ }
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__Update_NT4(kwsysProcess_List* self)
{
self->CurrentInfo = 0;
- for(;;)
- {
+ for (;;) {
/* Query number 5 is for system process list. */
NTSTATUS status =
self->P_ZwQuerySystemInformation(5, self->Buffer, self->BufferSize, 0);
- if(status == STATUS_INFO_LENGTH_MISMATCH)
- {
+ if (status == STATUS_INFO_LENGTH_MISMATCH) {
/* The query requires a bigger buffer. */
int newBufferSize = self->BufferSize * 2;
char* newBuffer = (char*)malloc(newBufferSize);
- if(newBuffer)
- {
+ if (newBuffer) {
free(self->Buffer);
self->Buffer = newBuffer;
self->BufferSize = newBufferSize;
- }
- else
- {
+ } else {
return 0;
- }
}
- else if(status >= 0)
- {
+ } else if (status >= 0) {
/* The query succeeded. Initialize traversal of the process list. */
self->CurrentInfo = (PSYSTEM_PROCESS_INFORMATION)self->Buffer;
return 1;
- }
- else
- {
+ } else {
/* The query failed. */
return 0;
- }
}
+ }
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__Next_NT4(kwsysProcess_List* self)
{
- if(self->CurrentInfo)
- {
- if(self->CurrentInfo->NextEntryDelta > 0)
- {
- self->CurrentInfo = ((PSYSTEM_PROCESS_INFORMATION)
- ((char*)self->CurrentInfo +
- self->CurrentInfo->NextEntryDelta));
+ if (self->CurrentInfo) {
+ if (self->CurrentInfo->NextEntryDelta > 0) {
+ self->CurrentInfo = ((PSYSTEM_PROCESS_INFORMATION)(
+ (char*)self->CurrentInfo + self->CurrentInfo->NextEntryDelta));
return 1;
- }
- self->CurrentInfo = 0;
}
+ self->CurrentInfo = 0;
+ }
return 0;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__GetProcessId_NT4(kwsysProcess_List* self)
{
- return self->CurrentInfo? self->CurrentInfo->ProcessId : -1;
+ return self->CurrentInfo ? self->CurrentInfo->ProcessId : -1;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__GetParentId_NT4(kwsysProcess_List* self)
{
- return self->CurrentInfo? self->CurrentInfo->InheritedFromProcessId : -1;
+ return self->CurrentInfo ? self->CurrentInfo->InheritedFromProcessId : -1;
}
/*--------------------------------------------------------------------------*/
@@ -2628,92 +2421,83 @@ static int kwsysProcess_List__New_Snapshot(kwsysProcess_List* self)
reference count to the module so we do not need to close the
handle. */
HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");
- if(hKernel)
- {
+ if (hKernel) {
self->P_CreateToolhelp32Snapshot =
- ((CreateToolhelp32SnapshotType)
- GetProcAddress(hKernel, "CreateToolhelp32Snapshot"));
+ ((CreateToolhelp32SnapshotType)GetProcAddress(
+ hKernel, "CreateToolhelp32Snapshot"));
self->P_Process32First =
- ((Process32FirstType)
- GetProcAddress(hKernel, "Process32First"));
+ ((Process32FirstType)GetProcAddress(hKernel, "Process32First"));
self->P_Process32Next =
- ((Process32NextType)
- GetProcAddress(hKernel, "Process32Next"));
- }
- return (self->P_CreateToolhelp32Snapshot &&
- self->P_Process32First &&
- self->P_Process32Next)? 1:0;
+ ((Process32NextType)GetProcAddress(hKernel, "Process32Next"));
+ }
+ return (self->P_CreateToolhelp32Snapshot && self->P_Process32First &&
+ self->P_Process32Next)
+ ? 1
+ : 0;
}
/*--------------------------------------------------------------------------*/
static void kwsysProcess_List__Delete_Snapshot(kwsysProcess_List* self)
{
- if(self->Snapshot)
- {
+ if (self->Snapshot) {
CloseHandle(self->Snapshot);
- }
+ }
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__Update_Snapshot(kwsysProcess_List* self)
{
- if(self->Snapshot)
- {
+ if (self->Snapshot) {
CloseHandle(self->Snapshot);
- }
- if(!(self->Snapshot =
- self->P_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)))
- {
+ }
+ if (!(self->Snapshot =
+ self->P_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0))) {
return 0;
- }
+ }
ZeroMemory(&self->CurrentEntry, sizeof(self->CurrentEntry));
self->CurrentEntry.dwSize = sizeof(self->CurrentEntry);
- if(!self->P_Process32First(self->Snapshot, &self->CurrentEntry))
- {
+ if (!self->P_Process32First(self->Snapshot, &self->CurrentEntry)) {
CloseHandle(self->Snapshot);
self->Snapshot = 0;
return 0;
- }
+ }
return 1;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__Next_Snapshot(kwsysProcess_List* self)
{
- if(self->Snapshot)
- {
- if(self->P_Process32Next(self->Snapshot, &self->CurrentEntry))
- {
+ if (self->Snapshot) {
+ if (self->P_Process32Next(self->Snapshot, &self->CurrentEntry)) {
return 1;
- }
+ }
CloseHandle(self->Snapshot);
self->Snapshot = 0;
- }
+ }
return 0;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__GetProcessId_Snapshot(kwsysProcess_List* self)
{
- return self->Snapshot? self->CurrentEntry.th32ProcessID : -1;
+ return self->Snapshot ? self->CurrentEntry.th32ProcessID : -1;
}
/*--------------------------------------------------------------------------*/
static int kwsysProcess_List__GetParentId_Snapshot(kwsysProcess_List* self)
{
- return self->Snapshot? self->CurrentEntry.th32ParentProcessID : -1;
+ return self->Snapshot ? self->CurrentEntry.th32ParentProcessID : -1;
}
/*--------------------------------------------------------------------------*/
static void kwsysProcessKill(DWORD pid)
{
HANDLE h = OpenProcess(PROCESS_TERMINATE, 0, pid);
- if(h)
- {
+ if (h) {
TerminateProcess(h, 255);
WaitForSingleObject(h, INFINITE);
CloseHandle(h);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2721,18 +2505,15 @@ static void kwsysProcessKillTree(int pid)
{
kwsysProcess_List* plist = kwsysProcess_List_New();
kwsysProcessKill(pid);
- if(plist)
- {
- do
- {
- if(kwsysProcess_List_GetCurrentParentId(plist) == pid)
- {
+ if (plist) {
+ do {
+ if (kwsysProcess_List_GetCurrentParentId(plist) == pid) {
int ppid = kwsysProcess_List_GetCurrentProcessId(plist);
kwsysProcessKillTree(ppid);
- }
- } while(kwsysProcess_List_NextProcess(plist));
+ }
+ } while (kwsysProcess_List_NextProcess(plist));
kwsysProcess_List_Delete(plist);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2741,16 +2522,14 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
int i;
/* If data were just reported data, release the pipe's thread. */
- if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT)
- {
+ if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) {
KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex));
ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
- }
+ }
/* Wakeup all reading threads that are not on closed pipes. */
- for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
- {
+ for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
/* The wakeup threads will write one byte to the pipe write ends.
If there are no data in the pipe then this is enough to wakeup
the reading threads. If there are already data in the pipe
@@ -2762,16 +2541,14 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
thread to call WriteFile. If it blocks, that is okay because
it will unblock when we close the read end and break the pipe
below. */
- if(cp->Pipe[i].Read)
- {
+ if (cp->Pipe[i].Read) {
KWSYSPE_DEBUG((stderr, "releasing waker %d\n", i));
ReleaseSemaphore(cp->Pipe[i].Waker.Go, 1, 0);
- }
}
+ }
/* Tell pipe threads to reset until we run another process. */
- while(cp->PipesLeft > 0)
- {
+ while (cp->PipesLeft > 0) {
/* The waking threads will cause all reading threads to report.
Wait for the next one and save its index. */
KWSYSPE_DEBUG((stderr, "waiting for reader\n"));
@@ -2788,7 +2565,7 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
/* Tell the reading thread we are done with the data. It will
reset immediately because the pipe is closed. */
ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2827,18 +2604,16 @@ static kwsysProcessInstances kwsysProcesses;
static int kwsysProcessesInitialize(void)
{
/* Initialize everything if not done already. */
- if(!kwsysProcesses.Initialized)
- {
+ if (!kwsysProcesses.Initialized) {
InitializeCriticalSection(&kwsysProcesses.Lock);
/* Set up console ctrl handler. */
- if(!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE))
- {
+ if (!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE)) {
return 0;
- }
+ }
kwsysProcesses.Initialized = 1;
- }
+ }
return 1;
}
@@ -2853,15 +2628,12 @@ static int kwsysTryEnterCreateProcessSection(void)
handler are mutually exclusive. */
EnterCriticalSection(&kwsysProcesses.Lock);
/* Indicate to the caller if they can create a process. */
- if(kwsysProcesses.Exiting)
- {
+ if (kwsysProcesses.Exiting) {
LeaveCriticalSection(&kwsysProcesses.Lock);
return 0;
- }
- else
- {
+ } else {
return 1;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -2880,41 +2652,35 @@ static void kwsysLeaveCreateProcessSection(void)
static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid,
int newProcessGroup)
{
- if(!kwsysProcessesInitialize() || !hProcess ||
- hProcess == INVALID_HANDLE_VALUE)
- {
+ if (!kwsysProcessesInitialize() || !hProcess ||
+ hProcess == INVALID_HANDLE_VALUE) {
return 0;
- }
+ }
/* Enter the critical section. */
EnterCriticalSection(&kwsysProcesses.Lock);
/* Make sure there is enough space for the new process handle. */
- if(kwsysProcesses.Count == kwsysProcesses.Size)
- {
+ if (kwsysProcesses.Count == kwsysProcesses.Size) {
size_t newSize;
- kwsysProcessInstance *newArray;
+ kwsysProcessInstance* newArray;
/* Start with enough space for a small number of process handles
and double the size each time more is needed. */
- newSize = kwsysProcesses.Size? kwsysProcesses.Size*2 : 4;
+ newSize = kwsysProcesses.Size ? kwsysProcesses.Size * 2 : 4;
/* Try allocating the new block of memory. */
- if(newArray = (kwsysProcessInstance*)malloc(
- newSize*sizeof(kwsysProcessInstance)))
- {
+ if (newArray = (kwsysProcessInstance*)malloc(
+ newSize * sizeof(kwsysProcessInstance))) {
/* Copy the old process handles to the new memory. */
- if(kwsysProcesses.Count > 0)
- {
+ if (kwsysProcesses.Count > 0) {
memcpy(newArray, kwsysProcesses.Processes,
kwsysProcesses.Count * sizeof(kwsysProcessInstance));
- }
}
- else
- {
+ } else {
/* Failed to allocate memory for the new process handle set. */
LeaveCriticalSection(&kwsysProcesses.Lock);
return 0;
- }
+ }
/* Free original array. */
free(kwsysProcesses.Processes);
@@ -2922,7 +2688,7 @@ static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid,
/* Update original structure with new allocation. */
kwsysProcesses.Size = newSize;
kwsysProcesses.Processes = newArray;
- }
+ }
/* Append the new process information to the set. */
kwsysProcesses.Processes[kwsysProcesses.Count].hProcess = hProcess;
@@ -2942,38 +2708,32 @@ static void kwsysProcessesRemove(HANDLE hProcess)
{
size_t i;
- if (!hProcess || hProcess == INVALID_HANDLE_VALUE)
- {
+ if (!hProcess || hProcess == INVALID_HANDLE_VALUE) {
return;
- }
+ }
EnterCriticalSection(&kwsysProcesses.Lock);
/* Find the given process in the set. */
- for(i=0; i < kwsysProcesses.Count; ++i)
- {
- if(kwsysProcesses.Processes[i].hProcess == hProcess)
- {
+ for (i = 0; i < kwsysProcesses.Count; ++i) {
+ if (kwsysProcesses.Processes[i].hProcess == hProcess) {
break;
- }
}
- if(i < kwsysProcesses.Count)
- {
+ }
+ if (i < kwsysProcesses.Count) {
/* Found it! Remove the process from the set. */
--kwsysProcesses.Count;
- for(; i < kwsysProcesses.Count; ++i)
- {
- kwsysProcesses.Processes[i] = kwsysProcesses.Processes[i+1];
- }
+ for (; i < kwsysProcesses.Count; ++i) {
+ kwsysProcesses.Processes[i] = kwsysProcesses.Processes[i + 1];
+ }
/* If this was the last process, free the array. */
- if(kwsysProcesses.Count == 0)
- {
+ if (kwsysProcesses.Count == 0) {
kwsysProcesses.Size = 0;
free(kwsysProcesses.Processes);
kwsysProcesses.Processes = 0;
- }
}
+ }
LeaveCriticalSection(&kwsysProcesses.Lock);
}
@@ -2991,25 +2751,21 @@ static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType)
/* If some of our processes were created in a new process group, we must
manually interrupt them. They won't otherwise receive a Ctrl+C/Break. */
- for(i=0; i < kwsysProcesses.Count; ++i)
- {
- if(kwsysProcesses.Processes[i].NewProcessGroup)
- {
+ for (i = 0; i < kwsysProcesses.Count; ++i) {
+ if (kwsysProcesses.Processes[i].NewProcessGroup) {
DWORD groupId = kwsysProcesses.Processes[i].dwProcessId;
- if(groupId)
- {
+ if (groupId) {
GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, groupId);
- }
}
}
+ }
/* Wait for each child process to exit. This is the key step that prevents
us from leaving several orphaned children processes running in the
background when the user presses Ctrl+C. */
- for(i=0; i < kwsysProcesses.Count; ++i)
- {
+ for (i = 0; i < kwsysProcesses.Count; ++i) {
WaitForSingleObject(kwsysProcesses.Processes[i].hProcess, INFINITE);
- }
+ }
/* Leave critical section. */
LeaveCriticalSection(&kwsysProcesses.Lock);
@@ -3021,10 +2777,9 @@ static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType)
/*--------------------------------------------------------------------------*/
void kwsysProcess_ResetStartTime(kwsysProcess* cp)
{
- if(!cp)
- {
+ if (!cp) {
return;
- }
+ }
/* Reset start time. */
cp->StartTime = kwsysProcessTimeGetCurrent();
}
diff --git a/Source/kwsys/RegularExpression.cxx b/Source/kwsys/RegularExpression.cxx
index 22593b4..6d7f832 100644
--- a/Source/kwsys/RegularExpression.cxx
+++ b/Source/kwsys/RegularExpression.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
//
// Copyright (C) 1991 Texas Instruments Incorporated.
//
@@ -34,30 +25,29 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "RegularExpression.hxx.in"
+#include "RegularExpression.hxx.in"
#endif
#include <stdio.h>
#include <string.h>
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
// RegularExpression -- Copies the given regular expression.
-RegularExpression::RegularExpression (const RegularExpression& rxp) {
- if ( !rxp.program )
- {
+RegularExpression::RegularExpression(const RegularExpression& rxp)
+{
+ if (!rxp.program) {
this->program = 0;
return;
- }
+ }
int ind;
- this->progsize = rxp.progsize; // Copy regular expression size
- this->program = new char[this->progsize]; // Allocate storage
- for(ind=this->progsize; ind-- != 0;) // Copy regular expresion
+ this->progsize = rxp.progsize; // Copy regular expression size
+ this->program = new char[this->progsize]; // Allocate storage
+ for (ind = this->progsize; ind-- != 0;) // Copy regular expresion
this->program[ind] = rxp.program[ind];
- this->startp[0] = rxp.startp[0]; // Copy pointers into last
- this->endp[0] = rxp.endp[0]; // Successful "find" operation
- this->regmust = rxp.regmust; // Copy field
+ this->startp[0] = rxp.startp[0]; // Copy pointers into last
+ this->endp[0] = rxp.endp[0]; // Successful "find" operation
+ this->regmust = rxp.regmust; // Copy field
if (rxp.regmust != 0) {
char* dum = rxp.program;
ind = 0;
@@ -67,32 +57,30 @@ RegularExpression::RegularExpression (const RegularExpression& rxp) {
}
this->regmust = this->program + ind;
}
- this->regstart = rxp.regstart; // Copy starting index
- this->reganch = rxp.reganch; // Copy remaining private data
- this->regmlen = rxp.regmlen; // Copy remaining private data
+ this->regstart = rxp.regstart; // Copy starting index
+ this->reganch = rxp.reganch; // Copy remaining private data
+ this->regmlen = rxp.regmlen; // Copy remaining private data
}
// operator= -- Copies the given regular expression.
-RegularExpression& RegularExpression::operator= (const RegularExpression& rxp)
+RegularExpression& RegularExpression::operator=(const RegularExpression& rxp)
{
- if(this == &rxp)
- {
+ if (this == &rxp) {
return *this;
- }
- if ( !rxp.program )
- {
+ }
+ if (!rxp.program) {
this->program = 0;
return *this;
- }
+ }
int ind;
- this->progsize = rxp.progsize; // Copy regular expression size
- delete [] this->program;
- this->program = new char[this->progsize]; // Allocate storage
- for(ind=this->progsize; ind-- != 0;) // Copy regular expresion
+ this->progsize = rxp.progsize; // Copy regular expression size
+ delete[] this->program;
+ this->program = new char[this->progsize]; // Allocate storage
+ for (ind = this->progsize; ind-- != 0;) // Copy regular expresion
this->program[ind] = rxp.program[ind];
- this->startp[0] = rxp.startp[0]; // Copy pointers into last
- this->endp[0] = rxp.endp[0]; // Successful "find" operation
- this->regmust = rxp.regmust; // Copy field
+ this->startp[0] = rxp.startp[0]; // Copy pointers into last
+ this->endp[0] = rxp.endp[0]; // Successful "find" operation
+ this->regmust = rxp.regmust; // Copy field
if (rxp.regmust != 0) {
char* dum = rxp.program;
ind = 0;
@@ -102,37 +90,38 @@ RegularExpression& RegularExpression::operator= (const RegularExpression& rxp)
}
this->regmust = this->program + ind;
}
- this->regstart = rxp.regstart; // Copy starting index
- this->reganch = rxp.reganch; // Copy remaining private data
- this->regmlen = rxp.regmlen; // Copy remaining private data
+ this->regstart = rxp.regstart; // Copy starting index
+ this->reganch = rxp.reganch; // Copy remaining private data
+ this->regmlen = rxp.regmlen; // Copy remaining private data
return *this;
}
// operator== -- Returns true if two regular expressions have the same
// compiled program for pattern matching.
-bool RegularExpression::operator== (const RegularExpression& rxp) const {
- if (this != &rxp) { // Same address?
- int ind = this->progsize; // Get regular expression size
- if (ind != rxp.progsize) // If different size regexp
- return false; // Return failure
- while(ind-- != 0) // Else while still characters
- if(this->program[ind] != rxp.program[ind]) // If regexp are different
- return false; // Return failure
+bool RegularExpression::operator==(const RegularExpression& rxp) const
+{
+ if (this != &rxp) { // Same address?
+ int ind = this->progsize; // Get regular expression size
+ if (ind != rxp.progsize) // If different size regexp
+ return false; // Return failure
+ while (ind-- != 0) // Else while still characters
+ if (this->program[ind] != rxp.program[ind]) // If regexp are different
+ return false; // Return failure
}
- return true; // Else same, return success
+ return true; // Else same, return success
}
-
// deep_equal -- Returns true if have the same compiled regular expressions
// and the same start and end pointers.
-bool RegularExpression::deep_equal (const RegularExpression& rxp) const {
+bool RegularExpression::deep_equal(const RegularExpression& rxp) const
+{
int ind = this->progsize; // Get regular expression size
if (ind != rxp.progsize) // If different size regexp
return false; // Return failure
- while(ind-- != 0) // Else while still characters
- if(this->program[ind] != rxp.program[ind]) // If regexp are different
+ while (ind-- != 0) // Else while still characters
+ if (this->program[ind] != rxp.program[ind]) // If regexp are different
return false; // Return failure
return (this->startp[0] == rxp.startp[0] && // Else if same start/end ptrs,
this->endp[0] == rxp.endp[0]); // Return true
@@ -204,26 +193,26 @@ bool RegularExpression::deep_equal (const RegularExpression& rxp) const {
*/
// definition number opnd? meaning
-#define END 0 // no End of program.
-#define BOL 1 // no Match "" at beginning of line.
-#define EOL 2 // no Match "" at end of line.
-#define ANY 3 // no Match any one character.
-#define ANYOF 4 // str Match any character in this string.
-#define ANYBUT 5 // str Match any character not in this
- // string.
-#define BRANCH 6 // node Match this alternative, or the
- // next...
-#define BACK 7 // no Match "", "next" ptr points backward.
-#define EXACTLY 8 // str Match this string.
-#define NOTHING 9 // no Match empty string.
-#define STAR 10 // node Match this (simple) thing 0 or more
- // times.
-#define PLUS 11 // node Match this (simple) thing 1 or more
- // times.
-#define OPEN 20 // no Mark this point in input as start of
- // #n.
+#define END 0 // no End of program.
+#define BOL 1 // no Match "" at beginning of line.
+#define EOL 2 // no Match "" at end of line.
+#define ANY 3 // no Match any one character.
+#define ANYOF 4 // str Match any character in this string.
+#define ANYBUT 5 // str Match any character not in this
+ // string.
+#define BRANCH 6 // node Match this alternative, or the
+ // next...
+#define BACK 7 // no Match "", "next" ptr points backward.
+#define EXACTLY 8 // str Match this string.
+#define NOTHING 9 // no Match empty string.
+#define STAR 10 // node Match this (simple) thing 0 or more
+ // times.
+#define PLUS 11 // node Match this (simple) thing 1 or more
+ // times.
+#define OPEN 20 // no Mark this point in input as start of
+ // #n.
// OPEN+1 is number 1, etc.
-#define CLOSE 30 // no Analogous to OPEN.
+#define CLOSE 30 // no Analogous to OPEN.
/*
* Opcode notes:
@@ -258,32 +247,32 @@ bool RegularExpression::deep_equal (const RegularExpression& rxp) const {
* but allows patterns to get big without disasters.
*/
-#define OP(p) (*(p))
-#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
-#define OPERAND(p) ((p) + 3)
+#define OP(p) (*(p))
+#define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
+#define OPERAND(p) ((p) + 3)
const unsigned char MAGIC = 0234;
/*
* Utility definitions.
*/
-#define UCHARAT(p) (reinterpret_cast<const unsigned char*>(p))[0]
-
-
-#define FAIL(m) { regerror(m); return(0); }
-#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
-#define META "^$.[()|?+*\\"
+#define UCHARAT(p) (reinterpret_cast<const unsigned char*>(p))[0]
+#define FAIL(m) \
+ { \
+ regerror(m); \
+ return (0); \
+ }
+#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
+#define META "^$.[()|?+*\\"
/*
* Flags to be passed up and down.
*/
-#define HASWIDTH 01 // Known never to match null string.
-#define SIMPLE 02 // Simple enough to be STAR/PLUS operand.
-#define SPSTART 04 // Starts with * or +.
-#define WORST 0 // Worst case.
-
-
+#define HASWIDTH 01 // Known never to match null string.
+#define SIMPLE 02 // Simple enough to be STAR/PLUS operand.
+#define SPSTART 04 // Starts with * or +.
+#define WORST 0 // Worst case.
/////////////////////////////////////////////////////////////////////////
//
@@ -291,15 +280,14 @@ const unsigned char MAGIC = 0234;
//
/////////////////////////////////////////////////////////////////////////
-
/*
* Global work variables for compile().
*/
-static const char* regparse; // Input-scan pointer.
-static int regnpar; // () count.
-static char regdummy;
-static char* regcode; // Code-emit pointer; &regdummy = don't.
-static long regsize; // Code size.
+static const char* regparse; // Input-scan pointer.
+static int regnpar; // () count.
+static char regdummy;
+static char* regcode; // Code-emit pointer; &regdummy = don't.
+static long regsize; // Code size.
/*
* Forward declarations for compile()'s friends.
@@ -307,24 +295,22 @@ static long regsize; // Code size.
// #ifndef static
// #define static static
// #endif
-static char* reg (int, int*);
-static char* regbranch (int*);
-static char* regpiece (int*);
-static char* regatom (int*);
-static char* regnode (char);
-static const char* regnext (const char*);
-static char* regnext (char*);
-static void regc (char);
-static void reginsert (char, char*);
-static void regtail (char*, const char*);
-static void regoptail (char*, const char*);
+static char* reg(int, int*);
+static char* regbranch(int*);
+static char* regpiece(int*);
+static char* regatom(int*);
+static char* regnode(char);
+static const char* regnext(const char*);
+static char* regnext(char*);
+static void regc(char);
+static void reginsert(char, char*);
+static void regtail(char*, const char*);
+static void regoptail(char*, const char*);
#ifdef STRCSPN
-static int strcspn ();
+static int strcspn();
#endif
-
-
/*
* We can't allocate space until we know how big the compiled form will be,
* but we can't compile it (and thus know how big it is) until we've got a
@@ -339,101 +325,100 @@ static int strcspn ();
* of the structure of the compiled regexp.
*/
-
// compile -- compile a regular expression into internal code
// for later pattern matching.
-bool RegularExpression::compile (const char* exp) {
- const char* scan;
- const char* longest;
- size_t len;
- int flags;
+bool RegularExpression::compile(const char* exp)
+{
+ const char* scan;
+ const char* longest;
+ size_t len;
+ int flags;
+
+ if (exp == 0) {
+ // RAISE Error, SYM(RegularExpression), SYM(No_Expr),
+ printf("RegularExpression::compile(): No expression supplied.\n");
+ return false;
+ }
- if (exp == 0) {
- //RAISE Error, SYM(RegularExpression), SYM(No_Expr),
- printf ("RegularExpression::compile(): No expression supplied.\n");
- return false;
- }
+ // First pass: determine size, legality.
+ regparse = exp;
+ regnpar = 1;
+ regsize = 0L;
+ regcode = &regdummy;
+ regc(static_cast<char>(MAGIC));
+ if (!reg(0, &flags)) {
+ printf("RegularExpression::compile(): Error in compile.\n");
+ return false;
+ }
+ this->startp[0] = this->endp[0] = this->searchstring = 0;
- // First pass: determine size, legality.
- regparse = exp;
- regnpar = 1;
- regsize = 0L;
- regcode = &regdummy;
- regc(static_cast<char>(MAGIC));
- if(!reg(0, &flags))
- {
- printf ("RegularExpression::compile(): Error in compile.\n");
- return false;
- }
- this->startp[0] = this->endp[0] = this->searchstring = 0;
+ // Small enough for pointer-storage convention?
+ if (regsize >= 32767L) { // Probably could be 65535L.
+ // RAISE Error, SYM(RegularExpression), SYM(Expr_Too_Big),
+ printf("RegularExpression::compile(): Expression too big.\n");
+ return false;
+ }
- // Small enough for pointer-storage convention?
- if (regsize >= 32767L) { // Probably could be 65535L.
- //RAISE Error, SYM(RegularExpression), SYM(Expr_Too_Big),
- printf ("RegularExpression::compile(): Expression too big.\n");
- return false;
- }
+ // Allocate space.
+ //#ifndef _WIN32
+ if (this->program != 0)
+ delete[] this->program;
+ //#endif
+ this->program = new char[regsize];
+ this->progsize = static_cast<int>(regsize);
+
+ if (this->program == 0) {
+ // RAISE Error, SYM(RegularExpression), SYM(Out_Of_Memory),
+ printf("RegularExpression::compile(): Out of memory.\n");
+ return false;
+ }
- // Allocate space.
-//#ifndef _WIN32
- if (this->program != 0) delete [] this->program;
-//#endif
- this->program = new char[regsize];
- this->progsize = static_cast<int>(regsize);
-
- if (this->program == 0) {
- //RAISE Error, SYM(RegularExpression), SYM(Out_Of_Memory),
- printf ("RegularExpression::compile(): Out of memory.\n");
- return false;
- }
+ // Second pass: emit code.
+ regparse = exp;
+ regnpar = 1;
+ regcode = this->program;
+ regc(static_cast<char>(MAGIC));
+ reg(0, &flags);
+
+ // Dig out information for optimizations.
+ this->regstart = '\0'; // Worst-case defaults.
+ this->reganch = 0;
+ this->regmust = 0;
+ this->regmlen = 0;
+ scan = this->program + 1; // First BRANCH.
+ if (OP(regnext(scan)) == END) { // Only one top-level choice.
+ scan = OPERAND(scan);
+
+ // Starting-point info.
+ if (OP(scan) == EXACTLY)
+ this->regstart = *OPERAND(scan);
+ else if (OP(scan) == BOL)
+ this->reganch++;
- // Second pass: emit code.
- regparse = exp;
- regnpar = 1;
- regcode = this->program;
- regc(static_cast<char>(MAGIC));
- reg(0, &flags);
-
- // Dig out information for optimizations.
- this->regstart = '\0'; // Worst-case defaults.
- this->reganch = 0;
- this->regmust = 0;
- this->regmlen = 0;
- scan = this->program + 1; // First BRANCH.
- if (OP(regnext(scan)) == END) { // Only one top-level choice.
- scan = OPERAND(scan);
-
- // Starting-point info.
- if (OP(scan) == EXACTLY)
- this->regstart = *OPERAND(scan);
- else if (OP(scan) == BOL)
- this->reganch++;
-
- //
- // If there's something expensive in the r.e., find the longest
- // literal string that must appear and make it the regmust. Resolve
- // ties in favor of later strings, since the regstart check works
- // with the beginning of the r.e. and avoiding duplication
- // strengthens checking. Not a strong reason, but sufficient in the
- // absence of others.
- //
- if (flags & SPSTART) {
- longest = 0;
- len = 0;
- for (; scan != 0; scan = regnext(scan))
- if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
- longest = OPERAND(scan);
- len = strlen(OPERAND(scan));
- }
- this->regmust = longest;
- this->regmlen = len;
+ //
+ // If there's something expensive in the r.e., find the longest
+ // literal string that must appear and make it the regmust. Resolve
+ // ties in favor of later strings, since the regstart check works
+ // with the beginning of the r.e. and avoiding duplication
+ // strengthens checking. Not a strong reason, but sufficient in the
+ // absence of others.
+ //
+ if (flags & SPSTART) {
+ longest = 0;
+ len = 0;
+ for (; scan != 0; scan = regnext(scan))
+ if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
+ longest = OPERAND(scan);
+ len = strlen(OPERAND(scan));
}
+ this->regmust = longest;
+ this->regmlen = len;
}
- return true;
+ }
+ return true;
}
-
/*
- reg - regular expression, i.e. main body or parenthesized thing
*
@@ -443,115 +428,112 @@ bool RegularExpression::compile (const char* exp) {
* is a trifle forced, but the need to tie the tails of the branches to what
* follows makes it hard to avoid.
*/
-static char* reg (int paren, int *flagp) {
- char* ret;
- char* br;
- char* ender;
- int parno =0;
- int flags;
-
- *flagp = HASWIDTH; // Tentatively.
-
- // Make an OPEN node, if parenthesized.
- if (paren) {
- if (regnpar >= RegularExpression::NSUBEXP) {
- //RAISE Error, SYM(RegularExpression), SYM(Too_Many_Parens),
- printf ("RegularExpression::compile(): Too many parentheses.\n");
- return 0;
- }
- parno = regnpar;
- regnpar++;
- ret = regnode(static_cast<char>(OPEN + parno));
+static char* reg(int paren, int* flagp)
+{
+ char* ret;
+ char* br;
+ char* ender;
+ int parno = 0;
+ int flags;
+
+ *flagp = HASWIDTH; // Tentatively.
+
+ // Make an OPEN node, if parenthesized.
+ if (paren) {
+ if (regnpar >= RegularExpression::NSUBEXP) {
+ // RAISE Error, SYM(RegularExpression), SYM(Too_Many_Parens),
+ printf("RegularExpression::compile(): Too many parentheses.\n");
+ return 0;
}
- else
- ret = 0;
-
- // Pick up the branches, linking them together.
+ parno = regnpar;
+ regnpar++;
+ ret = regnode(static_cast<char>(OPEN + parno));
+ } else
+ ret = 0;
+
+ // Pick up the branches, linking them together.
+ br = regbranch(&flags);
+ if (br == 0)
+ return (0);
+ if (ret != 0)
+ regtail(ret, br); // OPEN -> first.
+ else
+ ret = br;
+ if (!(flags & HASWIDTH))
+ *flagp &= ~HASWIDTH;
+ *flagp |= flags & SPSTART;
+ while (*regparse == '|') {
+ regparse++;
br = regbranch(&flags);
if (br == 0)
- return (0);
- if (ret != 0)
- regtail(ret, br); // OPEN -> first.
- else
- ret = br;
+ return (0);
+ regtail(ret, br); // BRANCH -> BRANCH.
if (!(flags & HASWIDTH))
- *flagp &= ~HASWIDTH;
+ *flagp &= ~HASWIDTH;
*flagp |= flags & SPSTART;
- while (*regparse == '|') {
- regparse++;
- br = regbranch(&flags);
- if (br == 0)
- return (0);
- regtail(ret, br); // BRANCH -> BRANCH.
- if (!(flags & HASWIDTH))
- *flagp &= ~HASWIDTH;
- *flagp |= flags & SPSTART;
- }
-
- // Make a closing node, and hook it on the end.
- ender = regnode(static_cast<char>((paren) ? CLOSE + parno : END));
- regtail(ret, ender);
-
- // Hook the tails of the branches to the closing node.
- for (br = ret; br != 0; br = regnext(br))
- regoptail(br, ender);
+ }
- // Check for proper termination.
- if (paren && *regparse++ != ')') {
- //RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
- printf ("RegularExpression::compile(): Unmatched parentheses.\n");
- return 0;
- }
- else if (!paren && *regparse != '\0') {
- if (*regparse == ')') {
- //RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
- printf ("RegularExpression::compile(): Unmatched parentheses.\n");
- return 0;
- }
- else {
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("RegularExpression::compile(): Internal error.\n");
- return 0;
- }
- // NOTREACHED
+ // Make a closing node, and hook it on the end.
+ ender = regnode(static_cast<char>((paren) ? CLOSE + parno : END));
+ regtail(ret, ender);
+
+ // Hook the tails of the branches to the closing node.
+ for (br = ret; br != 0; br = regnext(br))
+ regoptail(br, ender);
+
+ // Check for proper termination.
+ if (paren && *regparse++ != ')') {
+ // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
+ printf("RegularExpression::compile(): Unmatched parentheses.\n");
+ return 0;
+ } else if (!paren && *regparse != '\0') {
+ if (*regparse == ')') {
+ // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
+ printf("RegularExpression::compile(): Unmatched parentheses.\n");
+ return 0;
+ } else {
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf("RegularExpression::compile(): Internal error.\n");
+ return 0;
}
- return (ret);
+ // NOTREACHED
+ }
+ return (ret);
}
-
/*
- regbranch - one alternative of an | operator
*
* Implements the concatenation operator.
*/
-static char* regbranch (int *flagp) {
- char* ret;
- char* chain;
- char* latest;
- int flags;
-
- *flagp = WORST; // Tentatively.
-
- ret = regnode(BRANCH);
- chain = 0;
- while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
- latest = regpiece(&flags);
- if (latest == 0)
- return (0);
- *flagp |= flags & HASWIDTH;
- if (chain == 0) // First piece.
- *flagp |= flags & SPSTART;
- else
- regtail(chain, latest);
- chain = latest;
- }
- if (chain == 0) // Loop ran zero times.
- regnode(NOTHING);
+static char* regbranch(int* flagp)
+{
+ char* ret;
+ char* chain;
+ char* latest;
+ int flags;
+
+ *flagp = WORST; // Tentatively.
+
+ ret = regnode(BRANCH);
+ chain = 0;
+ while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
+ latest = regpiece(&flags);
+ if (latest == 0)
+ return (0);
+ *flagp |= flags & HASWIDTH;
+ if (chain == 0) // First piece.
+ *flagp |= flags & SPSTART;
+ else
+ regtail(chain, latest);
+ chain = latest;
+ }
+ if (chain == 0) // Loop ran zero times.
+ regnode(NOTHING);
- return (ret);
+ return (ret);
}
-
/*
- regpiece - something followed by possible [*+?]
*
@@ -561,66 +543,64 @@ static char* regbranch (int *flagp) {
* It might seem that this node could be dispensed with entirely, but the
* endmarker role is not redundant.
*/
-static char* regpiece (int *flagp) {
- char* ret;
- char op;
- char* next;
- int flags;
-
- ret = regatom(&flags);
- if (ret == 0)
- return (0);
+static char* regpiece(int* flagp)
+{
+ char* ret;
+ char op;
+ char* next;
+ int flags;
- op = *regparse;
- if (!ISMULT(op)) {
- *flagp = flags;
- return (ret);
- }
+ ret = regatom(&flags);
+ if (ret == 0)
+ return (0);
- if (!(flags & HASWIDTH) && op != '?') {
- //RAISE Error, SYM(RegularExpression), SYM(Empty_Operand),
- printf ("RegularExpression::compile() : *+ operand could be empty.\n");
- return 0;
- }
- *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
-
- if (op == '*' && (flags & SIMPLE))
- reginsert(STAR, ret);
- else if (op == '*') {
- // Emit x* as (x&|), where & means "self".
- reginsert(BRANCH, ret); // Either x
- regoptail(ret, regnode(BACK)); // and loop
- regoptail(ret, ret); // back
- regtail(ret, regnode(BRANCH)); // or
- regtail(ret, regnode(NOTHING)); // null.
- }
- else if (op == '+' && (flags & SIMPLE))
- reginsert(PLUS, ret);
- else if (op == '+') {
- // Emit x+ as x(&|), where & means "self".
- next = regnode(BRANCH); // Either
- regtail(ret, next);
- regtail(regnode(BACK), ret); // loop back
- regtail(next, regnode(BRANCH)); // or
- regtail(ret, regnode(NOTHING)); // null.
- }
- else if (op == '?') {
- // Emit x? as (x|)
- reginsert(BRANCH, ret); // Either x
- regtail(ret, regnode(BRANCH)); // or
- next = regnode(NOTHING);// null.
- regtail(ret, next);
- regoptail(ret, next);
- }
- regparse++;
- if (ISMULT(*regparse)) {
- //RAISE Error, SYM(RegularExpression), SYM(Nested_Operand),
- printf ("RegularExpression::compile(): Nested *?+.\n");
- return 0;
- }
+ op = *regparse;
+ if (!ISMULT(op)) {
+ *flagp = flags;
return (ret);
-}
+ }
+ if (!(flags & HASWIDTH) && op != '?') {
+ // RAISE Error, SYM(RegularExpression), SYM(Empty_Operand),
+ printf("RegularExpression::compile() : *+ operand could be empty.\n");
+ return 0;
+ }
+ *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
+
+ if (op == '*' && (flags & SIMPLE))
+ reginsert(STAR, ret);
+ else if (op == '*') {
+ // Emit x* as (x&|), where & means "self".
+ reginsert(BRANCH, ret); // Either x
+ regoptail(ret, regnode(BACK)); // and loop
+ regoptail(ret, ret); // back
+ regtail(ret, regnode(BRANCH)); // or
+ regtail(ret, regnode(NOTHING)); // null.
+ } else if (op == '+' && (flags & SIMPLE))
+ reginsert(PLUS, ret);
+ else if (op == '+') {
+ // Emit x+ as x(&|), where & means "self".
+ next = regnode(BRANCH); // Either
+ regtail(ret, next);
+ regtail(regnode(BACK), ret); // loop back
+ regtail(next, regnode(BRANCH)); // or
+ regtail(ret, regnode(NOTHING)); // null.
+ } else if (op == '?') {
+ // Emit x? as (x|)
+ reginsert(BRANCH, ret); // Either x
+ regtail(ret, regnode(BRANCH)); // or
+ next = regnode(NOTHING); // null.
+ regtail(ret, next);
+ regoptail(ret, next);
+ }
+ regparse++;
+ if (ISMULT(*regparse)) {
+ // RAISE Error, SYM(RegularExpression), SYM(Nested_Operand),
+ printf("RegularExpression::compile(): Nested *?+.\n");
+ return 0;
+ }
+ return (ret);
+}
/*
- regatom - the lowest level
@@ -630,349 +610,340 @@ static char* regpiece (int *flagp) {
* faster to run. Backslashed characters are exceptions, each becoming a
* separate node; the code is simpler that way and it's not worth fixing.
*/
-static char* regatom (int *flagp) {
- char* ret;
- int flags;
-
- *flagp = WORST; // Tentatively.
-
- switch (*regparse++) {
- case '^':
- ret = regnode(BOL);
- break;
- case '$':
- ret = regnode(EOL);
- break;
- case '.':
- ret = regnode(ANY);
- *flagp |= HASWIDTH | SIMPLE;
- break;
- case '[':{
- int rxpclass;
- int rxpclassend;
-
- if (*regparse == '^') { // Complement of range.
- ret = regnode(ANYBUT);
- regparse++;
- }
- else
- ret = regnode(ANYOF);
- if (*regparse == ']' || *regparse == '-')
- regc(*regparse++);
- while (*regparse != '\0' && *regparse != ']') {
- if (*regparse == '-') {
- regparse++;
- if (*regparse == ']' || *regparse == '\0')
- regc('-');
- else {
- rxpclass = UCHARAT(regparse - 2) + 1;
- rxpclassend = UCHARAT(regparse);
- if (rxpclass > rxpclassend + 1) {
- //RAISE Error, SYM(RegularExpression), SYM(Invalid_Range),
- printf ("RegularExpression::compile(): Invalid range in [].\n");
- return 0;
- }
- for (; rxpclass <= rxpclassend; rxpclass++)
- regc(static_cast<char>(rxpclass));
- regparse++;
- }
- }
- else
- regc(*regparse++);
- }
- regc('\0');
- if (*regparse != ']') {
- //RAISE Error, SYM(RegularExpression), SYM(Unmatched_Bracket),
- printf ("RegularExpression::compile(): Unmatched [].\n");
- return 0;
- }
- regparse++;
- *flagp |= HASWIDTH | SIMPLE;
- }
- break;
- case '(':
- ret = reg(1, &flags);
- if (ret == 0)
- return (0);
- *flagp |= flags & (HASWIDTH | SPSTART);
- break;
- case '\0':
- case '|':
- case ')':
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("RegularExpression::compile(): Internal error.\n"); // Never here
- return 0;
- case '?':
- case '+':
- case '*':
- //RAISE Error, SYM(RegularExpression), SYM(No_Operand),
- printf ("RegularExpression::compile(): ?+* follows nothing.\n");
- return 0;
- case '\\':
- if (*regparse == '\0') {
- //RAISE Error, SYM(RegularExpression), SYM(Trailing_Backslash),
- printf ("RegularExpression::compile(): Trailing backslash.\n");
- return 0;
- }
- ret = regnode(EXACTLY);
- regc(*regparse++);
- regc('\0');
- *flagp |= HASWIDTH | SIMPLE;
- break;
- default:{
- int len;
- char ender;
-
- regparse--;
- len = int(strcspn(regparse, META));
- if (len <= 0) {
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("RegularExpression::compile(): Internal error.\n");
- return 0;
- }
- ender = *(regparse + len);
- if (len > 1 && ISMULT(ender))
- len--; // Back off clear of ?+* operand.
- *flagp |= HASWIDTH;
- if (len == 1)
- *flagp |= SIMPLE;
- ret = regnode(EXACTLY);
- while (len > 0) {
- regc(*regparse++);
- len--;
- }
- regc('\0');
+static char* regatom(int* flagp)
+{
+ char* ret;
+ int flags;
+
+ *flagp = WORST; // Tentatively.
+
+ switch (*regparse++) {
+ case '^':
+ ret = regnode(BOL);
+ break;
+ case '$':
+ ret = regnode(EOL);
+ break;
+ case '.':
+ ret = regnode(ANY);
+ *flagp |= HASWIDTH | SIMPLE;
+ break;
+ case '[': {
+ int rxpclass;
+ int rxpclassend;
+
+ if (*regparse == '^') { // Complement of range.
+ ret = regnode(ANYBUT);
+ regparse++;
+ } else
+ ret = regnode(ANYOF);
+ if (*regparse == ']' || *regparse == '-')
+ regc(*regparse++);
+ while (*regparse != '\0' && *regparse != ']') {
+ if (*regparse == '-') {
+ regparse++;
+ if (*regparse == ']' || *regparse == '\0')
+ regc('-');
+ else {
+ rxpclass = UCHARAT(regparse - 2) + 1;
+ rxpclassend = UCHARAT(regparse);
+ if (rxpclass > rxpclassend + 1) {
+ // RAISE Error, SYM(RegularExpression), SYM(Invalid_Range),
+ printf("RegularExpression::compile(): Invalid range in [].\n");
+ return 0;
}
- break;
- }
- return (ret);
+ for (; rxpclass <= rxpclassend; rxpclass++)
+ regc(static_cast<char>(rxpclass));
+ regparse++;
+ }
+ } else
+ regc(*regparse++);
+ }
+ regc('\0');
+ if (*regparse != ']') {
+ // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Bracket),
+ printf("RegularExpression::compile(): Unmatched [].\n");
+ return 0;
+ }
+ regparse++;
+ *flagp |= HASWIDTH | SIMPLE;
+ } break;
+ case '(':
+ ret = reg(1, &flags);
+ if (ret == 0)
+ return (0);
+ *flagp |= flags & (HASWIDTH | SPSTART);
+ break;
+ case '\0':
+ case '|':
+ case ')':
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf("RegularExpression::compile(): Internal error.\n"); // Never here
+ return 0;
+ case '?':
+ case '+':
+ case '*':
+ // RAISE Error, SYM(RegularExpression), SYM(No_Operand),
+ printf("RegularExpression::compile(): ?+* follows nothing.\n");
+ return 0;
+ case '\\':
+ if (*regparse == '\0') {
+ // RAISE Error, SYM(RegularExpression), SYM(Trailing_Backslash),
+ printf("RegularExpression::compile(): Trailing backslash.\n");
+ return 0;
+ }
+ ret = regnode(EXACTLY);
+ regc(*regparse++);
+ regc('\0');
+ *flagp |= HASWIDTH | SIMPLE;
+ break;
+ default: {
+ int len;
+ char ender;
+
+ regparse--;
+ len = int(strcspn(regparse, META));
+ if (len <= 0) {
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf("RegularExpression::compile(): Internal error.\n");
+ return 0;
+ }
+ ender = *(regparse + len);
+ if (len > 1 && ISMULT(ender))
+ len--; // Back off clear of ?+* operand.
+ *flagp |= HASWIDTH;
+ if (len == 1)
+ *flagp |= SIMPLE;
+ ret = regnode(EXACTLY);
+ while (len > 0) {
+ regc(*regparse++);
+ len--;
+ }
+ regc('\0');
+ } break;
+ }
+ return (ret);
}
-
/*
- regnode - emit a node
Location.
*/
-static char* regnode (char op) {
- char* ret;
- char* ptr;
-
- ret = regcode;
- if (ret == &regdummy) {
- regsize += 3;
- return (ret);
- }
-
- ptr = ret;
- *ptr++ = op;
- *ptr++ = '\0'; // Null "next" pointer.
- *ptr++ = '\0';
- regcode = ptr;
+static char* regnode(char op)
+{
+ char* ret;
+ char* ptr;
+ ret = regcode;
+ if (ret == &regdummy) {
+ regsize += 3;
return (ret);
-}
+ }
+ ptr = ret;
+ *ptr++ = op;
+ *ptr++ = '\0'; // Null "next" pointer.
+ *ptr++ = '\0';
+ regcode = ptr;
+
+ return (ret);
+}
/*
- regc - emit (if appropriate) a byte of code
*/
-static void regc (char b) {
- if (regcode != &regdummy)
- *regcode++ = b;
- else
- regsize++;
+static void regc(char b)
+{
+ if (regcode != &regdummy)
+ *regcode++ = b;
+ else
+ regsize++;
}
-
/*
- reginsert - insert an operator in front of already-emitted operand
*
* Means relocating the operand.
*/
-static void reginsert (char op, char* opnd) {
- char* src;
- char* dst;
- char* place;
-
- if (regcode == &regdummy) {
- regsize += 3;
- return;
- }
+static void reginsert(char op, char* opnd)
+{
+ char* src;
+ char* dst;
+ char* place;
+
+ if (regcode == &regdummy) {
+ regsize += 3;
+ return;
+ }
- src = regcode;
- regcode += 3;
- dst = regcode;
- while (src > opnd)
- *--dst = *--src;
+ src = regcode;
+ regcode += 3;
+ dst = regcode;
+ while (src > opnd)
+ *--dst = *--src;
- place = opnd; // Op node, where operand used to be.
- *place++ = op;
- *place++ = '\0';
- *place = '\0';
+ place = opnd; // Op node, where operand used to be.
+ *place++ = op;
+ *place++ = '\0';
+ *place = '\0';
}
-
/*
- regtail - set the next-pointer at the end of a node chain
*/
-static void regtail (char* p, const char* val) {
- char* scan;
- char* temp;
- int offset;
-
- if (p == &regdummy)
- return;
-
- // Find last node.
- scan = p;
- for (;;) {
- temp = regnext(scan);
- if (temp == 0)
- break;
- scan = temp;
- }
+static void regtail(char* p, const char* val)
+{
+ char* scan;
+ char* temp;
+ int offset;
- if (OP(scan) == BACK)
- offset = int(scan - val);
- else
- offset = int(val - scan);
- *(scan + 1) = static_cast<char>((offset >> 8) & 0377);
- *(scan + 2) = static_cast<char>(offset & 0377);
-}
+ if (p == &regdummy)
+ return;
+
+ // Find last node.
+ scan = p;
+ for (;;) {
+ temp = regnext(scan);
+ if (temp == 0)
+ break;
+ scan = temp;
+ }
+ if (OP(scan) == BACK)
+ offset = int(scan - val);
+ else
+ offset = int(val - scan);
+ *(scan + 1) = static_cast<char>((offset >> 8) & 0377);
+ *(scan + 2) = static_cast<char>(offset & 0377);
+}
/*
- regoptail - regtail on operand of first argument; nop if operandless
*/
-static void regoptail (char* p, const char* val) {
- // "Operandless" and "op != BRANCH" are synonymous in practice.
- if (p == 0 || p == &regdummy || OP(p) != BRANCH)
- return;
- regtail(OPERAND(p), val);
+static void regoptail(char* p, const char* val)
+{
+ // "Operandless" and "op != BRANCH" are synonymous in practice.
+ if (p == 0 || p == &regdummy || OP(p) != BRANCH)
+ return;
+ regtail(OPERAND(p), val);
}
-
-
////////////////////////////////////////////////////////////////////////
-//
+//
// find and friends
-//
+//
////////////////////////////////////////////////////////////////////////
-
/*
* Global work variables for find().
*/
-static const char* reginput; // String-input pointer.
-static const char* regbol; // Beginning of input, for ^ check.
-static const char* *regstartp; // Pointer to startp array.
-static const char* *regendp; // Ditto for endp.
+static const char* reginput; // String-input pointer.
+static const char* regbol; // Beginning of input, for ^ check.
+static const char** regstartp; // Pointer to startp array.
+static const char** regendp; // Ditto for endp.
/*
* Forwards.
*/
-static int regtry (const char*, const char* *,
- const char* *, const char*);
-static int regmatch (const char*);
-static int regrepeat (const char*);
+static int regtry(const char*, const char**, const char**, const char*);
+static int regmatch(const char*);
+static int regrepeat(const char*);
#ifdef DEBUG
-int regnarrate = 0;
-void regdump ();
-static char* regprop ();
+int regnarrate = 0;
+void regdump();
+static char* regprop();
#endif
// find -- Matches the regular expression to the given string.
// Returns true if found, and sets start and end indexes accordingly.
-bool RegularExpression::find (const char* string) {
- const char* s;
+bool RegularExpression::find(const char* string)
+{
+ const char* s;
- this->searchstring = string;
+ this->searchstring = string;
- if (!this->program)
- {
- return false;
- }
+ if (!this->program) {
+ return false;
+ }
- // Check validity of program.
- if (UCHARAT(this->program) != MAGIC) {
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("RegularExpression::find(): Compiled regular expression corrupted.\n");
- return 0;
- }
+ // Check validity of program.
+ if (UCHARAT(this->program) != MAGIC) {
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf(
+ "RegularExpression::find(): Compiled regular expression corrupted.\n");
+ return 0;
+ }
- // If there is a "must appear" string, look for it.
- if (this->regmust != 0) {
- s = string;
- while ((s = strchr(s, this->regmust[0])) != 0) {
- if (strncmp(s, this->regmust, this->regmlen) == 0)
- break; // Found it.
- s++;
- }
- if (s == 0) // Not present.
- return (0);
+ // If there is a "must appear" string, look for it.
+ if (this->regmust != 0) {
+ s = string;
+ while ((s = strchr(s, this->regmust[0])) != 0) {
+ if (strncmp(s, this->regmust, this->regmlen) == 0)
+ break; // Found it.
+ s++;
}
+ if (s == 0) // Not present.
+ return (0);
+ }
- // Mark beginning of line for ^ .
- regbol = string;
-
- // Simplest case: anchored match need be tried only once.
- if (this->reganch)
- return (regtry(string, this->startp, this->endp, this->program) != 0);
+ // Mark beginning of line for ^ .
+ regbol = string;
- // Messy cases: unanchored match.
- s = string;
- if (this->regstart != '\0')
- // We know what char it must start with.
- while ((s = strchr(s, this->regstart)) != 0) {
- if (regtry(s, this->startp, this->endp, this->program))
- return (1);
- s++;
+ // Simplest case: anchored match need be tried only once.
+ if (this->reganch)
+ return (regtry(string, this->startp, this->endp, this->program) != 0);
- }
- else
- // We don't -- general case.
- do {
- if (regtry(s, this->startp, this->endp, this->program))
- return (1);
- } while (*s++ != '\0');
+ // Messy cases: unanchored match.
+ s = string;
+ if (this->regstart != '\0')
+ // We know what char it must start with.
+ while ((s = strchr(s, this->regstart)) != 0) {
+ if (regtry(s, this->startp, this->endp, this->program))
+ return (1);
+ s++;
+ }
+ else
+ // We don't -- general case.
+ do {
+ if (regtry(s, this->startp, this->endp, this->program))
+ return (1);
+ } while (*s++ != '\0');
- // Failure.
- return (0);
+ // Failure.
+ return (0);
}
-
/*
- regtry - try match at specific point
0 failure, 1 success
*/
-static int regtry (const char* string, const char* *start,
- const char* *end, const char* prog) {
- int i;
- const char* *sp1;
- const char* *ep;
-
- reginput = string;
- regstartp = start;
- regendp = end;
-
- sp1 = start;
- ep = end;
- for (i = RegularExpression::NSUBEXP; i > 0; i--) {
- *sp1++ = 0;
- *ep++ = 0;
- }
- if (regmatch(prog + 1)) {
- start[0] = string;
- end[0] = reginput;
- return (1);
- }
- else
- return (0);
+static int regtry(const char* string, const char** start, const char** end,
+ const char* prog)
+{
+ int i;
+ const char** sp1;
+ const char** ep;
+
+ reginput = string;
+ regstartp = start;
+ regendp = end;
+
+ sp1 = start;
+ ep = end;
+ for (i = RegularExpression::NSUBEXP; i > 0; i--) {
+ *sp1++ = 0;
+ *ep++ = 0;
+ }
+ if (regmatch(prog + 1)) {
+ start[0] = string;
+ end[0] = reginput;
+ return (1);
+ } else
+ return (0);
}
-
/*
- regmatch - main matching routine
*
@@ -984,261 +955,260 @@ static int regtry (const char* string, const char* *start,
* by recursion.
* 0 failure, 1 success
*/
-static int regmatch (const char* prog) {
- const char* scan; // Current node.
- const char* next; // Next node.
-
- scan = prog;
-
- while (scan != 0) {
-
- next = regnext(scan);
-
- switch (OP(scan)) {
- case BOL:
- if (reginput != regbol)
- return (0);
- break;
- case EOL:
- if (*reginput != '\0')
- return (0);
- break;
- case ANY:
- if (*reginput == '\0')
- return (0);
- reginput++;
- break;
- case EXACTLY:{
- size_t len;
- const char* opnd;
-
- opnd = OPERAND(scan);
- // Inline the first character, for speed.
- if (*opnd != *reginput)
- return (0);
- len = strlen(opnd);
- if (len > 1 && strncmp(opnd, reginput, len) != 0)
- return (0);
- reginput += len;
- }
- break;
- case ANYOF:
- if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == 0)
- return (0);
- reginput++;
- break;
- case ANYBUT:
- if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != 0)
- return (0);
- reginput++;
- break;
- case NOTHING:
- break;
- case BACK:
- break;
- case OPEN + 1:
- case OPEN + 2:
- case OPEN + 3:
- case OPEN + 4:
- case OPEN + 5:
- case OPEN + 6:
- case OPEN + 7:
- case OPEN + 8:
- case OPEN + 9:{
- int no;
- const char* save;
-
- no = OP(scan) - OPEN;
- save = reginput;
-
- if (regmatch(next)) {
-
- //
- // Don't set startp if some later invocation of the
- // same parentheses already has.
- //
- if (regstartp[no] == 0)
- regstartp[no] = save;
- return (1);
- }
- else
- return (0);
- }
-// break;
- case CLOSE + 1:
- case CLOSE + 2:
- case CLOSE + 3:
- case CLOSE + 4:
- case CLOSE + 5:
- case CLOSE + 6:
- case CLOSE + 7:
- case CLOSE + 8:
- case CLOSE + 9:{
- int no;
- const char* save;
-
- no = OP(scan) - CLOSE;
- save = reginput;
-
- if (regmatch(next)) {
-
- //
- // Don't set endp if some later invocation of the
- // same parentheses already has.
- //
- if (regendp[no] == 0)
- regendp[no] = save;
- return (1);
- }
- else
- return (0);
- }
-// break;
- case BRANCH:{
-
- const char* save;
-
- if (OP(next) != BRANCH) // No choice.
- next = OPERAND(scan); // Avoid recursion.
- else {
- do {
- save = reginput;
- if (regmatch(OPERAND(scan)))
- return (1);
- reginput = save;
- scan = regnext(scan);
- } while (scan != 0 && OP(scan) == BRANCH);
- return (0);
- // NOTREACHED
- }
- }
- break;
- case STAR:
- case PLUS:{
- char nextch;
- int no;
- const char* save;
- int min_no;
-
- //
- // Lookahead to avoid useless match attempts when we know
- // what character comes next.
- //
- nextch = '\0';
- if (OP(next) == EXACTLY)
- nextch = *OPERAND(next);
- min_no = (OP(scan) == STAR) ? 0 : 1;
- save = reginput;
- no = regrepeat(OPERAND(scan));
- while (no >= min_no) {
- // If it could work, try it.
- if (nextch == '\0' || *reginput == nextch)
- if (regmatch(next))
- return (1);
- // Couldn't or didn't -- back up.
- no--;
- reginput = save + no;
- }
- return (0);
- }
-// break;
- case END:
- return (1); // Success!
-
- default:
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("RegularExpression::find(): Internal error -- memory corrupted.\n");
- return 0;
+static int regmatch(const char* prog)
+{
+ const char* scan; // Current node.
+ const char* next; // Next node.
+
+ scan = prog;
+
+ while (scan != 0) {
+
+ next = regnext(scan);
+
+ switch (OP(scan)) {
+ case BOL:
+ if (reginput != regbol)
+ return (0);
+ break;
+ case EOL:
+ if (*reginput != '\0')
+ return (0);
+ break;
+ case ANY:
+ if (*reginput == '\0')
+ return (0);
+ reginput++;
+ break;
+ case EXACTLY: {
+ size_t len;
+ const char* opnd;
+
+ opnd = OPERAND(scan);
+ // Inline the first character, for speed.
+ if (*opnd != *reginput)
+ return (0);
+ len = strlen(opnd);
+ if (len > 1 && strncmp(opnd, reginput, len) != 0)
+ return (0);
+ reginput += len;
+ } break;
+ case ANYOF:
+ if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == 0)
+ return (0);
+ reginput++;
+ break;
+ case ANYBUT:
+ if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != 0)
+ return (0);
+ reginput++;
+ break;
+ case NOTHING:
+ break;
+ case BACK:
+ break;
+ case OPEN + 1:
+ case OPEN + 2:
+ case OPEN + 3:
+ case OPEN + 4:
+ case OPEN + 5:
+ case OPEN + 6:
+ case OPEN + 7:
+ case OPEN + 8:
+ case OPEN + 9: {
+ int no;
+ const char* save;
+
+ no = OP(scan) - OPEN;
+ save = reginput;
+
+ if (regmatch(next)) {
+
+ //
+ // Don't set startp if some later invocation of the
+ // same parentheses already has.
+ //
+ if (regstartp[no] == 0)
+ regstartp[no] = save;
+ return (1);
+ } else
+ return (0);
+ }
+ // break;
+ case CLOSE + 1:
+ case CLOSE + 2:
+ case CLOSE + 3:
+ case CLOSE + 4:
+ case CLOSE + 5:
+ case CLOSE + 6:
+ case CLOSE + 7:
+ case CLOSE + 8:
+ case CLOSE + 9: {
+ int no;
+ const char* save;
+
+ no = OP(scan) - CLOSE;
+ save = reginput;
+
+ if (regmatch(next)) {
+
+ //
+ // Don't set endp if some later invocation of the
+ // same parentheses already has.
+ //
+ if (regendp[no] == 0)
+ regendp[no] = save;
+ return (1);
+ } else
+ return (0);
+ }
+ // break;
+ case BRANCH: {
+
+ const char* save;
+
+ if (OP(next) != BRANCH) // No choice.
+ next = OPERAND(scan); // Avoid recursion.
+ else {
+ do {
+ save = reginput;
+ if (regmatch(OPERAND(scan)))
+ return (1);
+ reginput = save;
+ scan = regnext(scan);
+ } while (scan != 0 && OP(scan) == BRANCH);
+ return (0);
+ // NOTREACHED
+ }
+ } break;
+ case STAR:
+ case PLUS: {
+ char nextch;
+ int no;
+ const char* save;
+ int min_no;
+
+ //
+ // Lookahead to avoid useless match attempts when we know
+ // what character comes next.
+ //
+ nextch = '\0';
+ if (OP(next) == EXACTLY)
+ nextch = *OPERAND(next);
+ min_no = (OP(scan) == STAR) ? 0 : 1;
+ save = reginput;
+ no = regrepeat(OPERAND(scan));
+ while (no >= min_no) {
+ // If it could work, try it.
+ if (nextch == '\0' || *reginput == nextch)
+ if (regmatch(next))
+ return (1);
+ // Couldn't or didn't -- back up.
+ no--;
+ reginput = save + no;
}
- scan = next;
+ return (0);
+ }
+ // break;
+ case END:
+ return (1); // Success!
+
+ default:
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf(
+ "RegularExpression::find(): Internal error -- memory corrupted.\n");
+ return 0;
}
+ scan = next;
+ }
- //
- // We get here only if there's trouble -- normally "case END" is the
- // terminating point.
- //
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("RegularExpression::find(): Internal error -- corrupted pointers.\n");
- return (0);
+ //
+ // We get here only if there's trouble -- normally "case END" is the
+ // terminating point.
+ //
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf("RegularExpression::find(): Internal error -- corrupted pointers.\n");
+ return (0);
}
-
/*
- regrepeat - repeatedly match something simple, report how many
*/
-static int regrepeat (const char* p) {
- int count = 0;
- const char* scan;
- const char* opnd;
-
- scan = reginput;
- opnd = OPERAND(p);
- switch (OP(p)) {
- case ANY:
- count = int(strlen(scan));
- scan += count;
- break;
- case EXACTLY:
- while (*opnd == *scan) {
- count++;
- scan++;
- }
- break;
- case ANYOF:
- while (*scan != '\0' && strchr(opnd, *scan) != 0) {
- count++;
- scan++;
- }
- break;
- case ANYBUT:
- while (*scan != '\0' && strchr(opnd, *scan) == 0) {
- count++;
- scan++;
- }
- break;
- default: // Oh dear. Called inappropriately.
- //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
- printf ("cm RegularExpression::find(): Internal error.\n");
- return 0;
- }
- reginput = scan;
- return (count);
+static int regrepeat(const char* p)
+{
+ int count = 0;
+ const char* scan;
+ const char* opnd;
+
+ scan = reginput;
+ opnd = OPERAND(p);
+ switch (OP(p)) {
+ case ANY:
+ count = int(strlen(scan));
+ scan += count;
+ break;
+ case EXACTLY:
+ while (*opnd == *scan) {
+ count++;
+ scan++;
+ }
+ break;
+ case ANYOF:
+ while (*scan != '\0' && strchr(opnd, *scan) != 0) {
+ count++;
+ scan++;
+ }
+ break;
+ case ANYBUT:
+ while (*scan != '\0' && strchr(opnd, *scan) == 0) {
+ count++;
+ scan++;
+ }
+ break;
+ default: // Oh dear. Called inappropriately.
+ // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+ printf("cm RegularExpression::find(): Internal error.\n");
+ return 0;
+ }
+ reginput = scan;
+ return (count);
}
-
/*
- regnext - dig the "next" pointer out of a node
*/
-static const char* regnext (const char* p) {
- int offset;
+static const char* regnext(const char* p)
+{
+ int offset;
- if (p == &regdummy)
- return (0);
+ if (p == &regdummy)
+ return (0);
- offset = NEXT(p);
- if (offset == 0)
- return (0);
+ offset = NEXT(p);
+ if (offset == 0)
+ return (0);
- if (OP(p) == BACK)
- return (p - offset);
- else
- return (p + offset);
+ if (OP(p) == BACK)
+ return (p - offset);
+ else
+ return (p + offset);
}
-static char* regnext (char* p) {
- int offset;
+static char* regnext(char* p)
+{
+ int offset;
- if (p == &regdummy)
- return (0);
+ if (p == &regdummy)
+ return (0);
- offset = NEXT(p);
- if (offset == 0)
- return (0);
+ offset = NEXT(p);
+ if (offset == 0)
+ return (0);
- if (OP(p) == BACK)
- return (p - offset);
- else
- return (p + offset);
+ if (OP(p) == BACK)
+ return (p - offset);
+ else
+ return (p + offset);
}
} // namespace KWSYS_NAMESPACE
diff --git a/Source/kwsys/RegularExpression.hxx.in b/Source/kwsys/RegularExpression.hxx.in
index 0bb700f..606e3da 100644
--- a/Source/kwsys/RegularExpression.hxx.in
+++ b/Source/kwsys/RegularExpression.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
// Original Copyright notice:
// Copyright (C) 1991 Texas Instruments Incorporated.
//
@@ -38,11 +29,10 @@
/* Disable useless Borland warnings. KWSys tries not to force things
on its includers, but there is no choice here. */
#if defined(__BORLANDC__)
-# pragma warn -8027 /* function not inlined. */
+#pragma warn - 8027 /* function not inlined. */
#endif
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
/** \class RegularExpression
* \brief Implements pattern matching with regular expressions.
@@ -68,10 +58,10 @@ namespace @KWSYS_NAMESPACE@
* and utilities.
*
* Example: The perl code
- *
+ *
* $filename =~ m"([a-z]+)\.cc";
* print $1;
- *
+ *
* Is written as follows in C++
*
* RegularExpression re("([a-z]+)\\.cc");
@@ -181,28 +171,28 @@ namespace @KWSYS_NAMESPACE@
* the line. It would match "drepa qrepb" in "rep drepa qrepb".
*
*/
-class @KWSYS_NAMESPACE@_EXPORT RegularExpression
+class @KWSYS_NAMESPACE@_EXPORT RegularExpression
{
public:
/**
* Instantiate RegularExpression with program=NULL.
*/
- inline RegularExpression ();
+ inline RegularExpression();
/**
* Instantiate RegularExpression with compiled char*.
*/
- inline RegularExpression (char const*);
+ inline RegularExpression(char const*);
/**
* Instantiate RegularExpression as a copy of another regular expression.
*/
- RegularExpression (RegularExpression const&);
+ RegularExpression(RegularExpression const&);
/**
* Instantiate RegularExpression with compiled string.
*/
- inline RegularExpression (std::string const&);
+ inline RegularExpression(std::string const&);
/**
* Destructor.
@@ -213,25 +203,25 @@ public:
* Compile a regular expression into internal code
* for later pattern matching.
*/
- bool compile (char const*);
+ bool compile(char const*);
/**
* Compile a regular expression into internal code
* for later pattern matching.
*/
- inline bool compile (std::string const&);
+ inline bool compile(std::string const&);
/**
* Matches the regular expression to the given string.
* Returns true if found, and sets start and end indexes accordingly.
*/
- bool find (char const*);
+ bool find(char const*);
/**
* Matches the regular expression to the given std string.
* Returns true if found, and sets start and end indexes accordingly.
*/
- inline bool find (std::string const&);
+ inline bool find(std::string const&);
/**
* Index to start of first find.
@@ -246,26 +236,26 @@ public:
/**
* Copy the given regular expression.
*/
- RegularExpression& operator= (const RegularExpression& rxp);
+ RegularExpression& operator=(const RegularExpression& rxp);
/**
* Returns true if two regular expressions have the same
* compiled program for pattern matching.
*/
- bool operator== (RegularExpression const&) const;
+ bool operator==(RegularExpression const&) const;
/**
* Returns true if two regular expressions have different
* compiled program for pattern matching.
*/
- inline bool operator!= (RegularExpression const&) const;
+ inline bool operator!=(RegularExpression const&) const;
/**
* Returns true if have the same compiled regular expressions
* and the same start and end pointers.
*/
- bool deep_equal (RegularExpression const&) const;
-
+ bool deep_equal(RegularExpression const&) const;
+
/**
* True if the compiled regexp is valid.
*/
@@ -274,7 +264,7 @@ public:
/**
* Marks the regular expression as invalid.
*/
- inline void set_invalid();
+ inline void set_invalid();
/**
* Destructor.
@@ -283,25 +273,29 @@ public:
std::string::size_type start(int n) const;
std::string::size_type end(int n) const;
std::string match(int n) const;
-
- enum { NSUBEXP = 10 };
-private:
+
+ enum
+ {
+ NSUBEXP = 10
+ };
+
+private:
const char* startp[NSUBEXP];
const char* endp[NSUBEXP];
- char regstart; // Internal use only
- char reganch; // Internal use only
- const char* regmust; // Internal use only
- std::string::size_type regmlen; // Internal use only
- char* program;
- int progsize;
+ char regstart; // Internal use only
+ char reganch; // Internal use only
+ const char* regmust; // Internal use only
+ std::string::size_type regmlen; // Internal use only
+ char* program;
+ int progsize;
const char* searchstring;
};
/**
* Create an empty regular expression.
*/
-inline RegularExpression::RegularExpression ()
-{
+inline RegularExpression::RegularExpression()
+{
this->program = 0;
}
@@ -309,20 +303,19 @@ inline RegularExpression::RegularExpression ()
* Creates a regular expression from string s, and
* compiles s.
*/
-inline RegularExpression::RegularExpression (const char* s)
-{
+inline RegularExpression::RegularExpression(const char* s)
+{
this->program = 0;
- if ( s )
- {
+ if (s) {
this->compile(s);
- }
+ }
}
/**
* Creates a regular expression from string s, and
* compiles s.
*/
-inline RegularExpression::RegularExpression (const std::string& s)
+inline RegularExpression::RegularExpression(const std::string& s)
{
this->program = 0;
this->compile(s);
@@ -331,18 +324,18 @@ inline RegularExpression::RegularExpression (const std::string& s)
/**
* Destroys and frees space allocated for the regular expression.
*/
-inline RegularExpression::~RegularExpression ()
+inline RegularExpression::~RegularExpression()
{
-//#ifndef _WIN32
- delete [] this->program;
-//#endif
+ //#ifndef _WIN32
+ delete[] this->program;
+ //#endif
}
/**
* Compile a regular expression into internal code
* for later pattern matching.
*/
-inline bool RegularExpression::compile (std::string const& s)
+inline bool RegularExpression::compile(std::string const& s)
{
return this->compile(s.c_str());
}
@@ -351,7 +344,7 @@ inline bool RegularExpression::compile (std::string const& s)
* Matches the regular expression to the given std string.
* Returns true if found, and sets start and end indexes accordingly.
*/
-inline bool RegularExpression::find (std::string const& s)
+inline bool RegularExpression::find(std::string const& s)
{
return this->find(s.c_str());
}
@@ -359,46 +352,42 @@ inline bool RegularExpression::find (std::string const& s)
/**
* Set the start position for the regular expression.
*/
-inline std::string::size_type RegularExpression::start () const
+inline std::string::size_type RegularExpression::start() const
{
- return static_cast<std::string::size_type>(
- this->startp[0] - searchstring);
+ return static_cast<std::string::size_type>(this->startp[0] - searchstring);
}
-
/**
* Returns the start/end index of the last item found.
*/
-inline std::string::size_type RegularExpression::end () const
+inline std::string::size_type RegularExpression::end() const
{
- return static_cast<std::string::size_type>(
- this->endp[0] - searchstring);
+ return static_cast<std::string::size_type>(this->endp[0] - searchstring);
}
/**
* Returns true if two regular expressions have different
* compiled program for pattern matching.
*/
-inline bool RegularExpression::operator!= (const RegularExpression& r) const
+inline bool RegularExpression::operator!=(const RegularExpression& r) const
{
- return(!(*this == r));
+ return (!(*this == r));
}
/**
* Returns true if a valid regular expression is compiled
* and ready for pattern matching.
*/
-inline bool RegularExpression::is_valid () const
+inline bool RegularExpression::is_valid() const
{
return (this->program != 0);
}
-
-inline void RegularExpression::set_invalid ()
+inline void RegularExpression::set_invalid()
{
-//#ifndef _WIN32
- delete [] this->program;
-//#endif
+ //#ifndef _WIN32
+ delete[] this->program;
+ //#endif
this->program = 0;
}
@@ -407,18 +396,15 @@ inline void RegularExpression::set_invalid ()
*/
inline std::string::size_type RegularExpression::start(int n) const
{
- return static_cast<std::string::size_type>(
- this->startp[n] - searchstring);
+ return static_cast<std::string::size_type>(this->startp[n] - searchstring);
}
-
/**
* Return end index of nth submatch. end(0) is the end of the full match.
*/
inline std::string::size_type RegularExpression::end(int n) const
{
- return static_cast<std::string::size_type>(
- this->endp[n] - searchstring);
+ return static_cast<std::string::size_type>(this->endp[n] - searchstring);
}
/**
@@ -426,16 +412,12 @@ inline std::string::size_type RegularExpression::end(int n) const
*/
inline std::string RegularExpression::match(int n) const
{
- if (this->startp[n]==0)
- {
+ if (this->startp[n] == 0) {
return std::string("");
- }
- else
- {
- return std::string(this->startp[n],
- static_cast<std::string::size_type>(
- this->endp[n] - this->startp[n]));
- }
+ } else {
+ return std::string(this->startp[n], static_cast<std::string::size_type>(
+ this->endp[n] - this->startp[n]));
+ }
}
} // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/SharedForward.h.in b/Source/kwsys/SharedForward.h.in
index f80ef84..c9ae135 100644
--- a/Source/kwsys/SharedForward.h.in
+++ b/Source/kwsys/SharedForward.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_SharedForward_h
#define @KWSYS_NAMESPACE@_SharedForward_h
@@ -30,7 +21,8 @@
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL "../lib/foo-1.2"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD CONFIG_DIR_PRE "foo-real"
- #define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL "../lib/foo-1.2/foo-real"
+ #define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL
+ "../lib/foo-1.2/foo-real"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND "--command"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT "--print"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD "--ldd"
@@ -68,16 +60,16 @@
/* Disable -Wcast-qual warnings since they are too hard to fix in a
cross-platform way. */
#if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wcast-qual")
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wcast-qual"
-# endif
+#if __has_warning("-Wcast-qual")
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wcast-qual"
+#endif
#endif
#if defined(__BORLANDC__) && !defined(__cplusplus)
- /* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
- unused parameter using "(param)" syntax (i.e. no cast to void). */
-# pragma warn -8019
+/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
+ unused parameter using "(param)" syntax (i.e. no cast to void). */
+#pragma warn - 8019
#endif
/*--------------------------------------------------------------------------*/
@@ -85,96 +77,107 @@
/* Full path to the directory in which this executable is built. Do
not include a trailing slash. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD)
-# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD"
+#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD"
#endif
#if !defined(KWSYS_SHARED_FORWARD_DIR_BUILD)
-# define KWSYS_SHARED_FORWARD_DIR_BUILD @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD
+#define KWSYS_SHARED_FORWARD_DIR_BUILD \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD
#endif
/* Library search path for build tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD)
-# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD"
+#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD"
#endif
#if !defined(KWSYS_SHARED_FORWARD_PATH_BUILD)
-# define KWSYS_SHARED_FORWARD_PATH_BUILD @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD
+#define KWSYS_SHARED_FORWARD_PATH_BUILD \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD
#endif
/* Library search path for install tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL)
-# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL"
+#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL"
#endif
#if !defined(KWSYS_SHARED_FORWARD_PATH_INSTALL)
-# define KWSYS_SHARED_FORWARD_PATH_INSTALL @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL
+#define KWSYS_SHARED_FORWARD_PATH_INSTALL \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL
#endif
/* The real executable to which to forward in the build tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD)
-# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD"
+#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD"
#endif
#if !defined(KWSYS_SHARED_FORWARD_EXE_BUILD)
-# define KWSYS_SHARED_FORWARD_EXE_BUILD @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD
+#define KWSYS_SHARED_FORWARD_EXE_BUILD \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD
#endif
/* The real executable to which to forward in the install tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL)
-# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL"
+#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL"
#endif
#if !defined(KWSYS_SHARED_FORWARD_EXE_INSTALL)
-# define KWSYS_SHARED_FORWARD_EXE_INSTALL @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL
+#define KWSYS_SHARED_FORWARD_EXE_INSTALL \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL
#endif
-/* The configuration name with which this executable was built (Debug/Release). */
+/* The configuration name with which this executable was built (Debug/Release).
+ */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME)
-# define KWSYS_SHARED_FORWARD_CONFIG_NAME @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME
+#define KWSYS_SHARED_FORWARD_CONFIG_NAME \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME
#else
-# undef KWSYS_SHARED_FORWARD_CONFIG_NAME
+#undef KWSYS_SHARED_FORWARD_CONFIG_NAME
#endif
/* Create command line option to replace executable. */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND)
-# if !defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
-# define KWSYS_SHARED_FORWARD_OPTION_COMMAND @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND
-# endif
+#if !defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
+#define KWSYS_SHARED_FORWARD_OPTION_COMMAND \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND
+#endif
#else
-# undef KWSYS_SHARED_FORWARD_OPTION_COMMAND
+#undef KWSYS_SHARED_FORWARD_OPTION_COMMAND
#endif
/* Create command line option to print environment setting and exit. */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT)
-# if !defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
-# define KWSYS_SHARED_FORWARD_OPTION_PRINT @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT
-# endif
+#if !defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
+#define KWSYS_SHARED_FORWARD_OPTION_PRINT \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT
+#endif
#else
-# undef KWSYS_SHARED_FORWARD_OPTION_PRINT
+#undef KWSYS_SHARED_FORWARD_OPTION_PRINT
#endif
/* Create command line option to run ldd or equivalent. */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD)
-# if !defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
-# define KWSYS_SHARED_FORWARD_OPTION_LDD @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD
-# endif
+#if !defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
+#define KWSYS_SHARED_FORWARD_OPTION_LDD \
+ @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD
+#endif
#else
-# undef KWSYS_SHARED_FORWARD_OPTION_LDD
+#undef KWSYS_SHARED_FORWARD_OPTION_LDD
#endif
/*--------------------------------------------------------------------------*/
/* Include needed system headers. */
-#include <stddef.h> /* size_t */
+#include <errno.h>
#include <limits.h>
+#include <stddef.h> /* size_t */
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <errno.h>
-#include <stdio.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
-# include <io.h>
-# include <windows.h>
-# include <process.h>
-# define KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* re-escape argv for execvp */
+#include <windows.h>
+
+#include <io.h>
+#include <process.h>
+#define KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* re-escape argv for execvp */
#else
-# include <unistd.h>
-# include <sys/stat.h>
+#include <sys/stat.h>
+#include <unistd.h>
#endif
/*--------------------------------------------------------------------------*/
@@ -182,22 +185,26 @@
/* The path separator for this platform. */
#if defined(_WIN32) && !defined(__CYGWIN__)
-# define KWSYS_SHARED_FORWARD_PATH_SEP ';'
-# define KWSYS_SHARED_FORWARD_PATH_SLASH '\\'
+#define KWSYS_SHARED_FORWARD_PATH_SEP ';'
+#define KWSYS_SHARED_FORWARD_PATH_SLASH '\\'
#else
-# define KWSYS_SHARED_FORWARD_PATH_SEP ':'
-# define KWSYS_SHARED_FORWARD_PATH_SLASH '/'
+#define KWSYS_SHARED_FORWARD_PATH_SEP ':'
+#define KWSYS_SHARED_FORWARD_PATH_SLASH '/'
#endif
-static const char kwsys_shared_forward_path_sep[2] = {KWSYS_SHARED_FORWARD_PATH_SEP, 0};
-static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PATH_SLASH, 0};
+static const char kwsys_shared_forward_path_sep[2] = {
+ KWSYS_SHARED_FORWARD_PATH_SEP, 0
+};
+static const char kwsys_shared_forward_path_slash[2] = {
+ KWSYS_SHARED_FORWARD_PATH_SLASH, 0
+};
/* The maximum length of a file name. */
#if defined(PATH_MAX)
-# define KWSYS_SHARED_FORWARD_MAXPATH PATH_MAX
+#define KWSYS_SHARED_FORWARD_MAXPATH PATH_MAX
#elif defined(MAXPATHLEN)
-# define KWSYS_SHARED_FORWARD_MAXPATH MAXPATHLEN
+#define KWSYS_SHARED_FORWARD_MAXPATH MAXPATHLEN
#else
-# define KWSYS_SHARED_FORWARD_MAXPATH 16384
+#define KWSYS_SHARED_FORWARD_MAXPATH 16384
#endif
/* Select the environment variable holding the shared library runtime
@@ -206,82 +213,82 @@ static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PAT
/* Linux */
#if defined(__linux)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
/* FreeBSD */
#elif defined(__FreeBSD__)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
/* OpenBSD */
#elif defined(__OpenBSD__)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
/* OSX */
#elif defined(__APPLE__)
-# define KWSYS_SHARED_FORWARD_LDD "otool", "-L"
-# define KWSYS_SHARED_FORWARD_LDD_N 2
-# define KWSYS_SHARED_FORWARD_LDPATH "DYLD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "otool", "-L"
+#define KWSYS_SHARED_FORWARD_LDD_N 2
+#define KWSYS_SHARED_FORWARD_LDPATH "DYLD_LIBRARY_PATH"
/* AIX */
#elif defined(_AIX)
-# define KWSYS_SHARED_FORWARD_LDD "dump", "-H"
-# define KWSYS_SHARED_FORWARD_LDD_N 2
-# define KWSYS_SHARED_FORWARD_LDPATH "LIBPATH"
+#define KWSYS_SHARED_FORWARD_LDD "dump", "-H"
+#define KWSYS_SHARED_FORWARD_LDD_N 2
+#define KWSYS_SHARED_FORWARD_LDPATH "LIBPATH"
/* SUN */
#elif defined(__sun)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# include <sys/isa_defs.h>
-# if defined(_ILP32)
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
-# elif defined(_LP64)
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH_64"
-# endif
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#include <sys/isa_defs.h>
+#if defined(_ILP32)
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#elif defined(_LP64)
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH_64"
+#endif
/* HP-UX */
#elif defined(__hpux)
-# define KWSYS_SHARED_FORWARD_LDD "chatr"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# if defined(__LP64__)
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
-# else
-# define KWSYS_SHARED_FORWARD_LDPATH "SHLIB_PATH"
-# endif
+#define KWSYS_SHARED_FORWARD_LDD "chatr"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#if defined(__LP64__)
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#else
+#define KWSYS_SHARED_FORWARD_LDPATH "SHLIB_PATH"
+#endif
/* SGI MIPS */
#elif defined(__sgi) && defined(_MIPS_SIM)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# if _MIPS_SIM == _ABIO32
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
-# elif _MIPS_SIM == _ABIN32
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARYN32_PATH"
-# elif _MIPS_SIM == _ABI64
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH"
-# endif
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#if _MIPS_SIM == _ABIO32
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#elif _MIPS_SIM == _ABIN32
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARYN32_PATH"
+#elif _MIPS_SIM == _ABI64
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH"
+#endif
/* Cygwin */
#elif defined(__CYGWIN__)
-# define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "PATH"
+#define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "PATH"
/* Windows */
#elif defined(_WIN32)
-# define KWSYS_SHARED_FORWARD_LDPATH "PATH"
+#define KWSYS_SHARED_FORWARD_LDPATH "PATH"
/* Guess on this unknown system. */
#else
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
#endif
#ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV
@@ -312,45 +319,37 @@ static kwsys_sf_arg_info kwsys_sf_get_arg_info(const char* in)
info.quote = 0;
/* Scan the string for characters that require escaping or quoting. */
- for(c=in; *c; ++c)
- {
+ for (c = in; *c; ++c) {
/* Check whether this character needs quotes. */
- if(strchr(" \t?'#&<>|^", *c))
- {
+ if (strchr(" \t?'#&<>|^", *c)) {
info.quote = 1;
- }
+ }
/* On Windows only backslashes and double-quotes need escaping. */
- if(*c == '\\')
- {
+ if (*c == '\\') {
/* Found a backslash. It may need to be escaped later. */
++windows_backslashes;
- }
- else if(*c == '"')
- {
+ } else if (*c == '"') {
/* Found a double-quote. We need to escape it and all
immediately preceding backslashes. */
info.size += windows_backslashes + 1;
windows_backslashes = 0;
- }
- else
- {
+ } else {
/* Found another character. This eliminates the possibility
that any immediately preceding backslashes will be
escaped. */
windows_backslashes = 0;
- }
}
+ }
/* Check whether the argument needs surrounding quotes. */
- if(info.quote)
- {
+ if (info.quote) {
/* Surrounding quotes are needed. Allocate space for them. */
info.size += 2;
/* We must escape all ending backslashes when quoting on windows. */
info.size += windows_backslashes;
- }
+ }
return info;
}
@@ -365,57 +364,47 @@ static char* kwsys_sf_get_arg(kwsys_sf_arg_info info, char* out)
int windows_backslashes = 0;
/* Whether the argument must be quoted. */
- if(info.quote)
- {
+ if (info.quote) {
/* Add the opening quote for this argument. */
*out++ = '"';
- }
+ }
/* Scan the string for characters that require escaping or quoting. */
- for(c=info.arg; *c; ++c)
- {
+ for (c = info.arg; *c; ++c) {
/* On Windows only backslashes and double-quotes need escaping. */
- if(*c == '\\')
- {
+ if (*c == '\\') {
/* Found a backslash. It may need to be escaped later. */
++windows_backslashes;
- }
- else if(*c == '"')
- {
+ } else if (*c == '"') {
/* Found a double-quote. Escape all immediately preceding
backslashes. */
- while(windows_backslashes > 0)
- {
+ while (windows_backslashes > 0) {
--windows_backslashes;
*out++ = '\\';
- }
+ }
/* Add the backslash to escape the double-quote. */
*out++ = '\\';
- }
- else
- {
+ } else {
/* We encountered a normal character. This eliminates any
escaping needed for preceding backslashes. */
windows_backslashes = 0;
- }
+ }
/* Store this character. */
*out++ = *c;
- }
+ }
- if(info.quote)
- {
+ if (info.quote) {
/* Add enough backslashes to escape any trailing ones. */
- while(windows_backslashes > 0)
- {
+ while (windows_backslashes > 0) {
--windows_backslashes;
*out++ = '\\';
- }
+ }
/* Add the closing quote for this argument. */
*out++ = '"';
- }
+ }
/* Store a terminating null without incrementing. */
*out = 0;
@@ -430,8 +419,8 @@ static int kwsys_shared_forward_realpath(const char* in_path, char* out_path)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Implementation for Windows. */
- DWORD n = GetFullPathNameA(in_path, KWSYS_SHARED_FORWARD_MAXPATH,
- out_path, 0);
+ DWORD n =
+ GetFullPathNameA(in_path, KWSYS_SHARED_FORWARD_MAXPATH, out_path, 0);
return n > 0 && n <= KWSYS_SHARED_FORWARD_MAXPATH;
#else
/* Implementation for UNIX. */
@@ -445,11 +434,10 @@ static int kwsys_shared_forward_samepath(const char* file1, const char* file2)
#if defined(_WIN32)
int result = 0;
HANDLE h1 = CreateFileA(file1, GENERIC_READ, FILE_SHARE_READ, NULL,
- OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
HANDLE h2 = CreateFileA(file2, GENERIC_READ, FILE_SHARE_READ, NULL,
- OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
- if(h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE)
- {
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+ if (h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE) {
BY_HANDLE_FILE_INFORMATION fi1;
BY_HANDLE_FILE_INFORMATION fi2;
GetFileInformationByHandle(h1, &fi1);
@@ -457,10 +445,10 @@ static int kwsys_shared_forward_samepath(const char* file1, const char* file2)
result = (fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber &&
fi1.nFileIndexHigh == fi2.nFileIndexHigh &&
fi1.nFileIndexLow == fi2.nFileIndexLow);
- }
- CloseHandle(h1);
- CloseHandle(h2);
- return result;
+ }
+ CloseHandle(h1);
+ CloseHandle(h2);
+ return result;
#else
struct stat fs1, fs2;
return (stat(file1, &fs1) == 0 && stat(file2, &fs2) == 0 &&
@@ -477,17 +465,16 @@ static void kwsys_shared_forward_strerror(char* message)
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Implementation for Windows. */
DWORD original = GetLastError();
- DWORD length = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS, 0, original,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- message, KWSYS_SHARED_FORWARD_MAXPATH, 0);
- if(length < 1 || length > KWSYS_SHARED_FORWARD_MAXPATH)
- {
+ DWORD length =
+ FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+ 0, original, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ message, KWSYS_SHARED_FORWARD_MAXPATH, 0);
+ if (length < 1 || length > KWSYS_SHARED_FORWARD_MAXPATH) {
/* FormatMessage failed. Use a default message. */
_snprintf(message, KWSYS_SHARED_FORWARD_MAXPATH,
- "Error 0x%X (FormatMessage failed with error 0x%X)",
- original, GetLastError());
- }
+ "Error 0x%X (FormatMessage failed with error 0x%X)", original,
+ GetLastError());
+ }
#else
/* Implementation for UNIX. */
strcpy(message, strerror(errno));
@@ -503,28 +490,28 @@ static void kwsys_shared_forward_execvp(const char* cmd,
/* Count the number of arguments. */
int argc = 0;
{
- char const* const* argvc;
- for(argvc = argv; *argvc; ++argvc,++argc) {}
+ char const* const* argvc;
+ for (argvc = argv; *argvc; ++argvc, ++argc) {
+ }
}
/* Create the escaped arguments. */
{
- char** nargv = (char**)malloc((argc+1) * sizeof(char*));
- int i;
- for(i=0; i < argc; ++i)
- {
- kwsys_sf_arg_info info = kwsys_sf_get_arg_info(argv[i]);
- nargv[i] = (char*)malloc(info.size);
- kwsys_sf_get_arg(info, nargv[i]);
+ char** nargv = (char**)malloc((argc + 1) * sizeof(char*));
+ int i;
+ for (i = 0; i < argc; ++i) {
+ kwsys_sf_arg_info info = kwsys_sf_get_arg_info(argv[i]);
+ nargv[i] = (char*)malloc(info.size);
+ kwsys_sf_get_arg(info, nargv[i]);
}
- nargv[argc] = 0;
+ nargv[argc] = 0;
- /* Replace the command line to be used. */
- argv = (char const* const*)nargv;
+ /* Replace the command line to be used. */
+ argv = (char const* const*)nargv;
}
#endif
- /* Invoke the child process. */
+/* Invoke the child process. */
#if defined(_MSC_VER)
_execvp(cmd, argv);
#elif defined(__MINGW32__) && !defined(__MINGW64__)
@@ -541,40 +528,33 @@ static void kwsys_shared_forward_dirname(const char* begin, char* result)
/* Find the location of the last slash. */
int last_slash_index = -1;
const char* end = begin + strlen(begin);
- for(;begin <= end && last_slash_index < 0; --end)
- {
- if(*end == '/' || *end == '\\')
- {
- last_slash_index = (int)(end-begin);
- }
+ for (; begin <= end && last_slash_index < 0; --end) {
+ if (*end == '/' || *end == '\\') {
+ last_slash_index = (int)(end - begin);
}
+ }
/* Handle each case of the index of the last slash. */
- if(last_slash_index < 0)
- {
+ if (last_slash_index < 0) {
/* No slashes. */
strcpy(result, ".");
- }
- else if(last_slash_index == 0)
- {
+ } else if (last_slash_index == 0) {
/* Only one leading slash. */
strcpy(result, kwsys_shared_forward_path_slash);
- }
+ }
#if defined(_WIN32)
- else if(last_slash_index == 2 && begin[1] == ':')
- {
+ else if (last_slash_index == 2 && begin[1] == ':') {
/* Only one leading drive letter and slash. */
strncpy(result, begin, (size_t)last_slash_index);
result[last_slash_index] = KWSYS_SHARED_FORWARD_PATH_SLASH;
- result[last_slash_index+1] = 0;
- }
+ result[last_slash_index + 1] = 0;
+ }
#endif
- else
- {
+ else {
/* A non-leading slash. */
strncpy(result, begin, (size_t)last_slash_index);
result[last_slash_index] = 0;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -582,23 +562,20 @@ static void kwsys_shared_forward_dirname(const char* begin, char* result)
static int kwsys_shared_forward_is_executable(const char* f)
{
#if defined(_MSC_VER)
-# define KWSYS_SHARED_FORWARD_ACCESS _access
+#define KWSYS_SHARED_FORWARD_ACCESS _access
#else
-# define KWSYS_SHARED_FORWARD_ACCESS access
+#define KWSYS_SHARED_FORWARD_ACCESS access
#endif
#if defined(X_OK)
-# define KWSYS_SHARED_FORWARD_ACCESS_OK X_OK
+#define KWSYS_SHARED_FORWARD_ACCESS_OK X_OK
#else
-# define KWSYS_SHARED_FORWARD_ACCESS_OK 04
+#define KWSYS_SHARED_FORWARD_ACCESS_OK 04
#endif
- if(KWSYS_SHARED_FORWARD_ACCESS(f, KWSYS_SHARED_FORWARD_ACCESS_OK) == 0)
- {
+ if (KWSYS_SHARED_FORWARD_ACCESS(f, KWSYS_SHARED_FORWARD_ACCESS_OK) == 0) {
return 1;
- }
- else
- {
+ } else {
return 0;
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -608,66 +585,60 @@ static int kwsys_shared_forward_self_path(const char* argv0, char* result)
/* Check whether argv0 has a slash. */
int has_slash = 0;
const char* p = argv0;
- for(;*p && !has_slash; ++p)
- {
- if(*p == '/' || *p == '\\')
- {
+ for (; *p && !has_slash; ++p) {
+ if (*p == '/' || *p == '\\') {
has_slash = 1;
- }
}
+ }
- if(has_slash)
- {
+ if (has_slash) {
/* There is a slash. Use the dirname of the given location. */
kwsys_shared_forward_dirname(argv0, result);
return 1;
- }
- else
- {
+ } else {
/* There is no slash. Search the PATH for the executable. */
const char* path = getenv("PATH");
const char* begin = path;
- const char* end = begin + (begin?strlen(begin):0);
+ const char* end = begin + (begin ? strlen(begin) : 0);
const char* first = begin;
- while(first != end)
- {
+ while (first != end) {
/* Store the end of this path entry. */
const char* last;
/* Skip all path separators. */
- for(;*first && *first == KWSYS_SHARED_FORWARD_PATH_SEP; ++first);
+ for (; *first && *first == KWSYS_SHARED_FORWARD_PATH_SEP; ++first)
+ ;
/* Find the next separator. */
- for(last = first;*last && *last != KWSYS_SHARED_FORWARD_PATH_SEP; ++last);
+ for (last = first; *last && *last != KWSYS_SHARED_FORWARD_PATH_SEP;
+ ++last)
+ ;
/* If we got a non-empty directory, look for the executable there. */
- if(first < last)
- {
+ if (first < last) {
/* Determine the length without trailing slash. */
- size_t length = (size_t)(last-first);
- if(*(last-1) == '/' || *(last-1) == '\\')
- {
+ size_t length = (size_t)(last - first);
+ if (*(last - 1) == '/' || *(last - 1) == '\\') {
--length;
- }
+ }
/* Construct the name of the executable in this location. */
strncpy(result, first, length);
result[length] = KWSYS_SHARED_FORWARD_PATH_SLASH;
- strcpy(result+(length)+1, argv0);
+ strcpy(result + (length) + 1, argv0);
/* Check if it exists and is executable. */
- if(kwsys_shared_forward_is_executable(result))
- {
+ if (kwsys_shared_forward_is_executable(result)) {
/* Found it. */
result[length] = 0;
return 1;
- }
}
+ }
/* Move to the next directory in the path. */
first = last;
- }
}
+ }
/* We could not find the executable. */
return 0;
@@ -677,42 +648,36 @@ static int kwsys_shared_forward_self_path(const char* argv0, char* result)
/* Function to convert a specified path to a full path. If it is not
already full, it is taken relative to the self path. */
static int kwsys_shared_forward_fullpath(const char* self_path,
- const char* in_path,
- char* result,
+ const char* in_path, char* result,
const char* desc)
{
/* Check the specified path type. */
- if(in_path[0] == '/')
- {
+ if (in_path[0] == '/') {
/* Already a full path. */
strcpy(result, in_path);
- }
+ }
#if defined(_WIN32)
- else if(in_path[0] && in_path[1] == ':')
- {
+ else if (in_path[0] && in_path[1] == ':') {
/* Already a full path. */
strcpy(result, in_path);
- }
+ }
#endif
- else
- {
+ else {
/* Relative to self path. */
char temp_path[KWSYS_SHARED_FORWARD_MAXPATH];
strcpy(temp_path, self_path);
strcat(temp_path, kwsys_shared_forward_path_slash);
strcat(temp_path, in_path);
- if(!kwsys_shared_forward_realpath(temp_path, result))
- {
- if(desc)
- {
+ if (!kwsys_shared_forward_realpath(temp_path, result)) {
+ if (desc) {
char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
kwsys_shared_forward_strerror(msgbuf);
- fprintf(stderr, "Error converting %s \"%s\" to real path: %s\n",
- desc, temp_path, msgbuf);
- }
- return 0;
+ fprintf(stderr, "Error converting %s \"%s\" to real path: %s\n", desc,
+ temp_path, msgbuf);
}
+ return 0;
}
+ }
return 1;
}
@@ -723,16 +688,20 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
char* ldpath, char* exe)
{
/* Possible search paths. */
- static const char* search_path_build[] = {KWSYS_SHARED_FORWARD_PATH_BUILD, 0};
- static const char* search_path_install[] = {KWSYS_SHARED_FORWARD_PATH_INSTALL, 0};
+ static const char* search_path_build[] = { KWSYS_SHARED_FORWARD_PATH_BUILD,
+ 0 };
+ static const char* search_path_install[] = {
+ KWSYS_SHARED_FORWARD_PATH_INSTALL, 0
+ };
/* Chosen paths. */
const char** search_path;
const char* exe_path;
- /* Get the real name of the build and self paths. */
+/* Get the real name of the build and self paths. */
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
- char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD "/" KWSYS_SHARED_FORWARD_CONFIG_NAME;
+ char build_path[] =
+ KWSYS_SHARED_FORWARD_DIR_BUILD "/" KWSYS_SHARED_FORWARD_CONFIG_NAME;
char self_path_logical[KWSYS_SHARED_FORWARD_MAXPATH];
#else
char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD;
@@ -740,19 +709,17 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
#endif
char build_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
char self_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
- if(!kwsys_shared_forward_realpath(self_path, self_path_real))
- {
+ if (!kwsys_shared_forward_realpath(self_path, self_path_real)) {
char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
kwsys_shared_forward_strerror(msgbuf);
fprintf(stderr, "Error converting self path \"%s\" to real path: %s\n",
self_path, msgbuf);
return 0;
- }
+ }
/* Check whether we are running in the build tree or an install tree. */
- if(kwsys_shared_forward_realpath(build_path, build_path_real) &&
- kwsys_shared_forward_samepath(self_path_real, build_path_real))
- {
+ if (kwsys_shared_forward_realpath(build_path, build_path_real) &&
+ kwsys_shared_forward_samepath(self_path_real, build_path_real)) {
/* Running in build tree. Use the build path and exe. */
search_path = search_path_build;
#if defined(_WIN32)
@@ -765,9 +732,7 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
/* Remove the configuration directory from self_path. */
kwsys_shared_forward_dirname(self_path, self_path_logical);
#endif
- }
- else
- {
+ } else {
/* Running in install tree. Use the install path and exe. */
search_path = search_path_install;
#if defined(_WIN32)
@@ -780,35 +745,31 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
/* Use the original self path directory. */
strcpy(self_path_logical, self_path);
#endif
- }
+ }
/* Construct the runtime search path. */
{
- const char** dir;
- for(dir = search_path; *dir; ++dir)
- {
- /* Add separator between path components. */
- if(dir != search_path)
- {
- strcat(ldpath, kwsys_shared_forward_path_sep);
+ const char** dir;
+ for (dir = search_path; *dir; ++dir) {
+ /* Add separator between path components. */
+ if (dir != search_path) {
+ strcat(ldpath, kwsys_shared_forward_path_sep);
}
- /* Add this path component. */
- if(!kwsys_shared_forward_fullpath(self_path_logical, *dir,
- ldpath+strlen(ldpath),
- "runtime path entry"))
- {
- return 0;
+ /* Add this path component. */
+ if (!kwsys_shared_forward_fullpath(self_path_logical, *dir,
+ ldpath + strlen(ldpath),
+ "runtime path entry")) {
+ return 0;
}
}
}
/* Construct the executable location. */
- if(!kwsys_shared_forward_fullpath(self_path_logical, exe_path, exe,
- "executable file"))
- {
+ if (!kwsys_shared_forward_fullpath(self_path_logical, exe_path, exe,
+ "executable file")) {
return 0;
- }
+ }
return 1;
}
@@ -820,15 +781,15 @@ static void kwsys_shared_forward_print_failure(char const* const* argv)
char const* const* arg = argv;
kwsys_shared_forward_strerror(msg);
fprintf(stderr, "Error running");
- for(; *arg; ++arg)
- {
+ for (; *arg; ++arg) {
fprintf(stderr, " \"%s\"", *arg);
- }
+ }
fprintf(stderr, ": %s\n", msg);
}
/* Static storage space to store the updated environment variable. */
-static char kwsys_shared_forward_ldpath[65535] = KWSYS_SHARED_FORWARD_LDPATH "=";
+static char kwsys_shared_forward_ldpath[65535] =
+ KWSYS_SHARED_FORWARD_LDPATH "=";
/*--------------------------------------------------------------------------*/
/* Main driver function to be called from main. */
@@ -837,74 +798,67 @@ static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv_in)
char const** argv = (char const**)argv_in;
/* Get the directory containing this executable. */
char self_path[KWSYS_SHARED_FORWARD_MAXPATH];
- if(kwsys_shared_forward_self_path(argv[0], self_path))
- {
+ if (kwsys_shared_forward_self_path(argv[0], self_path)) {
/* Found this executable. Use it to get the library directory. */
char exe[KWSYS_SHARED_FORWARD_MAXPATH];
- if(kwsys_shared_forward_get_settings(self_path,
- kwsys_shared_forward_ldpath, exe))
- {
+ if (kwsys_shared_forward_get_settings(self_path,
+ kwsys_shared_forward_ldpath, exe)) {
/* Append the old runtime search path. */
const char* old_ldpath = getenv(KWSYS_SHARED_FORWARD_LDPATH);
- if(old_ldpath)
- {
+ if (old_ldpath) {
strcat(kwsys_shared_forward_ldpath, kwsys_shared_forward_path_sep);
strcat(kwsys_shared_forward_ldpath, old_ldpath);
- }
+ }
/* Store the environment variable. */
putenv(kwsys_shared_forward_ldpath);
#if defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
/* Look for the command line replacement option. */
- if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_COMMAND) == 0)
- {
- if(argc > 2)
- {
+ if (argc > 1 &&
+ strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_COMMAND) == 0) {
+ if (argc > 2) {
/* Use the command line given. */
strcpy(exe, argv[2]);
argv += 2;
argc -= 2;
- }
- else
- {
+ } else {
/* The option was not given an executable. */
fprintf(stderr, "Option " KWSYS_SHARED_FORWARD_OPTION_COMMAND
- " must be followed by a command line.\n");
+ " must be followed by a command line.\n");
return 1;
- }
}
+ }
#endif
#if defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
/* Look for the print command line option. */
- if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_PRINT) == 0)
- {
+ if (argc > 1 &&
+ strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_PRINT) == 0) {
fprintf(stdout, "%s\n", kwsys_shared_forward_ldpath);
fprintf(stdout, "%s\n", exe);
return 0;
- }
+ }
#endif
#if defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
/* Look for the ldd command line option. */
- if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_LDD) == 0)
- {
-# if defined(KWSYS_SHARED_FORWARD_LDD)
+ if (argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_LDD) == 0) {
+#if defined(KWSYS_SHARED_FORWARD_LDD)
/* Use the named ldd-like executable and arguments. */
- char const* ldd_argv[] = {KWSYS_SHARED_FORWARD_LDD, 0, 0};
+ char const* ldd_argv[] = { KWSYS_SHARED_FORWARD_LDD, 0, 0 };
ldd_argv[KWSYS_SHARED_FORWARD_LDD_N] = exe;
kwsys_shared_forward_execvp(ldd_argv[0], ldd_argv);
/* Report why execution failed. */
kwsys_shared_forward_print_failure(ldd_argv);
return 1;
-# else
+#else
/* We have no ldd-like executable available on this platform. */
fprintf(stderr, "No ldd-like tool is known to this executable.\n");
return 1;
-# endif
- }
+#endif
+ }
#endif
/* Replace this process with the real executable. */
@@ -913,17 +867,13 @@ static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv_in)
/* Report why execution failed. */
kwsys_shared_forward_print_failure(argv);
- }
- else
- {
+ } else {
/* Could not convert self path to the library directory. */
- }
}
- else
- {
+ } else {
/* Could not find this executable. */
fprintf(stderr, "Error locating executable \"%s\".\n", argv[0]);
- }
+ }
/* Avoid unused argument warning. */
(void)argc;
@@ -934,11 +884,11 @@ static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv_in)
/* Restore warning stack. */
#if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wcast-qual")
-# pragma clang diagnostic pop
-# endif
+#if __has_warning("-Wcast-qual")
+#pragma clang diagnostic pop
+#endif
#endif
#else
-# error "@KWSYS_NAMESPACE@/SharedForward.h should be included only once."
+#error "@KWSYS_NAMESPACE@/SharedForward.h should be included only once."
#endif
diff --git a/Source/kwsys/String.c b/Source/kwsys/String.c
index ed4a6c5..0482229 100644
--- a/Source/kwsys/String.c
+++ b/Source/kwsys/String.c
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifdef KWSYS_STRING_C
/*
All code in this source file is conditionally compiled to work-around
@@ -23,53 +14,49 @@ condition blocks the compiler from seeing the symbols defined here.
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "String.h.in"
+#include "String.h.in"
#endif
/* Select an implementation for strcasecmp. */
#if defined(_MSC_VER)
-# define KWSYS_STRING_USE_STRICMP
-# include <string.h>
+#define KWSYS_STRING_USE_STRICMP
+#include <string.h>
#elif defined(__GNUC__)
-# define KWSYS_STRING_USE_STRCASECMP
-# include <strings.h>
+#define KWSYS_STRING_USE_STRCASECMP
+#include <strings.h>
#else
/* Table to convert upper case letters to lower case and leave all
other characters alone. */
-static char kwsysString_strcasecmp_tolower[] =
-{
- '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
- '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
- '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
- '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
- '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
- '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
- '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
- '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
- '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
- '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
- '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
- '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
- '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
- '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
- '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
- '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
- '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
- '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
- '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
- '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
- '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
- '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
- '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
- '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
- '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
- '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
- '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
- '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
- '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
- '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
- '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
- '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377'
+static char kwsysString_strcasecmp_tolower[] = {
+ '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010',
+ '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021',
+ '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032',
+ '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043',
+ '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054',
+ '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065',
+ '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076',
+ '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
+ '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
+ '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171',
+ '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142',
+ '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153',
+ '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164',
+ '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175',
+ '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206',
+ '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
+ '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230',
+ '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\241',
+ '\242', '\243', '\244', '\245', '\246', '\247', '\250', '\251', '\252',
+ '\253', '\254', '\255', '\256', '\257', '\260', '\261', '\262', '\263',
+ '\264', '\265', '\266', '\267', '\270', '\271', '\272', '\273', '\274',
+ '\275', '\276', '\277', '\300', '\301', '\302', '\303', '\304', '\305',
+ '\306', '\307', '\310', '\311', '\312', '\313', '\314', '\315', '\316',
+ '\317', '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
+ '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340',
+ '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351',
+ '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362',
+ '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373',
+ '\374', '\375', '\376', '\377'
};
#endif
@@ -85,9 +72,8 @@ int kwsysString_strcasecmp(const char* lhs, const char* rhs)
unsigned char const* us1 = (unsigned char const*)lhs;
unsigned char const* us2 = (unsigned char const*)rhs;
int result;
- while((result = lower[*us1] - lower[*us2++], result == 0) && *us1++)
- {
- }
+ while ((result = lower[*us1] - lower[*us2++], result == 0) && *us1++) {
+ }
return result;
#endif
}
@@ -104,10 +90,9 @@ int kwsysString_strncasecmp(const char* lhs, const char* rhs, size_t n)
unsigned char const* us1 = (unsigned char const*)lhs;
unsigned char const* us2 = (unsigned char const*)rhs;
int result = 0;
- while(n && (result = lower[*us1] - lower[*us2++], result == 0) && *us1++)
- {
+ while (n && (result = lower[*us1] - lower[*us2++], result == 0) && *us1++) {
--n;
- }
+ }
return result;
#endif
}
diff --git a/Source/kwsys/String.h.in b/Source/kwsys/String.h.in
index f5bab6e..3c1d571 100644
--- a/Source/kwsys/String.h.in
+++ b/Source/kwsys/String.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_String_h
#define @KWSYS_NAMESPACE@_String_h
@@ -21,17 +12,16 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysString_strcasecmp kwsys_ns(String_strcasecmp)
-# define kwsysString_strncasecmp kwsys_ns(String_strncasecmp)
+#define kwsysString_strcasecmp kwsys_ns(String_strcasecmp)
+#define kwsysString_strncasecmp kwsys_ns(String_strncasecmp)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
/**
@@ -56,12 +46,12 @@ kwsysEXPORT int kwsysString_strncasecmp(const char* lhs, const char* rhs,
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysString_strcasecmp
-# undef kwsysString_strncasecmp
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysString_strcasecmp
+#undef kwsysString_strncasecmp
+#endif
#endif
#endif
diff --git a/Source/kwsys/String.hxx.in b/Source/kwsys/String.hxx.in
index 2e9aedb..db1cf22 100644
--- a/Source/kwsys/String.hxx.in
+++ b/Source/kwsys/String.hxx.in
@@ -1,21 +1,11 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_String_hxx
#define @KWSYS_NAMESPACE@_String_hxx
#include <string>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
/** \class String
* \brief Short-name version of the STL basic_string class template.
@@ -25,39 +15,49 @@ namespace @KWSYS_NAMESPACE@
* simply a subclass of this type with the same interface so that the
* name is shorter in debugging symbols and error messages.
*/
-class String: public std::string
+class String : public std::string
{
/** The original string type. */
typedef std::string stl_string;
public:
-
/** String member types. */
- typedef stl_string::value_type value_type;
- typedef stl_string::pointer pointer;
- typedef stl_string::reference reference;
- typedef stl_string::const_reference const_reference;
- typedef stl_string::size_type size_type;
- typedef stl_string::difference_type difference_type;
- typedef stl_string::iterator iterator;
- typedef stl_string::const_iterator const_iterator;
- typedef stl_string::reverse_iterator reverse_iterator;
+ typedef stl_string::value_type value_type;
+ typedef stl_string::pointer pointer;
+ typedef stl_string::reference reference;
+ typedef stl_string::const_reference const_reference;
+ typedef stl_string::size_type size_type;
+ typedef stl_string::difference_type difference_type;
+ typedef stl_string::iterator iterator;
+ typedef stl_string::const_iterator const_iterator;
+ typedef stl_string::reverse_iterator reverse_iterator;
typedef stl_string::const_reverse_iterator const_reverse_iterator;
/** String constructors. */
- String(): stl_string() {}
- String(const value_type* s): stl_string(s) {}
- String(const value_type* s, size_type n): stl_string(s, n) {}
- String(const stl_string& s, size_type pos=0, size_type n=npos):
- stl_string(s, pos, n) {}
+ String()
+ : stl_string()
+ {
+ }
+ String(const value_type* s)
+ : stl_string(s)
+ {
+ }
+ String(const value_type* s, size_type n)
+ : stl_string(s, n)
+ {
+ }
+ String(const stl_string& s, size_type pos = 0, size_type n = npos)
+ : stl_string(s, pos, n)
+ {
+ }
}; // End Class: String
#if defined(__WATCOMC__)
inline bool operator<(String const& l, String const& r)
- {
+{
return (static_cast<std::string const&>(l) <
static_cast<std::string const&>(r));
- }
+}
#endif
} // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/System.c b/Source/kwsys/System.c
index ccc7e81..43c60c5 100644
--- a/Source/kwsys/System.c
+++ b/Source/kwsys/System.c
@@ -1,27 +1,18 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(System.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "System.h.in"
+#include "System.h.in"
#endif
+#include <ctype.h> /* isspace */
#include <stddef.h> /* ptrdiff_t */
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memcpy */
-#include <ctype.h> /* isspace */
#include <stdio.h>
@@ -32,28 +23,24 @@ typedef int kwsysSystem_ptrdiff_t;
#endif
/*--------------------------------------------------------------------------*/
-static int kwsysSystem__AppendByte(char* local,
- char** begin, char** end,
+static int kwsysSystem__AppendByte(char* local, char** begin, char** end,
int* size, char c)
{
/* Allocate space for the character. */
- if((*end - *begin) >= *size)
- {
+ if ((*end - *begin) >= *size) {
kwsysSystem_ptrdiff_t length = *end - *begin;
- char* newBuffer = (char*)malloc((size_t)(*size*2));
- if(!newBuffer)
- {
+ char* newBuffer = (char*)malloc((size_t)(*size * 2));
+ if (!newBuffer) {
return 0;
- }
- memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char));
- if(*begin != local)
- {
+ }
+ memcpy(newBuffer, *begin, (size_t)(length) * sizeof(char));
+ if (*begin != local) {
free(*begin);
- }
+ }
*begin = newBuffer;
*end = *begin + length;
*size *= 2;
- }
+ }
/* Store the character. */
*(*end)++ = c;
@@ -61,47 +48,41 @@ static int kwsysSystem__AppendByte(char* local,
}
/*--------------------------------------------------------------------------*/
-static int kwsysSystem__AppendArgument(char** local,
- char*** begin, char*** end,
- int* size,
- char* arg_local,
+static int kwsysSystem__AppendArgument(char** local, char*** begin,
+ char*** end, int* size, char* arg_local,
char** arg_begin, char** arg_end,
int* arg_size)
{
/* Append a null-terminator to the argument string. */
- if(!kwsysSystem__AppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
- {
+ if (!kwsysSystem__AppendByte(arg_local, arg_begin, arg_end, arg_size,
+ '\0')) {
return 0;
- }
+ }
/* Allocate space for the argument pointer. */
- if((*end - *begin) >= *size)
- {
+ if ((*end - *begin) >= *size) {
kwsysSystem_ptrdiff_t length = *end - *begin;
- char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*));
- if(!newPointers)
- {
+ char** newPointers = (char**)malloc((size_t)(*size) * 2 * sizeof(char*));
+ if (!newPointers) {
return 0;
- }
- memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*));
- if(*begin != local)
- {
+ }
+ memcpy(newPointers, *begin, (size_t)(length) * sizeof(char*));
+ if (*begin != local) {
free(*begin);
- }
+ }
*begin = newPointers;
*end = *begin + length;
*size *= 2;
- }
+ }
/* Allocate space for the argument string. */
**end = (char*)malloc((size_t)(*arg_end - *arg_begin));
- if(!**end)
- {
+ if (!**end) {
return 0;
- }
+ }
/* Store the argument in the command array. */
- memcpy(**end, *arg_begin,(size_t)(*arg_end - *arg_begin));
+ memcpy(**end, *arg_begin, (size_t)(*arg_end - *arg_begin));
++(*end);
/* Reset the argument to be empty. */
@@ -135,150 +116,109 @@ static char** kwsysSystem__ParseUnixCommand(const char* command, int flags)
int in_single = 0;
int in_double = 0;
int failed = 0;
- for(;*c; ++c)
- {
- if(in_escape)
- {
+ for (; *c; ++c) {
+ if (in_escape) {
/* This character is escaped so do no special handling. */
- if(!in_argument)
- {
+ if (!in_argument) {
in_argument = 1;
- }
- if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
- &buffer_end, &buffer_size, *c))
- {
+ }
+ if (!kwsysSystem__AppendByte(local_buffer, &buffer_begin, &buffer_end,
+ &buffer_size, *c)) {
failed = 1;
break;
- }
- in_escape = 0;
}
- else if(*c == '\\')
- {
+ in_escape = 0;
+ } else if (*c == '\\') {
/* The next character should be escaped. */
in_escape = 1;
- }
- else if(*c == '\'' && !in_double)
- {
+ } else if (*c == '\'' && !in_double) {
/* Enter or exit single-quote state. */
- if(in_single)
- {
+ if (in_single) {
in_single = 0;
- }
- else
- {
+ } else {
in_single = 1;
- if(!in_argument)
- {
+ if (!in_argument) {
in_argument = 1;
- }
}
}
- else if(*c == '"' && !in_single)
- {
+ } else if (*c == '"' && !in_single) {
/* Enter or exit double-quote state. */
- if(in_double)
- {
+ if (in_double) {
in_double = 0;
- }
- else
- {
+ } else {
in_double = 1;
- if(!in_argument)
- {
+ if (!in_argument) {
in_argument = 1;
- }
}
}
- else if(isspace((unsigned char) *c))
- {
- if(in_argument)
- {
- if(in_single || in_double)
- {
+ } else if (isspace((unsigned char)*c)) {
+ if (in_argument) {
+ if (in_single || in_double) {
/* This space belongs to a quoted argument. */
- if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
- &buffer_end, &buffer_size, *c))
- {
+ if (!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
+ &buffer_end, &buffer_size, *c)) {
failed = 1;
break;
- }
}
- else
- {
+ } else {
/* This argument has been terminated by whitespace. */
- if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin,
- &pointer_end, &pointers_size,
- local_buffer, &buffer_begin,
- &buffer_end, &buffer_size))
- {
+ if (!kwsysSystem__AppendArgument(
+ local_pointers, &pointer_begin, &pointer_end, &pointers_size,
+ local_buffer, &buffer_begin, &buffer_end, &buffer_size)) {
failed = 1;
break;
- }
- in_argument = 0;
}
+ in_argument = 0;
}
}
- else
- {
+ } else {
/* This character belong to an argument. */
- if(!in_argument)
- {
+ if (!in_argument) {
in_argument = 1;
- }
- if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
- &buffer_end, &buffer_size, *c))
- {
+ }
+ if (!kwsysSystem__AppendByte(local_buffer, &buffer_begin, &buffer_end,
+ &buffer_size, *c)) {
failed = 1;
break;
- }
}
}
+ }
/* Finish the last argument. */
- if(in_argument)
- {
- if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin,
- &pointer_end, &pointers_size,
- local_buffer, &buffer_begin,
- &buffer_end, &buffer_size))
- {
+ if (in_argument) {
+ if (!kwsysSystem__AppendArgument(
+ local_pointers, &pointer_begin, &pointer_end, &pointers_size,
+ local_buffer, &buffer_begin, &buffer_end, &buffer_size)) {
failed = 1;
- }
}
+ }
/* If we still have memory allocate space for the new command
buffer. */
- if(!failed)
- {
+ if (!failed) {
kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin;
- newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*));
- }
+ newCommand = (char**)malloc((size_t)(n + 1) * sizeof(char*));
+ }
- if(newCommand)
- {
+ if (newCommand) {
/* Copy the arguments into the new command buffer. */
kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin;
- memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n));
+ memcpy(newCommand, pointer_begin, sizeof(char*) * (size_t)(n));
newCommand[n] = 0;
- }
- else
- {
+ } else {
/* Free arguments already allocated. */
- while(pointer_end != pointer_begin)
- {
+ while (pointer_end != pointer_begin) {
free(*(--pointer_end));
- }
}
+ }
/* Free temporary buffers. */
- if(pointer_begin != local_pointers)
- {
+ if (pointer_begin != local_pointers) {
free(pointer_begin);
- }
- if(buffer_begin != local_buffer)
- {
+ }
+ if (buffer_begin != local_buffer) {
free(buffer_begin);
- }
+ }
/* The flags argument is currently unused. */
(void)flags;
@@ -291,10 +231,9 @@ static char** kwsysSystem__ParseUnixCommand(const char* command, int flags)
char** kwsysSystem_Parse_CommandForUnix(const char* command, int flags)
{
/* Validate the flags. */
- if(flags != 0)
- {
+ if (flags != 0) {
return 0;
- }
+ }
/* Forward to our internal implementation. */
return kwsysSystem__ParseUnixCommand(command, flags);
diff --git a/Source/kwsys/System.h.in b/Source/kwsys/System.h.in
index 3f3d3f4..102974d 100644
--- a/Source/kwsys/System.h.in
+++ b/Source/kwsys/System.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_System_h
#define @KWSYS_NAMESPACE@_System_h
@@ -19,16 +10,15 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysSystem_Parse_CommandForUnix kwsys_ns(System_Parse_CommandForUnix)
+#define kwsysSystem_Parse_CommandForUnix kwsys_ns(System_Parse_CommandForUnix)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
/**
@@ -59,11 +49,11 @@ kwsysEXPORT char** kwsysSystem_Parse_CommandForUnix(const char* command,
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysSystem_Parse_CommandForUnix
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysSystem_Parse_CommandForUnix
+#endif
#endif
#endif
diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx
index 56a635a..e01dcd7 100644
--- a/Source/kwsys/SystemInformation.cxx
+++ b/Source/kwsys/SystemInformation.cxx
@@ -1,25 +1,15 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#if defined(_WIN32)
-# define NOMINMAX // use our min,max
-# if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
-# define _WIN32_WINNT 0x0501
-# endif
-# include <winsock.h> // WSADATA, include before sys/types.h
+#define NOMINMAX // use our min,max
+#if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
+#define _WIN32_WINNT 0x0501
+#endif
+#include <winsock.h> // WSADATA, include before sys/types.h
#endif
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
#endif
// TODO:
@@ -41,157 +31,163 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "SystemInformation.hxx.in"
-# include "Process.h.in"
+#include "Process.h.in"
+#include "SystemInformation.hxx.in"
#endif
+#include <fstream>
#include <iostream>
#include <sstream>
-#include <fstream>
#include <string>
#include <vector>
#if defined(_WIN32)
-# include <windows.h>
-# if defined(_MSC_VER) && _MSC_VER >= 1800
-# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# endif
-# include <errno.h>
-# if defined(KWSYS_SYS_HAS_PSAPI)
-# include <psapi.h>
-# endif
-# if !defined(siginfo_t)
+#include <windows.h>
+#if defined(_MSC_VER) && _MSC_VER >= 1800
+#define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+#endif
+#include <errno.h>
+#if defined(KWSYS_SYS_HAS_PSAPI)
+#include <psapi.h>
+#endif
+#if !defined(siginfo_t)
typedef int siginfo_t;
-# endif
+#endif
#else
-# include <sys/types.h>
-# include <sys/time.h>
-# include <sys/utsname.h> // int uname(struct utsname *buf);
-# include <sys/resource.h> // getrlimit
-# include <unistd.h>
-# include <signal.h>
-# include <fcntl.h>
-# include <errno.h> // extern int errno;
+#include <sys/types.h>
+
+#include <errno.h> // extern int errno;
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/resource.h> // getrlimit
+#include <sys/time.h>
+#include <sys/utsname.h> // int uname(struct utsname *buf);
+#include <unistd.h>
#endif
-#if defined (__CYGWIN__) && !defined(_WIN32)
-# include <windows.h>
-# undef _WIN32
+#if defined(__CYGWIN__) && !defined(_WIN32)
+#include <windows.h>
+#undef _WIN32
#endif
-#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
-# include <sys/param.h>
-# include <sys/sysctl.h>
-# include <sys/socket.h>
-# include <netdb.h>
-# include <netinet/in.h>
-# if defined(KWSYS_SYS_HAS_IFADDRS_H)
-# include <ifaddrs.h>
-# define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
-# endif
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
+ defined(__DragonFly__)
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+#if defined(KWSYS_SYS_HAS_IFADDRS_H)
+#include <ifaddrs.h>
+#include <net/if.h>
+#define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
+#endif
#endif
#if defined(KWSYS_SYS_HAS_MACHINE_CPU_H)
-# include <machine/cpu.h>
+#include <machine/cpu.h>
#endif
#ifdef __APPLE__
-# include <sys/sysctl.h>
-# include <mach/vm_statistics.h>
-# include <mach/host_info.h>
-# include <mach/mach.h>
-# include <mach/mach_types.h>
-# include <fenv.h>
-# include <sys/socket.h>
-# include <netdb.h>
-# include <netinet/in.h>
-# if defined(KWSYS_SYS_HAS_IFADDRS_H)
-# include <ifaddrs.h>
-# define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
-# endif
-# if !(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0 >= 1050)
-# undef KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE
-# endif
-#endif
-
-#if defined(__linux) || defined (__sun) || defined(_SCO_DS)
-# include <fenv.h>
-# include <sys/socket.h>
-# include <netdb.h>
-# include <netinet/in.h>
-# if defined(KWSYS_SYS_HAS_IFADDRS_H)
-# include <ifaddrs.h>
-# if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
-# define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
-# endif
-# endif
-# if defined(KWSYS_CXX_HAS_RLIMIT64)
+#include <fenv.h>
+#include <mach/host_info.h>
+#include <mach/mach.h>
+#include <mach/mach_types.h>
+#include <mach/vm_statistics.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+#if defined(KWSYS_SYS_HAS_IFADDRS_H)
+#include <ifaddrs.h>
+#include <net/if.h>
+#define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
+#endif
+#if !(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ - 0 >= 1050)
+#undef KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE
+#endif
+#endif
+
+#if defined(__linux) || defined(__sun) || defined(_SCO_DS)
+#include <fenv.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#if defined(KWSYS_SYS_HAS_IFADDRS_H)
+#include <ifaddrs.h>
+#include <net/if.h>
+#if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
+#define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
+#endif
+#endif
+#if defined(KWSYS_CXX_HAS_RLIMIT64)
typedef struct rlimit64 ResourceLimitType;
-# define GetResourceLimit getrlimit64
-# else
+#define GetResourceLimit getrlimit64
+#else
typedef struct rlimit ResourceLimitType;
-# define GetResourceLimit getrlimit
-# endif
-#elif defined( __hpux )
-# include <sys/param.h>
-# include <sys/pstat.h>
-# if defined(KWSYS_SYS_HAS_MPCTL_H)
-# include <sys/mpctl.h>
-# endif
+#define GetResourceLimit getrlimit
+#endif
+#elif defined(__hpux)
+#include <sys/param.h>
+#include <sys/pstat.h>
+#if defined(KWSYS_SYS_HAS_MPCTL_H)
+#include <sys/mpctl.h>
+#endif
#endif
#ifdef __HAIKU__
-# include <OS.h>
+#include <OS.h>
#endif
#if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-# include <execinfo.h>
-# if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
-# include <cxxabi.h>
-# endif
-# if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
-# include <dlfcn.h>
-# endif
+#include <execinfo.h>
+#if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
+#include <cxxabi.h>
+#endif
+#if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
+#include <dlfcn.h>
+#endif
#else
-# undef KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE
-# undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
+#undef KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE
+#undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
#endif
+#include <ctype.h> // int isdigit(int c);
#include <memory.h>
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
-#include <ctype.h> // int isdigit(int c);
#if defined(KWSYS_USE_LONG_LONG)
-# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)(x))
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)(x))
+#endif
#elif defined(KWSYS_USE___INT64)
-# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)(x))
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)(x))
+#endif
#else
-# error "No Long Long"
+#error "No Long Long"
#endif
#if defined(KWSYS_CXX_HAS_ATOLL)
-# define atoLongLong atoll
+#define atoLongLong atoll
#else
-# if defined(KWSYS_CXX_HAS__ATOI64)
-# define atoLongLong _atoi64
-# elif defined(KWSYS_CXX_HAS_ATOL)
-# define atoLongLong atol
-# else
-# define atoLongLong atoi
-# endif
+#if defined(KWSYS_CXX_HAS__ATOI64)
+#define atoLongLong _atoi64
+#elif defined(KWSYS_CXX_HAS_ATOL)
+#define atoLongLong atol
+#else
+#define atoLongLong atoi
+#endif
#endif
-#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64) && !defined(__clang__)
+#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64) && \
+ !defined(__clang__)
#define USE_ASM_INSTRUCTIONS 1
#else
#define USE_ASM_INSTRUCTIONS 0
@@ -204,10 +200,11 @@ typedef struct rlimit ResourceLimitType;
#define USE_CPUID_INTRINSICS 0
#endif
-#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
-# define USE_CPUID 1
+#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || \
+ defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
+#define USE_CPUID 1
#else
-# define USE_CPUID 0
+#define USE_CPUID 0
#endif
#if USE_CPUID
@@ -258,14 +255,12 @@ static bool call_cpuid(int select, int result[4])
pop ebx
pop eax
#endif
- }
}
- __except(1)
- {
+ } __except (1) {
return false;
- }
+ }
- memcpy(result, tmp, sizeof(tmp));
+ memcpy(result, tmp, sizeof(tmp));
#elif defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
unsigned int a, b, c, d;
__asm {
@@ -289,33 +284,36 @@ static bool call_cpuid(int select, int result[4])
}
#endif
-
-namespace KWSYS_NAMESPACE
+namespace KWSYS_NAMESPACE {
+template <typename T>
+T min(T a, T b)
{
-template<typename T>
-T min(T a, T b){ return a<b ? a : b; }
+ return a < b ? a : b;
+}
-extern "C" { typedef void (*SigAction)(int,siginfo_t*,void*); }
+extern "C" {
+typedef void (*SigAction)(int, siginfo_t*, void*);
+}
// Define SystemInformationImplementation class
-typedef void (*DELAY_FUNC)(unsigned int uiMS);
+typedef void (*DELAY_FUNC)(unsigned int uiMS);
class SystemInformationImplementation
{
public:
typedef SystemInformation::LongLong LongLong;
- SystemInformationImplementation ();
- ~SystemInformationImplementation ();
+ SystemInformationImplementation();
+ ~SystemInformationImplementation();
- const char * GetVendorString();
- const char * GetVendorID();
+ const char* GetVendorString();
+ const char* GetVendorID();
std::string GetTypeID();
std::string GetFamilyID();
std::string GetModelID();
std::string GetModelName();
std::string GetSteppingCode();
- const char * GetExtendedProcessorName();
- const char * GetProcessorSerialNumber();
+ const char* GetExtendedProcessorName();
+ const char* GetProcessorSerialNumber();
int GetProcessorCacheSize();
unsigned int GetLogicalProcessorsPerPhysical();
float GetProcessorClockFrequency();
@@ -323,12 +321,12 @@ public:
int GetProcessorCacheXSize(long int);
bool DoesCPUSupportFeature(long int);
- const char * GetOSName();
- const char * GetHostname();
- int GetFullyQualifiedDomainName(std::string &fqdn);
- const char * GetOSRelease();
- const char * GetOSVersion();
- const char * GetOSPlatform();
+ const char* GetOSName();
+ const char* GetHostname();
+ int GetFullyQualifiedDomainName(std::string& fqdn);
+ const char* GetOSRelease();
+ const char* GetOSVersion();
+ const char* GetOSPlatform();
bool Is64Bits();
@@ -347,23 +345,20 @@ public:
// Retrieve memory information in kib
LongLong GetHostMemoryTotal();
- LongLong GetHostMemoryAvailable(const char *envVarName);
+ LongLong GetHostMemoryAvailable(const char* envVarName);
LongLong GetHostMemoryUsed();
- LongLong GetProcMemoryAvailable(
- const char *hostLimitEnvVarName,
- const char *procLimitEnvVarName);
+ LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName,
+ const char* procLimitEnvVarName);
LongLong GetProcMemoryUsed();
double GetLoadAverage();
// enable/disable stack trace signal handler.
- static
- void SetStackTraceOnError(int enable);
+ static void SetStackTraceOnError(int enable);
// get current stack
- static
- std::string GetProgramStack(int firstFrame, int wholePath);
+ static std::string GetProgramStack(int firstFrame, int wholePath);
/** Run the different checks */
void RunCPUCheck();
@@ -372,7 +367,7 @@ public:
public:
typedef struct tagID
- {
+ {
int Type;
int Family;
int Model;
@@ -383,17 +378,17 @@ public:
std::string Vendor;
std::string SerialNumber;
std::string ModelName;
- } ID;
+ } ID;
typedef struct tagCPUPowerManagement
- {
+ {
bool HasVoltageID;
bool HasFrequencyID;
bool HasTempSenseDiode;
- } CPUPowerManagement;
+ } CPUPowerManagement;
typedef struct tagCPUExtendedFeatures
- {
+ {
bool Has3DNow;
bool Has3DNowPlus;
bool SupportsMP;
@@ -403,10 +398,10 @@ public:
unsigned int LogicalProcessorsPerPhysical;
int APIC_ID;
CPUPowerManagement PowerManagement;
- } CPUExtendedFeatures;
+ } CPUExtendedFeatures;
typedef struct CPUtagFeatures
- {
+ {
bool HasFPU;
bool HasTSC;
bool HasMMX;
@@ -425,13 +420,25 @@ public:
int L2CacheSize;
int L3CacheSize;
CPUExtendedFeatures ExtendedFeatures;
- } CPUFeatures;
+ } CPUFeatures;
enum Manufacturer
- {
- AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, IBM,
- Motorola, HP, UnknownManufacturer
- };
+ {
+ AMD,
+ Intel,
+ NSC,
+ UMC,
+ Cyrix,
+ NexGen,
+ IDT,
+ Rise,
+ Transmeta,
+ Sun,
+ IBM,
+ Motorola,
+ HP,
+ UnknownManufacturer
+ };
protected:
// For windows
@@ -449,12 +456,12 @@ protected:
bool RetrieveExtendedCPUIdentity();
// Processor information
- Manufacturer ChipManufacturer;
- CPUFeatures Features;
- ID ChipID;
- float CPUSpeedInMHz;
- unsigned int NumberOfLogicalCPU;
- unsigned int NumberOfPhysicalCPU;
+ Manufacturer ChipManufacturer;
+ CPUFeatures Features;
+ ID ChipID;
+ float CPUSpeedInMHz;
+ unsigned int NumberOfLogicalCPU;
+ unsigned int NumberOfPhysicalCPU;
int CPUCount(); // For windows
unsigned char LogicalCPUPerPhysicalCPU();
@@ -464,20 +471,20 @@ protected:
// For Linux and Cygwin, /proc/cpuinfo formats are slightly different
bool RetreiveInformationFromCpuInfoFile();
- std::string ExtractValueFromCpuInfoFile(std::string buffer,
- const char* word, size_t init=0);
+ std::string ExtractValueFromCpuInfoFile(std::string buffer, const char* word,
+ size_t init = 0);
bool QueryLinuxMemory();
bool QueryCygwinMemory();
- static void Delay (unsigned int);
- static void DelayOverhead (unsigned int);
+ static void Delay(unsigned int);
+ static void DelayOverhead(unsigned int);
- void FindManufacturer(const std::string &family = "");
+ void FindManufacturer(const std::string& family = "");
// For Mac
bool ParseSysCtl();
- int CallSwVers(const char *arg, std::string &ver);
+ int CallSwVers(const char* arg, std::string& ver);
void TrimNewline(std::string&);
std::string ExtractValueFromSysCtl(const char* word);
std::string SysCtlBuffer;
@@ -488,25 +495,25 @@ protected:
std::string ParseValueFromKStat(const char* arguments);
std::string RunProcess(std::vector<const char*> args);
- //For Haiku OS
+ // For Haiku OS
bool QueryHaikuInfo();
- //For QNX
+ // For QNX
bool QueryQNXMemory();
bool QueryQNXProcessor();
- //For OpenBSD, FreeBSD, NetBSD, DragonFly
+ // For OpenBSD, FreeBSD, NetBSD, DragonFly
bool QueryBSDMemory();
bool QueryBSDProcessor();
- //For HP-UX
+ // For HP-UX
bool QueryHPUXMemory();
bool QueryHPUXProcessor();
- //For Microsoft Windows
+ // For Microsoft Windows
bool QueryWindowsMemory();
- //For AIX
+ // For AIX
bool QueryAIXMemory();
bool QueryProcessorBySysconf();
@@ -531,7 +538,6 @@ protected:
std::string OSPlatform;
};
-
SystemInformation::SystemInformation()
{
this->Implementation = new SystemInformationImplementation;
@@ -542,12 +548,12 @@ SystemInformation::~SystemInformation()
delete this->Implementation;
}
-const char * SystemInformation::GetVendorString()
+const char* SystemInformation::GetVendorString()
{
return this->Implementation->GetVendorString();
}
-const char * SystemInformation::GetVendorID()
+const char* SystemInformation::GetVendorID()
{
return this->Implementation->GetVendorID();
}
@@ -577,12 +583,12 @@ std::string SystemInformation::GetSteppingCode()
return this->Implementation->GetSteppingCode();
}
-const char * SystemInformation::GetExtendedProcessorName()
+const char* SystemInformation::GetExtendedProcessorName()
{
return this->Implementation->GetExtendedProcessorName();
}
-const char * SystemInformation::GetProcessorSerialNumber()
+const char* SystemInformation::GetProcessorSerialNumber()
{
return this->Implementation->GetProcessorSerialNumber();
}
@@ -620,40 +626,30 @@ bool SystemInformation::DoesCPUSupportFeature(long int i)
std::string SystemInformation::GetCPUDescription()
{
std::ostringstream oss;
- oss
- << this->GetNumberOfPhysicalCPU()
- << " core ";
- if (this->GetModelName().empty())
- {
- oss
- << this->GetProcessorClockFrequency()
- << " MHz "
- << this->GetVendorString()
- << " "
- << this->GetExtendedProcessorName();
- }
- else
- {
+ oss << this->GetNumberOfPhysicalCPU() << " core ";
+ if (this->GetModelName().empty()) {
+ oss << this->GetProcessorClockFrequency() << " MHz "
+ << this->GetVendorString() << " " << this->GetExtendedProcessorName();
+ } else {
oss << this->GetModelName();
- }
+ }
// remove extra spaces
- std::string tmp=oss.str();
+ std::string tmp = oss.str();
size_t pos;
- while( (pos=tmp.find(" "))!=std::string::npos)
- {
- tmp.replace(pos,2," ");
- }
+ while ((pos = tmp.find(" ")) != std::string::npos) {
+ tmp.replace(pos, 2, " ");
+ }
return tmp;
}
-const char * SystemInformation::GetOSName()
+const char* SystemInformation::GetOSName()
{
return this->Implementation->GetOSName();
}
-const char * SystemInformation::GetHostname()
+const char* SystemInformation::GetHostname()
{
return this->Implementation->GetHostname();
}
@@ -665,17 +661,17 @@ std::string SystemInformation::GetFullyQualifiedDomainName()
return fqdn;
}
-const char * SystemInformation::GetOSRelease()
+const char* SystemInformation::GetOSRelease()
{
return this->Implementation->GetOSRelease();
}
-const char * SystemInformation::GetOSVersion()
+const char* SystemInformation::GetOSVersion()
{
return this->Implementation->GetOSVersion();
}
-const char * SystemInformation::GetOSPlatform()
+const char* SystemInformation::GetOSPlatform()
{
return this->Implementation->GetOSPlatform();
}
@@ -710,12 +706,8 @@ int SystemInformation::GetOSIsApple()
std::string SystemInformation::GetOSDescription()
{
std::ostringstream oss;
- oss
- << this->GetOSName()
- << " "
- << this->GetOSRelease()
- << " "
- << this->GetOSVersion();
+ oss << this->GetOSName() << " " << this->GetOSRelease() << " "
+ << this->GetOSVersion();
return oss.str();
}
@@ -762,19 +754,16 @@ size_t SystemInformation::GetAvailablePhysicalMemory()
}
std::string SystemInformation::GetMemoryDescription(
- const char *hostLimitEnvVarName,
- const char *procLimitEnvVarName)
+ const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
{
std::ostringstream oss;
- oss
- << "Host Total: "
- << iostreamLongLong(this->GetHostMemoryTotal())
- << " KiB, Host Available: "
- << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
- << " KiB, Process Available: "
- << iostreamLongLong(
- this->GetProcMemoryAvailable(hostLimitEnvVarName,procLimitEnvVarName))
- << " KiB";
+ oss << "Host Total: " << iostreamLongLong(this->GetHostMemoryTotal())
+ << " KiB, Host Available: "
+ << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
+ << " KiB, Process Available: "
+ << iostreamLongLong(this->GetProcMemoryAvailable(hostLimitEnvVarName,
+ procLimitEnvVarName))
+ << " KiB";
return oss.str();
}
@@ -784,8 +773,8 @@ SystemInformation::LongLong SystemInformation::GetHostMemoryTotal()
return this->Implementation->GetHostMemoryTotal();
}
-SystemInformation::LongLong
-SystemInformation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
+SystemInformation::LongLong SystemInformation::GetHostMemoryAvailable(
+ const char* hostLimitEnvVarName)
{
return this->Implementation->GetHostMemoryAvailable(hostLimitEnvVarName);
}
@@ -796,14 +785,11 @@ SystemInformation::LongLong SystemInformation::GetHostMemoryUsed()
}
// process memory info in units of KiB.
-SystemInformation::LongLong
-SystemInformation::GetProcMemoryAvailable(
- const char *hostLimitEnvVarName,
- const char *procLimitEnvVarName)
+SystemInformation::LongLong SystemInformation::GetProcMemoryAvailable(
+ const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
{
- return this->Implementation->GetProcMemoryAvailable(
- hostLimitEnvVarName,
- procLimitEnvVarName);
+ return this->Implementation->GetProcMemoryAvailable(hostLimitEnvVarName,
+ procLimitEnvVarName);
}
SystemInformation::LongLong SystemInformation::GetProcMemoryUsed()
@@ -828,7 +814,8 @@ void SystemInformation::SetStackTraceOnError(int enable)
std::string SystemInformation::GetProgramStack(int firstFrame, int wholePath)
{
- return SystemInformationImplementation::GetProgramStack(firstFrame, wholePath);
+ return SystemInformationImplementation::GetProgramStack(firstFrame,
+ wholePath);
}
/** Run the different checks */
@@ -847,60 +834,59 @@ void SystemInformation::RunMemoryCheck()
this->Implementation->RunMemoryCheck();
}
-
// --------------------------------------------------------------
// SystemInformationImplementation starts here
-#define STORE_TLBCACHE_INFO(x,y) x = (x < (y)) ? (y) : x
-#define TLBCACHE_INFO_UNITS (15)
-#define CLASSICAL_CPU_FREQ_LOOP 10000000
-#define RDTSC_INSTRUCTION _asm _emit 0x0f _asm _emit 0x31
+#define STORE_TLBCACHE_INFO(x, y) x = (x < (y)) ? (y) : x
+#define TLBCACHE_INFO_UNITS (15)
+#define CLASSICAL_CPU_FREQ_LOOP 10000000
+#define RDTSC_INSTRUCTION _asm _emit 0x0f _asm _emit 0x31
-#define MMX_FEATURE 0x00000001
-#define MMX_PLUS_FEATURE 0x00000002
-#define SSE_FEATURE 0x00000004
-#define SSE2_FEATURE 0x00000008
-#define AMD_3DNOW_FEATURE 0x00000010
+#define MMX_FEATURE 0x00000001
+#define MMX_PLUS_FEATURE 0x00000002
+#define SSE_FEATURE 0x00000004
+#define SSE2_FEATURE 0x00000008
+#define AMD_3DNOW_FEATURE 0x00000010
#define AMD_3DNOW_PLUS_FEATURE 0x00000020
-#define IA64_FEATURE 0x00000040
-#define MP_CAPABLE 0x00000080
-#define HYPERTHREAD_FEATURE 0x00000100
-#define SERIALNUMBER_FEATURE 0x00000200
-#define APIC_FEATURE 0x00000400
-#define SSE_FP_FEATURE 0x00000800
-#define SSE_MMX_FEATURE 0x00001000
-#define CMOV_FEATURE 0x00002000
-#define MTRR_FEATURE 0x00004000
-#define L1CACHE_FEATURE 0x00008000
-#define L2CACHE_FEATURE 0x00010000
-#define L3CACHE_FEATURE 0x00020000
-#define ACPI_FEATURE 0x00040000
+#define IA64_FEATURE 0x00000040
+#define MP_CAPABLE 0x00000080
+#define HYPERTHREAD_FEATURE 0x00000100
+#define SERIALNUMBER_FEATURE 0x00000200
+#define APIC_FEATURE 0x00000400
+#define SSE_FP_FEATURE 0x00000800
+#define SSE_MMX_FEATURE 0x00001000
+#define CMOV_FEATURE 0x00002000
+#define MTRR_FEATURE 0x00004000
+#define L1CACHE_FEATURE 0x00008000
+#define L2CACHE_FEATURE 0x00010000
+#define L3CACHE_FEATURE 0x00020000
+#define ACPI_FEATURE 0x00040000
#define THERMALMONITOR_FEATURE 0x00080000
#define TEMPSENSEDIODE_FEATURE 0x00100000
-#define FREQUENCYID_FEATURE 0x00200000
-#define VOLTAGEID_FREQUENCY 0x00400000
+#define FREQUENCYID_FEATURE 0x00200000
+#define VOLTAGEID_FREQUENCY 0x00400000
// Status Flag
-#define HT_NOT_CAPABLE 0
-#define HT_ENABLED 1
-#define HT_DISABLED 2
+#define HT_NOT_CAPABLE 0
+#define HT_ENABLED 1
+#define HT_DISABLED 2
#define HT_SUPPORTED_NOT_ENABLED 3
-#define HT_CANNOT_DETECT 4
+#define HT_CANNOT_DETECT 4
// EDX[28] Bit 28 is set if HT is supported
-#define HT_BIT 0x10000000
+#define HT_BIT 0x10000000
// EAX[11:8] Bit 8-11 contains family processor ID.
-#define FAMILY_ID 0x0F00
-#define PENTIUM4_ID 0x0F00
+#define FAMILY_ID 0x0F00
+#define PENTIUM4_ID 0x0F00
// EAX[23:20] Bit 20-23 contains extended family processor ID
-#define EXT_FAMILY_ID 0x0F00000
+#define EXT_FAMILY_ID 0x0F00000
// EBX[23:16] Bit 16-23 in ebx contains the number of logical
-#define NUM_LOGICAL_BITS 0x00FF0000
+#define NUM_LOGICAL_BITS 0x00FF0000
// processors per physical processor when execute cpuid with
// eax set to 1
// EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
-#define INITIAL_APIC_ID_BITS 0xFF000000
+#define INITIAL_APIC_ID_BITS 0xFF000000
// initial APIC ID for the processor this code is running on.
// Default value = 0xff if HT is not supported
@@ -908,174 +894,142 @@ void SystemInformation::RunMemoryCheck()
namespace {
// *****************************************************************************
#if defined(__linux) || defined(__APPLE__)
-int LoadLines(
- FILE *file,
- std::vector<std::string> &lines)
+int LoadLines(FILE* file, std::vector<std::string>& lines)
{
// Load each line in the given file into a the vector.
- int nRead=0;
- const int bufSize=1024;
- char buf[bufSize]={'\0'};
- while (!feof(file) && !ferror(file))
- {
- errno=0;
- if (fgets(buf,bufSize,file) == 0)
- {
- if (ferror(file) && (errno==EINTR))
- {
+ int nRead = 0;
+ const int bufSize = 1024;
+ char buf[bufSize] = { '\0' };
+ while (!feof(file) && !ferror(file)) {
+ errno = 0;
+ if (fgets(buf, bufSize, file) == 0) {
+ if (ferror(file) && (errno == EINTR)) {
clearerr(file);
- }
- continue;
- }
- char *pBuf=buf;
- while(*pBuf)
- {
- if (*pBuf=='\n') *pBuf='\0';
- pBuf+=1;
}
+ continue;
+ }
+ char* pBuf = buf;
+ while (*pBuf) {
+ if (*pBuf == '\n')
+ *pBuf = '\0';
+ pBuf += 1;
+ }
lines.push_back(buf);
++nRead;
- }
- if (ferror(file))
- {
+ }
+ if (ferror(file)) {
return 0;
- }
+ }
return nRead;
}
-# if defined(__linux)
+#if defined(__linux)
// *****************************************************************************
-int LoadLines(
- const char *fileName,
- std::vector<std::string> &lines)
+int LoadLines(const char* fileName, std::vector<std::string>& lines)
{
- FILE *file=fopen(fileName,"r");
- if (file==0)
- {
+ FILE* file = fopen(fileName, "r");
+ if (file == 0) {
return 0;
- }
- int nRead=LoadLines(file,lines);
+ }
+ int nRead = LoadLines(file, lines);
fclose(file);
return nRead;
}
-# endif
+#endif
// ****************************************************************************
-template<typename T>
-int NameValue(
- std::vector<std::string> &lines,
- std::string name, T &value)
+template <typename T>
+int NameValue(std::vector<std::string>& lines, std::string name, T& value)
{
- size_t nLines=lines.size();
- for (size_t i=0; i<nLines; ++i)
- {
- size_t at=lines[i].find(name);
- if (at==std::string::npos)
- {
+ size_t nLines = lines.size();
+ for (size_t i = 0; i < nLines; ++i) {
+ size_t at = lines[i].find(name);
+ if (at == std::string::npos) {
continue;
- }
- std::istringstream is(lines[i].substr(at+name.size()));
+ }
+ std::istringstream is(lines[i].substr(at + name.size()));
is >> value;
return 0;
- }
+ }
return -1;
}
#endif
#if defined(__linux)
// ****************************************************************************
-template<typename T>
-int GetFieldsFromFile(
- const char *fileName,
- const char **fieldNames,
- T *values)
+template <typename T>
+int GetFieldsFromFile(const char* fileName, const char** fieldNames, T* values)
{
std::vector<std::string> fields;
- if (!LoadLines(fileName,fields))
- {
+ if (!LoadLines(fileName, fields)) {
return -1;
+ }
+ int i = 0;
+ while (fieldNames[i] != NULL) {
+ int ierr = NameValue(fields, fieldNames[i], values[i]);
+ if (ierr) {
+ return -(i + 2);
}
- int i=0;
- while (fieldNames[i]!=NULL)
- {
- int ierr=NameValue(fields,fieldNames[i],values[i]);
- if (ierr)
- {
- return -(i+2);
- }
- i+=1;
- }
+ i += 1;
+ }
return 0;
}
// ****************************************************************************
-template<typename T>
-int GetFieldFromFile(
- const char *fileName,
- const char *fieldName,
- T &value)
-{
- const char *fieldNames[2]={fieldName,NULL};
- T values[1]={T(0)};
- int ierr=GetFieldsFromFile(fileName,fieldNames,values);
- if (ierr)
- {
+template <typename T>
+int GetFieldFromFile(const char* fileName, const char* fieldName, T& value)
+{
+ const char* fieldNames[2] = { fieldName, NULL };
+ T values[1] = { T(0) };
+ int ierr = GetFieldsFromFile(fileName, fieldNames, values);
+ if (ierr) {
return ierr;
- }
- value=values[0];
+ }
+ value = values[0];
return 0;
}
#endif
// ****************************************************************************
#if defined(__APPLE__)
-template<typename T>
-int GetFieldsFromCommand(
- const char *command,
- const char **fieldNames,
- T *values)
-{
- FILE *file=popen(command,"r");
- if (file==0)
- {
+template <typename T>
+int GetFieldsFromCommand(const char* command, const char** fieldNames,
+ T* values)
+{
+ FILE* file = popen(command, "r");
+ if (file == 0) {
return -1;
- }
+ }
std::vector<std::string> fields;
- int nl=LoadLines(file,fields);
+ int nl = LoadLines(file, fields);
pclose(file);
- if (nl==0)
- {
+ if (nl == 0) {
return -1;
+ }
+ int i = 0;
+ while (fieldNames[i] != NULL) {
+ int ierr = NameValue(fields, fieldNames[i], values[i]);
+ if (ierr) {
+ return -(i + 2);
}
- int i=0;
- while (fieldNames[i]!=NULL)
- {
- int ierr=NameValue(fields,fieldNames[i],values[i]);
- if (ierr)
- {
- return -(i+2);
- }
- i+=1;
- }
+ i += 1;
+ }
return 0;
}
#endif
// ****************************************************************************
#if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
-void StacktraceSignalHandler(
- int sigNo,
- siginfo_t *sigInfo,
- void * /*sigContext*/)
+void StacktraceSignalHandler(int sigNo, siginfo_t* sigInfo,
+ void* /*sigContext*/)
{
#if defined(__linux) || defined(__APPLE__)
std::ostringstream oss;
- oss
- << std::endl
- << "=========================================================" << std::endl
- << "Process id " << getpid() << " ";
- switch (sigNo)
- {
+ oss << std::endl
+ << "========================================================="
+ << std::endl
+ << "Process id " << getpid() << " ";
+ switch (sigNo) {
case SIGINT:
oss << "Caught SIGINT";
break;
@@ -1089,24 +1043,20 @@ void StacktraceSignalHandler(
break;
case SIGFPE:
- oss
- << "Caught SIGFPE at "
- << (sigInfo->si_addr==0?"0x":"")
- << sigInfo->si_addr
- << " ";
- switch (sigInfo->si_code)
- {
-# if defined(FPE_INTDIV)
+ oss << "Caught SIGFPE at " << (sigInfo->si_addr == 0 ? "0x" : "")
+ << sigInfo->si_addr << " ";
+ switch (sigInfo->si_code) {
+#if defined(FPE_INTDIV)
case FPE_INTDIV:
oss << "integer division by zero";
break;
-# endif
+#endif
-# if defined(FPE_INTOVF)
+#if defined(FPE_INTOVF)
case FPE_INTOVF:
oss << "integer overflow";
break;
-# endif
+#endif
case FPE_FLTDIV:
oss << "floating point divide by zero";
@@ -1137,17 +1087,13 @@ void StacktraceSignalHandler(
default:
oss << "code " << sigInfo->si_code;
break;
- }
+ }
break;
case SIGSEGV:
- oss
- << "Caught SIGSEGV at "
- << (sigInfo->si_addr==0?"0x":"")
- << sigInfo->si_addr
- << " ";
- switch (sigInfo->si_code)
- {
+ oss << "Caught SIGSEGV at " << (sigInfo->si_addr == 0 ? "0x" : "")
+ << sigInfo->si_addr << " ";
+ switch (sigInfo->si_code) {
case SEGV_MAPERR:
oss << "address not mapped to object";
break;
@@ -1159,74 +1105,68 @@ void StacktraceSignalHandler(
default:
oss << "code " << sigInfo->si_code;
break;
- }
+ }
break;
case SIGBUS:
- oss
- << "Caught SIGBUS at "
- << (sigInfo->si_addr==0?"0x":"")
- << sigInfo->si_addr
- << " ";
- switch (sigInfo->si_code)
- {
+ oss << "Caught SIGBUS at " << (sigInfo->si_addr == 0 ? "0x" : "")
+ << sigInfo->si_addr << " ";
+ switch (sigInfo->si_code) {
case BUS_ADRALN:
oss << "invalid address alignment";
break;
-# if defined(BUS_ADRERR)
+#if defined(BUS_ADRERR)
case BUS_ADRERR:
oss << "nonexistent physical address";
break;
-# endif
+#endif
-# if defined(BUS_OBJERR)
+#if defined(BUS_OBJERR)
case BUS_OBJERR:
oss << "object-specific hardware error";
break;
-# endif
+#endif
-# if defined(BUS_MCEERR_AR)
+#if defined(BUS_MCEERR_AR)
case BUS_MCEERR_AR:
- oss << "Hardware memory error consumed on a machine check; action required.";
+ oss << "Hardware memory error consumed on a machine check; action "
+ "required.";
break;
-# endif
+#endif
-# if defined(BUS_MCEERR_AO)
+#if defined(BUS_MCEERR_AO)
case BUS_MCEERR_AO:
- oss << "Hardware memory error detected in process but not consumed; action optional.";
+ oss << "Hardware memory error detected in process but not consumed; "
+ "action optional.";
break;
-# endif
+#endif
default:
oss << "code " << sigInfo->si_code;
break;
- }
+ }
break;
case SIGILL:
- oss
- << "Caught SIGILL at "
- << (sigInfo->si_addr==0?"0x":"")
- << sigInfo->si_addr
- << " ";
- switch (sigInfo->si_code)
- {
+ oss << "Caught SIGILL at " << (sigInfo->si_addr == 0 ? "0x" : "")
+ << sigInfo->si_addr << " ";
+ switch (sigInfo->si_code) {
case ILL_ILLOPC:
oss << "illegal opcode";
break;
-# if defined(ILL_ILLOPN)
+#if defined(ILL_ILLOPN)
case ILL_ILLOPN:
oss << "illegal operand";
break;
-# endif
+#endif
-# if defined(ILL_ILLADR)
+#if defined(ILL_ILLADR)
case ILL_ILLADR:
oss << "illegal addressing mode.";
break;
-# endif
+#endif
case ILL_ILLTRP:
oss << "illegal trap";
@@ -1236,39 +1176,39 @@ void StacktraceSignalHandler(
oss << "privileged opcode";
break;
-# if defined(ILL_PRVREG)
+#if defined(ILL_PRVREG)
case ILL_PRVREG:
oss << "privileged register";
break;
-# endif
+#endif
-# if defined(ILL_COPROC)
+#if defined(ILL_COPROC)
case ILL_COPROC:
oss << "co-processor error";
break;
-# endif
+#endif
-# if defined(ILL_BADSTK)
+#if defined(ILL_BADSTK)
case ILL_BADSTK:
oss << "internal stack error";
break;
-# endif
+#endif
default:
oss << "code " << sigInfo->si_code;
break;
- }
+ }
break;
default:
oss << "Caught " << sigNo << " code " << sigInfo->si_code;
break;
- }
- oss
- << std::endl
- << "Program Stack:" << std::endl
- << SystemInformationImplementation::GetProgramStack(2,0)
- << "=========================================================" << std::endl;
+ }
+ oss << std::endl
+ << "Program Stack:" << std::endl
+ << SystemInformationImplementation::GetProgramStack(2, 0)
+ << "========================================================="
+ << std::endl;
std::cerr << oss.str() << std::endl;
// restore the previously registered handlers
@@ -1284,7 +1224,7 @@ void StacktraceSignalHandler(
#endif
#if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-#define safes(_arg)((_arg)?(_arg):"???")
+#define safes(_arg) ((_arg) ? (_arg) : "???")
// Description:
// A container for symbol properties. Each instance
@@ -1297,65 +1237,73 @@ public:
// Description:
// The SymbolProperties instance must be initialized by
// passing a stack address.
- void Initialize(void *address);
+ void Initialize(void* address);
// Description:
// Get the symbol's stack address.
- void *GetAddress() const { return this->Address; }
+ void* GetAddress() const { return this->Address; }
// Description:
// If not set paths will be removed. eg, from a binary
// or source file.
- void SetReportPath(int rp){ this->ReportPath=rp; }
+ void SetReportPath(int rp) { this->ReportPath = rp; }
// Description:
// Set/Get the name of the binary file that the symbol
// is found in.
- void SetBinary(const char *binary)
- { this->Binary=safes(binary); }
+ void SetBinary(const char* binary) { this->Binary = safes(binary); }
std::string GetBinary() const;
// Description:
// Set the name of the function that the symbol is found in.
// If c++ demangling is supported it will be demangled.
- void SetFunction(const char *function)
- { this->Function=this->Demangle(function); }
+ void SetFunction(const char* function)
+ {
+ this->Function = this->Demangle(function);
+ }
- std::string GetFunction() const
- { return this->Function; }
+ std::string GetFunction() const { return this->Function; }
// Description:
// Set/Get the name of the source file where the symbol
// is defined.
- void SetSourceFile(const char *sourcefile)
- { this->SourceFile=safes(sourcefile); }
+ void SetSourceFile(const char* sourcefile)
+ {
+ this->SourceFile = safes(sourcefile);
+ }
std::string GetSourceFile() const
- { return this->GetFileName(this->SourceFile); }
+ {
+ return this->GetFileName(this->SourceFile);
+ }
// Description:
// Set/Get the line number where the symbol is defined
- void SetLineNumber(long linenumber){ this->LineNumber=linenumber; }
+ void SetLineNumber(long linenumber) { this->LineNumber = linenumber; }
long GetLineNumber() const { return this->LineNumber; }
// Description:
// Set the address where the biinary image is mapped
// into memory.
- void SetBinaryBaseAddress(void *address)
- { this->BinaryBaseAddress=address; }
+ void SetBinaryBaseAddress(void* address)
+ {
+ this->BinaryBaseAddress = address;
+ }
private:
- void *GetRealAddress() const
- { return (void*)((char*)this->Address-(char*)this->BinaryBaseAddress); }
+ void* GetRealAddress() const
+ {
+ return (void*)((char*)this->Address - (char*)this->BinaryBaseAddress);
+ }
- std::string GetFileName(const std::string &path) const;
- std::string Demangle(const char *symbol) const;
+ std::string GetFileName(const std::string& path) const;
+ std::string Demangle(const char* symbol) const;
private:
std::string Binary;
- void *BinaryBaseAddress;
- void *Address;
+ void* BinaryBaseAddress;
+ void* Address;
std::string SourceFile;
std::string Function;
long LineNumber;
@@ -1363,20 +1311,15 @@ private:
};
// --------------------------------------------------------------------------
-std::ostream &operator<<(
- std::ostream &os,
- const SymbolProperties &sp)
+std::ostream& operator<<(std::ostream& os, const SymbolProperties& sp)
{
#if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
- os
- << std::hex << sp.GetAddress() << " : "
- << sp.GetFunction()
- << " [(" << sp.GetBinary() << ") "
- << sp.GetSourceFile() << ":"
- << std::dec << sp.GetLineNumber() << "]";
+ os << std::hex << sp.GetAddress() << " : " << sp.GetFunction() << " [("
+ << sp.GetBinary() << ") " << sp.GetSourceFile() << ":" << std::dec
+ << sp.GetLineNumber() << "]";
#elif defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
- void *addr = sp.GetAddress();
- char **syminfo = backtrace_symbols(&addr,1);
+ void* addr = sp.GetAddress();
+ char** syminfo = backtrace_symbols(&addr, 1);
os << safes(syminfo[0]);
free(syminfo);
#else
@@ -1406,17 +1349,15 @@ SymbolProperties::SymbolProperties()
}
// --------------------------------------------------------------------------
-std::string SymbolProperties::GetFileName(const std::string &path) const
+std::string SymbolProperties::GetFileName(const std::string& path) const
{
std::string file(path);
- if (!this->ReportPath)
- {
+ if (!this->ReportPath) {
size_t at = file.rfind("/");
- if (at!=std::string::npos)
- {
- file = file.substr(at+1,std::string::npos);
- }
+ if (at != std::string::npos) {
+ file = file.substr(at + 1, std::string::npos);
}
+ }
return file;
}
@@ -1425,40 +1366,35 @@ std::string SymbolProperties::GetBinary() const
{
// only linux has proc fs
#if defined(__linux__)
- if (this->Binary=="/proc/self/exe")
- {
+ if (this->Binary == "/proc/self/exe") {
std::string binary;
- char buf[1024]={'\0'};
- ssize_t ll=0;
- if ((ll=readlink("/proc/self/exe",buf,1024))>0)
- {
- buf[ll]='\0';
- binary=buf;
- }
- else
- {
- binary="/proc/self/exe";
- }
- return this->GetFileName(binary);
+ char buf[1024] = { '\0' };
+ ssize_t ll = 0;
+ if ((ll = readlink("/proc/self/exe", buf, 1024)) > 0) {
+ buf[ll] = '\0';
+ binary = buf;
+ } else {
+ binary = "/proc/self/exe";
}
+ return this->GetFileName(binary);
+ }
#endif
return this->GetFileName(this->Binary);
}
// --------------------------------------------------------------------------
-std::string SymbolProperties::Demangle(const char *symbol) const
+std::string SymbolProperties::Demangle(const char* symbol) const
{
std::string result = safes(symbol);
#if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
int status = 0;
size_t bufferLen = 1024;
- char *buffer = (char*)malloc(1024);
- char *demangledSymbol =
+ char* buffer = (char*)malloc(1024);
+ char* demangledSymbol =
abi::__cxa_demangle(symbol, buffer, &bufferLen, &status);
- if (!status)
- {
+ if (!status) {
result = demangledSymbol;
- }
+ }
free(buffer);
#else
(void)symbol;
@@ -1467,31 +1403,30 @@ std::string SymbolProperties::Demangle(const char *symbol) const
}
// --------------------------------------------------------------------------
-void SymbolProperties::Initialize(void *address)
+void SymbolProperties::Initialize(void* address)
{
this->Address = address;
#if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
// first fallback option can demangle c++ functions
Dl_info info;
- int ierr=dladdr(this->Address,&info);
- if (ierr && info.dli_sname && info.dli_saddr)
- {
+ int ierr = dladdr(this->Address, &info);
+ if (ierr && info.dli_sname && info.dli_saddr) {
this->SetBinary(info.dli_fname);
this->SetFunction(info.dli_sname);
- }
+ }
#else
- // second fallback use builtin backtrace_symbols
- // to decode the bactrace.
+// second fallback use builtin backtrace_symbols
+// to decode the bactrace.
#endif
}
#endif // don't define this class if we're not using it
// --------------------------------------------------------------------------
#if defined(_WIN32) || defined(__CYGWIN__)
-# define KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
+#define KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
#endif
#if defined(_MSC_VER) && _MSC_VER < 1310
-# undef KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
+#undef KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
#endif
#if defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
double calculateCPULoad(unsigned __int64 idleTicks,
@@ -1507,22 +1442,18 @@ double calculateCPULoad(unsigned __int64 idleTicks,
totalTicks - previousTotalTicks;
double load;
- if (previousTotalTicks == 0 || totalTicksSinceLastTime == 0)
- {
+ if (previousTotalTicks == 0 || totalTicksSinceLastTime == 0) {
// No new information. Use previous result.
load = previousLoad;
- }
- else
- {
+ } else {
// Calculate load since last time.
load = 1.0 - double(idleTicksSinceLastTime) / totalTicksSinceLastTime;
// Smooth if possible.
- if (previousLoad > 0)
- {
+ if (previousLoad > 0) {
load = 0.25 * load + 0.75 * previousLoad;
- }
}
+ }
previousLoad = load;
previousIdleTicks = idleTicks;
@@ -1542,7 +1473,6 @@ unsigned __int64 fileTimeToUInt64(FILETIME const& ft)
} // anonymous namespace
-
SystemInformationImplementation::SystemInformationImplementation()
{
this->TotalVirtualMemory = 0;
@@ -1578,56 +1508,52 @@ void SystemInformationImplementation::RunCPUCheck()
// Check to see if this processor supports CPUID.
bool supportsCPUID = DoesCPUSupportCPUID();
- if (supportsCPUID)
- {
+ if (supportsCPUID) {
// Retrieve the CPU details.
RetrieveCPUIdentity();
this->FindManufacturer();
RetrieveCPUFeatures();
- }
+ }
// These two may be called without support for the CPUID instruction.
// (But if the instruction is there, they should be called *after*
// the above call to RetrieveCPUIdentity... that's why the two if
// blocks exist with the same "if (supportsCPUID)" logic...
//
- if (!RetrieveCPUClockSpeed())
- {
+ if (!RetrieveCPUClockSpeed()) {
RetrieveClassicalCPUClockSpeed();
- }
+ }
- if (supportsCPUID)
- {
+ if (supportsCPUID) {
// Retrieve cache information.
- if (!RetrieveCPUCacheDetails())
- {
+ if (!RetrieveCPUCacheDetails()) {
RetrieveClassicalCPUCacheDetails();
- }
+ }
// Retrieve the extended CPU details.
- if (!RetrieveExtendedCPUIdentity())
- {
+ if (!RetrieveExtendedCPUIdentity()) {
RetrieveClassicalCPUIdentity();
- }
+ }
RetrieveExtendedCPUFeatures();
RetrieveCPUPowerManagement();
// Now attempt to retrieve the serial number (if possible).
RetrieveProcessorSerialNumber();
- }
+ }
this->CPUCount();
#elif defined(__APPLE__)
this->ParseSysCtl();
-#elif defined (__SVR4) && defined (__sun)
+#elif defined(__SVR4) && defined(__sun)
this->QuerySolarisProcessor();
#elif defined(__HAIKU__)
this->QueryHaikuInfo();
#elif defined(__QNX__)
this->QueryQNXProcessor();
-#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
+ defined(__DragonFly__)
this->QueryBSDProcessor();
#elif defined(__hpux)
this->QueryHPUXProcessor();
@@ -1647,13 +1573,14 @@ void SystemInformationImplementation::RunMemoryCheck()
{
#if defined(__APPLE__)
this->ParseSysCtl();
-#elif defined (__SVR4) && defined (__sun)
+#elif defined(__SVR4) && defined(__sun)
this->QuerySolarisMemory();
#elif defined(__HAIKU__)
this->QueryHaikuInfo();
#elif defined(__QNX__)
this->QueryQNXMemory();
-#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
+ defined(__DragonFly__)
this->QueryBSDMemory();
#elif defined(__CYGWIN__)
this->QueryCygwinMemory();
@@ -1671,13 +1598,13 @@ void SystemInformationImplementation::RunMemoryCheck()
}
/** Get the vendor string */
-const char * SystemInformationImplementation::GetVendorString()
+const char* SystemInformationImplementation::GetVendorString()
{
return this->ChipID.Vendor.c_str();
}
/** Get the OS Name */
-const char * SystemInformationImplementation::GetOSName()
+const char* SystemInformationImplementation::GetOSName()
{
return this->OSName.c_str();
}
@@ -1685,65 +1612,59 @@ const char * SystemInformationImplementation::GetOSName()
/** Get the hostname */
const char* SystemInformationImplementation::GetHostname()
{
- if (this->Hostname.empty())
- {
- this->Hostname="localhost";
+ if (this->Hostname.empty()) {
+ this->Hostname = "localhost";
#if defined(_WIN32)
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
- wVersionRequested = MAKEWORD(2,0);
- if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
- {
- gethostname(name,sizeof(name));
- WSACleanup( );
- }
+ wVersionRequested = MAKEWORD(2, 0);
+ if (WSAStartup(wVersionRequested, &wsaData) == 0) {
+ gethostname(name, sizeof(name));
+ WSACleanup();
+ }
this->Hostname = name;
#else
struct utsname unameInfo;
int errorFlag = uname(&unameInfo);
- if(errorFlag == 0)
- {
+ if (errorFlag == 0) {
this->Hostname = unameInfo.nodename;
- }
-#endif
}
+#endif
+ }
return this->Hostname.c_str();
}
/** Get the FQDN */
int SystemInformationImplementation::GetFullyQualifiedDomainName(
- std::string &fqdn)
+ std::string& fqdn)
{
// in the event of absolute failure return localhost.
- fqdn="localhost";
+ fqdn = "localhost";
#if defined(_WIN32)
int ierr;
// TODO - a more robust implementation for windows, see comments
// in unix implementation.
WSADATA wsaData;
- WORD ver=MAKEWORD(2,0);
- ierr=WSAStartup(ver,&wsaData);
- if (ierr)
- {
+ WORD ver = MAKEWORD(2, 0);
+ ierr = WSAStartup(ver, &wsaData);
+ if (ierr) {
return -1;
- }
+ }
- char base[256]={'\0'};
- ierr=gethostname(base,256);
- if (ierr)
- {
+ char base[256] = { '\0' };
+ ierr = gethostname(base, 256);
+ if (ierr) {
WSACleanup();
return -2;
- }
- fqdn=base;
+ }
+ fqdn = base;
- HOSTENT *hent=gethostbyname(base);
- if (hent)
- {
- fqdn=hent->h_name;
- }
+ HOSTENT* hent = gethostbyname(base);
+ if (hent) {
+ fqdn = hent->h_name;
+ }
WSACleanup();
return 0;
@@ -1760,66 +1681,57 @@ int SystemInformationImplementation::GetFullyQualifiedDomainName(
// system lives on a private network such as in the case of a cluster
// node.
- int ierr=0;
+ int ierr = 0;
char base[NI_MAXHOST];
- ierr=gethostname(base,NI_MAXHOST);
- if (ierr)
- {
+ ierr = gethostname(base, NI_MAXHOST);
+ if (ierr) {
return -1;
- }
- size_t baseSize=strlen(base);
- fqdn=base;
+ }
+ size_t baseSize = strlen(base);
+ fqdn = base;
- struct ifaddrs *ifas;
- struct ifaddrs *ifa;
- ierr=getifaddrs(&ifas);
- if (ierr)
- {
+ struct ifaddrs* ifas;
+ struct ifaddrs* ifa;
+ ierr = getifaddrs(&ifas);
+ if (ierr) {
return -2;
- }
+ }
- for (ifa=ifas; ifa!=NULL; ifa=ifa->ifa_next)
- {
- int fam = ifa->ifa_addr? ifa->ifa_addr->sa_family : -1;
- if ((fam==AF_INET) || (fam==AF_INET6))
- {
- char host[NI_MAXHOST]={'\0'};
-
- const size_t addrlen
- = (fam==AF_INET?sizeof(struct sockaddr_in):sizeof(struct sockaddr_in6));
-
- ierr=getnameinfo(
- ifa->ifa_addr,
- static_cast<socklen_t>(addrlen),
- host,
- NI_MAXHOST,
- NULL,
- 0,
- NI_NAMEREQD);
- if (ierr)
- {
+ for (ifa = ifas; ifa != NULL; ifa = ifa->ifa_next) {
+ int fam = ifa->ifa_addr ? ifa->ifa_addr->sa_family : -1;
+ // Skip Loopback interfaces
+ if (((fam == AF_INET) || (fam == AF_INET6)) &&
+ !(ifa->ifa_flags & IFF_LOOPBACK)) {
+ char host[NI_MAXHOST] = { '\0' };
+
+ const size_t addrlen = (fam == AF_INET ? sizeof(struct sockaddr_in)
+ : sizeof(struct sockaddr_in6));
+
+ ierr = getnameinfo(ifa->ifa_addr, static_cast<socklen_t>(addrlen), host,
+ NI_MAXHOST, NULL, 0, NI_NAMEREQD);
+ if (ierr) {
// don't report the failure now since we may succeed on another
// interface. If all attempts fail then return the failure code.
- ierr=-3;
+ ierr = -3;
continue;
- }
+ }
- std::string candidate=host;
- if ((candidate.find(base)!=std::string::npos) && baseSize<candidate.size())
- {
+ std::string candidate = host;
+ if ((candidate.find(base) != std::string::npos) &&
+ baseSize < candidate.size()) {
// success, stop now.
- ierr=0;
- fqdn=candidate;
+ ierr = 0;
+ fqdn = candidate;
break;
- }
}
}
+ }
freeifaddrs(ifas);
return ierr;
#else
/* TODO: Implement on more platforms. */
- fqdn=this->GetHostname();
+ fqdn = this->GetHostname();
return -1;
#endif
}
@@ -1843,11 +1755,10 @@ const char* SystemInformationImplementation::GetOSPlatform()
}
/** Get the vendor ID */
-const char * SystemInformationImplementation::GetVendorID()
+const char* SystemInformationImplementation::GetVendorID()
{
// Return the vendor ID.
- switch (this->ChipManufacturer)
- {
+ switch (this->ChipManufacturer) {
case Intel:
return "Intel Corporation";
case AMD:
@@ -1877,7 +1788,7 @@ const char * SystemInformationImplementation::GetVendorID()
case UnknownManufacturer:
default:
return "Unknown Manufacturer";
- }
+ }
}
/** Return the type ID of the CPU */
@@ -1919,14 +1830,14 @@ std::string SystemInformationImplementation::GetSteppingCode()
}
/** Return the stepping code of the CPU present. */
-const char * SystemInformationImplementation::GetExtendedProcessorName()
+const char* SystemInformationImplementation::GetExtendedProcessorName()
{
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()
{
return this->ChipID.SerialNumber.c_str();
}
@@ -1958,93 +1869,123 @@ int SystemInformationImplementation::GetProcessorCacheSize()
/** Return the chosen cache size. */
int SystemInformationImplementation::GetProcessorCacheXSize(long int dwCacheID)
{
- switch (dwCacheID)
- {
+ switch (dwCacheID) {
case L1CACHE_FEATURE:
return this->Features.L1CacheSize;
case L2CACHE_FEATURE:
return this->Features.L2CacheSize;
case L3CACHE_FEATURE:
return this->Features.L3CacheSize;
- }
+ }
return -1;
}
-
bool SystemInformationImplementation::DoesCPUSupportFeature(long int dwFeature)
{
bool bHasFeature = false;
// Check for MMX instructions.
- if (((dwFeature & MMX_FEATURE) != 0) && this->Features.HasMMX) bHasFeature = true;
+ if (((dwFeature & MMX_FEATURE) != 0) && this->Features.HasMMX)
+ bHasFeature = true;
// Check for MMX+ instructions.
- if (((dwFeature & MMX_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.HasMMXPlus) bHasFeature = true;
+ if (((dwFeature & MMX_PLUS_FEATURE) != 0) &&
+ this->Features.ExtendedFeatures.HasMMXPlus)
+ bHasFeature = true;
// Check for SSE FP instructions.
- if (((dwFeature & SSE_FEATURE) != 0) && this->Features.HasSSE) bHasFeature = true;
+ if (((dwFeature & SSE_FEATURE) != 0) && this->Features.HasSSE)
+ bHasFeature = true;
// Check for SSE FP instructions.
- if (((dwFeature & SSE_FP_FEATURE) != 0) && this->Features.HasSSEFP) bHasFeature = true;
+ if (((dwFeature & SSE_FP_FEATURE) != 0) && this->Features.HasSSEFP)
+ bHasFeature = true;
// Check for SSE MMX instructions.
- if (((dwFeature & SSE_MMX_FEATURE) != 0) && this->Features.ExtendedFeatures.HasSSEMMX) bHasFeature = true;
+ if (((dwFeature & SSE_MMX_FEATURE) != 0) &&
+ this->Features.ExtendedFeatures.HasSSEMMX)
+ bHasFeature = true;
// Check for SSE2 instructions.
- if (((dwFeature & SSE2_FEATURE) != 0) && this->Features.HasSSE2) bHasFeature = true;
+ if (((dwFeature & SSE2_FEATURE) != 0) && this->Features.HasSSE2)
+ bHasFeature = true;
// Check for 3DNow! instructions.
- if (((dwFeature & AMD_3DNOW_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNow) bHasFeature = true;
+ if (((dwFeature & AMD_3DNOW_FEATURE) != 0) &&
+ this->Features.ExtendedFeatures.Has3DNow)
+ bHasFeature = true;
// Check for 3DNow+ instructions.
- if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNowPlus) bHasFeature = true;
+ if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) &&
+ this->Features.ExtendedFeatures.Has3DNowPlus)
+ bHasFeature = true;
// Check for IA64 instructions.
- if (((dwFeature & IA64_FEATURE) != 0) && this->Features.HasIA64) bHasFeature = true;
+ if (((dwFeature & IA64_FEATURE) != 0) && this->Features.HasIA64)
+ bHasFeature = true;
// Check for MP capable.
- if (((dwFeature & MP_CAPABLE) != 0) && this->Features.ExtendedFeatures.SupportsMP) bHasFeature = true;
+ if (((dwFeature & MP_CAPABLE) != 0) &&
+ this->Features.ExtendedFeatures.SupportsMP)
+ bHasFeature = true;
// Check for a serial number for the processor.
- if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && this->Features.HasSerial) bHasFeature = true;
+ if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && this->Features.HasSerial)
+ bHasFeature = true;
// Check for a local APIC in the processor.
- if (((dwFeature & APIC_FEATURE) != 0) && this->Features.HasAPIC) bHasFeature = true;
+ if (((dwFeature & APIC_FEATURE) != 0) && this->Features.HasAPIC)
+ bHasFeature = true;
// Check for CMOV instructions.
- if (((dwFeature & CMOV_FEATURE) != 0) && this->Features.HasCMOV) bHasFeature = true;
+ if (((dwFeature & CMOV_FEATURE) != 0) && this->Features.HasCMOV)
+ bHasFeature = true;
// Check for MTRR instructions.
- if (((dwFeature & MTRR_FEATURE) != 0) && this->Features.HasMTRR) bHasFeature = true;
+ if (((dwFeature & MTRR_FEATURE) != 0) && this->Features.HasMTRR)
+ bHasFeature = true;
// Check for L1 cache size.
- if (((dwFeature & L1CACHE_FEATURE) != 0) && (this->Features.L1CacheSize != -1)) bHasFeature = true;
+ if (((dwFeature & L1CACHE_FEATURE) != 0) &&
+ (this->Features.L1CacheSize != -1))
+ bHasFeature = true;
// Check for L2 cache size.
- if (((dwFeature & L2CACHE_FEATURE) != 0) && (this->Features.L2CacheSize != -1)) bHasFeature = true;
+ if (((dwFeature & L2CACHE_FEATURE) != 0) &&
+ (this->Features.L2CacheSize != -1))
+ bHasFeature = true;
// Check for L3 cache size.
- if (((dwFeature & L3CACHE_FEATURE) != 0) && (this->Features.L3CacheSize != -1)) bHasFeature = true;
+ if (((dwFeature & L3CACHE_FEATURE) != 0) &&
+ (this->Features.L3CacheSize != -1))
+ bHasFeature = true;
// Check for ACPI capability.
- if (((dwFeature & ACPI_FEATURE) != 0) && this->Features.HasACPI) bHasFeature = true;
+ if (((dwFeature & ACPI_FEATURE) != 0) && this->Features.HasACPI)
+ bHasFeature = true;
// Check for thermal monitor support.
- if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && this->Features.HasThermal) bHasFeature = true;
+ if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && this->Features.HasThermal)
+ bHasFeature = true;
// Check for temperature sensing diode support.
- if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode) bHasFeature = true;
+ if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) &&
+ this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode)
+ bHasFeature = true;
// Check for frequency ID support.
- if (((dwFeature & FREQUENCYID_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID) bHasFeature = true;
+ if (((dwFeature & FREQUENCYID_FEATURE) != 0) &&
+ this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID)
+ bHasFeature = true;
// Check for voltage ID support.
- if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasVoltageID) bHasFeature = true;
+ if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) &&
+ this->Features.ExtendedFeatures.PowerManagement.HasVoltageID)
+ bHasFeature = true;
return bHasFeature;
}
-
void SystemInformationImplementation::Delay(unsigned int uiMS)
{
#ifdef _WIN32
@@ -2052,21 +1993,21 @@ void SystemInformationImplementation::Delay(unsigned int uiMS)
__int64 x;
// Get the frequency of the high performance counter.
- if (!QueryPerformanceFrequency (&Frequency)) return;
+ if (!QueryPerformanceFrequency(&Frequency))
+ return;
x = Frequency.QuadPart / 1000 * uiMS;
// Get the starting position of the counter.
- QueryPerformanceCounter (&StartCounter);
+ QueryPerformanceCounter(&StartCounter);
do {
// Get the ending position of the counter.
- QueryPerformanceCounter (&EndCounter);
- } while (EndCounter.QuadPart - StartCounter.QuadPart < x);
+ QueryPerformanceCounter(&EndCounter);
+ } while (EndCounter.QuadPart - StartCounter.QuadPart < x);
#endif
(void)uiMS;
}
-
bool SystemInformationImplementation::DoesCPUSupportCPUID()
{
#if USE_CPUID
@@ -2084,76 +2025,86 @@ bool SystemInformationImplementation::DoesCPUSupportCPUID()
#endif
}
-
bool SystemInformationImplementation::RetrieveCPUFeatures()
{
#if USE_CPUID
int cpuinfo[4] = { 0, 0, 0, 0 };
- if (!call_cpuid(1, cpuinfo))
- {
+ if (!call_cpuid(1, cpuinfo)) {
return false;
- }
+ }
// Retrieve the features of CPU present.
- this->Features.HasFPU = ((cpuinfo[3] & 0x00000001) != 0); // FPU Present --> Bit 0
- this->Features.HasTSC = ((cpuinfo[3] & 0x00000010) != 0); // TSC Present --> Bit 4
- this->Features.HasAPIC = ((cpuinfo[3] & 0x00000200) != 0); // APIC Present --> Bit 9
- this->Features.HasMTRR = ((cpuinfo[3] & 0x00001000) != 0); // MTRR Present --> Bit 12
- this->Features.HasCMOV = ((cpuinfo[3] & 0x00008000) != 0); // CMOV Present --> Bit 15
- this->Features.HasSerial = ((cpuinfo[3] & 0x00040000) != 0); // Serial Present --> Bit 18
- this->Features.HasACPI = ((cpuinfo[3] & 0x00400000) != 0); // ACPI Capable --> Bit 22
- this->Features.HasMMX = ((cpuinfo[3] & 0x00800000) != 0); // MMX Present --> Bit 23
- this->Features.HasSSE = ((cpuinfo[3] & 0x02000000) != 0); // SSE Present --> Bit 25
- this->Features.HasSSE2 = ((cpuinfo[3] & 0x04000000) != 0); // SSE2 Present --> Bit 26
- this->Features.HasThermal = ((cpuinfo[3] & 0x20000000) != 0); // Thermal Monitor Present --> Bit 29
- this->Features.HasIA64 = ((cpuinfo[3] & 0x40000000) != 0); // IA64 Present --> Bit 30
+ this->Features.HasFPU =
+ ((cpuinfo[3] & 0x00000001) != 0); // FPU Present --> Bit 0
+ this->Features.HasTSC =
+ ((cpuinfo[3] & 0x00000010) != 0); // TSC Present --> Bit 4
+ this->Features.HasAPIC =
+ ((cpuinfo[3] & 0x00000200) != 0); // APIC Present --> Bit 9
+ this->Features.HasMTRR =
+ ((cpuinfo[3] & 0x00001000) != 0); // MTRR Present --> Bit 12
+ this->Features.HasCMOV =
+ ((cpuinfo[3] & 0x00008000) != 0); // CMOV Present --> Bit 15
+ this->Features.HasSerial =
+ ((cpuinfo[3] & 0x00040000) != 0); // Serial Present --> Bit 18
+ this->Features.HasACPI =
+ ((cpuinfo[3] & 0x00400000) != 0); // ACPI Capable --> Bit 22
+ this->Features.HasMMX =
+ ((cpuinfo[3] & 0x00800000) != 0); // MMX Present --> Bit 23
+ this->Features.HasSSE =
+ ((cpuinfo[3] & 0x02000000) != 0); // SSE Present --> Bit 25
+ this->Features.HasSSE2 =
+ ((cpuinfo[3] & 0x04000000) != 0); // SSE2 Present --> Bit 26
+ this->Features.HasThermal =
+ ((cpuinfo[3] & 0x20000000) != 0); // Thermal Monitor Present --> Bit 29
+ this->Features.HasIA64 =
+ ((cpuinfo[3] & 0x40000000) != 0); // IA64 Present --> Bit 30
#if USE_ASM_INSTRUCTIONS
// Retrieve extended SSE capabilities if SSE is available.
if (this->Features.HasSSE) {
// Attempt to __try some SSE FP instructions.
- __try
- {
+ __try {
// Perform: orps xmm0, xmm0
_asm
- {
+ {
_emit 0x0f
_emit 0x56
_emit 0xc0
- }
+ }
// SSE FP capable processor.
this->Features.HasSSEFP = true;
- }
- __except(1)
- {
+ } __except (1) {
// bad instruction - processor or OS cannot handle SSE FP.
this->Features.HasSSEFP = false;
- }
}
- else
- {
+ } else {
// Set the advanced SSE capabilities to not available.
this->Features.HasSSEFP = false;
- }
+ }
#else
this->Features.HasSSEFP = false;
#endif
// Retrieve Intel specific extended features.
- if (this->ChipManufacturer == Intel)
- {
- this->Features.ExtendedFeatures.SupportsHyperthreading = ((cpuinfo[3] & 0x10000000) != 0); // Intel specific: Hyperthreading --> Bit 28
- this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = (this->Features.ExtendedFeatures.SupportsHyperthreading) ? ((cpuinfo[1] & 0x00FF0000) >> 16) : 1;
-
- if ((this->Features.ExtendedFeatures.SupportsHyperthreading) && (this->Features.HasAPIC))
- {
+ if (this->ChipManufacturer == Intel) {
+ this->Features.ExtendedFeatures.SupportsHyperthreading =
+ ((cpuinfo[3] & 0x10000000) !=
+ 0); // Intel specific: Hyperthreading --> Bit 28
+ this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
+ (this->Features.ExtendedFeatures.SupportsHyperthreading)
+ ? ((cpuinfo[1] & 0x00FF0000) >> 16)
+ : 1;
+
+ if ((this->Features.ExtendedFeatures.SupportsHyperthreading) &&
+ (this->Features.HasAPIC)) {
// Retrieve APIC information if there is one present.
- this->Features.ExtendedFeatures.APIC_ID = ((cpuinfo[1] & 0xFF000000) >> 24);
- }
+ this->Features.ExtendedFeatures.APIC_ID =
+ ((cpuinfo[1] & 0xFF000000) >> 24);
}
+ }
return true;
@@ -2162,30 +2113,46 @@ bool SystemInformationImplementation::RetrieveCPUFeatures()
#endif
}
-
/** Find the manufacturer given the vendor id */
-void SystemInformationImplementation::FindManufacturer(const std::string& family)
-{
- if (this->ChipID.Vendor == "GenuineIntel") this->ChipManufacturer = Intel; // Intel Corp.
- else if (this->ChipID.Vendor == "UMC UMC UMC ") this->ChipManufacturer = UMC; // United Microelectronics Corp.
- else if (this->ChipID.Vendor == "AuthenticAMD") this->ChipManufacturer = AMD; // Advanced Micro Devices
- else if (this->ChipID.Vendor == "AMD ISBETTER") this->ChipManufacturer = AMD; // Advanced Micro Devices (1994)
- else if (this->ChipID.Vendor == "CyrixInstead") this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc.
- else if (this->ChipID.Vendor == "NexGenDriven") this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
- else if (this->ChipID.Vendor == "CentaurHauls") this->ChipManufacturer = IDT; // IDT/Centaur (now VIA)
- else if (this->ChipID.Vendor == "RiseRiseRise") this->ChipManufacturer = Rise; // Rise
- else if (this->ChipID.Vendor == "GenuineTMx86") this->ChipManufacturer = Transmeta; // Transmeta
- else if (this->ChipID.Vendor == "TransmetaCPU") this->ChipManufacturer = Transmeta; // Transmeta
- else if (this->ChipID.Vendor == "Geode By NSC") this->ChipManufacturer = NSC; // National Semiconductor
- else if (this->ChipID.Vendor == "Sun") this->ChipManufacturer = Sun; // Sun Microelectronics
- else if (this->ChipID.Vendor == "IBM") this->ChipManufacturer = IBM; // IBM Microelectronics
- else if (this->ChipID.Vendor == "Hewlett-Packard") this->ChipManufacturer = HP; // Hewlett-Packard
- else if (this->ChipID.Vendor == "Motorola") this->ChipManufacturer = Motorola; // Motorola Microelectronics
- else if (family.substr(0, 7) == "PA-RISC") this->ChipManufacturer = HP; // Hewlett-Packard
- else this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
+void SystemInformationImplementation::FindManufacturer(
+ const std::string& family)
+{
+ if (this->ChipID.Vendor == "GenuineIntel")
+ this->ChipManufacturer = Intel; // Intel Corp.
+ else if (this->ChipID.Vendor == "UMC UMC UMC ")
+ this->ChipManufacturer = UMC; // United Microelectronics Corp.
+ else if (this->ChipID.Vendor == "AuthenticAMD")
+ this->ChipManufacturer = AMD; // Advanced Micro Devices
+ else if (this->ChipID.Vendor == "AMD ISBETTER")
+ this->ChipManufacturer = AMD; // Advanced Micro Devices (1994)
+ else if (this->ChipID.Vendor == "CyrixInstead")
+ this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc.
+ else if (this->ChipID.Vendor == "NexGenDriven")
+ this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
+ else if (this->ChipID.Vendor == "CentaurHauls")
+ this->ChipManufacturer = IDT; // IDT/Centaur (now VIA)
+ else if (this->ChipID.Vendor == "RiseRiseRise")
+ this->ChipManufacturer = Rise; // Rise
+ else if (this->ChipID.Vendor == "GenuineTMx86")
+ this->ChipManufacturer = Transmeta; // Transmeta
+ else if (this->ChipID.Vendor == "TransmetaCPU")
+ this->ChipManufacturer = Transmeta; // Transmeta
+ else if (this->ChipID.Vendor == "Geode By NSC")
+ this->ChipManufacturer = NSC; // National Semiconductor
+ else if (this->ChipID.Vendor == "Sun")
+ this->ChipManufacturer = Sun; // Sun Microelectronics
+ else if (this->ChipID.Vendor == "IBM")
+ this->ChipManufacturer = IBM; // IBM Microelectronics
+ else if (this->ChipID.Vendor == "Hewlett-Packard")
+ this->ChipManufacturer = HP; // Hewlett-Packard
+ else if (this->ChipID.Vendor == "Motorola")
+ this->ChipManufacturer = Motorola; // Motorola Microelectronics
+ else if (family.substr(0, 7) == "PA-RISC")
+ this->ChipManufacturer = HP; // Hewlett-Packard
+ else
+ this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
}
-
/** */
bool SystemInformationImplementation::RetrieveCPUIdentity()
{
@@ -2193,14 +2160,12 @@ bool SystemInformationImplementation::RetrieveCPUIdentity()
int localCPUVendor[4];
int localCPUSignature[4];
- if (!call_cpuid(0, localCPUVendor))
- {
+ if (!call_cpuid(0, localCPUVendor)) {
return false;
- }
- if (!call_cpuid(1, localCPUSignature))
- {
+ }
+ if (!call_cpuid(1, localCPUSignature)) {
return false;
- }
+ }
// Process the returned information.
// ; eax = 0 --> eax: maximum value of CPUID instruction.
@@ -2208,22 +2173,30 @@ bool SystemInformationImplementation::RetrieveCPUIdentity()
// ; edx: part 2 of 3; CPU signature.
// ; ecx: part 3 of 3; CPU signature.
char vbuf[13];
- memcpy (&(vbuf[0]), &(localCPUVendor[1]), sizeof (int));
- memcpy (&(vbuf[4]), &(localCPUVendor[3]), sizeof (int));
- memcpy (&(vbuf[8]), &(localCPUVendor[2]), sizeof (int));
+ memcpy(&(vbuf[0]), &(localCPUVendor[1]), sizeof(int));
+ memcpy(&(vbuf[4]), &(localCPUVendor[3]), sizeof(int));
+ memcpy(&(vbuf[8]), &(localCPUVendor[2]), sizeof(int));
vbuf[12] = '\0';
this->ChipID.Vendor = vbuf;
// Retrieve the family of CPU present.
- // ; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
- // ; ebx: 31..24 - default APIC ID, 23..16 - logical processor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
+ // ; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type,
+ // bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
+ // ; ebx: 31..24 - default APIC ID, 23..16 - logical processor ID,
+ // 15..8 - CFLUSH chunk size , 7..0 - brand ID
// ; edx: CPU feature flags
- this->ChipID.ExtendedFamily = ((localCPUSignature[0] & 0x0FF00000) >> 20); // Bits 27..20 Used
- this->ChipID.ExtendedModel = ((localCPUSignature[0] & 0x000F0000) >> 16); // Bits 19..16 Used
- this->ChipID.Type = ((localCPUSignature[0] & 0x0000F000) >> 12); // Bits 15..12 Used
- this->ChipID.Family = ((localCPUSignature[0] & 0x00000F00) >> 8); // Bits 11..8 Used
- this->ChipID.Model = ((localCPUSignature[0] & 0x000000F0) >> 4); // Bits 7..4 Used
- this->ChipID.Revision = ((localCPUSignature[0] & 0x0000000F) >> 0); // Bits 3..0 Used
+ this->ChipID.ExtendedFamily =
+ ((localCPUSignature[0] & 0x0FF00000) >> 20); // Bits 27..20 Used
+ this->ChipID.ExtendedModel =
+ ((localCPUSignature[0] & 0x000F0000) >> 16); // Bits 19..16 Used
+ this->ChipID.Type =
+ ((localCPUSignature[0] & 0x0000F000) >> 12); // Bits 15..12 Used
+ this->ChipID.Family =
+ ((localCPUSignature[0] & 0x00000F00) >> 8); // Bits 11..8 Used
+ this->ChipID.Model =
+ ((localCPUSignature[0] & 0x000000F0) >> 4); // Bits 7..4 Used
+ this->ChipID.Revision =
+ ((localCPUSignature[0] & 0x0000000F) >> 0); // Bits 3..0 Used
return true;
@@ -2232,7 +2205,6 @@ bool SystemInformationImplementation::RetrieveCPUIdentity()
#endif
}
-
/** */
bool SystemInformationImplementation::RetrieveCPUCacheDetails()
{
@@ -2241,37 +2213,30 @@ bool SystemInformationImplementation::RetrieveCPUCacheDetails()
int L2Cache[4] = { 0, 0, 0, 0 };
// Check to see if what we are about to do is supported...
- if (RetrieveCPUExtendedLevelSupport (0x80000005))
- {
- if (!call_cpuid(0x80000005, L1Cache))
- {
+ if (RetrieveCPUExtendedLevelSupport(0x80000005)) {
+ if (!call_cpuid(0x80000005, L1Cache)) {
return false;
- }
- // Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as data cache size from edx: bits 31..24.
+ }
+ // Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as
+ // data cache size from edx: bits 31..24.
this->Features.L1CacheSize = ((L1Cache[2] & 0xFF000000) >> 24);
this->Features.L1CacheSize += ((L1Cache[3] & 0xFF000000) >> 24);
- }
- else
- {
+ } else {
// Store -1 to indicate the cache could not be queried.
this->Features.L1CacheSize = -1;
- }
+ }
// Check to see if what we are about to do is supported...
- if (RetrieveCPUExtendedLevelSupport (0x80000006))
- {
- if (!call_cpuid(0x80000006, L2Cache))
- {
+ if (RetrieveCPUExtendedLevelSupport(0x80000006)) {
+ if (!call_cpuid(0x80000006, L2Cache)) {
return false;
- }
+ }
// Save the L2 unified cache size (in KB) from ecx: bits 31..16.
this->Features.L2CacheSize = ((L2Cache[2] & 0xFFFF0000) >> 16);
- }
- else
- {
+ } else {
// Store -1 to indicate the cache could not be queried.
this->Features.L2CacheSize = -1;
- }
+ }
// Define L3 as being not present as we cannot test for it.
this->Features.L3CacheSize = -1;
@@ -2279,173 +2244,294 @@ bool SystemInformationImplementation::RetrieveCPUCacheDetails()
#endif
// Return failure if we cannot detect either cache with this method.
- return ((this->Features.L1CacheSize == -1) && (this->Features.L2CacheSize == -1)) ? false : true;
+ return ((this->Features.L1CacheSize == -1) &&
+ (this->Features.L2CacheSize == -1))
+ ? false
+ : true;
}
-
/** */
bool SystemInformationImplementation::RetrieveClassicalCPUCacheDetails()
{
#if USE_CPUID
- int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1, L2Unified = -1, L3Unified = -1;
+ int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1,
+ L2Unified = -1, L3Unified = -1;
int TLBCacheData[4] = { 0, 0, 0, 0 };
int TLBPassCounter = 0;
int TLBCacheUnit = 0;
-
do {
- if (!call_cpuid(2, TLBCacheData))
- {
+ if (!call_cpuid(2, TLBCacheData)) {
return false;
- }
+ }
int bob = ((TLBCacheData[0] & 0x00FF0000) >> 16);
(void)bob;
// Process the returned TLB and cache information.
- for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter ++)
- {
+ for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter++) {
// First of all - decide which unit we are dealing with.
- switch (nCounter)
- {
+ switch (nCounter) {
// eax: bits 8..15 : bits 16..23 : bits 24..31
- case 0: TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8); break;
- case 1: TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16); break;
- case 2: TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24); break;
+ case 0:
+ TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8);
+ break;
+ case 1:
+ TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16);
+ break;
+ case 2:
+ TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24);
+ break;
// ebx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
- case 3: TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0); break;
- case 4: TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8); break;
- case 5: TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16); break;
- case 6: TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24); break;
+ case 3:
+ TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0);
+ break;
+ case 4:
+ TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8);
+ break;
+ case 5:
+ TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16);
+ break;
+ case 6:
+ TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24);
+ break;
// ecx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
- case 7: TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0); break;
- case 8: TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8); break;
- case 9: TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16); break;
- case 10: TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24); break;
+ case 7:
+ TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0);
+ break;
+ case 8:
+ TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8);
+ break;
+ case 9:
+ TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16);
+ break;
+ case 10:
+ TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24);
+ break;
// edx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
- case 11: TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0); break;
- case 12: TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8); break;
- case 13: TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16); break;
- case 14: TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24); break;
+ case 11:
+ TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0);
+ break;
+ case 12:
+ TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8);
+ break;
+ case 13:
+ TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16);
+ break;
+ case 14:
+ TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24);
+ break;
// Default case - an error has occurred.
- default: return false;
- }
+ default:
+ return false;
+ }
// Now process the resulting unit to see what it means....
- switch (TLBCacheUnit)
- {
- case 0x00: break;
- case 0x01: STORE_TLBCACHE_INFO (TLBCode, 4); break;
- case 0x02: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
- case 0x03: STORE_TLBCACHE_INFO (TLBData, 4); break;
- case 0x04: STORE_TLBCACHE_INFO (TLBData, 4096); break;
- case 0x06: STORE_TLBCACHE_INFO (L1Code, 8); break;
- case 0x08: STORE_TLBCACHE_INFO (L1Code, 16); break;
- case 0x0a: STORE_TLBCACHE_INFO (L1Data, 8); break;
- case 0x0c: STORE_TLBCACHE_INFO (L1Data, 16); break;
- case 0x10: STORE_TLBCACHE_INFO (L1Data, 16); break; // <-- FIXME: IA-64 Only
- case 0x15: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
- case 0x1a: STORE_TLBCACHE_INFO (L2Unified, 96); break; // <-- FIXME: IA-64 Only
- case 0x22: STORE_TLBCACHE_INFO (L3Unified, 512); break;
- case 0x23: STORE_TLBCACHE_INFO (L3Unified, 1024); break;
- case 0x25: STORE_TLBCACHE_INFO (L3Unified, 2048); break;
- case 0x29: STORE_TLBCACHE_INFO (L3Unified, 4096); break;
- case 0x39: STORE_TLBCACHE_INFO (L2Unified, 128); break;
- case 0x3c: STORE_TLBCACHE_INFO (L2Unified, 256); break;
- case 0x40: STORE_TLBCACHE_INFO (L2Unified, 0); break; // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4 core).
- case 0x41: STORE_TLBCACHE_INFO (L2Unified, 128); break;
- case 0x42: STORE_TLBCACHE_INFO (L2Unified, 256); break;
- case 0x43: STORE_TLBCACHE_INFO (L2Unified, 512); break;
- case 0x44: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
- case 0x45: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
- case 0x50: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
- case 0x51: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
- case 0x52: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
- case 0x5b: STORE_TLBCACHE_INFO (TLBData, 4096); break;
- case 0x5c: STORE_TLBCACHE_INFO (TLBData, 4096); break;
- case 0x5d: STORE_TLBCACHE_INFO (TLBData, 4096); break;
- case 0x66: STORE_TLBCACHE_INFO (L1Data, 8); break;
- case 0x67: STORE_TLBCACHE_INFO (L1Data, 16); break;
- case 0x68: STORE_TLBCACHE_INFO (L1Data, 32); break;
- case 0x70: STORE_TLBCACHE_INFO (L1Trace, 12); break;
- case 0x71: STORE_TLBCACHE_INFO (L1Trace, 16); break;
- case 0x72: STORE_TLBCACHE_INFO (L1Trace, 32); break;
- case 0x77: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
- case 0x79: STORE_TLBCACHE_INFO (L2Unified, 128); break;
- case 0x7a: STORE_TLBCACHE_INFO (L2Unified, 256); break;
- case 0x7b: STORE_TLBCACHE_INFO (L2Unified, 512); break;
- case 0x7c: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
- case 0x7e: STORE_TLBCACHE_INFO (L2Unified, 256); break;
- case 0x81: STORE_TLBCACHE_INFO (L2Unified, 128); break;
- case 0x82: STORE_TLBCACHE_INFO (L2Unified, 256); break;
- case 0x83: STORE_TLBCACHE_INFO (L2Unified, 512); break;
- case 0x84: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
- case 0x85: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
- case 0x88: STORE_TLBCACHE_INFO (L3Unified, 2048); break; // <-- FIXME: IA-64 Only
- case 0x89: STORE_TLBCACHE_INFO (L3Unified, 4096); break; // <-- FIXME: IA-64 Only
- case 0x8a: STORE_TLBCACHE_INFO (L3Unified, 8192); break; // <-- FIXME: IA-64 Only
- case 0x8d: STORE_TLBCACHE_INFO (L3Unified, 3096); break; // <-- FIXME: IA-64 Only
- case 0x90: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
- case 0x96: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
- case 0x9b: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
+ switch (TLBCacheUnit) {
+ case 0x00:
+ break;
+ case 0x01:
+ STORE_TLBCACHE_INFO(TLBCode, 4);
+ break;
+ case 0x02:
+ STORE_TLBCACHE_INFO(TLBCode, 4096);
+ break;
+ case 0x03:
+ STORE_TLBCACHE_INFO(TLBData, 4);
+ break;
+ case 0x04:
+ STORE_TLBCACHE_INFO(TLBData, 4096);
+ break;
+ case 0x06:
+ STORE_TLBCACHE_INFO(L1Code, 8);
+ break;
+ case 0x08:
+ STORE_TLBCACHE_INFO(L1Code, 16);
+ break;
+ case 0x0a:
+ STORE_TLBCACHE_INFO(L1Data, 8);
+ break;
+ case 0x0c:
+ STORE_TLBCACHE_INFO(L1Data, 16);
+ break;
+ case 0x10:
+ STORE_TLBCACHE_INFO(L1Data, 16);
+ break; // <-- FIXME: IA-64 Only
+ case 0x15:
+ STORE_TLBCACHE_INFO(L1Code, 16);
+ break; // <-- FIXME: IA-64 Only
+ case 0x1a:
+ STORE_TLBCACHE_INFO(L2Unified, 96);
+ break; // <-- FIXME: IA-64 Only
+ case 0x22:
+ STORE_TLBCACHE_INFO(L3Unified, 512);
+ break;
+ case 0x23:
+ STORE_TLBCACHE_INFO(L3Unified, 1024);
+ break;
+ case 0x25:
+ STORE_TLBCACHE_INFO(L3Unified, 2048);
+ break;
+ case 0x29:
+ STORE_TLBCACHE_INFO(L3Unified, 4096);
+ break;
+ case 0x39:
+ STORE_TLBCACHE_INFO(L2Unified, 128);
+ break;
+ case 0x3c:
+ STORE_TLBCACHE_INFO(L2Unified, 256);
+ break;
+ case 0x40:
+ STORE_TLBCACHE_INFO(L2Unified, 0);
+ break; // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4
+ // core).
+ case 0x41:
+ STORE_TLBCACHE_INFO(L2Unified, 128);
+ break;
+ case 0x42:
+ STORE_TLBCACHE_INFO(L2Unified, 256);
+ break;
+ case 0x43:
+ STORE_TLBCACHE_INFO(L2Unified, 512);
+ break;
+ case 0x44:
+ STORE_TLBCACHE_INFO(L2Unified, 1024);
+ break;
+ case 0x45:
+ STORE_TLBCACHE_INFO(L2Unified, 2048);
+ break;
+ case 0x50:
+ STORE_TLBCACHE_INFO(TLBCode, 4096);
+ break;
+ case 0x51:
+ STORE_TLBCACHE_INFO(TLBCode, 4096);
+ break;
+ case 0x52:
+ STORE_TLBCACHE_INFO(TLBCode, 4096);
+ break;
+ case 0x5b:
+ STORE_TLBCACHE_INFO(TLBData, 4096);
+ break;
+ case 0x5c:
+ STORE_TLBCACHE_INFO(TLBData, 4096);
+ break;
+ case 0x5d:
+ STORE_TLBCACHE_INFO(TLBData, 4096);
+ break;
+ case 0x66:
+ STORE_TLBCACHE_INFO(L1Data, 8);
+ break;
+ case 0x67:
+ STORE_TLBCACHE_INFO(L1Data, 16);
+ break;
+ case 0x68:
+ STORE_TLBCACHE_INFO(L1Data, 32);
+ break;
+ case 0x70:
+ STORE_TLBCACHE_INFO(L1Trace, 12);
+ break;
+ case 0x71:
+ STORE_TLBCACHE_INFO(L1Trace, 16);
+ break;
+ case 0x72:
+ STORE_TLBCACHE_INFO(L1Trace, 32);
+ break;
+ case 0x77:
+ STORE_TLBCACHE_INFO(L1Code, 16);
+ break; // <-- FIXME: IA-64 Only
+ case 0x79:
+ STORE_TLBCACHE_INFO(L2Unified, 128);
+ break;
+ case 0x7a:
+ STORE_TLBCACHE_INFO(L2Unified, 256);
+ break;
+ case 0x7b:
+ STORE_TLBCACHE_INFO(L2Unified, 512);
+ break;
+ case 0x7c:
+ STORE_TLBCACHE_INFO(L2Unified, 1024);
+ break;
+ case 0x7e:
+ STORE_TLBCACHE_INFO(L2Unified, 256);
+ break;
+ case 0x81:
+ STORE_TLBCACHE_INFO(L2Unified, 128);
+ break;
+ case 0x82:
+ STORE_TLBCACHE_INFO(L2Unified, 256);
+ break;
+ case 0x83:
+ STORE_TLBCACHE_INFO(L2Unified, 512);
+ break;
+ case 0x84:
+ STORE_TLBCACHE_INFO(L2Unified, 1024);
+ break;
+ case 0x85:
+ STORE_TLBCACHE_INFO(L2Unified, 2048);
+ break;
+ case 0x88:
+ STORE_TLBCACHE_INFO(L3Unified, 2048);
+ break; // <-- FIXME: IA-64 Only
+ case 0x89:
+ STORE_TLBCACHE_INFO(L3Unified, 4096);
+ break; // <-- FIXME: IA-64 Only
+ case 0x8a:
+ STORE_TLBCACHE_INFO(L3Unified, 8192);
+ break; // <-- FIXME: IA-64 Only
+ case 0x8d:
+ STORE_TLBCACHE_INFO(L3Unified, 3096);
+ break; // <-- FIXME: IA-64 Only
+ case 0x90:
+ STORE_TLBCACHE_INFO(TLBCode, 262144);
+ break; // <-- FIXME: IA-64 Only
+ case 0x96:
+ STORE_TLBCACHE_INFO(TLBCode, 262144);
+ break; // <-- FIXME: IA-64 Only
+ case 0x9b:
+ STORE_TLBCACHE_INFO(TLBCode, 262144);
+ break; // <-- FIXME: IA-64 Only
// Default case - an error has occurred.
- default: return false;
- }
+ default:
+ return false;
}
+ }
// Increment the TLB pass counter.
- TLBPassCounter ++;
- } while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
+ TLBPassCounter++;
+ } while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
// Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
- if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1))
- {
+ if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1)) {
this->Features.L1CacheSize = -1;
- }
- else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1))
- {
+ } else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1)) {
this->Features.L1CacheSize = L1Trace;
- }
- else if ((L1Code != -1) && (L1Data == -1))
- {
+ } else if ((L1Code != -1) && (L1Data == -1)) {
this->Features.L1CacheSize = L1Code;
- }
- else if ((L1Code == -1) && (L1Data != -1))
- {
+ } else if ((L1Code == -1) && (L1Data != -1)) {
this->Features.L1CacheSize = L1Data;
- }
- else if ((L1Code != -1) && (L1Data != -1))
- {
+ } else if ((L1Code != -1) && (L1Data != -1)) {
this->Features.L1CacheSize = L1Code + L1Data;
- }
- else
- {
+ } else {
this->Features.L1CacheSize = -1;
- }
+ }
// Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
- if (L2Unified == -1)
- {
+ if (L2Unified == -1) {
this->Features.L2CacheSize = -1;
- }
- else
- {
+ } else {
this->Features.L2CacheSize = L2Unified;
- }
+ }
// Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
- if (L3Unified == -1)
- {
+ if (L3Unified == -1) {
this->Features.L3CacheSize = -1;
- }
- else
- {
+ } else {
this->Features.L3CacheSize = L3Unified;
- }
+ }
return true;
@@ -2454,7 +2540,6 @@ bool SystemInformationImplementation::RetrieveClassicalCPUCacheDetails()
#endif
}
-
/** */
bool SystemInformationImplementation::RetrieveCPUClockSpeed()
{
@@ -2463,22 +2548,19 @@ bool SystemInformationImplementation::RetrieveCPUClockSpeed()
#if defined(_WIN32)
unsigned int uiRepetitions = 1;
unsigned int uiMSecPerRepetition = 50;
- __int64 i64Total = 0;
+ __int64 i64Total = 0;
__int64 i64Overhead = 0;
// Check if the TSC implementation works at all
if (this->Features.HasTSC &&
GetCyclesDifference(SystemInformationImplementation::Delay,
- uiMSecPerRepetition) > 0)
- {
- for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter ++)
- {
- i64Total += GetCyclesDifference (SystemInformationImplementation::Delay,
- uiMSecPerRepetition);
- i64Overhead +=
- GetCyclesDifference (SystemInformationImplementation::DelayOverhead,
- uiMSecPerRepetition);
- }
+ uiMSecPerRepetition) > 0) {
+ for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter++) {
+ i64Total += GetCyclesDifference(SystemInformationImplementation::Delay,
+ uiMSecPerRepetition);
+ i64Overhead += GetCyclesDifference(
+ SystemInformationImplementation::DelayOverhead, uiMSecPerRepetition);
+ }
// Calculate the MHz speed.
i64Total -= i64Overhead;
@@ -2487,45 +2569,42 @@ bool SystemInformationImplementation::RetrieveCPUClockSpeed()
i64Total /= 1000;
// Save the CPU speed.
- this->CPUSpeedInMHz = (float) i64Total;
+ this->CPUSpeedInMHz = (float)i64Total;
retrieved = true;
- }
+ }
// If RDTSC is not supported, we fallback to trying to read this value
// from the registry:
- if (!retrieved)
- {
+ if (!retrieved) {
HKEY hKey = NULL;
- LONG err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
- L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
- KEY_READ, &hKey);
+ LONG err =
+ RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+ L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
+ KEY_READ, &hKey);
- if (ERROR_SUCCESS == err)
- {
+ if (ERROR_SUCCESS == err) {
DWORD dwType = 0;
DWORD data = 0;
DWORD dwSize = sizeof(DWORD);
- err = RegQueryValueExW(hKey, L"~MHz", 0,
- &dwType, (LPBYTE) &data, &dwSize);
+ err =
+ RegQueryValueExW(hKey, L"~MHz", 0, &dwType, (LPBYTE)&data, &dwSize);
- if (ERROR_SUCCESS == err)
- {
- this->CPUSpeedInMHz = (float) data;
+ if (ERROR_SUCCESS == err) {
+ this->CPUSpeedInMHz = (float)data;
retrieved = true;
- }
+ }
RegCloseKey(hKey);
hKey = NULL;
- }
}
+ }
#endif
return retrieved;
}
-
/** */
bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
{
@@ -2534,51 +2613,43 @@ bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
double dFrequency, dDifference;
// Attempt to get a starting tick count.
- QueryPerformanceCounter (&liStart);
+ QueryPerformanceCounter(&liStart);
- __try
- {
- _asm
- {
+ __try {
+ _asm {
mov eax, 0x80000000
mov ebx, CLASSICAL_CPU_FREQ_LOOP
Timer_Loop:
bsf ecx,eax
dec ebx
jnz Timer_Loop
- }
}
- __except(1)
- {
+ } __except (1) {
return false;
- }
+ }
// Attempt to get a starting tick count.
- QueryPerformanceCounter (&liEnd);
+ QueryPerformanceCounter(&liEnd);
// Get the difference... NB: This is in seconds....
- QueryPerformanceFrequency (&liCountsPerSecond);
- dDifference = (((double) liEnd.QuadPart - (double) liStart.QuadPart) / (double) liCountsPerSecond.QuadPart);
+ QueryPerformanceFrequency(&liCountsPerSecond);
+ dDifference = (((double)liEnd.QuadPart - (double)liStart.QuadPart) /
+ (double)liCountsPerSecond.QuadPart);
// Calculate the clock speed.
- if (this->ChipID.Family == 3)
- {
+ if (this->ChipID.Family == 3) {
// 80386 processors.... Loop time is 115 cycles!
dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1000000);
- }
- else if (this->ChipID.Family == 4)
- {
+ } else if (this->ChipID.Family == 4) {
// 80486 processors.... Loop time is 47 cycles!
dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1000000);
- }
- else if (this->ChipID.Family == 5)
- {
+ } else if (this->ChipID.Family == 5) {
// Pentium processors.... Loop time is 43 cycles!
dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1000000);
- }
+ }
// Save the clock speed.
- this->Features.CPUSpeed = (int) dFrequency;
+ this->Features.CPUSpeed = (int)dFrequency;
return true;
@@ -2587,13 +2658,14 @@ bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
#endif
}
-
/** */
-bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULevelToCheck)
+bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(
+ int CPULevelToCheck)
{
int cpuinfo[4] = { 0, 0, 0, 0 };
- // The extended CPUID is supported by various vendors starting with the following CPU models:
+ // The extended CPUID is supported by various vendors starting with the
+ // following CPU models:
//
// Manufacturer & Chip Name | Family Model Revision
//
@@ -2606,39 +2678,36 @@ bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULev
//
// We check to see if a supported processor is present...
- if (this->ChipManufacturer == AMD)
- {
- if (this->ChipID.Family < 5) return false;
- if ((this->ChipID.Family == 5) && (this->ChipID.Model < 6)) return false;
- }
- else if (this->ChipManufacturer == Cyrix)
- {
- if (this->ChipID.Family < 5) return false;
- if ((this->ChipID.Family == 5) && (this->ChipID.Model < 4)) return false;
- if ((this->ChipID.Family == 6) && (this->ChipID.Model < 5)) return false;
- }
- else if (this->ChipManufacturer == IDT)
- {
- if (this->ChipID.Family < 5) return false;
- if ((this->ChipID.Family == 5) && (this->ChipID.Model < 8)) return false;
- }
- else if (this->ChipManufacturer == Transmeta)
- {
- if (this->ChipID.Family < 5) return false;
- }
- else if (this->ChipManufacturer == Intel)
- {
- if (this->ChipID.Family < 0xf)
- {
+ if (this->ChipManufacturer == AMD) {
+ if (this->ChipID.Family < 5)
+ return false;
+ if ((this->ChipID.Family == 5) && (this->ChipID.Model < 6))
+ return false;
+ } else if (this->ChipManufacturer == Cyrix) {
+ if (this->ChipID.Family < 5)
+ return false;
+ if ((this->ChipID.Family == 5) && (this->ChipID.Model < 4))
+ return false;
+ if ((this->ChipID.Family == 6) && (this->ChipID.Model < 5))
+ return false;
+ } else if (this->ChipManufacturer == IDT) {
+ if (this->ChipID.Family < 5)
+ return false;
+ if ((this->ChipID.Family == 5) && (this->ChipID.Model < 8))
+ return false;
+ } else if (this->ChipManufacturer == Transmeta) {
+ if (this->ChipID.Family < 5)
+ return false;
+ } else if (this->ChipManufacturer == Intel) {
+ if (this->ChipID.Family < 0xf) {
return false;
- }
}
+ }
#if USE_CPUID
- if (!call_cpuid(0x80000000, cpuinfo))
- {
+ if (!call_cpuid(0x80000000, cpuinfo)) {
return false;
- }
+ }
#endif
// Now we have to check the level wanted vs level returned...
@@ -2646,56 +2715,62 @@ bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULev
int nLevelReturn = (cpuinfo[0] & 0x7FFFFFFF);
// Check to see if the level provided is supported...
- if (nLevelWanted > nLevelReturn)
- {
+ if (nLevelWanted > nLevelReturn) {
return false;
- }
+ }
return true;
}
-
/** */
bool SystemInformationImplementation::RetrieveExtendedCPUFeatures()
{
- // Check that we are not using an Intel processor as it does not support this.
- if (this->ChipManufacturer == Intel)
- {
+ // Check that we are not using an Intel processor as it does not support
+ // this.
+ if (this->ChipManufacturer == Intel) {
return false;
- }
+ }
// Check to see if what we are about to do is supported...
- if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001)))
- {
+ if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001))) {
return false;
- }
+ }
#if USE_CPUID
int localCPUExtendedFeatures[4] = { 0, 0, 0, 0 };
- if (!call_cpuid(0x80000001, localCPUExtendedFeatures))
- {
+ if (!call_cpuid(0x80000001, localCPUExtendedFeatures)) {
return false;
- }
+ }
// Retrieve the extended features of CPU present.
- this->Features.ExtendedFeatures.Has3DNow = ((localCPUExtendedFeatures[3] & 0x80000000) != 0); // 3DNow Present --> Bit 31.
- this->Features.ExtendedFeatures.Has3DNowPlus = ((localCPUExtendedFeatures[3] & 0x40000000) != 0); // 3DNow+ Present -- > Bit 30.
- this->Features.ExtendedFeatures.HasSSEMMX = ((localCPUExtendedFeatures[3] & 0x00400000) != 0); // SSE MMX Present --> Bit 22.
- this->Features.ExtendedFeatures.SupportsMP = ((localCPUExtendedFeatures[3] & 0x00080000) != 0); // MP Capable -- > Bit 19.
+ this->Features.ExtendedFeatures.Has3DNow =
+ ((localCPUExtendedFeatures[3] & 0x80000000) !=
+ 0); // 3DNow Present --> Bit 31.
+ this->Features.ExtendedFeatures.Has3DNowPlus =
+ ((localCPUExtendedFeatures[3] & 0x40000000) !=
+ 0); // 3DNow+ Present -- > Bit 30.
+ this->Features.ExtendedFeatures.HasSSEMMX =
+ ((localCPUExtendedFeatures[3] & 0x00400000) !=
+ 0); // SSE MMX Present --> Bit 22.
+ this->Features.ExtendedFeatures.SupportsMP =
+ ((localCPUExtendedFeatures[3] & 0x00080000) !=
+ 0); // MP Capable -- > Bit 19.
// Retrieve AMD specific extended features.
- if (this->ChipManufacturer == AMD)
- {
- this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x00400000) != 0); // AMD specific: MMX-SSE --> Bit 22
- }
+ if (this->ChipManufacturer == AMD) {
+ this->Features.ExtendedFeatures.HasMMXPlus =
+ ((localCPUExtendedFeatures[3] & 0x00400000) !=
+ 0); // AMD specific: MMX-SSE --> Bit 22
+ }
// Retrieve Cyrix specific extended features.
- if (this->ChipManufacturer == Cyrix)
- {
- this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x01000000) != 0); // Cyrix specific: Extended MMX --> Bit 24
- }
+ if (this->ChipManufacturer == Cyrix) {
+ this->Features.ExtendedFeatures.HasMMXPlus =
+ ((localCPUExtendedFeatures[3] & 0x01000000) !=
+ 0); // Cyrix specific: Extended MMX --> Bit 24
+ }
return true;
@@ -2704,42 +2779,40 @@ bool SystemInformationImplementation::RetrieveExtendedCPUFeatures()
#endif
}
-
/** */
bool SystemInformationImplementation::RetrieveProcessorSerialNumber()
{
// Check to see if the processor supports the processor serial number.
- if (!this->Features.HasSerial)
- {
+ if (!this->Features.HasSerial) {
return false;
- }
+ }
#if USE_CPUID
int SerialNumber[4];
- if (!call_cpuid(3, SerialNumber))
- {
+ if (!call_cpuid(3, SerialNumber)) {
return false;
- }
+ }
// Process the returned information.
- // ; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB: Transmeta only ?!?
+ // ; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB:
+ // Transmeta only ?!?
// ; ecx: middle 32 bits are the processor signature bits
// ; edx: bottom 32 bits are the processor signature bits
char sn[128];
- sprintf (sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x",
- ((SerialNumber[1] & 0xff000000) >> 24),
- ((SerialNumber[1] & 0x00ff0000) >> 16),
- ((SerialNumber[1] & 0x0000ff00) >> 8),
- ((SerialNumber[1] & 0x000000ff) >> 0),
- ((SerialNumber[2] & 0xff000000) >> 24),
- ((SerialNumber[2] & 0x00ff0000) >> 16),
- ((SerialNumber[2] & 0x0000ff00) >> 8),
- ((SerialNumber[2] & 0x000000ff) >> 0),
- ((SerialNumber[3] & 0xff000000) >> 24),
- ((SerialNumber[3] & 0x00ff0000) >> 16),
- ((SerialNumber[3] & 0x0000ff00) >> 8),
- ((SerialNumber[3] & 0x000000ff) >> 0));
+ sprintf(sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x",
+ ((SerialNumber[1] & 0xff000000) >> 24),
+ ((SerialNumber[1] & 0x00ff0000) >> 16),
+ ((SerialNumber[1] & 0x0000ff00) >> 8),
+ ((SerialNumber[1] & 0x000000ff) >> 0),
+ ((SerialNumber[2] & 0xff000000) >> 24),
+ ((SerialNumber[2] & 0x00ff0000) >> 16),
+ ((SerialNumber[2] & 0x0000ff00) >> 8),
+ ((SerialNumber[2] & 0x000000ff) >> 0),
+ ((SerialNumber[3] & 0xff000000) >> 24),
+ ((SerialNumber[3] & 0x00ff0000) >> 16),
+ ((SerialNumber[3] & 0x0000ff00) >> 8),
+ ((SerialNumber[3] & 0x000000ff) >> 0));
this->ChipID.SerialNumber = sn;
return true;
@@ -2748,31 +2821,31 @@ bool SystemInformationImplementation::RetrieveProcessorSerialNumber()
#endif
}
-
/** */
bool SystemInformationImplementation::RetrieveCPUPowerManagement()
{
// Check to see if what we are about to do is supported...
- if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007)))
- {
+ if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007))) {
this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = false;
this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = false;
this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = false;
return false;
- }
+ }
#if USE_CPUID
int localCPUPowerManagement[4] = { 0, 0, 0, 0 };
- if (!call_cpuid(0x80000007, localCPUPowerManagement))
- {
+ if (!call_cpuid(0x80000007, localCPUPowerManagement)) {
return false;
- }
+ }
// Check for the power management capabilities of the CPU.
- this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = ((localCPUPowerManagement[3] & 0x00000001) != 0);
- this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = ((localCPUPowerManagement[3] & 0x00000002) != 0);
- this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = ((localCPUPowerManagement[3] & 0x00000004) != 0);
+ this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode =
+ ((localCPUPowerManagement[3] & 0x00000001) != 0);
+ this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID =
+ ((localCPUPowerManagement[3] & 0x00000002) != 0);
+ this->Features.ExtendedFeatures.PowerManagement.HasVoltageID =
+ ((localCPUPowerManagement[3] & 0x00000004) != 0);
return true;
@@ -2785,12 +2858,12 @@ bool SystemInformationImplementation::RetrieveCPUPowerManagement()
// Used only in USE_CPUID implementation below.
static void SystemInformationStripLeadingSpace(std::string& str)
{
- // Because some manufacturers have leading white space - we have to post-process the name.
+ // Because some manufacturers have leading white space - we have to
+ // post-process the name.
std::string::size_type pos = str.find_first_not_of(" ");
- if(pos != std::string::npos)
- {
+ if (pos != std::string::npos) {
str = str.substr(pos);
- }
+ }
}
#endif
@@ -2808,38 +2881,36 @@ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity()
#if USE_CPUID
int CPUExtendedIdentity[12];
- if (!call_cpuid(0x80000002, CPUExtendedIdentity))
- {
+ if (!call_cpuid(0x80000002, CPUExtendedIdentity)) {
return false;
- }
- if (!call_cpuid(0x80000003, CPUExtendedIdentity + 4))
- {
+ }
+ if (!call_cpuid(0x80000003, CPUExtendedIdentity + 4)) {
return false;
- }
- if (!call_cpuid(0x80000004, CPUExtendedIdentity + 8))
- {
+ }
+ if (!call_cpuid(0x80000004, CPUExtendedIdentity + 8)) {
return false;
- }
+ }
// Process the returned information.
char nbuf[49];
- memcpy (&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof (int));
- memcpy (&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof (int));
- memcpy (&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof (int));
- memcpy (&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof (int));
- memcpy (&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof (int));
- memcpy (&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof (int));
- memcpy (&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof (int));
- memcpy (&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof (int));
- memcpy (&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof (int));
- memcpy (&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof (int));
- memcpy (&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof (int));
- memcpy (&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof (int));
+ memcpy(&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof(int));
+ memcpy(&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof(int));
+ memcpy(&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof(int));
+ memcpy(&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof(int));
+ memcpy(&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof(int));
+ memcpy(&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof(int));
+ memcpy(&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof(int));
+ memcpy(&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof(int));
+ memcpy(&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof(int));
+ memcpy(&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof(int));
+ memcpy(&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof(int));
+ memcpy(&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof(int));
nbuf[48] = '\0';
this->ChipID.ProcessorName = nbuf;
this->ChipID.ModelName = nbuf;
- // Because some manufacturers have leading white space - we have to post-process the name.
+ // Because some manufacturers have leading white space - we have to
+ // post-process the name.
SystemInformationStripLeadingSpace(this->ChipID.ProcessorName);
return true;
#else
@@ -2847,270 +2918,420 @@ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity()
#endif
}
-
/** */
bool SystemInformationImplementation::RetrieveClassicalCPUIdentity()
{
// Start by decided which manufacturer we are using....
- switch (this->ChipManufacturer)
- {
+ switch (this->ChipManufacturer) {
case Intel:
// Check the family / model / revision to determine the CPU ID.
switch (this->ChipID.Family) {
case 3:
- this->ChipID.ProcessorName = "Newer i80386 family";
+ this->ChipID.ProcessorName = "Newer i80386 family";
break;
case 4:
switch (this->ChipID.Model) {
- case 0: this->ChipID.ProcessorName = "i80486DX-25/33"; break;
- case 1: this->ChipID.ProcessorName = "i80486DX-50"; break;
- case 2: this->ChipID.ProcessorName = "i80486SX"; break;
- case 3: this->ChipID.ProcessorName = "i80486DX2"; break;
- case 4: this->ChipID.ProcessorName = "i80486SL"; break;
- case 5: this->ChipID.ProcessorName = "i80486SX2"; break;
- case 7: this->ChipID.ProcessorName = "i80486DX2 WriteBack"; break;
- case 8: this->ChipID.ProcessorName = "i80486DX4"; break;
- case 9: this->ChipID.ProcessorName = "i80486DX4 WriteBack"; break;
- default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
- }
+ case 0:
+ this->ChipID.ProcessorName = "i80486DX-25/33";
+ break;
+ case 1:
+ this->ChipID.ProcessorName = "i80486DX-50";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "i80486SX";
+ break;
+ case 3:
+ this->ChipID.ProcessorName = "i80486DX2";
+ break;
+ case 4:
+ this->ChipID.ProcessorName = "i80486SL";
+ break;
+ case 5:
+ this->ChipID.ProcessorName = "i80486SX2";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "i80486DX2 WriteBack";
+ break;
+ case 8:
+ this->ChipID.ProcessorName = "i80486DX4";
+ break;
+ case 9:
+ this->ChipID.ProcessorName = "i80486DX4 WriteBack";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown 80486 family";
+ return false;
+ }
break;
case 5:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "P5 A-Step"; break;
- case 1: this->ChipID.ProcessorName = "P5"; break;
- case 2: this->ChipID.ProcessorName = "P54C"; break;
- case 3: this->ChipID.ProcessorName = "P24T OverDrive"; break;
- case 4: this->ChipID.ProcessorName = "P55C"; break;
- case 7: this->ChipID.ProcessorName = "P54C"; break;
- case 8: this->ChipID.ProcessorName = "P55C (0.25micron)"; break;
- default: this->ChipID.ProcessorName = "Unknown Pentium family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "P5 A-Step";
+ break;
+ case 1:
+ this->ChipID.ProcessorName = "P5";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "P54C";
+ break;
+ case 3:
+ this->ChipID.ProcessorName = "P24T OverDrive";
+ break;
+ case 4:
+ this->ChipID.ProcessorName = "P55C";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "P54C";
+ break;
+ case 8:
+ this->ChipID.ProcessorName = "P55C (0.25micron)";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Pentium family";
+ return false;
+ }
break;
case 6:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "P6 A-Step"; break;
- case 1: this->ChipID.ProcessorName = "P6"; break;
- case 3: this->ChipID.ProcessorName = "Pentium II (0.28 micron)"; break;
- case 5: this->ChipID.ProcessorName = "Pentium II (0.25 micron)"; break;
- case 6: this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache"; break;
- case 7: this->ChipID.ProcessorName = "Pentium III (0.25 micron)"; break;
- case 8: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "; break;
- case 0xa: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "; break;
- case 0xb: this->ChipID.ProcessorName = "Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "; break;
- case 23: this->ChipID.ProcessorName = "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz"; break;
- default: this->ChipID.ProcessorName = "Unknown P6 family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "P6 A-Step";
+ break;
+ case 1:
+ this->ChipID.ProcessorName = "P6";
+ break;
+ case 3:
+ this->ChipID.ProcessorName = "Pentium II (0.28 micron)";
+ break;
+ case 5:
+ this->ChipID.ProcessorName = "Pentium II (0.25 micron)";
+ break;
+ case 6:
+ this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "Pentium III (0.25 micron)";
+ break;
+ case 8:
+ this->ChipID.ProcessorName =
+ "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache ";
+ break;
+ case 0xa:
+ this->ChipID.ProcessorName =
+ "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache ";
+ break;
+ case 0xb:
+ this->ChipID.ProcessorName = "Pentium III (0.13 micron) With "
+ "256 Or 512 KB On-Die L2 Cache ";
+ break;
+ case 23:
+ this->ChipID.ProcessorName =
+ "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown P6 family";
+ return false;
+ }
break;
case 7:
this->ChipID.ProcessorName = "Intel Merced (IA-64)";
break;
case 0xf:
// Check the extended family bits...
- switch (this->ChipID.ExtendedFamily)
- {
+ switch (this->ChipID.ExtendedFamily) {
case 0:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
- case 1: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
- case 2: this->ChipID.ProcessorName = "Pentium IV (0.13 micron)"; break;
- default: this->ChipID.ProcessorName = "Unknown Pentium 4 family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "Pentium IV (0.18 micron)";
+ break;
+ case 1:
+ this->ChipID.ProcessorName = "Pentium IV (0.18 micron)";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "Pentium IV (0.13 micron)";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Pentium 4 family";
+ return false;
+ }
break;
case 1:
this->ChipID.ProcessorName = "Intel McKinley (IA-64)";
break;
default:
this->ChipID.ProcessorName = "Pentium";
- }
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown Intel family";
return false;
- }
+ }
break;
case AMD:
// Check the family / model / revision to determine the CPU ID.
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 4:
- switch (this->ChipID.Model)
- {
- case 3: this->ChipID.ProcessorName = "80486DX2"; break;
- case 7: this->ChipID.ProcessorName = "80486DX2 WriteBack"; break;
- case 8: this->ChipID.ProcessorName = "80486DX4"; break;
- case 9: this->ChipID.ProcessorName = "80486DX4 WriteBack"; break;
- case 0xe: this->ChipID.ProcessorName = "5x86"; break;
- case 0xf: this->ChipID.ProcessorName = "5x86WB"; break;
- default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 3:
+ this->ChipID.ProcessorName = "80486DX2";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "80486DX2 WriteBack";
+ break;
+ case 8:
+ this->ChipID.ProcessorName = "80486DX4";
+ break;
+ case 9:
+ this->ChipID.ProcessorName = "80486DX4 WriteBack";
+ break;
+ case 0xe:
+ this->ChipID.ProcessorName = "5x86";
+ break;
+ case 0xf:
+ this->ChipID.ProcessorName = "5x86WB";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown 80486 family";
+ return false;
+ }
break;
case 5:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "SSA5 (PR75, PR90 = PR100)"; break;
- case 1: this->ChipID.ProcessorName = "5k86 (PR120 = PR133)"; break;
- case 2: this->ChipID.ProcessorName = "5k86 (PR166)"; break;
- case 3: this->ChipID.ProcessorName = "5k86 (PR200)"; break;
- case 6: this->ChipID.ProcessorName = "K6 (0.30 micron)"; break;
- case 7: this->ChipID.ProcessorName = "K6 (0.25 micron)"; break;
- case 8: this->ChipID.ProcessorName = "K6-2"; break;
- case 9: this->ChipID.ProcessorName = "K6-III"; break;
- case 0xd: this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)"; break;
- default: this->ChipID.ProcessorName = "Unknown 80586 family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "SSA5 (PR75, PR90 = PR100)";
+ break;
+ case 1:
+ this->ChipID.ProcessorName = "5k86 (PR120 = PR133)";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "5k86 (PR166)";
+ break;
+ case 3:
+ this->ChipID.ProcessorName = "5k86 (PR200)";
+ break;
+ case 6:
+ this->ChipID.ProcessorName = "K6 (0.30 micron)";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "K6 (0.25 micron)";
+ break;
+ case 8:
+ this->ChipID.ProcessorName = "K6-2";
+ break;
+ case 9:
+ this->ChipID.ProcessorName = "K6-III";
+ break;
+ case 0xd:
+ this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown 80586 family";
+ return false;
+ }
break;
case 6:
- switch (this->ChipID.Model)
- {
- case 1: this->ChipID.ProcessorName = "Athlon- (0.25 micron)"; break;
- case 2: this->ChipID.ProcessorName = "Athlon- (0.18 micron)"; break;
- case 3: this->ChipID.ProcessorName = "Duron- (SF core)"; break;
- case 4: this->ChipID.ProcessorName = "Athlon- (Thunderbird core)"; break;
- case 6: this->ChipID.ProcessorName = "Athlon- (Palomino core)"; break;
- case 7: this->ChipID.ProcessorName = "Duron- (Morgan core)"; break;
+ switch (this->ChipID.Model) {
+ case 1:
+ this->ChipID.ProcessorName = "Athlon- (0.25 micron)";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "Athlon- (0.18 micron)";
+ break;
+ case 3:
+ this->ChipID.ProcessorName = "Duron- (SF core)";
+ break;
+ case 4:
+ this->ChipID.ProcessorName = "Athlon- (Thunderbird core)";
+ break;
+ case 6:
+ this->ChipID.ProcessorName = "Athlon- (Palomino core)";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "Duron- (Morgan core)";
+ break;
case 8:
if (this->Features.ExtendedFeatures.SupportsMP)
this->ChipID.ProcessorName = "Athlon - MP (Thoroughbred core)";
- else this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)";
+ else
+ this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)";
break;
- default: this->ChipID.ProcessorName = "Unknown K7 family"; return false;
- }
+ default:
+ this->ChipID.ProcessorName = "Unknown K7 family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown AMD family";
return false;
- }
+ }
break;
case Transmeta:
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 5:
- switch (this->ChipID.Model)
- {
- case 4: this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00"; break;
- default: this->ChipID.ProcessorName = "Unknown Crusoe family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 4:
+ this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Crusoe family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown Transmeta family";
return false;
- }
+ }
break;
case Rise:
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 5:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "mP6 (0.25 micron)"; break;
- case 2: this->ChipID.ProcessorName = "mP6 (0.18 micron)"; break;
- default: this->ChipID.ProcessorName = "Unknown Rise family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "mP6 (0.25 micron)";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "mP6 (0.18 micron)";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Rise family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown Rise family";
return false;
- }
+ }
break;
case UMC:
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 4:
- switch (this->ChipID.Model)
- {
- case 1: this->ChipID.ProcessorName = "U5D"; break;
- case 2: this->ChipID.ProcessorName = "U5S"; break;
- default: this->ChipID.ProcessorName = "Unknown UMC family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 1:
+ this->ChipID.ProcessorName = "U5D";
+ break;
+ case 2:
+ this->ChipID.ProcessorName = "U5S";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown UMC family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown UMC family";
return false;
- }
+ }
break;
case IDT:
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 5:
- switch (this->ChipID.Model)
- {
- case 4: this->ChipID.ProcessorName = "C6"; break;
- case 8: this->ChipID.ProcessorName = "C2"; break;
- case 9: this->ChipID.ProcessorName = "C3"; break;
- default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 4:
+ this->ChipID.ProcessorName = "C6";
+ break;
+ case 8:
+ this->ChipID.ProcessorName = "C2";
+ break;
+ case 9:
+ this->ChipID.ProcessorName = "C3";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+ return false;
+ }
break;
case 6:
- switch (this->ChipID.Model)
- {
- case 6: this->ChipID.ProcessorName = "VIA Cyrix III - Samuel"; break;
- default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 6:
+ this->ChipID.ProcessorName = "VIA Cyrix III - Samuel";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
return false;
- }
+ }
break;
case Cyrix:
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 4:
- switch (this->ChipID.Model)
- {
- case 4: this->ChipID.ProcessorName = "MediaGX GX = GXm"; break;
- case 9: this->ChipID.ProcessorName = "5x86"; break;
- default: this->ChipID.ProcessorName = "Unknown Cx5x86 family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 4:
+ this->ChipID.ProcessorName = "MediaGX GX = GXm";
+ break;
+ case 9:
+ this->ChipID.ProcessorName = "5x86";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Cx5x86 family";
+ return false;
+ }
break;
case 5:
- switch (this->ChipID.Model)
- {
- case 2: this->ChipID.ProcessorName = "Cx6x86"; break;
- case 4: this->ChipID.ProcessorName = "MediaGX GXm"; break;
- default: this->ChipID.ProcessorName = "Unknown Cx6x86 family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 2:
+ this->ChipID.ProcessorName = "Cx6x86";
+ break;
+ case 4:
+ this->ChipID.ProcessorName = "MediaGX GXm";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Cx6x86 family";
+ return false;
+ }
break;
case 6:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "6x86MX"; break;
- case 5: this->ChipID.ProcessorName = "Cyrix M2 Core"; break;
- case 6: this->ChipID.ProcessorName = "WinChip C5A Core"; break;
- case 7: this->ChipID.ProcessorName = "WinChip C5B\\C5C Core"; break;
- case 8: this->ChipID.ProcessorName = "WinChip C5C-T Core"; break;
- default: this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "6x86MX";
+ break;
+ case 5:
+ this->ChipID.ProcessorName = "Cyrix M2 Core";
+ break;
+ case 6:
+ this->ChipID.ProcessorName = "WinChip C5A Core";
+ break;
+ case 7:
+ this->ChipID.ProcessorName = "WinChip C5B\\C5C Core";
+ break;
+ case 8:
+ this->ChipID.ProcessorName = "WinChip C5C-T Core";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown Cyrix family";
return false;
- }
+ }
break;
case NexGen:
- switch (this->ChipID.Family)
- {
+ switch (this->ChipID.Family) {
case 5:
- switch (this->ChipID.Model)
- {
- case 0: this->ChipID.ProcessorName = "Nx586 or Nx586FPU"; break;
- default: this->ChipID.ProcessorName = "Unknown NexGen family"; return false;
- }
+ switch (this->ChipID.Model) {
+ case 0:
+ this->ChipID.ProcessorName = "Nx586 or Nx586FPU";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown NexGen family";
+ return false;
+ }
break;
default:
this->ChipID.ProcessorName = "Unknown NexGen family";
return false;
- }
+ }
break;
case NSC:
@@ -3123,38 +3344,38 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity()
case HP:
case UnknownManufacturer:
default:
- this->ChipID.ProcessorName = "Unknown family"; // We cannot identify the processor.
+ this->ChipID.ProcessorName =
+ "Unknown family"; // We cannot identify the processor.
return false;
- }
+ }
return true;
}
-
/** Extract a value from the CPUInfo file */
-std::string SystemInformationImplementation::ExtractValueFromCpuInfoFile(std::string buffer,const char* word,size_t init)
+std::string SystemInformationImplementation::ExtractValueFromCpuInfoFile(
+ std::string buffer, const char* word, size_t init)
{
- size_t pos = buffer.find(word,init);
- if(pos != buffer.npos)
- {
+ size_t pos = buffer.find(word, init);
+ if (pos != buffer.npos) {
this->CurrentPositionInFile = pos;
- pos = buffer.find(":",pos);
- size_t pos2 = buffer.find("\n",pos);
- if(pos!=buffer.npos && pos2!=buffer.npos)
- {
- // It may happen that the beginning matches, but this is still not the requested key.
- // An example is looking for "cpu" when "cpu family" comes first. So we check that
+ pos = buffer.find(":", pos);
+ size_t pos2 = buffer.find("\n", pos);
+ if (pos != buffer.npos && pos2 != buffer.npos) {
+ // It may happen that the beginning matches, but this is still not the
+ // requested key.
+ // An example is looking for "cpu" when "cpu family" comes first. So we
+ // check that
// we have only spaces from here to pos, otherwise we search again.
- for(size_t i=this->CurrentPositionInFile+strlen(word); i < pos; ++i)
- {
- if(buffer[i] != ' ' && buffer[i] != '\t')
- {
+ for (size_t i = this->CurrentPositionInFile + strlen(word); i < pos;
+ ++i) {
+ if (buffer[i] != ' ' && buffer[i] != '\t') {
return this->ExtractValueFromCpuInfoFile(buffer, word, pos2);
- }
}
- return buffer.substr(pos+2,pos2-pos-2);
}
+ return buffer.substr(pos + 2, pos2 - pos - 2);
}
+ }
this->CurrentPositionInFile = buffer.npos;
return "";
}
@@ -3166,113 +3387,98 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
this->NumberOfPhysicalCPU = 0;
std::string buffer;
- FILE *fd = fopen("/proc/cpuinfo", "r" );
- if ( !fd )
- {
+ FILE* fd = fopen("/proc/cpuinfo", "r");
+ if (!fd) {
std::cout << "Problem opening /proc/cpuinfo" << std::endl;
return false;
- }
+ }
size_t fileSize = 0;
- while(!feof(fd))
- {
+ while (!feof(fd)) {
buffer += static_cast<char>(fgetc(fd));
fileSize++;
- }
- fclose( fd );
- buffer.resize(fileSize-2);
+ }
+ fclose(fd);
+ buffer.resize(fileSize - 2);
// Number of logical CPUs (combination of multiple processors, multi-core
// and hyperthreading)
size_t pos = buffer.find("processor\t");
- while(pos != buffer.npos)
- {
+ while (pos != buffer.npos) {
this->NumberOfLogicalCPU++;
- pos = buffer.find("processor\t",pos+1);
- }
+ pos = buffer.find("processor\t", pos + 1);
+ }
#ifdef __linux
// Find the largest physical id.
int maxId = -1;
- std::string idc =
- this->ExtractValueFromCpuInfoFile(buffer,"physical id");
- while(this->CurrentPositionInFile != buffer.npos)
- {
- int id = atoi(idc.c_str());
- if(id > maxId)
- {
- maxId=id;
- }
- idc = this->ExtractValueFromCpuInfoFile(buffer,"physical id",
- this->CurrentPositionInFile+1);
- }
+ std::string idc = this->ExtractValueFromCpuInfoFile(buffer, "physical id");
+ while (this->CurrentPositionInFile != buffer.npos) {
+ int id = atoi(idc.c_str());
+ if (id > maxId) {
+ maxId = id;
+ }
+ idc = this->ExtractValueFromCpuInfoFile(buffer, "physical id",
+ this->CurrentPositionInFile + 1);
+ }
// Physical ids returned by Linux don't distinguish cores.
// 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");
- int numberOfCoresPerCPU=atoi(cores.c_str());
- if (maxId > 0)
- {
- this->NumberOfPhysicalCPU=static_cast<unsigned int>(
- numberOfCoresPerCPU*(maxId+1));
- }
- else
- {
+ std::string cores = this->ExtractValueFromCpuInfoFile(buffer, "cpu cores");
+ int numberOfCoresPerCPU = atoi(cores.c_str());
+ if (maxId > 0) {
+ this->NumberOfPhysicalCPU =
+ static_cast<unsigned int>(numberOfCoresPerCPU * (maxId + 1));
+ } else {
// Linux Sparc: get cpu count
- this->NumberOfPhysicalCPU=
- atoi(this->ExtractValueFromCpuInfoFile(buffer,"ncpus active").c_str());
- }
+ this->NumberOfPhysicalCPU =
+ atoi(this->ExtractValueFromCpuInfoFile(buffer, "ncpus active").c_str());
+ }
#else // __CYGWIN__
// does not have "physical id" entries, neither "cpu cores"
// this has to be fixed for hyper-threading.
std::string cpucount =
- this->ExtractValueFromCpuInfoFile(buffer,"cpu count");
- this->NumberOfPhysicalCPU=
- this->NumberOfLogicalCPU = atoi(cpucount.c_str());
+ this->ExtractValueFromCpuInfoFile(buffer, "cpu count");
+ this->NumberOfPhysicalCPU = this->NumberOfLogicalCPU =
+ atoi(cpucount.c_str());
#endif
// gotta have one, and if this is 0 then we get a / by 0n
// better to have a bad answer than a crash
- if(this->NumberOfPhysicalCPU <= 0)
- {
+ if (this->NumberOfPhysicalCPU <= 0) {
this->NumberOfPhysicalCPU = 1;
- }
+ }
// LogicalProcessorsPerPhysical>1 => hyperthreading.
- this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical=
- this->NumberOfLogicalCPU/this->NumberOfPhysicalCPU;
+ this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
+ this->NumberOfLogicalCPU / this->NumberOfPhysicalCPU;
// CPU speed (checking only the first processor)
- std::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"cpu MHz");
- if(!CPUSpeed.empty())
- {
+ std::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer, "cpu MHz");
+ if (!CPUSpeed.empty()) {
this->CPUSpeedInMHz = static_cast<float>(atof(CPUSpeed.c_str()));
- }
+ }
#ifdef __linux
- else
- {
+ else {
// 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;
- }
+ CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer, "Cpu0ClkTck");
+ this->CPUSpeedInMHz =
+ static_cast<float>(strtoull(CPUSpeed.c_str(), 0, 16)) / 1000000.0f;
+ }
#endif
// Chip family
std::string familyStr =
- this->ExtractValueFromCpuInfoFile(buffer,"cpu family");
- if(familyStr.empty())
- {
- familyStr = this->ExtractValueFromCpuInfoFile(buffer,"CPU architecture");
- }
+ this->ExtractValueFromCpuInfoFile(buffer, "cpu family");
+ if (familyStr.empty()) {
+ familyStr = this->ExtractValueFromCpuInfoFile(buffer, "CPU architecture");
+ }
this->ChipID.Family = atoi(familyStr.c_str());
// Chip Vendor
- this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer,"vendor_id");
+ this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer, "vendor_id");
this->FindManufacturer(familyStr);
// second try for setting family
- if (this->ChipID.Family == 0 && this->ChipManufacturer == HP)
- {
+ if (this->ChipID.Family == 0 && this->ChipManufacturer == HP) {
if (familyStr == "PA-RISC 1.1a")
this->ChipID.Family = 0x11a;
else if (familyStr == "PA-RISC 2.0")
@@ -3280,31 +3486,30 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
// If you really get CMake to work on a machine not belonging to
// any of those families I owe you a dinner if you get it to
// contribute nightly builds regularly.
- }
+ }
// Chip Model
- this->ChipID.Model = atoi(this->ExtractValueFromCpuInfoFile(buffer,"model").c_str());
- if(!this->RetrieveClassicalCPUIdentity())
- {
+ this->ChipID.Model =
+ atoi(this->ExtractValueFromCpuInfoFile(buffer, "model").c_str());
+ if (!this->RetrieveClassicalCPUIdentity()) {
// Some platforms (e.g. PA-RISC) tell us their CPU name here.
// Note: x86 does not.
- std::string cpuname = this->ExtractValueFromCpuInfoFile(buffer,"cpu");
- if(!cpuname.empty())
- {
+ std::string cpuname = this->ExtractValueFromCpuInfoFile(buffer, "cpu");
+ if (!cpuname.empty()) {
this->ChipID.ProcessorName = cpuname;
- }
}
+ }
// Chip revision
- std::string cpurev = this->ExtractValueFromCpuInfoFile(buffer,"stepping");
- if(cpurev.empty())
- {
- cpurev = this->ExtractValueFromCpuInfoFile(buffer,"CPU revision");
- }
+ std::string cpurev = this->ExtractValueFromCpuInfoFile(buffer, "stepping");
+ if (cpurev.empty()) {
+ cpurev = this->ExtractValueFromCpuInfoFile(buffer, "CPU revision");
+ }
this->ChipID.Revision = atoi(cpurev.c_str());
// Chip Model Name
- this->ChipID.ModelName = this->ExtractValueFromCpuInfoFile(buffer,"model name").c_str();
+ this->ChipID.ModelName =
+ this->ExtractValueFromCpuInfoFile(buffer, "model name").c_str();
// L1 Cache size
// Different architectures may show different names for the caches.
@@ -3313,71 +3518,58 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
cachename.clear();
cachename.push_back("cache size"); // e.g. x86
- cachename.push_back("I-cache"); // e.g. PA-RISC
- cachename.push_back("D-cache"); // e.g. PA-RISC
+ cachename.push_back("I-cache"); // e.g. PA-RISC
+ 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]);
- if (!cacheSize.empty())
- {
+ for (size_t index = 0; index < cachename.size(); index++) {
+ std::string cacheSize =
+ this->ExtractValueFromCpuInfoFile(buffer, cachename[index]);
+ if (!cacheSize.empty()) {
pos = cacheSize.find(" KB");
- if(pos!=cacheSize.npos)
- {
- cacheSize = cacheSize.substr(0,pos);
- }
- this->Features.L1CacheSize += atoi(cacheSize.c_str());
+ if (pos != cacheSize.npos) {
+ cacheSize = cacheSize.substr(0, pos);
}
+ this->Features.L1CacheSize += atoi(cacheSize.c_str());
}
+ }
// processor feature flags (probably x86 specific)
- std::string cpuflags = this->ExtractValueFromCpuInfoFile(buffer,"flags");
- if(!cpurev.empty())
- {
+ std::string cpuflags = this->ExtractValueFromCpuInfoFile(buffer, "flags");
+ if (!cpurev.empty()) {
// now we can match every flags as space + flag + space
cpuflags = " " + cpuflags + " ";
- if ((cpuflags.find(" fpu ")!=std::string::npos))
- {
+ if ((cpuflags.find(" fpu ") != std::string::npos)) {
this->Features.HasFPU = true;
- }
- if ((cpuflags.find(" tsc ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" tsc ") != std::string::npos)) {
this->Features.HasTSC = true;
- }
- if ((cpuflags.find(" mmx ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" mmx ") != std::string::npos)) {
this->Features.HasMMX = true;
- }
- if ((cpuflags.find(" sse ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" sse ") != std::string::npos)) {
this->Features.HasSSE = true;
- }
- if ((cpuflags.find(" sse2 ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" sse2 ") != std::string::npos)) {
this->Features.HasSSE2 = true;
- }
- if ((cpuflags.find(" apic ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" apic ") != std::string::npos)) {
this->Features.HasAPIC = true;
- }
- if ((cpuflags.find(" cmov ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" cmov ") != std::string::npos)) {
this->Features.HasCMOV = true;
- }
- if ((cpuflags.find(" mtrr ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" mtrr ") != std::string::npos)) {
this->Features.HasMTRR = true;
- }
- if ((cpuflags.find(" acpi ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" acpi ") != std::string::npos)) {
this->Features.HasACPI = true;
- }
- if ((cpuflags.find(" 3dnow ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" 3dnow ") != std::string::npos)) {
this->Features.ExtendedFeatures.Has3DNow = true;
- }
}
+ }
return true;
}
@@ -3386,15 +3578,14 @@ bool SystemInformationImplementation::QueryProcessorBySysconf()
{
#if defined(_SC_NPROC_ONLN) && !defined(_SC_NPROCESSORS_ONLN)
// IRIX names this slightly different
-# define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
+#define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
#endif
#ifdef _SC_NPROCESSORS_ONLN
long c = sysconf(_SC_NPROCESSORS_ONLN);
- if (c <= 0)
- {
+ if (c <= 0) {
return false;
- }
+ }
this->NumberOfPhysicalCPU = static_cast<unsigned int>(c);
this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
@@ -3417,34 +3608,32 @@ SystemInformation::LongLong
SystemInformationImplementation::GetHostMemoryTotal()
{
#if defined(_WIN32)
-# if defined(_MSC_VER) && _MSC_VER < 1300
+#if defined(_MSC_VER) && _MSC_VER < 1300
MEMORYSTATUS stat;
stat.dwLength = sizeof(stat);
GlobalMemoryStatus(&stat);
- return stat.dwTotalPhys/1024;
-# else
+ return stat.dwTotalPhys / 1024;
+#else
MEMORYSTATUSEX statex;
- statex.dwLength=sizeof(statex);
+ statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
- return statex.ullTotalPhys/1024;
-# endif
+ return statex.ullTotalPhys / 1024;
+#endif
#elif defined(__linux)
- SystemInformation::LongLong memTotal=0;
- int ierr=GetFieldFromFile("/proc/meminfo","MemTotal:",memTotal);
- if (ierr)
- {
+ SystemInformation::LongLong memTotal = 0;
+ int ierr = GetFieldFromFile("/proc/meminfo", "MemTotal:", memTotal);
+ if (ierr) {
return -1;
- }
+ }
return memTotal;
#elif defined(__APPLE__)
uint64_t mem;
size_t len = sizeof(mem);
- int ierr=sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
- if (ierr)
- {
+ int ierr = sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
+ if (ierr) {
return -1;
- }
- return mem/1024;
+ }
+ return mem / 1024;
#else
return 0;
#endif
@@ -3455,9 +3644,10 @@ Get total system RAM in units of KiB. This may differ from the
host total if a host-wide resource limit is applied.
*/
SystemInformation::LongLong
-SystemInformationImplementation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
+SystemInformationImplementation::GetHostMemoryAvailable(
+ const char* hostLimitEnvVarName)
{
- SystemInformation::LongLong memTotal=this->GetHostMemoryTotal();
+ SystemInformation::LongLong memTotal = this->GetHostMemoryTotal();
// the following mechanism is provided for systems that
// apply resource limits across groups of processes.
@@ -3465,18 +3655,16 @@ SystemInformationImplementation::GetHostMemoryAvailable(const char *hostLimitEnv
// where the host has a large amount of ram but a given user's
// access to it is severly restricted. The system will
// apply a limit across a set of processes. Units are in KiB.
- if (hostLimitEnvVarName)
- {
- const char *hostLimitEnvVarValue=getenv(hostLimitEnvVarName);
- if (hostLimitEnvVarValue)
- {
- SystemInformation::LongLong hostLimit=atoLongLong(hostLimitEnvVarValue);
- if (hostLimit>0)
- {
- memTotal=min(hostLimit,memTotal);
- }
+ if (hostLimitEnvVarName) {
+ const char* hostLimitEnvVarValue = getenv(hostLimitEnvVarName);
+ if (hostLimitEnvVarValue) {
+ SystemInformation::LongLong hostLimit =
+ atoLongLong(hostLimitEnvVarValue);
+ if (hostLimit > 0) {
+ memTotal = min(hostLimit, memTotal);
}
}
+ }
return memTotal;
}
@@ -3487,55 +3675,52 @@ host total if a per-process resource limit is applied.
*/
SystemInformation::LongLong
SystemInformationImplementation::GetProcMemoryAvailable(
- const char *hostLimitEnvVarName,
- const char *procLimitEnvVarName)
+ const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
{
- SystemInformation::LongLong memAvail
- = this->GetHostMemoryAvailable(hostLimitEnvVarName);
+ SystemInformation::LongLong memAvail =
+ this->GetHostMemoryAvailable(hostLimitEnvVarName);
// the following mechanism is provide for systems where rlimits
// are not employed. Units are in KiB.
- if (procLimitEnvVarName)
- {
- const char *procLimitEnvVarValue=getenv(procLimitEnvVarName);
- if (procLimitEnvVarValue)
- {
- SystemInformation::LongLong procLimit=atoLongLong(procLimitEnvVarValue);
- if (procLimit>0)
- {
- memAvail=min(procLimit,memAvail);
- }
+ if (procLimitEnvVarName) {
+ const char* procLimitEnvVarValue = getenv(procLimitEnvVarName);
+ if (procLimitEnvVarValue) {
+ SystemInformation::LongLong procLimit =
+ atoLongLong(procLimitEnvVarValue);
+ if (procLimit > 0) {
+ memAvail = min(procLimit, memAvail);
}
}
+ }
#if defined(__linux)
int ierr;
ResourceLimitType rlim;
- ierr=GetResourceLimit(RLIMIT_DATA,&rlim);
- if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
- {
- memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
- }
+ ierr = GetResourceLimit(RLIMIT_DATA, &rlim);
+ if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+ memAvail =
+ min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ }
- ierr=GetResourceLimit(RLIMIT_AS,&rlim);
- if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
- {
- memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
- }
+ ierr = GetResourceLimit(RLIMIT_AS, &rlim);
+ if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+ memAvail =
+ min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ }
#elif defined(__APPLE__)
struct rlimit rlim;
int ierr;
- ierr=getrlimit(RLIMIT_DATA,&rlim);
- if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
- {
- memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
- }
+ ierr = getrlimit(RLIMIT_DATA, &rlim);
+ if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+ memAvail =
+ min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ }
- ierr=getrlimit(RLIMIT_RSS,&rlim);
- if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
- {
- memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
- }
+ ierr = getrlimit(RLIMIT_RSS, &rlim);
+ if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+ memAvail =
+ min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ }
#endif
return memAvail;
@@ -3548,56 +3733,54 @@ SystemInformation::LongLong
SystemInformationImplementation::GetHostMemoryUsed()
{
#if defined(_WIN32)
-# if defined(_MSC_VER) && _MSC_VER < 1300
+#if defined(_MSC_VER) && _MSC_VER < 1300
MEMORYSTATUS stat;
stat.dwLength = sizeof(stat);
GlobalMemoryStatus(&stat);
- return (stat.dwTotalPhys - stat.dwAvailPhys)/1024;
-# else
+ return (stat.dwTotalPhys - stat.dwAvailPhys) / 1024;
+#else
MEMORYSTATUSEX statex;
- statex.dwLength=sizeof(statex);
+ statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
- return (statex.ullTotalPhys - statex.ullAvailPhys)/1024;
-# endif
+ return (statex.ullTotalPhys - statex.ullAvailPhys) / 1024;
+#endif
#elif defined(__linux)
// First try to use MemAvailable, but it only works on newer kernels
- const char *names2[3]={"MemTotal:","MemAvailable:",NULL};
- SystemInformation::LongLong values2[2]={SystemInformation::LongLong(0)};
- int ierr=GetFieldsFromFile("/proc/meminfo",names2,values2);
- if (ierr)
- {
- const char *names4[5]={"MemTotal:","MemFree:","Buffers:","Cached:",NULL};
- SystemInformation::LongLong values4[4]={SystemInformation::LongLong(0)};
- ierr=GetFieldsFromFile("/proc/meminfo",names4,values4);
- if(ierr)
- {
+ const char* names2[3] = { "MemTotal:", "MemAvailable:", NULL };
+ SystemInformation::LongLong values2[2] = { SystemInformation::LongLong(0) };
+ int ierr = GetFieldsFromFile("/proc/meminfo", names2, values2);
+ if (ierr) {
+ const char* names4[5] = { "MemTotal:", "MemFree:", "Buffers:", "Cached:",
+ NULL };
+ SystemInformation::LongLong values4[4] = { SystemInformation::LongLong(
+ 0) };
+ ierr = GetFieldsFromFile("/proc/meminfo", names4, values4);
+ if (ierr) {
return ierr;
- }
- SystemInformation::LongLong &memTotal=values4[0];
- SystemInformation::LongLong &memFree=values4[1];
- SystemInformation::LongLong &memBuffers=values4[2];
- SystemInformation::LongLong &memCached=values4[3];
- return memTotal - memFree - memBuffers - memCached;
}
- SystemInformation::LongLong &memTotal=values2[0];
- SystemInformation::LongLong &memAvail=values2[1];
+ SystemInformation::LongLong& memTotal = values4[0];
+ SystemInformation::LongLong& memFree = values4[1];
+ SystemInformation::LongLong& memBuffers = values4[2];
+ SystemInformation::LongLong& memCached = values4[3];
+ return memTotal - memFree - memBuffers - memCached;
+ }
+ SystemInformation::LongLong& memTotal = values2[0];
+ SystemInformation::LongLong& memAvail = values2[1];
return memTotal - memAvail;
#elif defined(__APPLE__)
- SystemInformation::LongLong psz=getpagesize();
- if (psz<1)
- {
+ SystemInformation::LongLong psz = getpagesize();
+ if (psz < 1) {
return -1;
- }
- const char *names[3]={"Pages wired down:","Pages active:",NULL};
- SystemInformation::LongLong values[2]={SystemInformation::LongLong(0)};
- int ierr=GetFieldsFromCommand("vm_stat", names, values);
- if (ierr)
- {
+ }
+ const char* names[3] = { "Pages wired down:", "Pages active:", NULL };
+ SystemInformation::LongLong values[2] = { SystemInformation::LongLong(0) };
+ int ierr = GetFieldsFromCommand("vm_stat", names, values);
+ if (ierr) {
return -1;
- }
- SystemInformation::LongLong &vmWired=values[0];
- SystemInformation::LongLong &vmActive=values[1];
- return ((vmActive+vmWired)*psz)/1024;
+ }
+ SystemInformation::LongLong& vmWired = values[0];
+ SystemInformation::LongLong& vmActive = values[1];
+ return ((vmActive + vmWired) * psz) / 1024;
#else
return 0;
#endif
@@ -3611,60 +3794,51 @@ SystemInformation::LongLong
SystemInformationImplementation::GetProcMemoryUsed()
{
#if defined(_WIN32) && defined(KWSYS_SYS_HAS_PSAPI)
- long pid=GetCurrentProcessId();
+ long pid = GetCurrentProcessId();
HANDLE hProc;
- hProc=OpenProcess(
- PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
- false,
- pid);
- if (hProc==0)
- {
+ hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
+ if (hProc == 0) {
return -1;
- }
+ }
PROCESS_MEMORY_COUNTERS pmc;
- int ok=GetProcessMemoryInfo(hProc,&pmc,sizeof(pmc));
+ int ok = GetProcessMemoryInfo(hProc, &pmc, sizeof(pmc));
CloseHandle(hProc);
- if (!ok)
- {
+ if (!ok) {
return -2;
- }
- return pmc.WorkingSetSize/1024;
+ }
+ return pmc.WorkingSetSize / 1024;
#elif defined(__linux)
- SystemInformation::LongLong memUsed=0;
- int ierr=GetFieldFromFile("/proc/self/status","VmRSS:",memUsed);
- if (ierr)
- {
+ SystemInformation::LongLong memUsed = 0;
+ int ierr = GetFieldFromFile("/proc/self/status", "VmRSS:", memUsed);
+ if (ierr) {
return -1;
- }
+ }
return memUsed;
#elif defined(__APPLE__)
- SystemInformation::LongLong memUsed=0;
- pid_t pid=getpid();
+ SystemInformation::LongLong memUsed = 0;
+ pid_t pid = getpid();
std::ostringstream oss;
oss << "ps -o rss= -p " << pid;
- FILE *file=popen(oss.str().c_str(),"r");
- if (file==0)
- {
+ FILE* file = popen(oss.str().c_str(), "r");
+ if (file == 0) {
return -1;
- }
+ }
oss.str("");
- while (!feof(file) && !ferror(file))
- {
- char buf[256]={'\0'};
- errno=0;
- size_t nRead=fread(buf,1,256,file);
- if (ferror(file) && (errno==EINTR))
- {
+ while (!feof(file) && !ferror(file)) {
+ char buf[256] = { '\0' };
+ errno = 0;
+ size_t nRead = fread(buf, 1, 256, file);
+ if (ferror(file) && (errno == EINTR)) {
clearerr(file);
- }
- if (nRead) oss << buf;
}
- int ierr=ferror(file);
+ if (nRead)
+ oss << buf;
+ }
+ int ierr = ferror(file);
pclose(file);
- if (ierr)
- {
+ if (ierr) {
return -2;
- }
+ }
std::istringstream iss(oss.str());
iss >> memUsed;
return memUsed;
@@ -3677,27 +3851,24 @@ double SystemInformationImplementation::GetLoadAverage()
{
#if defined(KWSYS_CXX_HAS_GETLOADAVG)
double loadavg[3] = { 0.0, 0.0, 0.0 };
- if (getloadavg(loadavg, 3) > 0)
- {
+ if (getloadavg(loadavg, 3) > 0) {
return loadavg[0];
- }
+ }
return -0.0;
#elif defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
// Old windows.h headers do not provide GetSystemTimes.
- typedef BOOL (WINAPI *GetSystemTimesType)(LPFILETIME, LPFILETIME,
+ typedef BOOL(WINAPI * GetSystemTimesType)(LPFILETIME, LPFILETIME,
LPFILETIME);
static GetSystemTimesType pGetSystemTimes =
(GetSystemTimesType)GetProcAddress(GetModuleHandleW(L"kernel32"),
"GetSystemTimes");
FILETIME idleTime, kernelTime, userTime;
- if (pGetSystemTimes && pGetSystemTimes(&idleTime, &kernelTime, &userTime))
- {
- unsigned __int64 const idleTicks =
- fileTimeToUInt64(idleTime);
+ if (pGetSystemTimes && pGetSystemTimes(&idleTime, &kernelTime, &userTime)) {
+ unsigned __int64 const idleTicks = fileTimeToUInt64(idleTime);
unsigned __int64 const totalTicks =
fileTimeToUInt64(kernelTime) + fileTimeToUInt64(userTime);
return calculateCPULoad(idleTicks, totalTicks) * GetNumberOfPhysicalCPU();
- }
+ }
return -0.0;
#else
// Not implemented on this platform.
@@ -3708,8 +3879,7 @@ double SystemInformationImplementation::GetLoadAverage()
/**
Get the process id of the running process.
*/
-SystemInformation::LongLong
-SystemInformationImplementation::GetProcessId()
+SystemInformation::LongLong SystemInformationImplementation::GetProcessId()
{
#if defined(_WIN32)
return GetCurrentProcessId();
@@ -3724,40 +3894,39 @@ SystemInformationImplementation::GetProcessId()
return current program stack in a string
demangle cxx symbols if possible.
*/
-std::string SystemInformationImplementation::GetProgramStack(
- int firstFrame,
- int wholePath)
+std::string SystemInformationImplementation::GetProgramStack(int firstFrame,
+ int wholePath)
{
std::string programStack = ""
#if !defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
- "WARNING: The stack could not be examined "
- "because backtrace is not supported.\n"
+ "WARNING: The stack could not be examined "
+ "because backtrace is not supported.\n"
#elif !defined(KWSYS_SYSTEMINFORMATION_HAS_DEBUG_BUILD)
- "WARNING: The stack trace will not use advanced "
- "capabilities because this is a release build.\n"
+ "WARNING: The stack trace will not use advanced "
+ "capabilities because this is a release build.\n"
#else
-# if !defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
- "WARNING: Function names will not be demangled because "
- "dladdr is not available.\n"
-# endif
-# if !defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
- "WARNING: Function names will not be demangled "
- "because cxxabi is not available.\n"
-# endif
+#if !defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
+ "WARNING: Function names will not be demangled "
+ "because "
+ "dladdr is not available.\n"
+#endif
+#if !defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
+ "WARNING: Function names will not be demangled "
+ "because cxxabi is not available.\n"
+#endif
#endif
;
std::ostringstream oss;
#if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
- void *stackSymbols[256];
- int nFrames=backtrace(stackSymbols,256);
- for (int i=firstFrame; i<nFrames; ++i)
- {
+ void* stackSymbols[256];
+ int nFrames = backtrace(stackSymbols, 256);
+ for (int i = firstFrame; i < nFrames; ++i) {
SymbolProperties symProps;
symProps.SetReportPath(wholePath);
symProps.Initialize(stackSymbols[i]);
oss << symProps << std::endl;
- }
+ }
#else
(void)firstFrame;
(void)wholePath;
@@ -3767,14 +3936,13 @@ std::string SystemInformationImplementation::GetProgramStack(
return programStack;
}
-
/**
when set print stack trace in response to common signals.
*/
void SystemInformationImplementation::SetStackTraceOnError(int enable)
{
#if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
- static int saOrigValid=0;
+ static int saOrigValid = 0;
static struct sigaction saABRTOrig;
static struct sigaction saSEGVOrig;
static struct sigaction saTERMOrig;
@@ -3783,53 +3951,48 @@ void SystemInformationImplementation::SetStackTraceOnError(int enable)
static struct sigaction saBUSOrig;
static struct sigaction saFPEOrig;
-
- if (enable && !saOrigValid)
- {
+ if (enable && !saOrigValid) {
// save the current actions
- sigaction(SIGABRT,0,&saABRTOrig);
- sigaction(SIGSEGV,0,&saSEGVOrig);
- sigaction(SIGTERM,0,&saTERMOrig);
- sigaction(SIGINT,0,&saINTOrig);
- sigaction(SIGILL,0,&saILLOrig);
- sigaction(SIGBUS,0,&saBUSOrig);
- sigaction(SIGFPE,0,&saFPEOrig);
+ sigaction(SIGABRT, 0, &saABRTOrig);
+ sigaction(SIGSEGV, 0, &saSEGVOrig);
+ sigaction(SIGTERM, 0, &saTERMOrig);
+ sigaction(SIGINT, 0, &saINTOrig);
+ sigaction(SIGILL, 0, &saILLOrig);
+ sigaction(SIGBUS, 0, &saBUSOrig);
+ sigaction(SIGFPE, 0, &saFPEOrig);
// enable read, disable write
- saOrigValid=1;
+ saOrigValid = 1;
// install ours
struct sigaction sa;
- sa.sa_sigaction=(SigAction)StacktraceSignalHandler;
- sa.sa_flags=SA_SIGINFO|SA_RESETHAND;
-# ifdef SA_RESTART
- sa.sa_flags|=SA_RESTART;
-# endif
+ sa.sa_sigaction = (SigAction)StacktraceSignalHandler;
+ sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
+#ifdef SA_RESTART
+ sa.sa_flags |= SA_RESTART;
+#endif
sigemptyset(&sa.sa_mask);
- sigaction(SIGABRT,&sa,0);
- sigaction(SIGSEGV,&sa,0);
- sigaction(SIGTERM,&sa,0);
- sigaction(SIGINT,&sa,0);
- sigaction(SIGILL,&sa,0);
- sigaction(SIGBUS,&sa,0);
- sigaction(SIGFPE,&sa,0);
- }
- else
- if (!enable && saOrigValid)
- {
+ sigaction(SIGABRT, &sa, 0);
+ sigaction(SIGSEGV, &sa, 0);
+ sigaction(SIGTERM, &sa, 0);
+ sigaction(SIGINT, &sa, 0);
+ sigaction(SIGILL, &sa, 0);
+ sigaction(SIGBUS, &sa, 0);
+ sigaction(SIGFPE, &sa, 0);
+ } else if (!enable && saOrigValid) {
// restore previous actions
- sigaction(SIGABRT,&saABRTOrig,0);
- sigaction(SIGSEGV,&saSEGVOrig,0);
- sigaction(SIGTERM,&saTERMOrig,0);
- sigaction(SIGINT,&saINTOrig,0);
- sigaction(SIGILL,&saILLOrig,0);
- sigaction(SIGBUS,&saBUSOrig,0);
- sigaction(SIGFPE,&saFPEOrig,0);
+ sigaction(SIGABRT, &saABRTOrig, 0);
+ sigaction(SIGSEGV, &saSEGVOrig, 0);
+ sigaction(SIGTERM, &saTERMOrig, 0);
+ sigaction(SIGINT, &saINTOrig, 0);
+ sigaction(SIGILL, &saILLOrig, 0);
+ sigaction(SIGBUS, &saBUSOrig, 0);
+ sigaction(SIGFPE, &saFPEOrig, 0);
// enable write, disable read
- saOrigValid=0;
- }
+ saOrigValid = 0;
+ }
#else
// avoid warning C4100
(void)enable;
@@ -3839,30 +4002,29 @@ void SystemInformationImplementation::SetStackTraceOnError(int enable)
bool SystemInformationImplementation::QueryWindowsMemory()
{
#if defined(_WIN32)
-# if defined(_MSC_VER) && _MSC_VER < 1300
+#if defined(_MSC_VER) && _MSC_VER < 1300
MEMORYSTATUS ms;
unsigned long tv, tp, av, ap;
ms.dwLength = sizeof(ms);
GlobalMemoryStatus(&ms);
-# define MEM_VAL(value) dw##value
-# else
+#define MEM_VAL(value) dw##value
+#else
MEMORYSTATUSEX ms;
DWORDLONG tv, tp, av, ap;
ms.dwLength = sizeof(ms);
- if (0 == GlobalMemoryStatusEx(&ms))
- {
+ if (0 == GlobalMemoryStatusEx(&ms)) {
return 0;
}
-# define MEM_VAL(value) ull##value
-# endif
+#define MEM_VAL(value) ull##value
+#endif
tv = ms.MEM_VAL(TotalPageFile);
tp = ms.MEM_VAL(TotalPhys);
av = ms.MEM_VAL(AvailPageFile);
ap = ms.MEM_VAL(AvailPhys);
- this->TotalVirtualMemory = tv>>10>>10;
- this->TotalPhysicalMemory = tp>>10>>10;
- this->AvailableVirtualMemory = av>>10>>10;
- this->AvailablePhysicalMemory = ap>>10>>10;
+ this->TotalVirtualMemory = tv >> 10 >> 10;
+ this->TotalPhysicalMemory = tp >> 10 >> 10;
+ this->AvailableVirtualMemory = av >> 10 >> 10;
+ this->AvailablePhysicalMemory = ap >> 10 >> 10;
return true;
#else
return false;
@@ -3872,10 +4034,10 @@ bool SystemInformationImplementation::QueryWindowsMemory()
bool SystemInformationImplementation::QueryLinuxMemory()
{
#if defined(__linux)
- unsigned long tv=0;
- unsigned long tp=0;
- unsigned long av=0;
- unsigned long ap=0;
+ unsigned long tv = 0;
+ unsigned long tp = 0;
+ unsigned long av = 0;
+ unsigned long ap = 0;
char buffer[1024]; // for reading lines
@@ -3885,109 +4047,99 @@ bool SystemInformationImplementation::QueryLinuxMemory()
// Find the Linux kernel version first
struct utsname unameInfo;
int errorFlag = uname(&unameInfo);
- if( errorFlag!=0 )
- {
+ if (errorFlag != 0) {
std::cout << "Problem calling uname(): " << strerror(errno) << std::endl;
return false;
- }
+ }
- if( strlen(unameInfo.release)>=3 )
- {
+ if (strlen(unameInfo.release) >= 3) {
// release looks like "2.6.3-15mdk-i686-up-4GB"
- char majorChar=unameInfo.release[0];
- char minorChar=unameInfo.release[2];
+ char majorChar = unameInfo.release[0];
+ char minorChar = unameInfo.release[2];
- if( isdigit(majorChar) )
- {
- linuxMajor=majorChar-'0';
- }
+ if (isdigit(majorChar)) {
+ linuxMajor = majorChar - '0';
+ }
- if( isdigit(minorChar) )
- {
- linuxMinor=minorChar-'0';
- }
+ if (isdigit(minorChar)) {
+ linuxMinor = minorChar - '0';
}
+ }
- FILE *fd = fopen("/proc/meminfo", "r" );
- if ( !fd )
- {
+ FILE* fd = fopen("/proc/meminfo", "r");
+ if (!fd) {
std::cout << "Problem opening /proc/meminfo" << std::endl;
return false;
- }
+ }
- if( linuxMajor>=3 || ( (linuxMajor>=2) && (linuxMinor>=6) ) )
- {
+ if (linuxMajor >= 3 || ((linuxMajor >= 2) && (linuxMinor >= 6))) {
// new /proc/meminfo format since kernel 2.6.x
// Rigorously, this test should check from the developping version 2.5.x
// that introduced the new format...
- enum { mMemTotal, mMemFree, mBuffers, mCached, mSwapTotal, mSwapFree };
- const char* format[6] =
- { "MemTotal:%lu kB", "MemFree:%lu kB", "Buffers:%lu kB",
- "Cached:%lu kB", "SwapTotal:%lu kB", "SwapFree:%lu kB" };
+ enum
+ {
+ mMemTotal,
+ mMemFree,
+ mBuffers,
+ mCached,
+ mSwapTotal,
+ mSwapFree
+ };
+ const char* format[6] = { "MemTotal:%lu kB", "MemFree:%lu kB",
+ "Buffers:%lu kB", "Cached:%lu kB",
+ "SwapTotal:%lu kB", "SwapFree:%lu kB" };
bool have[6] = { false, false, false, false, false, false };
unsigned long value[6];
int count = 0;
- while(fgets(buffer, static_cast<int>(sizeof(buffer)), fd))
- {
- for(int i=0; i < 6; ++i)
- {
- if(!have[i] && sscanf(buffer, format[i], &value[i]) == 1)
- {
+ while (fgets(buffer, static_cast<int>(sizeof(buffer)), fd)) {
+ for (int i = 0; i < 6; ++i) {
+ if (!have[i] && sscanf(buffer, format[i], &value[i]) == 1) {
have[i] = true;
++count;
- }
}
}
- if(count == 6)
- {
+ }
+ if (count == 6) {
this->TotalPhysicalMemory = value[mMemTotal] / 1024;
this->AvailablePhysicalMemory =
(value[mMemFree] + value[mBuffers] + value[mCached]) / 1024;
this->TotalVirtualMemory = value[mSwapTotal] / 1024;
this->AvailableVirtualMemory = value[mSwapFree] / 1024;
- }
- else
- {
+ } else {
std::cout << "Problem parsing /proc/meminfo" << std::endl;
fclose(fd);
return false;
- }
}
- else
- {
+ } else {
// /proc/meminfo format for kernel older than 2.6.x
unsigned long temp;
unsigned long cachedMem;
unsigned long buffersMem;
// Skip "total: used:..."
- char *r=fgets(buffer, static_cast<int>(sizeof(buffer)), fd);
- int status=0;
- if(r==buffer)
- {
- status+=fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n",
- &tp, &temp, &ap, &temp, &buffersMem, &cachedMem);
- }
- if(status==6)
- {
- status+=fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av);
- }
- if(status==9)
- {
- this->TotalVirtualMemory = tv>>10>>10;
- this->TotalPhysicalMemory = tp>>10>>10;
- this->AvailableVirtualMemory = av>>10>>10;
- this->AvailablePhysicalMemory = (ap+buffersMem+cachedMem)>>10>>10;
- }
- else
- {
+ char* r = fgets(buffer, static_cast<int>(sizeof(buffer)), fd);
+ int status = 0;
+ if (r == buffer) {
+ status += fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n", &tp, &temp, &ap,
+ &temp, &buffersMem, &cachedMem);
+ }
+ if (status == 6) {
+ status += fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av);
+ }
+ if (status == 9) {
+ this->TotalVirtualMemory = tv >> 10 >> 10;
+ this->TotalPhysicalMemory = tp >> 10 >> 10;
+ this->AvailableVirtualMemory = av >> 10 >> 10;
+ this->AvailablePhysicalMemory =
+ (ap + buffersMem + cachedMem) >> 10 >> 10;
+ } else {
std::cout << "Problem parsing /proc/meminfo" << std::endl;
fclose(fd);
return false;
- }
}
- fclose( fd );
+ }
+ fclose(fd);
return true;
#else
@@ -4002,10 +4154,9 @@ bool SystemInformationImplementation::QueryCygwinMemory()
// see http://cygwin.com/ml/cygwin/2006-06/msg00350.html
// Therefore just use 4096 as the page size of Windows.
long m = sysconf(_SC_PHYS_PAGES);
- if (m < 0)
- {
+ if (m < 0) {
return false;
- }
+ }
this->TotalPhysicalMemory = m >> 8;
return true;
#else
@@ -4017,10 +4168,9 @@ bool SystemInformationImplementation::QueryAIXMemory()
{
#if defined(_AIX) && defined(_SC_AIX_REALMEM)
long c = sysconf(_SC_AIX_REALMEM);
- if (c <= 0)
- {
+ if (c <= 0) {
return false;
- }
+ }
this->TotalPhysicalMemory = c / 1024;
@@ -4039,10 +4189,9 @@ bool SystemInformationImplementation::QueryMemoryBySysconf()
long p = sysconf(_SC_PHYS_PAGES);
long m = sysconf(_SC_PAGESIZE);
- if (p < 0 || m < 0)
- {
+ if (p < 0 || m < 0) {
return false;
- }
+ }
// assume pagesize is a power of 2 and smaller 1 MiB
size_t pagediv = (1024 * 1024 / m);
@@ -4052,10 +4201,9 @@ bool SystemInformationImplementation::QueryMemoryBySysconf()
#if defined(_SC_AVPHYS_PAGES)
p = sysconf(_SC_AVPHYS_PAGES);
- if (p < 0)
- {
+ if (p < 0) {
return false;
- }
+ }
this->AvailablePhysicalMemory = p;
this->AvailablePhysicalMemory /= pagediv;
@@ -4098,8 +4246,8 @@ size_t SystemInformationImplementation::GetAvailablePhysicalMemory()
/** Get Cycle differences */
SystemInformation::LongLong
-SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
- unsigned int uiParameter)
+SystemInformationImplementation::GetCyclesDifference(DELAY_FUNC DelayFunction,
+ unsigned int uiParameter)
{
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
unsigned __int64 stamp1, stamp2;
@@ -4137,13 +4285,11 @@ SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
mov edx1, edi ; edx2 = edi
mov eax1, esi ; eax2 = esi
}
- }
- __except(1)
- {
+ } __except (1) {
return -1;
- }
+ }
- return ((((__int64) edx2 << 32) + eax2) - (((__int64) edx1 << 32) + eax1));
+ return ((((__int64)edx2 << 32) + eax2) - (((__int64)edx1 << 32) + eax1));
#else
(void)DelayFunction;
@@ -4152,7 +4298,6 @@ SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
#endif
}
-
/** Compute the delay overhead */
void SystemInformationImplementation::DelayOverhead(unsigned int uiMS)
{
@@ -4161,238 +4306,213 @@ void SystemInformationImplementation::DelayOverhead(unsigned int uiMS)
__int64 x;
// Get the frequency of the high performance counter.
- if(!QueryPerformanceFrequency (&Frequency))
- {
+ if (!QueryPerformanceFrequency(&Frequency)) {
return;
- }
+ }
x = Frequency.QuadPart / 1000 * uiMS;
// Get the starting position of the counter.
- QueryPerformanceCounter (&StartCounter);
+ QueryPerformanceCounter(&StartCounter);
do {
// Get the ending position of the counter.
- QueryPerformanceCounter (&EndCounter);
+ QueryPerformanceCounter(&EndCounter);
} while (EndCounter.QuadPart - StartCounter.QuadPart == x);
#endif
(void)uiMS;
}
-/** Return the number of logical CPU per physical CPUs Works only for windows */
+/** Return the number of logical CPU per physical CPUs Works only for windows
+ */
unsigned char SystemInformationImplementation::LogicalCPUPerPhysicalCPU(void)
{
#ifdef __APPLE__
size_t len = 4;
int cores_per_package = 0;
- int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &len, NULL, 0);
- if (err != 0)
- {
- return 1; // That name was not found, default to 1
- }
+ int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package,
+ &len, NULL, 0);
+ if (err != 0) {
+ return 1; // That name was not found, default to 1
+ }
return static_cast<unsigned char>(cores_per_package);
#else
int Regs[4] = { 0, 0, 0, 0 };
#if USE_CPUID
- if (!this->IsHyperThreadingSupported())
- {
- return static_cast<unsigned char>(1); // HT not supported
- }
+ if (!this->IsHyperThreadingSupported()) {
+ return static_cast<unsigned char>(1); // HT not supported
+ }
call_cpuid(1, Regs);
#endif
- return static_cast<unsigned char> ((Regs[1] & NUM_LOGICAL_BITS) >> 16);
+ return static_cast<unsigned char>((Regs[1] & NUM_LOGICAL_BITS) >> 16);
#endif
}
-
/** Works only for windows */
bool SystemInformationImplementation::IsHyperThreadingSupported()
{
- if (this->Features.ExtendedFeatures.SupportsHyperthreading)
- {
+ if (this->Features.ExtendedFeatures.SupportsHyperthreading) {
return true;
- }
+ }
#if USE_CPUID
- int Regs[4] = { 0, 0, 0, 0 },
- VendorId[4] = { 0, 0, 0, 0 };
+ int Regs[4] = { 0, 0, 0, 0 }, VendorId[4] = { 0, 0, 0, 0 };
// Get vendor id string
- if (!call_cpuid(0, VendorId))
- {
+ if (!call_cpuid(0, VendorId)) {
return false;
- }
+ }
// eax contains family processor type
// edx has info about the availability of hyper-Threading
- if (!call_cpuid(1, Regs))
- {
+ if (!call_cpuid(1, Regs)) {
return false;
- }
+ }
- if (((Regs[0] & FAMILY_ID) == PENTIUM4_ID) || (Regs[0] & EXT_FAMILY_ID))
- {
+ if (((Regs[0] & FAMILY_ID) == PENTIUM4_ID) || (Regs[0] & EXT_FAMILY_ID)) {
if (VendorId[1] == 0x756e6547) // 'uneG'
- {
+ {
if (VendorId[3] == 0x49656e69) // 'Ieni'
- {
+ {
if (VendorId[2] == 0x6c65746e) // 'letn'
- {
+ {
// Genuine Intel with hyper-Threading technology
- this->Features.ExtendedFeatures.SupportsHyperthreading = ((Regs[3] & HT_BIT) != 0);
+ this->Features.ExtendedFeatures.SupportsHyperthreading =
+ ((Regs[3] & HT_BIT) != 0);
return this->Features.ExtendedFeatures.SupportsHyperthreading;
- }
}
}
}
+ }
#endif
- return 0; // Not genuine Intel processor
+ return 0; // Not genuine Intel processor
}
-
/** Return the APIC Id. Works only for windows. */
unsigned char SystemInformationImplementation::GetAPICId()
{
int Regs[4] = { 0, 0, 0, 0 };
#if USE_CPUID
- if (!this->IsHyperThreadingSupported())
- {
- return static_cast<unsigned char>(-1); // HT not supported
- } // Logical processor = 1
+ if (!this->IsHyperThreadingSupported()) {
+ return static_cast<unsigned char>(-1); // HT not supported
+ } // Logical processor = 1
call_cpuid(1, Regs);
#endif
return static_cast<unsigned char>((Regs[1] & INITIAL_APIC_ID_BITS) >> 24);
}
-
/** Count the number of CPUs. Works only on windows. */
int SystemInformationImplementation::CPUCount()
{
#if defined(_WIN32)
- unsigned char StatusFlag = 0;
+ unsigned char StatusFlag = 0;
SYSTEM_INFO info;
this->NumberOfPhysicalCPU = 0;
this->NumberOfLogicalCPU = 0;
info.dwNumberOfProcessors = 0;
- GetSystemInfo (&info);
+ GetSystemInfo(&info);
// Number of physical processors in a non-Intel system
// or in a 32-bit Intel system with Hyper-Threading technology disabled
- this->NumberOfPhysicalCPU = (unsigned char) info.dwNumberOfProcessors;
+ this->NumberOfPhysicalCPU = (unsigned char)info.dwNumberOfProcessors;
- if (this->IsHyperThreadingSupported())
- {
+ if (this->IsHyperThreadingSupported()) {
unsigned char HT_Enabled = 0;
this->NumberOfLogicalCPU = this->LogicalCPUPerPhysicalCPU();
- if (this->NumberOfLogicalCPU >= 1) // >1 Doesn't mean HT is enabled in the BIOS
- {
+ if (this->NumberOfLogicalCPU >=
+ 1) // >1 Doesn't mean HT is enabled in the BIOS
+ {
HANDLE hCurrentProcessHandle;
#ifndef _WIN64
-# define DWORD_PTR DWORD
+#define DWORD_PTR DWORD
#endif
- DWORD_PTR dwProcessAffinity;
- DWORD_PTR dwSystemAffinity;
- DWORD dwAffinityMask;
+ DWORD_PTR dwProcessAffinity;
+ DWORD_PTR dwSystemAffinity;
+ DWORD dwAffinityMask;
// Calculate the appropriate shifts and mask based on the
// number of logical processors.
unsigned int i = 1;
- unsigned char PHY_ID_MASK = 0xFF;
- //unsigned char PHY_ID_SHIFT = 0;
+ unsigned char PHY_ID_MASK = 0xFF;
+ // unsigned char PHY_ID_SHIFT = 0;
- while (i < this->NumberOfLogicalCPU)
- {
+ while (i < this->NumberOfLogicalCPU) {
i *= 2;
- PHY_ID_MASK <<= 1;
- // PHY_ID_SHIFT++;
- }
+ PHY_ID_MASK <<= 1;
+ // PHY_ID_SHIFT++;
+ }
hCurrentProcessHandle = GetCurrentProcess();
GetProcessAffinityMask(hCurrentProcessHandle, &dwProcessAffinity,
- &dwSystemAffinity);
+ &dwSystemAffinity);
// Check if available process affinity mask is equal to the
// available system affinity mask
- if (dwProcessAffinity != dwSystemAffinity)
- {
+ if (dwProcessAffinity != dwSystemAffinity) {
StatusFlag = HT_CANNOT_DETECT;
this->NumberOfPhysicalCPU = (unsigned char)-1;
return StatusFlag;
- }
+ }
dwAffinityMask = 1;
- while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity)
- {
+ while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity) {
// Check if this CPU is available
- if (dwAffinityMask & dwProcessAffinity)
- {
- if (SetProcessAffinityMask(hCurrentProcessHandle,
- dwAffinityMask))
- {
+ if (dwAffinityMask & dwProcessAffinity) {
+ if (SetProcessAffinityMask(hCurrentProcessHandle, dwAffinityMask)) {
unsigned char APIC_ID, LOG_ID;
Sleep(0); // Give OS time to switch CPU
APIC_ID = GetAPICId();
- LOG_ID = APIC_ID & ~PHY_ID_MASK;
+ LOG_ID = APIC_ID & ~PHY_ID_MASK;
- if (LOG_ID != 0)
- {
+ if (LOG_ID != 0) {
HT_Enabled = 1;
- }
}
}
- dwAffinityMask = dwAffinityMask << 1;
}
+ dwAffinityMask = dwAffinityMask << 1;
+ }
// Reset the processor affinity
SetProcessAffinityMask(hCurrentProcessHandle, dwProcessAffinity);
- if (this->NumberOfLogicalCPU == 1) // Normal P4 : HT is disabled in hardware
- {
+ if (this->NumberOfLogicalCPU ==
+ 1) // Normal P4 : HT is disabled in hardware
+ {
StatusFlag = HT_DISABLED;
- }
- else
- {
- if (HT_Enabled)
- {
+ } else {
+ if (HT_Enabled) {
// Total physical processors in a Hyper-Threading enabled system.
this->NumberOfPhysicalCPU /= (this->NumberOfLogicalCPU);
StatusFlag = HT_ENABLED;
- }
- else
- {
+ } else {
StatusFlag = HT_SUPPORTED_NOT_ENABLED;
- }
}
}
}
- else
- {
+ } else {
// Processors do not have Hyper-Threading technology
StatusFlag = HT_NOT_CAPABLE;
this->NumberOfLogicalCPU = 1;
- }
+ }
return StatusFlag;
#else
return 0;
#endif
}
-
/** Return the number of logical CPUs on the system */
unsigned int SystemInformationImplementation::GetNumberOfLogicalCPU()
{
return this->NumberOfLogicalCPU;
}
-
/** Return the number of physical CPUs on the system */
unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU()
{
return this->NumberOfPhysicalCPU;
}
-
/** For Mac use sysctlbyname calls to find system info */
bool SystemInformationImplementation::ParseSysCtl()
{
@@ -4402,20 +4522,20 @@ bool SystemInformationImplementation::ParseSysCtl()
uint64_t value = 0;
size_t len = sizeof(value);
sysctlbyname("hw.memsize", &value, &len, NULL, 0);
- this->TotalPhysicalMemory = static_cast< size_t >( value/1048576 );
+ this->TotalPhysicalMemory = static_cast<size_t>(value / 1048576);
// Parse values for Mac
this->AvailablePhysicalMemory = 0;
- vm_statistics_data_t vmstat;
+ vm_statistics_data_t vmstat;
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
- if ( host_statistics(mach_host_self(), HOST_VM_INFO,
- (host_info_t) &vmstat, &count) == KERN_SUCCESS )
- {
+ if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat,
+ &count) == KERN_SUCCESS) {
len = sizeof(value);
err = sysctlbyname("hw.pagesize", &value, &len, NULL, 0);
int64_t available_memory = vmstat.free_count * value;
- this->AvailablePhysicalMemory = static_cast< size_t >( available_memory / 1048576 );
- }
+ this->AvailablePhysicalMemory =
+ static_cast<size_t>(available_memory / 1048576);
+ }
#ifdef VM_SWAPUSAGE
// Virtual memory.
@@ -4424,17 +4544,17 @@ bool SystemInformationImplementation::ParseSysCtl()
struct xsw_usage swap;
len = sizeof(swap);
err = sysctl(mib, miblen, &swap, &len, NULL, 0);
- if (err == 0)
- {
- this->AvailableVirtualMemory = static_cast< size_t >( swap.xsu_avail/1048576 );
- this->TotalVirtualMemory = static_cast< size_t >( swap.xsu_total/1048576 );
- }
+ if (err == 0) {
+ this->AvailableVirtualMemory =
+ static_cast<size_t>(swap.xsu_avail / 1048576);
+ this->TotalVirtualMemory = static_cast<size_t>(swap.xsu_total / 1048576);
+ }
#else
- this->AvailableVirtualMemory = 0;
- this->TotalVirtualMemory = 0;
+ this->AvailableVirtualMemory = 0;
+ this->TotalVirtualMemory = 0;
#endif
-// CPU Info
+ // CPU Info
len = sizeof(this->NumberOfPhysicalCPU);
sysctlbyname("hw.physicalcpu", &this->NumberOfPhysicalCPU, &len, NULL, 0);
len = sizeof(this->NumberOfLogicalCPU);
@@ -4444,34 +4564,31 @@ bool SystemInformationImplementation::ParseSysCtl()
len = sizeof(value);
sysctlbyname("hw.cpufrequency", &value, &len, NULL, 0);
- this->CPUSpeedInMHz = static_cast< float >( value )/ 1000000;
-
+ this->CPUSpeedInMHz = static_cast<float>(value) / 1000000;
// Chip family
len = sizeof(this->ChipID.Family);
- //Seems only the intel chips will have this name so if this fails it is
- //probably a PPC machine
- err = sysctlbyname("machdep.cpu.family",
- &this->ChipID.Family, &len, NULL, 0);
+ // Seems only the intel chips will have this name so if this fails it is
+ // probably a PPC machine
+ err =
+ sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0);
if (err != 0) // Go back to names we know but are less descriptive
- {
+ {
this->ChipID.Family = 0;
::memset(retBuf, 0, 128);
len = 32;
err = sysctlbyname("hw.machine", &retBuf, &len, NULL, 0);
std::string machineBuf(retBuf);
- if (machineBuf.find_first_of("Power") != std::string::npos)
- {
+ if (machineBuf.find_first_of("Power") != std::string::npos) {
this->ChipID.Vendor = "IBM";
len = sizeof(this->ChipID.Family);
err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, NULL, 0);
len = sizeof(this->ChipID.Model);
err = sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, NULL, 0);
this->FindManufacturer();
- }
}
- else // Should be an Intel Chip.
- {
+ } else // Should be an Intel Chip.
+ {
len = sizeof(this->ChipID.Family);
err =
sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0);
@@ -4486,101 +4603,88 @@ bool SystemInformationImplementation::ParseSysCtl()
// Chip Model
len = sizeof(value);
err = sysctlbyname("machdep.cpu.model", &value, &len, NULL, 0);
- this->ChipID.Model = static_cast< int >( value );
+ this->ChipID.Model = static_cast<int>(value);
// Chip Stepping
len = sizeof(value);
value = 0;
err = sysctlbyname("machdep.cpu.stepping", &value, &len, NULL, 0);
- if (!err)
- {
- this->ChipID.Revision = static_cast< int >( value );
- }
+ if (!err) {
+ this->ChipID.Revision = static_cast<int>(value);
+ }
// feature string
- char *buf = 0;
+ char* buf = 0;
size_t allocSize = 128;
err = 0;
len = 0;
- // sysctlbyname() will return with err==0 && len==0 if the buffer is too small
- while (err == 0 && len == 0)
- {
+ // sysctlbyname() will return with err==0 && len==0 if the buffer is too
+ // small
+ while (err == 0 && len == 0) {
delete[] buf;
allocSize *= 2;
buf = new char[allocSize];
- if (!buf)
- {
+ if (!buf) {
break;
- }
+ }
buf[0] = ' ';
len = allocSize - 2; // keep space for leading and trailing space
err = sysctlbyname("machdep.cpu.features", buf + 1, &len, NULL, 0);
- }
- if (!err && buf && len)
- {
+ }
+ if (!err && buf && len) {
// now we can match every flags as space + flag + space
buf[len + 1] = ' ';
std::string cpuflags(buf, len + 2);
- if ((cpuflags.find(" FPU ")!=std::string::npos))
- {
+ if ((cpuflags.find(" FPU ") != std::string::npos)) {
this->Features.HasFPU = true;
- }
- if ((cpuflags.find(" TSC ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" TSC ") != std::string::npos)) {
this->Features.HasTSC = true;
- }
- if ((cpuflags.find(" MMX ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" MMX ") != std::string::npos)) {
this->Features.HasMMX = true;
- }
- if ((cpuflags.find(" SSE ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" SSE ") != std::string::npos)) {
this->Features.HasSSE = true;
- }
- if ((cpuflags.find(" SSE2 ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" SSE2 ") != std::string::npos)) {
this->Features.HasSSE2 = true;
- }
- if ((cpuflags.find(" APIC ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" APIC ") != std::string::npos)) {
this->Features.HasAPIC = true;
- }
- if ((cpuflags.find(" CMOV ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" CMOV ") != std::string::npos)) {
this->Features.HasCMOV = true;
- }
- if ((cpuflags.find(" MTRR ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" MTRR ") != std::string::npos)) {
this->Features.HasMTRR = true;
- }
- if ((cpuflags.find(" ACPI ")!=std::string::npos))
- {
+ }
+ if ((cpuflags.find(" ACPI ") != std::string::npos)) {
this->Features.HasACPI = true;
- }
}
- delete[] buf;
}
+ delete[] buf;
+ }
// brand string
::memset(retBuf, 0, sizeof(retBuf));
len = sizeof(retBuf);
err = sysctlbyname("machdep.cpu.brand_string", retBuf, &len, NULL, 0);
- if (!err)
- {
+ if (!err) {
this->ChipID.ProcessorName = retBuf;
this->ChipID.ModelName = retBuf;
- }
+ }
// Cache size
len = sizeof(value);
err = sysctlbyname("hw.l1icachesize", &value, &len, NULL, 0);
- this->Features.L1CacheSize = static_cast< int >( value );
+ this->Features.L1CacheSize = static_cast<int>(value);
len = sizeof(value);
err = sysctlbyname("hw.l2cachesize", &value, &len, NULL, 0);
- this->Features.L2CacheSize = static_cast< int >( value );
+ this->Features.L2CacheSize = static_cast<int>(value);
return true;
#else
@@ -4588,33 +4692,31 @@ bool SystemInformationImplementation::ParseSysCtl()
#endif
}
-
/** Extract a value from sysctl command */
-std::string SystemInformationImplementation::ExtractValueFromSysCtl(const char* word)
+std::string SystemInformationImplementation::ExtractValueFromSysCtl(
+ const char* word)
{
size_t pos = this->SysCtlBuffer.find(word);
- if(pos != this->SysCtlBuffer.npos)
- {
- pos = this->SysCtlBuffer.find(": ",pos);
- size_t pos2 = this->SysCtlBuffer.find("\n",pos);
- if(pos!=this->SysCtlBuffer.npos && pos2!=this->SysCtlBuffer.npos)
- {
- return this->SysCtlBuffer.substr(pos+2,pos2-pos-2);
- }
+ if (pos != this->SysCtlBuffer.npos) {
+ pos = this->SysCtlBuffer.find(": ", pos);
+ size_t pos2 = this->SysCtlBuffer.find("\n", pos);
+ if (pos != this->SysCtlBuffer.npos && pos2 != this->SysCtlBuffer.npos) {
+ return this->SysCtlBuffer.substr(pos + 2, pos2 - pos - 2);
}
+ }
return "";
}
-
/** Run a given process */
-std::string SystemInformationImplementation::RunProcess(std::vector<const char*> args)
+std::string SystemInformationImplementation::RunProcess(
+ std::vector<const char*> args)
{
std::string buffer = "";
// Run the application
kwsysProcess* gp = kwsysProcess_New();
kwsysProcess_SetCommand(gp, &*args.begin());
- kwsysProcess_SetOption(gp,kwsysProcess_Option_HideWindow,1);
+ kwsysProcess_SetOption(gp, kwsysProcess_Option_HideWindow, 1);
kwsysProcess_Execute(gp);
@@ -4623,51 +4725,46 @@ std::string SystemInformationImplementation::RunProcess(std::vector<const char*>
double timeout = 255;
int pipe; // pipe id as returned by kwsysProcess_WaitForData()
- while( ( static_cast<void>(pipe = kwsysProcess_WaitForData(gp,&data,&length,&timeout)),
- (pipe == kwsysProcess_Pipe_STDOUT || pipe == kwsysProcess_Pipe_STDERR) ) ) // wait for 1s
- {
- buffer.append(data, length);
- }
+ while ((static_cast<void>(
+ pipe = kwsysProcess_WaitForData(gp, &data, &length, &timeout)),
+ (pipe == kwsysProcess_Pipe_STDOUT ||
+ pipe == kwsysProcess_Pipe_STDERR))) // wait for 1s
+ {
+ buffer.append(data, length);
+ }
kwsysProcess_WaitForExit(gp, 0);
int result = 0;
- switch(kwsysProcess_GetState(gp))
- {
- case kwsysProcess_State_Exited:
- {
+ switch (kwsysProcess_GetState(gp)) {
+ case kwsysProcess_State_Exited: {
result = kwsysProcess_GetExitValue(gp);
- } break;
- case kwsysProcess_State_Error:
- {
+ } break;
+ case kwsysProcess_State_Error: {
std::cerr << "Error: Could not run " << args[0] << ":\n";
std::cerr << kwsysProcess_GetErrorString(gp) << "\n";
- } break;
- case kwsysProcess_State_Exception:
- {
- std::cerr << "Error: " << args[0]
- << " terminated with an exception: "
+ } break;
+ case kwsysProcess_State_Exception: {
+ std::cerr << "Error: " << args[0] << " terminated with an exception: "
<< kwsysProcess_GetExceptionString(gp) << "\n";
- } break;
+ } break;
case kwsysProcess_State_Starting:
case kwsysProcess_State_Executing:
case kwsysProcess_State_Expired:
- case kwsysProcess_State_Killed:
- {
+ case kwsysProcess_State_Killed: {
// Should not get here.
std::cerr << "Unexpected ending state after running " << args[0]
<< std::endl;
- } break;
- }
+ } break;
+ }
kwsysProcess_Delete(gp);
- if(result)
- {
+ if (result) {
std::cerr << "Error " << args[0] << " returned :" << result << "\n";
- }
+ }
return buffer;
}
-
-std::string SystemInformationImplementation::ParseValueFromKStat(const char* arguments)
+std::string SystemInformationImplementation::ParseValueFromKStat(
+ const char* arguments)
{
std::vector<const char*> args;
args.clear();
@@ -4676,41 +4773,36 @@ std::string SystemInformationImplementation::ParseValueFromKStat(const char* arg
std::string command = arguments;
size_t start = command.npos;
- size_t pos = command.find(' ',0);
- while(pos!=command.npos)
- {
+ size_t pos = command.find(' ', 0);
+ while (pos != command.npos) {
bool inQuotes = false;
// Check if we are between quotes
- size_t b0 = command.find('"',0);
- size_t b1 = command.find('"',b0+1);
- while(b0 != command.npos && b1 != command.npos && b1>b0)
- {
- if(pos>b0 && pos<b1)
- {
+ size_t b0 = command.find('"', 0);
+ size_t b1 = command.find('"', b0 + 1);
+ while (b0 != command.npos && b1 != command.npos && b1 > b0) {
+ if (pos > b0 && pos < b1) {
inQuotes = true;
break;
- }
- b0 = command.find('"',b1+1);
- b1 = command.find('"',b0+1);
}
+ b0 = command.find('"', b1 + 1);
+ b1 = command.find('"', b0 + 1);
+ }
- if(!inQuotes)
- {
- std::string arg = command.substr(start+1,pos-start-1);
+ if (!inQuotes) {
+ std::string arg = command.substr(start + 1, pos - start - 1);
// Remove the quotes if any
size_t quotes = arg.find('"');
- while(quotes != arg.npos)
- {
- arg.erase(quotes,1);
+ while (quotes != arg.npos) {
+ arg.erase(quotes, 1);
quotes = arg.find('"');
- }
+ }
args.push_back(arg.c_str());
start = pos;
- }
- pos = command.find(' ',pos+1);
}
- std::string lastArg = command.substr(start+1,command.size()-start-1);
+ pos = command.find(' ', pos + 1);
+ }
+ std::string lastArg = command.substr(start + 1, command.size() - start - 1);
args.push_back(lastArg.c_str());
args.push_back(0);
@@ -4718,41 +4810,37 @@ std::string SystemInformationImplementation::ParseValueFromKStat(const char* arg
std::string buffer = this->RunProcess(args);
std::string value = "";
- for(size_t i=buffer.size()-1;i>0;i--)
- {
- if(buffer[i] == ' ' || buffer[i] == '\t')
- {
+ for (size_t i = buffer.size() - 1; i > 0; i--) {
+ if (buffer[i] == ' ' || buffer[i] == '\t') {
break;
- }
- if(buffer[i] != '\n' && buffer[i] != '\r')
- {
+ }
+ if (buffer[i] != '\n' && buffer[i] != '\r') {
std::string val = value;
value = buffer[i];
value += val;
- }
}
+ }
return value;
}
/** Querying for system information from Solaris */
bool SystemInformationImplementation::QuerySolarisMemory()
{
-#if defined (__SVR4) && defined (__sun)
- // Solaris allows querying this value by sysconf, but if this is
- // a 32 bit process on a 64 bit host the returned memory will be
- // limited to 4GiB. So if this is a 32 bit process or if the sysconf
- // method fails use the kstat interface.
+#if defined(__SVR4) && defined(__sun)
+// Solaris allows querying this value by sysconf, but if this is
+// a 32 bit process on a 64 bit host the returned memory will be
+// limited to 4GiB. So if this is a 32 bit process or if the sysconf
+// method fails use the kstat interface.
#if SIZEOF_VOID_P == 8
- if (this->QueryMemoryBySysconf())
- {
+ if (this->QueryMemoryBySysconf()) {
return true;
- }
+ }
#endif
char* tail;
unsigned long totalMemory =
- strtoul(this->ParseValueFromKStat("-s physmem").c_str(),&tail,0);
- this->TotalPhysicalMemory = totalMemory/128;
+ strtoul(this->ParseValueFromKStat("-s physmem").c_str(), &tail, 0);
+ this->TotalPhysicalMemory = totalMemory / 128;
return true;
#else
@@ -4762,13 +4850,13 @@ bool SystemInformationImplementation::QuerySolarisMemory()
bool SystemInformationImplementation::QuerySolarisProcessor()
{
- if (!this->QueryProcessorBySysconf())
- {
+ if (!this->QueryProcessorBySysconf()) {
return false;
- }
+ }
// Parse values
- this->CPUSpeedInMHz = static_cast<float>(atoi(this->ParseValueFromKStat("-s clock_MHz").c_str()));
+ this->CPUSpeedInMHz = static_cast<float>(
+ atoi(this->ParseValueFromKStat("-s clock_MHz").c_str()));
// Chip family
this->ChipID.Family = 0;
@@ -4778,16 +4866,14 @@ bool SystemInformationImplementation::QuerySolarisProcessor()
this->ChipID.Model = 0;
// Chip Vendor
- if (this->ChipID.ProcessorName != "i386")
- {
+ if (this->ChipID.ProcessorName != "i386") {
this->ChipID.Vendor = "Sun";
this->FindManufacturer();
- }
+ }
return true;
}
-
/** Querying for system information from Haiku OS */
bool SystemInformationImplementation::QueryHaikuInfo()
{
@@ -4808,8 +4894,8 @@ bool SystemInformationImplementation::QueryHaikuInfo()
for (uint32 i = 0; i < topologyNodeCount; i++) {
if (topology[i].type == B_TOPOLOGY_CORE) {
- this->CPUSpeedInMHz = topology[i].data.core.default_frequency /
- 1000000.0f;
+ this->CPUSpeedInMHz =
+ topology[i].data.core.default_frequency / 1000000.0f;
break;
}
}
@@ -4817,11 +4903,10 @@ bool SystemInformationImplementation::QueryHaikuInfo()
delete[] topology;
// Physical Memory
- this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024) ;
+ this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024);
this->AvailablePhysicalMemory = this->TotalPhysicalMemory -
((info.used_pages * B_PAGE_SIZE) / (1024 * 1024));
-
// NOTE: get_system_info_etc is currently a private call so just set to 0
// until it becomes public
this->TotalVirtualMemory = 0;
@@ -4910,7 +4995,8 @@ bool SystemInformationImplementation::QueryQNXMemory()
bool SystemInformationImplementation::QueryBSDMemory()
{
-#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
+ defined(__DragonFly__)
int ctrl[2] = { CTL_HW, HW_PHYSMEM };
#if defined(HW_PHYSMEM64)
int64_t k;
@@ -4920,12 +5006,11 @@ bool SystemInformationImplementation::QueryBSDMemory()
#endif
size_t sz = sizeof(k);
- if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
- {
+ if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
return false;
- }
+ }
- this->TotalPhysicalMemory = k>>10>>10;
+ this->TotalPhysicalMemory = k >> 10 >> 10;
return true;
#else
@@ -4963,21 +5048,19 @@ bool SystemInformationImplementation::QueryQNXProcessor()
this->CPUSpeedInMHz = atoi(buffer.substr(pos3 + 1, pos2 - pos3 - 1).c_str());
pos2 = buffer.find(" Stepping", pos);
- if (pos2 != buffer.npos)
- {
+ if (pos2 != buffer.npos) {
pos2 = buffer.find(" ", pos2 + 1);
- if (pos2 != buffer.npos && pos2 < pos3)
- {
- this->ChipID.Revision = atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str());
- }
+ if (pos2 != buffer.npos && pos2 < pos3) {
+ this->ChipID.Revision =
+ atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str());
}
+ }
this->NumberOfPhysicalCPU = 0;
- do
- {
+ do {
pos = buffer.find("\nProcessor", pos + 1);
++this->NumberOfPhysicalCPU;
- } while (pos != buffer.npos);
+ } while (pos != buffer.npos);
this->NumberOfLogicalCPU = 1;
return true;
@@ -4988,15 +5071,15 @@ bool SystemInformationImplementation::QueryQNXProcessor()
bool SystemInformationImplementation::QueryBSDProcessor()
{
-#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
+ defined(__DragonFly__)
int k;
size_t sz = sizeof(k);
int ctrl[2] = { CTL_HW, HW_NCPU };
- if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
- {
+ if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
return false;
- }
+ }
this->NumberOfPhysicalCPU = k;
this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
@@ -5004,22 +5087,20 @@ bool SystemInformationImplementation::QueryBSDProcessor()
#if defined(HW_CPUSPEED)
ctrl[1] = HW_CPUSPEED;
- if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
- {
+ if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
return false;
- }
+ }
- this->CPUSpeedInMHz = (float) k;
+ this->CPUSpeedInMHz = (float)k;
#endif
#if defined(CPU_SSE)
ctrl[0] = CTL_MACHDEP;
ctrl[1] = CPU_SSE;
- if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
- {
+ if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
return false;
- }
+ }
this->Features.HasSSE = (k > 0);
#endif
@@ -5028,10 +5109,9 @@ bool SystemInformationImplementation::QueryBSDProcessor()
ctrl[0] = CTL_MACHDEP;
ctrl[1] = CPU_SSE2;
- if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
- {
+ if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
return false;
- }
+ }
this->Features.HasSSE2 = (k > 0);
#endif
@@ -5042,10 +5122,9 @@ bool SystemInformationImplementation::QueryBSDProcessor()
char vbuf[25];
::memset(vbuf, 0, sizeof(vbuf));
sz = sizeof(vbuf) - 1;
- if (sysctl(ctrl, 2, vbuf, &sz, NULL, 0) != 0)
- {
+ if (sysctl(ctrl, 2, vbuf, &sz, NULL, 0) != 0) {
return false;
- }
+ }
this->ChipID.Vendor = vbuf;
this->FindManufacturer();
@@ -5060,33 +5139,31 @@ bool SystemInformationImplementation::QueryBSDProcessor()
bool SystemInformationImplementation::QueryHPUXMemory()
{
#if defined(__hpux)
- unsigned long tv=0;
- unsigned long tp=0;
- unsigned long av=0;
- unsigned long ap=0;
+ unsigned long tv = 0;
+ unsigned long tp = 0;
+ unsigned long av = 0;
+ unsigned long ap = 0;
struct pst_static pst;
struct pst_dynamic pdy;
unsigned long ps = 0;
- if (pstat_getstatic(&pst, sizeof(pst), (size_t) 1, 0) == -1)
- {
+ if (pstat_getstatic(&pst, sizeof(pst), (size_t)1, 0) == -1) {
return false;
- }
+ }
ps = pst.page_size;
- tp = pst.physical_memory *ps;
+ tp = pst.physical_memory * ps;
tv = (pst.physical_memory + pst.pst_maxmem) * ps;
- if (pstat_getdynamic(&pdy, sizeof(pdy), (size_t) 1, 0) == -1)
- {
+ if (pstat_getdynamic(&pdy, sizeof(pdy), (size_t)1, 0) == -1) {
return false;
- }
+ }
ap = tp - pdy.psd_rm * ps;
av = tv - pdy.psd_vm;
- this->TotalVirtualMemory = tv>>10>>10;
- this->TotalPhysicalMemory = tp>>10>>10;
- this->AvailableVirtualMemory = av>>10>>10;
- this->AvailablePhysicalMemory = ap>>10>>10;
+ this->TotalVirtualMemory = tv >> 10 >> 10;
+ this->TotalPhysicalMemory = tp >> 10 >> 10;
+ this->AvailableVirtualMemory = av >> 10 >> 10;
+ this->AvailablePhysicalMemory = ap >> 10 >> 10;
return true;
#else
return false;
@@ -5096,25 +5173,22 @@ bool SystemInformationImplementation::QueryHPUXMemory()
bool SystemInformationImplementation::QueryHPUXProcessor()
{
#if defined(__hpux)
-# if defined(KWSYS_SYS_HAS_MPCTL_H)
+#if defined(KWSYS_SYS_HAS_MPCTL_H)
int c = mpctl(MPC_GETNUMSPUS_SYS, 0, 0);
- if (c <= 0)
- {
+ if (c <= 0) {
return false;
- }
+ }
this->NumberOfPhysicalCPU = c;
this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
long t = sysconf(_SC_CPU_VERSION);
- if (t == -1)
- {
+ if (t == -1) {
return false;
- }
+ }
- switch (t)
- {
+ switch (t) {
case CPU_PA_RISC1_0:
this->ChipID.Vendor = "Hewlett-Packard";
this->ChipID.Family = 0x100;
@@ -5127,27 +5201,27 @@ bool SystemInformationImplementation::QueryHPUXProcessor()
this->ChipID.Vendor = "Hewlett-Packard";
this->ChipID.Family = 0x200;
break;
-# if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0)
-# ifdef CPU_HP_INTEL_EM_1_0
+#if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0)
+#ifdef CPU_HP_INTEL_EM_1_0
case CPU_HP_INTEL_EM_1_0:
-# endif
-# ifdef CPU_IA64_ARCHREV_0
+#endif
+#ifdef CPU_IA64_ARCHREV_0
case CPU_IA64_ARCHREV_0:
-# endif
+#endif
this->ChipID.Vendor = "GenuineIntel";
this->Features.HasIA64 = true;
break;
-# endif
+#endif
default:
return false;
- }
+ }
this->FindManufacturer();
return true;
-# else
+#else
return false;
-# endif
+#endif
#else
return false;
#endif
@@ -5166,215 +5240,178 @@ bool SystemInformationImplementation::QueryOSInformation()
char operatingSystem[256];
// Try calling GetVersionEx using the OSVERSIONINFOEX structure.
- ZeroMemory (&osvi, sizeof (OSVERSIONINFOEXW));
- osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
+ ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXW));
+ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-# pragma warning (disable:1478)
-# else
-# pragma warning (disable:4996)
-# endif
-#endif
- bOsVersionInfoEx = GetVersionExW ((OSVERSIONINFOW*)&osvi);
- if (!bOsVersionInfoEx)
- {
- osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOW);
- if (!GetVersionExW((OSVERSIONINFOW*)&osvi))
- {
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
+#endif
+ bOsVersionInfoEx = GetVersionExW((OSVERSIONINFOW*)&osvi);
+ if (!bOsVersionInfoEx) {
+ osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
+ if (!GetVersionExW((OSVERSIONINFOW*)&osvi)) {
return false;
- }
}
+ }
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
#endif
- switch (osvi.dwPlatformId)
- {
+ switch (osvi.dwPlatformId) {
case VER_PLATFORM_WIN32_NT:
// Test for the product.
- if (osvi.dwMajorVersion <= 4)
- {
+ if (osvi.dwMajorVersion <= 4) {
this->OSRelease = "NT";
- }
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
- {
+ }
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
this->OSRelease = "2000";
- }
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
+ }
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
this->OSRelease = "XP";
- }
+ }
// XP Professional x64
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
- {
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
this->OSRelease = "XP";
- }
+ }
#ifdef VER_NT_WORKSTATION
// Test for product type.
- if (bOsVersionInfoEx)
- {
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
- {
+ if (bOsVersionInfoEx) {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
+ if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) {
this->OSRelease = "Vista";
- }
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
- {
+ }
+ if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) {
this->OSRelease = "7";
- }
+ }
// VER_SUITE_PERSONAL may not be defined
#ifdef VER_SUITE_PERSONAL
- else
- {
- if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
- {
+ else {
+ if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
this->OSRelease += " Personal";
- }
- else
- {
+ } else {
this->OSRelease += " Professional";
- }
}
-#endif
}
- else if (osvi.wProductType == VER_NT_SERVER)
- {
+#endif
+ } else if (osvi.wProductType == VER_NT_SERVER) {
// Check for .NET Server instead of Windows XP.
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
this->OSRelease = ".NET";
- }
+ }
// Continue with the type detection.
- if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
- {
+ if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
this->OSRelease += " DataCenter Server";
- }
- else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
- {
+ } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
this->OSRelease += " Advanced Server";
- }
- else
- {
+ } else {
this->OSRelease += " Server";
- }
}
+ }
- sprintf (operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
+ sprintf(operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion,
+ osvi.dwBuildNumber & 0xFFFF);
this->OSVersion = operatingSystem;
- }
- else
-#endif // VER_NT_WORKSTATION
- {
+ } else
+#endif // VER_NT_WORKSTATION
+ {
HKEY hKey;
wchar_t szProductType[80];
DWORD dwBufLen;
// Query the registry to retrieve information.
- RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey);
- RegQueryValueExW(hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen);
- RegCloseKey (hKey);
-
- if (lstrcmpiW(L"WINNT", szProductType) == 0)
- {
+ RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+ L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0,
+ KEY_QUERY_VALUE, &hKey);
+ RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
+ (LPBYTE)szProductType, &dwBufLen);
+ RegCloseKey(hKey);
+
+ if (lstrcmpiW(L"WINNT", szProductType) == 0) {
this->OSRelease += " Professional";
- }
- if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
- {
- // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
+ }
+ if (lstrcmpiW(L"LANMANNT", szProductType) == 0) {
+ // Decide between Windows 2000 Advanced Server and Windows .NET
+ // Enterprise Server.
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
this->OSRelease += " Standard Server";
- }
- else
- {
+ } else {
this->OSRelease += " Server";
- }
}
- if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
- {
- // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
+ }
+ if (lstrcmpiW(L"SERVERNT", szProductType) == 0) {
+ // Decide between Windows 2000 Advanced Server and Windows .NET
+ // Enterprise Server.
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
this->OSRelease += " Enterprise Server";
- }
- else
- {
+ } else {
this->OSRelease += " Advanced Server";
- }
}
- }
+ }
+ }
// Display version, service pack (if any), and build number.
- if (osvi.dwMajorVersion <= 4)
- {
+ if (osvi.dwMajorVersion <= 4) {
// NB: NT 4.0 and earlier.
- sprintf (operatingSystem, "version %ld.%ld %ls (Build %ld)",
- osvi.dwMajorVersion,
- osvi.dwMinorVersion,
- osvi.szCSDVersion,
- osvi.dwBuildNumber & 0xFFFF);
+ sprintf(operatingSystem, "version %ld.%ld %ls (Build %ld)",
+ osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.szCSDVersion,
+ osvi.dwBuildNumber & 0xFFFF);
this->OSVersion = operatingSystem;
- }
- else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
+ } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
// Windows XP and .NET server.
- typedef BOOL (CALLBACK* LPFNPROC) (HANDLE, BOOL *);
+ typedef BOOL(CALLBACK * LPFNPROC)(HANDLE, BOOL*);
HINSTANCE hKernelDLL;
LPFNPROC DLLProc;
// Load the Kernel32 DLL.
hKernelDLL = LoadLibraryW(L"kernel32");
- if (hKernelDLL != NULL) {
- // Only XP and .NET Server support IsWOW64Process so... Load dynamically!
- DLLProc = (LPFNPROC) GetProcAddress (hKernelDLL, "IsWow64Process");
+ if (hKernelDLL != NULL) {
+ // Only XP and .NET Server support IsWOW64Process so... Load
+ // dynamically!
+ DLLProc = (LPFNPROC)GetProcAddress(hKernelDLL, "IsWow64Process");
// If the function address is valid, call the function.
- if (DLLProc != NULL) (DLLProc) (GetCurrentProcess (), &bIsWindows64Bit);
- else bIsWindows64Bit = false;
+ if (DLLProc != NULL)
+ (DLLProc)(GetCurrentProcess(), &bIsWindows64Bit);
+ else
+ bIsWindows64Bit = false;
// Free the DLL module.
- FreeLibrary (hKernelDLL);
- }
+ FreeLibrary(hKernelDLL);
}
- else
- {
+ } else {
// Windows 2000 and everything else.
- sprintf (operatingSystem,"%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
+ sprintf(operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion,
+ osvi.dwBuildNumber & 0xFFFF);
this->OSVersion = operatingSystem;
- }
+ }
break;
case VER_PLATFORM_WIN32_WINDOWS:
// Test for the product.
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
- {
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
this->OSRelease = "95";
- if(osvi.szCSDVersion[1] == 'C')
- {
+ if (osvi.szCSDVersion[1] == 'C') {
this->OSRelease += "OSR 2.5";
- }
- else if(osvi.szCSDVersion[1] == 'B')
- {
+ } else if (osvi.szCSDVersion[1] == 'B') {
this->OSRelease += "OSR 2";
- }
+ }
}
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
- {
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
this->OSRelease = "98";
- if (osvi.szCSDVersion[1] == 'A' )
- {
+ if (osvi.szCSDVersion[1] == 'A') {
this->OSRelease += "SE";
- }
}
+ }
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
- {
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) {
this->OSRelease = "Me";
- }
+ }
break;
case VER_PLATFORM_WIN32s:
@@ -5390,42 +5427,39 @@ bool SystemInformationImplementation::QueryOSInformation()
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
- wVersionRequested = MAKEWORD(2,0);
+ wVersionRequested = MAKEWORD(2, 0);
- if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
- {
- gethostname(name,sizeof(name));
- WSACleanup( );
- }
+ if (WSAStartup(wVersionRequested, &wsaData) == 0) {
+ gethostname(name, sizeof(name));
+ WSACleanup();
+ }
this->Hostname = name;
const char* arch = getenv("PROCESSOR_ARCHITECTURE");
- if(arch)
- {
+ if (arch) {
this->OSPlatform = arch;
- }
+ }
#else
struct utsname unameInfo;
int errorFlag = uname(&unameInfo);
- if(errorFlag == 0)
- {
+ if (errorFlag == 0) {
this->OSName = unameInfo.sysname;
this->Hostname = unameInfo.nodename;
this->OSRelease = unameInfo.release;
this->OSVersion = unameInfo.version;
this->OSPlatform = unameInfo.machine;
- }
+ }
#ifdef __APPLE__
- this->OSName="Unknown Apple OS";
- this->OSRelease="Unknown product version";
- this->OSVersion="Unknown build version";
+ this->OSName = "Unknown Apple OS";
+ this->OSRelease = "Unknown product version";
+ this->OSVersion = "Unknown build version";
- this->CallSwVers("-productName",this->OSName);
- this->CallSwVers("-productVersion",this->OSRelease);
- this->CallSwVers("-buildVersion",this->OSVersion);
+ this->CallSwVers("-productName", this->OSName);
+ this->CallSwVers("-productVersion", this->OSRelease);
+ this->CallSwVers("-buildVersion", this->OSVersion);
#endif
#endif
@@ -5433,9 +5467,8 @@ bool SystemInformationImplementation::QueryOSInformation()
return true;
}
-int SystemInformationImplementation::CallSwVers(
- const char *arg,
- std::string &ver)
+int SystemInformationImplementation::CallSwVers(const char* arg,
+ std::string& ver)
{
#ifdef __APPLE__
std::vector<const char*> args;
@@ -5455,26 +5488,21 @@ int SystemInformationImplementation::CallSwVers(
void SystemInformationImplementation::TrimNewline(std::string& output)
{
// remove \r
- std::string::size_type pos=0;
- while((pos = output.find("\r", pos)) != std::string::npos)
- {
+ std::string::size_type pos = 0;
+ while ((pos = output.find("\r", pos)) != std::string::npos) {
output.erase(pos);
- }
+ }
// remove \n
pos = 0;
- while((pos = output.find("\n", pos)) != std::string::npos)
- {
+ while ((pos = output.find("\n", pos)) != std::string::npos) {
output.erase(pos);
- }
+ }
}
-
/** Return true if the machine is 64 bits */
bool SystemInformationImplementation::Is64Bits()
{
return (sizeof(void*) == 8);
}
-
-
-} // namespace @KWSYS_NAMESPACE@
+}
diff --git a/Source/kwsys/SystemInformation.hxx.in b/Source/kwsys/SystemInformation.hxx.in
index 7c45388..0fc1067 100644
--- a/Source/kwsys/SystemInformation.hxx.in
+++ b/Source/kwsys/SystemInformation.hxx.in
@@ -1,23 +1,14 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_SystemInformation_h
#define @KWSYS_NAMESPACE@_SystemInformation_h
#include <@KWSYS_NAMESPACE@/Configure.hxx>
+
#include <stddef.h> /* size_t */
#include <string>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
// forward declare the implementation class
class SystemInformationImplementation;
@@ -29,24 +20,24 @@ class @KWSYS_NAMESPACE@_EXPORT SystemInformation
#elif @KWSYS_USE___INT64@
typedef __int64 LongLong;
#else
-# error "No Long Long"
+#error "No Long Long"
#endif
friend class SystemInformationImplementation;
SystemInformationImplementation* Implementation;
-public:
- SystemInformation ();
- ~SystemInformation ();
+public:
+ SystemInformation();
+ ~SystemInformation();
- const char * GetVendorString();
- const char * GetVendorID();
+ const char* GetVendorString();
+ const char* GetVendorID();
std::string GetTypeID();
std::string GetFamilyID();
std::string GetModelID();
std::string GetModelName();
std::string GetSteppingCode();
- const char * GetExtendedProcessorName();
- const char * GetProcessorSerialNumber();
+ const char* GetExtendedProcessorName();
+ const char* GetProcessorSerialNumber();
int GetProcessorCacheSize();
unsigned int GetLogicalProcessorsPerPhysical();
float GetProcessorClockFrequency();
@@ -58,13 +49,13 @@ public:
// on this system.
std::string GetCPUDescription();
- const char * GetHostname();
+ const char* GetHostname();
std::string GetFullyQualifiedDomainName();
- const char * GetOSName();
- const char * GetOSRelease();
- const char * GetOSVersion();
- const char * GetOSPlatform();
+ const char* GetOSName();
+ const char* GetOSRelease();
+ const char* GetOSVersion();
+ const char* GetOSPlatform();
int GetOSIsWindows();
int GetOSIsLinux();
@@ -93,9 +84,8 @@ public:
// returns an informative general description if the installed and
// available ram on this system. See the GetHostMmeoryTotal, and
// Get{Host,Proc}MemoryAvailable methods for more information.
- std::string GetMemoryDescription(
- const char *hostLimitEnvVarName=NULL,
- const char *procLimitEnvVarName=NULL);
+ std::string GetMemoryDescription(const char* hostLimitEnvVarName = NULL,
+ const char* procLimitEnvVarName = NULL);
// Retrieve amount of physical memory installed on the system in KiB
// units.
@@ -107,7 +97,7 @@ public:
// parallel. The amount of memory reported may differ from the host
// total if a host wide resource limit is applied. Such reource limits
// are reported to us via an applicaiton specified environment variable.
- LongLong GetHostMemoryAvailable(const char *hostLimitEnvVarName=NULL);
+ LongLong GetHostMemoryAvailable(const char* hostLimitEnvVarName = NULL);
// Get total system RAM in units of KiB available to this process.
// This may differ from the host available if a per-process resource
@@ -115,9 +105,8 @@ public:
// system via rlimit API. Resource limits that are not imposed via
// rlimit API may be reported to us via an application specified
// environment variable.
- LongLong GetProcMemoryAvailable(
- const char *hostLimitEnvVarName=NULL,
- const char *procLimitEnvVarName=NULL);
+ LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName = NULL,
+ const char* procLimitEnvVarName = NULL);
// Get the system RAM used by all processes on the host, in units of KiB.
LongLong GetHostMemoryUsed();
@@ -132,14 +121,12 @@ public:
// enable/disable stack trace signal handler. In order to
// produce an informative stack trace the application should
// be dynamically linked and compiled with debug symbols.
- static
- void SetStackTraceOnError(int enable);
+ static void SetStackTraceOnError(int enable);
// format and return the current program stack in a string. In
// order to produce an informative stack trace the application
// should be dynamically linked and compiled with debug symbols.
- static
- std::string GetProgramStack(int firstFrame, int wholePath);
+ static std::string GetProgramStack(int firstFrame, int wholePath);
/** Run the different checks */
void RunCPUCheck();
diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx
index 5da715f..b018a43 100644
--- a/Source/kwsys/SystemTools.cxx
+++ b/Source/kwsys/SystemTools.cxx
@@ -1,27 +1,18 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifdef __osf__
-# define _OSF_SOURCE
-# define _POSIX_C_SOURCE 199506L
-# define _XOPEN_SOURCE_EXTENDED
+#define _OSF_SOURCE
+#define _POSIX_C_SOURCE 199506L
+#define _XOPEN_SOURCE_EXTENDED
#endif
-#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
-# define KWSYS_WINDOWS_DIRS
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || \
+ defined(__BORLANDC__) || defined(__MINGW32__))
+#define KWSYS_WINDOWS_DIRS
#else
-# if defined(__SUNPRO_CC)
-# include <fcntl.h>
-# endif
+#if defined(__SUNPRO_CC)
+#include <fcntl.h>
+#endif
#endif
#include "kwsysPrivate.h"
@@ -31,34 +22,34 @@
#include KWSYS_HEADER(FStream.hxx)
#include KWSYS_HEADER(Encoding.hxx)
-#include <iostream>
#include <fstream>
-#include <sstream>
+#include <iostream>
#include <set>
+#include <sstream>
#include <vector>
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "RegularExpression.hxx.in"
-# include "SystemTools.hxx.in"
-# include "Directory.hxx.in"
-# include "FStream.hxx.in"
-# include "Encoding.hxx.in"
+#include "Directory.hxx.in"
+#include "Encoding.hxx.in"
+#include "FStream.hxx.in"
+#include "RegularExpression.hxx.in"
+#include "SystemTools.hxx.in"
#endif
#ifdef _MSC_VER
-# pragma warning (disable: 4786)
+#pragma warning(disable : 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1375 /* base class destructor not virtual */
+#pragma set woff 1375 /* base class destructor not virtual */
#endif
#include <ctype.h>
#include <errno.h>
#ifdef __QNX__
-# include <malloc.h> /* for malloc/free on QNX */
+#include <malloc.h> /* for malloc/free on QNX */
#endif
#include <stdio.h>
#include <stdlib.h>
@@ -67,64 +58,66 @@
#include <time.h>
#if defined(_WIN32) && !defined(_MSC_VER) && defined(__GNUC__)
-# include <strings.h> /* for strcasecmp */
+#include <strings.h> /* for strcasecmp */
#endif
#ifdef _MSC_VER
-# define umask _umask // Note this is still umask on Borland
+#define umask _umask // Note this is still umask on Borland
#endif
// support for realpath call
#ifndef _WIN32
-#include <sys/time.h>
-#include <utime.h>
#include <limits.h>
-#include <sys/wait.h>
+#include <pwd.h>
#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <sys/wait.h>
#include <unistd.h>
-#include <pwd.h>
+#include <utime.h>
#ifndef __VMS
#include <sys/param.h>
#include <termios.h>
#endif
-#include <signal.h> /* sigprocmask */
+#include <signal.h> /* sigprocmask */
#endif
// Windows API.
#if defined(_WIN32)
-# include <windows.h>
-# include <winioctl.h>
-# ifndef INVALID_FILE_ATTRIBUTES
-# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
-# endif
-# if defined(_MSC_VER) && _MSC_VER >= 1800
-# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# endif
-#elif defined (__CYGWIN__)
-# include <windows.h>
-# undef _WIN32
+#include <windows.h>
+#include <winioctl.h>
+#ifndef INVALID_FILE_ATTRIBUTES
+#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
+#endif
+#if defined(_MSC_VER) && _MSC_VER >= 1800
+#define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+#endif
+#elif defined(__CYGWIN__)
+#include <windows.h>
+#undef _WIN32
#endif
#if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
-extern char **environ;
+extern char** environ;
#endif
#ifdef __CYGWIN__
-# include <sys/cygwin.h>
+#include <sys/cygwin.h>
#endif
// getpwnam doesn't exist on Windows and Cray Xt3/Catamount
// same for TIOCGWINSZ
-#if defined(_WIN32) || defined (__LIBCATAMOUNT__)
-# undef HAVE_GETPWNAM
-# undef HAVE_TTY_INFO
+#if defined(_WIN32) || defined(__LIBCATAMOUNT__)
+#undef HAVE_GETPWNAM
+#undef HAVE_TTY_INFO
#else
-# define HAVE_GETPWNAM 1
-# define HAVE_TTY_INFO 1
+#define HAVE_GETPWNAM 1
+#define HAVE_TTY_INFO 1
#endif
#define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
-#define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"
+#define VTK_URL_REGEX \
+ "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/" \
+ "(.+)?"
#ifdef _MSC_VER
#include <sys/utime.h>
@@ -132,13 +125,11 @@ extern char **environ;
#include <utime.h>
#endif
-
// This is a hack to prevent warnings about these functions being
// declared but not referenced.
#if defined(__sgi) && !defined(__GNUC__)
-# include <sys/termios.h>
-namespace KWSYS_NAMESPACE
-{
+#include <sys/termios.h>
+namespace KWSYS_NAMESPACE {
class SystemToolsHack
{
public:
@@ -148,26 +139,27 @@ public:
Ref2 = sizeof(cfgetispeed(0)),
Ref3 = sizeof(tcgetattr(0, 0)),
Ref4 = sizeof(tcsetattr(0, 0, 0)),
- Ref5 = sizeof(cfsetospeed(0,0)),
- Ref6 = sizeof(cfsetispeed(0,0))
+ Ref5 = sizeof(cfsetospeed(0, 0)),
+ Ref6 = sizeof(cfsetispeed(0, 0))
};
};
}
#endif
-#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
-#include <io.h>
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || \
+ defined(__BORLANDC__) || defined(__MINGW32__))
#include <direct.h>
+#include <io.h>
#define _unlink unlink
#endif
/* The maximum length of a file name. */
#if defined(PATH_MAX)
-# define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
+#define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
#elif defined(MAXPATHLEN)
-# define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
+#define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
#else
-# define KWSYS_SYSTEMTOOLS_MAXPATH 16384
+#define KWSYS_SYSTEMTOOLS_MAXPATH 16384
#endif
#if defined(__WATCOMC__)
#include <direct.h>
@@ -188,20 +180,19 @@ static inline void usleep(unsigned int msec)
}
// BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
-static inline char *realpath(const char *path, char *resolved_path)
+static inline char* realpath(const char* path, char* resolved_path)
{
const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
snprintf(resolved_path, maxlen, "%s", path);
BPath normalized(resolved_path, NULL, true);
- const char *resolved = normalized.Path();
- if (resolved != NULL) // NULL == No such file.
- {
- if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
- {
+ const char* resolved = normalized.Path();
+ if (resolved != NULL) // NULL == No such file.
+ {
+ if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen) {
return resolved_path;
- }
}
- return NULL; // something went wrong.
+ }
+ return NULL; // something went wrong.
}
#endif
@@ -236,74 +227,60 @@ inline int Rmdir(const std::string& dir)
inline const char* Getcwd(char* buf, unsigned int len)
{
std::vector<wchar_t> w_buf(len);
- if(_wgetcwd(&w_buf[0], len))
- {
+ if (_wgetcwd(&w_buf[0], len)) {
// make sure the drive letter is capital
- if(wcslen(&w_buf[0]) > 1 && w_buf[1] == L':')
- {
+ if (wcslen(&w_buf[0]) > 1 && w_buf[1] == L':') {
w_buf[0] = towupper(w_buf[0]);
- }
+ }
std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]);
strcpy(buf, tmp.c_str());
return buf;
- }
+ }
return 0;
}
inline int Chdir(const std::string& dir)
{
- #if defined(__BORLANDC__)
+#if defined(__BORLANDC__)
return chdir(dir.c_str());
- #else
+#else
return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
- #endif
+#endif
}
-inline void Realpath(const std::string& path,
- std::string& resolved_path,
+inline void Realpath(const std::string& path, std::string& resolved_path,
std::string* errorMessage = 0)
{
std::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
- wchar_t *ptemp;
+ wchar_t* ptemp;
wchar_t fullpath[MAX_PATH];
- DWORD bufferLen = GetFullPathNameW(tmp.c_str(),
- sizeof(fullpath) / sizeof(fullpath[0]),
- fullpath, &ptemp);
- if( bufferLen < sizeof(fullpath)/sizeof(fullpath[0]) )
- {
+ DWORD bufferLen = GetFullPathNameW(
+ tmp.c_str(), sizeof(fullpath) / sizeof(fullpath[0]), fullpath, &ptemp);
+ if (bufferLen < sizeof(fullpath) / sizeof(fullpath[0])) {
resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath);
KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
- }
- else if(errorMessage)
- {
- if(bufferLen)
- {
+ } else if (errorMessage) {
+ if (bufferLen) {
*errorMessage = "Destination path buffer size too small.";
- }
- else if(unsigned int errorId = GetLastError())
- {
+ } else if (unsigned int errorId = GetLastError()) {
LPSTR message = NULL;
- DWORD size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
- | FORMAT_MESSAGE_FROM_SYSTEM
- | FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, errorId,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPSTR)&message, 0, NULL);
+ DWORD size = FormatMessageA(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, errorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR)&message, 0, NULL);
*errorMessage = std::string(message, size);
LocalFree(message);
- }
- else
- {
+ } else {
*errorMessage = "Unknown error.";
- }
+ }
resolved_path = "";
- }
- else
- {
+ } else {
resolved_path = path;
- }
+ }
}
#else
#include <sys/types.h>
+
#include <fcntl.h>
#include <unistd.h>
inline int Mkdir(const std::string& dir)
@@ -323,72 +300,59 @@ inline int Chdir(const std::string& dir)
{
return chdir(dir.c_str());
}
-inline void Realpath(const std::string& path,
- std::string& resolved_path,
+inline void Realpath(const std::string& path, std::string& resolved_path,
std::string* errorMessage = 0)
{
char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
errno = 0;
- char *ret = realpath(path.c_str(), resolved_name);
- if(ret)
- {
+ char* ret = realpath(path.c_str(), resolved_name);
+ if (ret) {
resolved_path = ret;
- }
- else if(errorMessage)
- {
- if(errno)
- {
+ } else if (errorMessage) {
+ if (errno) {
*errorMessage = strerror(errno);
- }
- else
- {
+ } else {
*errorMessage = "Unknown error.";
- }
+ }
resolved_path = "";
- }
- else
- {
+ } else {
// if path resolution fails, return what was passed in
resolved_path = path;
- }
+ }
}
#endif
#if !defined(_WIN32) && defined(__COMO__)
// Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
-extern "C"
-{
-extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
-extern int pclose (FILE *__stream) __THROW;
-extern char *realpath (__const char *__restrict __name,
- char *__restrict __resolved) __THROW;
-extern char *strdup (__const char *__s) __THROW;
-extern int putenv (char *__string) __THROW;
+extern "C" {
+extern FILE* popen(__const char* __command, __const char* __modes) __THROW;
+extern int pclose(FILE* __stream) __THROW;
+extern char* realpath(__const char* __restrict __name,
+ char* __restrict __resolved) __THROW;
+extern char* strdup(__const char* __s) __THROW;
+extern int putenv(char* __string) __THROW;
}
#endif
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
double SystemTools::GetTime(void)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
- return (429.4967296*ft.dwHighDateTime
- + 0.0000001*ft.dwLowDateTime
- - 11644473600.0);
+ return (429.4967296 * ft.dwHighDateTime + 0.0000001 * ft.dwLowDateTime -
+ 11644473600.0);
#else
struct timeval t;
gettimeofday(&t, 0);
- return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec);
+ return 1.0 * double(t.tv_sec) + 0.000001 * double(t.tv_usec);
#endif
}
-class SystemToolsTranslationMap :
- public std::map<std::string,std::string>
+class SystemToolsTranslationMap : public std::map<std::string, std::string>
{
};
@@ -402,83 +366,82 @@ typedef char envchar;
/* Order by environment key only (VAR from VAR=VALUE). */
struct kwsysEnvCompare
{
- bool operator() (const envchar* l, const envchar* r) const
- {
+ bool operator()(const envchar* l, const envchar* r) const
+ {
#if defined(_WIN32)
const wchar_t* leq = wcschr(l, L'=');
const wchar_t* req = wcschr(r, L'=');
- size_t llen = leq? (leq-l) : wcslen(l);
- size_t rlen = req? (req-r) : wcslen(r);
- if(llen == rlen)
- {
- return wcsncmp(l,r,llen) < 0;
- }
- else
- {
- return wcscmp(l,r) < 0;
- }
+ size_t llen = leq ? (leq - l) : wcslen(l);
+ size_t rlen = req ? (req - r) : wcslen(r);
+ if (llen == rlen) {
+ return wcsncmp(l, r, llen) < 0;
+ } else {
+ return wcscmp(l, r) < 0;
+ }
#else
const char* leq = strchr(l, '=');
const char* req = strchr(r, '=');
- size_t llen = leq? (leq-l) : strlen(l);
- size_t rlen = req? (req-r) : strlen(r);
- if(llen == rlen)
- {
- return strncmp(l,r,llen) < 0;
- }
- else
- {
- return strcmp(l,r) < 0;
- }
-#endif
+ size_t llen = leq ? (leq - l) : strlen(l);
+ size_t rlen = req ? (req - r) : strlen(r);
+ if (llen == rlen) {
+ return strncmp(l, r, llen) < 0;
+ } else {
+ return strcmp(l, r) < 0;
}
+#endif
+ }
};
-class kwsysEnvSet: public std::set<const envchar*, kwsysEnvCompare>
+class kwsysEnvSet : public std::set<const envchar*, kwsysEnvCompare>
{
public:
class Free
{
const envchar* Env;
+
public:
- Free(const envchar* env): Env(env) {}
+ Free(const envchar* env)
+ : Env(env)
+ {
+ }
~Free() { free(const_cast<envchar*>(this->Env)); }
};
const envchar* Release(const envchar* env)
- {
+ {
const envchar* old = 0;
iterator i = this->find(env);
- if(i != this->end())
- {
+ if (i != this->end()) {
old = *i;
this->erase(i);
- }
- return old;
}
+ return old;
+ }
};
#ifdef _WIN32
struct SystemToolsPathCaseCmp
{
bool operator()(std::string const& l, std::string const& r) const
- {
-# ifdef _MSC_VER
+ {
+#ifdef _MSC_VER
return _stricmp(l.c_str(), r.c_str()) < 0;
-# elif defined(__GNUC__)
+#elif defined(__GNUC__)
return strcasecmp(l.c_str(), r.c_str()) < 0;
-# else
+#else
return SystemTools::Strucmp(l.c_str(), r.c_str()) < 0;
-# endif
- }
+#endif
+ }
};
-class SystemToolsPathCaseMap:
- public std::map<std::string, std::string,
- SystemToolsPathCaseCmp> {};
+class SystemToolsPathCaseMap
+ : public std::map<std::string, std::string, SystemToolsPathCaseCmp>
+{
+};
-class SystemToolsEnvMap :
- public std::map<std::string,std::string> {};
+class SystemToolsEnvMap : public std::map<std::string, std::string>
+{
+};
#endif
// adds the elements of the env variable path to the arg passed in
@@ -490,54 +453,45 @@ void SystemTools::GetPath(std::vector<std::string>& path, const char* env)
#else
const char pathSep = ':';
#endif
- if(!env)
- {
+ if (!env) {
env = "PATH";
- }
+ }
std::string pathEnv;
- if ( !SystemTools::GetEnv(env, pathEnv) )
- {
+ if (!SystemTools::GetEnv(env, pathEnv)) {
return;
- }
+ }
// A hack to make the below algorithm work.
- if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep)
- {
+ if (!pathEnv.empty() && *pathEnv.rbegin() != pathSep) {
pathEnv += pathSep;
- }
- std::string::size_type start =0;
+ }
+ std::string::size_type start = 0;
bool done = false;
- while(!done)
- {
+ while (!done) {
std::string::size_type endpos = pathEnv.find(pathSep, start);
- if(endpos != std::string::npos)
- {
- path.push_back(pathEnv.substr(start, endpos-start));
- start = endpos+1;
- }
- else
- {
+ if (endpos != std::string::npos) {
+ path.push_back(pathEnv.substr(start, endpos - start));
+ start = endpos + 1;
+ } else {
done = true;
- }
}
- for(std::vector<std::string>::iterator i = path.begin() + old_size;
- i != path.end(); ++i)
- {
+ }
+ for (std::vector<std::string>::iterator i = path.begin() + old_size;
+ i != path.end(); ++i) {
SystemTools::ConvertToUnixSlashes(*i);
- }
+ }
}
const char* SystemTools::GetEnvImpl(const char* key)
{
- const char *v = 0;
+ const char* v = 0;
#if defined(_WIN32)
std::string env;
- if (SystemTools::GetEnv(key, env))
- {
+ if (SystemTools::GetEnv(key, env)) {
std::string& menv = (*SystemTools::EnvMap)[key];
menv = env;
v = menv.c_str();
- }
+ }
#else
v = getenv(key);
#endif
@@ -559,18 +513,16 @@ bool SystemTools::GetEnv(const char* key, std::string& result)
#if defined(_WIN32)
const std::wstring wkey = Encoding::ToWide(key);
const wchar_t* wv = _wgetenv(wkey.c_str());
- if (wv)
- {
+ if (wv) {
result = Encoding::ToNarrow(wv);
return true;
- }
+ }
#else
const char* v = getenv(key);
- if(v)
- {
+ if (v) {
result = v;
return true;
- }
+ }
#endif
return false;
}
@@ -604,15 +556,12 @@ bool SystemTools::HasEnv(const std::string& key)
static int kwsysUnPutEnv(const std::string& env)
{
size_t pos = env.find('=');
- if(pos != env.npos)
- {
+ if (pos != env.npos) {
std::string name = env.substr(0, pos);
unsetenv(name.c_str());
- }
- else
- {
+ } else {
unsetenv(env.c_str());
- }
+ }
return 0;
}
@@ -627,25 +576,21 @@ static int kwsysUnPutEnv(const std::string& env)
size_t const sz = len + 1;
char local_buf[256];
char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
- if(!buf)
- {
+ if (!buf) {
return -1;
- }
+ }
strncpy(buf, env.c_str(), len);
buf[len] = 0;
- if(putenv(buf) < 0 && errno != EINVAL)
- {
+ if (putenv(buf) < 0 && errno != EINVAL) {
err = errno;
- }
- if(buf != local_buf)
- {
+ }
+ if (buf != local_buf) {
free(buf);
- }
- if(err)
- {
+ }
+ if (err) {
errno = err;
return -1;
- }
+ }
return 0;
}
@@ -662,12 +607,11 @@ static int kwsysUnPutEnv(std::string const& env)
std::wstring wEnv = Encoding::ToWide(env);
size_t const pos = wEnv.find('=');
size_t const len = pos == wEnv.npos ? wEnv.size() : pos;
- wEnv.resize(len+1, L'=');
+ wEnv.resize(len + 1, L'=');
wchar_t* newEnv = _wcsdup(wEnv.c_str());
- if(!newEnv)
- {
+ if (!newEnv) {
return -1;
- }
+ }
kwsysEnvSet::Free oldEnv(kwsysUnPutEnvSet.Release(newEnv));
kwsysUnPutEnvSet.insert(newEnv);
return _wputenv(newEnv);
@@ -681,23 +625,17 @@ static int kwsysUnPutEnv(const std::string& env)
size_t const len = pos == env.npos ? env.size() : pos;
int in = 0;
int out = 0;
- while(environ[in])
- {
- if(strlen(environ[in]) > len &&
- environ[in][len] == '=' &&
- strncmp(env.c_str(), environ[in], len) == 0)
- {
+ while (environ[in]) {
+ if (strlen(environ[in]) > len && environ[in][len] == '=' &&
+ strncmp(env.c_str(), environ[in], len) == 0) {
++in;
- }
- else
- {
+ } else {
environ[out++] = environ[in++];
- }
}
- while(out < in)
- {
+ }
+ while (out < in) {
environ[out++] = 0;
- }
+ }
return 0;
}
#endif
@@ -711,15 +649,12 @@ static int kwsysUnPutEnv(const std::string& env)
bool SystemTools::PutEnv(const std::string& env)
{
size_t pos = env.find('=');
- if(pos != env.npos)
- {
+ if (pos != env.npos) {
std::string name = env.substr(0, pos);
return setenv(name.c_str(), env.c_str() + pos + 1, 1) == 0;
- }
- else
- {
+ } else {
return kwsysUnPutEnv(env) == 0;
- }
+ }
}
bool SystemTools::UnPutEnv(const std::string& env)
@@ -736,17 +671,16 @@ bool SystemTools::UnPutEnv(const std::string& env)
environment values that may still reference memory we allocated. Then free
the memory. This will not affect any environment values we never set. */
-# ifdef __INTEL_COMPILER
-# pragma warning disable 444 /* base has non-virtual destructor */
-# endif
+#ifdef __INTEL_COMPILER
+#pragma warning disable 444 /* base has non-virtual destructor */
+#endif
-class kwsysEnv: public kwsysEnvSet
+class kwsysEnv : public kwsysEnvSet
{
public:
~kwsysEnv()
- {
- for(iterator i = this->begin(); i != this->end(); ++i)
- {
+ {
+ for (iterator i = this->begin(); i != this->end(); ++i) {
#if defined(_WIN32)
const std::string s = Encoding::ToNarrow(*i);
kwsysUnPutEnv(s.c_str());
@@ -754,10 +688,10 @@ public:
kwsysUnPutEnv(*i);
#endif
free(const_cast<envchar*>(*i));
- }
}
+ }
bool Put(const char* env)
- {
+ {
#if defined(_WIN32)
const std::wstring wEnv = Encoding::ToWide(env);
wchar_t* newEnv = _wcsdup(wEnv.c_str());
@@ -771,9 +705,9 @@ public:
#else
return putenv(newEnv) == 0;
#endif
- }
+ }
bool UnPut(const char* env)
- {
+ {
#if defined(_WIN32)
const std::wstring wEnv = Encoding::ToWide(env);
Free oldEnv(this->Release(wEnv.c_str()));
@@ -781,7 +715,7 @@ public:
Free oldEnv(this->Release(env));
#endif
return kwsysUnPutEnv(env) == 0;
- }
+ }
};
static kwsysEnv kwsysEnvInstance;
@@ -821,54 +755,47 @@ FILE* SystemTools::Fopen(const std::string& file, const char* mode)
bool SystemTools::MakeDirectory(const char* path)
{
- if(!path)
- {
+ if (!path) {
return false;
- }
+ }
return SystemTools::MakeDirectory(std::string(path));
}
bool SystemTools::MakeDirectory(const std::string& path)
{
- if(SystemTools::FileExists(path))
- {
+ if (SystemTools::FileExists(path)) {
return SystemTools::FileIsDirectory(path);
- }
- if(path.empty())
- {
+ }
+ if (path.empty()) {
return false;
- }
+ }
std::string dir = path;
SystemTools::ConvertToUnixSlashes(dir);
std::string::size_type pos = 0;
std::string topdir;
- while((pos = dir.find('/', pos)) != std::string::npos)
- {
+ while ((pos = dir.find('/', pos)) != std::string::npos) {
topdir = dir.substr(0, pos);
Mkdir(topdir);
pos++;
- }
+ }
topdir = dir;
- if(Mkdir(topdir) != 0)
- {
+ if (Mkdir(topdir) != 0) {
// There is a bug in the Borland Run time library which makes MKDIR
// return EACCES when it should return EEXISTS
// if it is some other error besides directory exists
// then return false
- if( (errno != EEXIST)
+ if ((errno != EEXIST)
#ifdef __BORLANDC__
&& (errno != EACCES)
#endif
- )
- {
+ ) {
return false;
- }
}
+ }
return true;
}
-
// replace replace with with as many times as it shows up in source.
// write the result into source.
void SystemTools::ReplaceString(std::string& source,
@@ -876,58 +803,51 @@ void SystemTools::ReplaceString(std::string& source,
const std::string& with)
{
// do while hangs if replaceSize is 0
- if (replace.empty())
- {
+ if (replace.empty()) {
return;
- }
+ }
SystemTools::ReplaceString(source, replace.c_str(), replace.size(), with);
}
-void SystemTools::ReplaceString(std::string& source,
- const char* replace,
+void SystemTools::ReplaceString(std::string& source, const char* replace,
const char* with)
{
// do while hangs if replaceSize is 0
- if (!*replace)
- {
+ if (!*replace) {
return;
- }
+ }
- SystemTools::ReplaceString(source, replace, strlen(replace), with ? with : "");
+ SystemTools::ReplaceString(source, replace, strlen(replace),
+ with ? with : "");
}
-void SystemTools::ReplaceString(std::string& source,
- const char* replace,
- size_t replaceSize,
- const std::string& with)
+void SystemTools::ReplaceString(std::string& source, const char* replace,
+ size_t replaceSize, const std::string& with)
{
- const char *src = source.c_str();
- char *searchPos = const_cast<char *>(strstr(src,replace));
+ const char* src = source.c_str();
+ char* searchPos = const_cast<char*>(strstr(src, replace));
// get out quick if string is not found
- if (!searchPos)
- {
+ if (!searchPos) {
return;
- }
+ }
// perform replacements until done
- char *orig = strdup(src);
- char *currentPos = orig;
+ char* orig = strdup(src);
+ char* currentPos = orig;
searchPos = searchPos - src + orig;
// initialize the result
- source.erase(source.begin(),source.end());
- do
- {
+ source.erase(source.begin(), source.end());
+ do {
*searchPos = '\0';
source += currentPos;
currentPos = searchPos + replaceSize;
// replace
source += with;
- searchPos = strstr(currentPos,replace);
- }
- while (searchPos);
+ searchPos = strstr(currentPos, replace);
+ } while (searchPos);
// copy any trailing text
source += currentPos;
@@ -935,56 +855,48 @@ void SystemTools::ReplaceString(std::string& source,
}
#if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
-# define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
-# define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
+#define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
+#define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
#else
-# define KWSYS_ST_KEY_WOW64_32KEY 0x0200
-# define KWSYS_ST_KEY_WOW64_64KEY 0x0100
+#define KWSYS_ST_KEY_WOW64_32KEY 0x0200
+#define KWSYS_ST_KEY_WOW64_64KEY 0x0100
#endif
#if defined(_WIN32) && !defined(__CYGWIN__)
static bool SystemToolsParseRegistryKey(const std::string& key,
- HKEY& primaryKey,
- std::string& second,
+ HKEY& primaryKey, std::string& second,
std::string& valuename)
{
std::string primary = key;
size_t start = primary.find('\\');
- if (start == std::string::npos)
- {
+ if (start == std::string::npos) {
return false;
- }
+ }
size_t valuenamepos = primary.find(';');
- if (valuenamepos != std::string::npos)
- {
- valuename = primary.substr(valuenamepos+1);
- }
+ if (valuenamepos != std::string::npos) {
+ valuename = primary.substr(valuenamepos + 1);
+ }
- second = primary.substr(start+1, valuenamepos-start-1);
+ second = primary.substr(start + 1, valuenamepos - start - 1);
primary = primary.substr(0, start);
- if (primary == "HKEY_CURRENT_USER")
- {
+ if (primary == "HKEY_CURRENT_USER") {
primaryKey = HKEY_CURRENT_USER;
- }
- if (primary == "HKEY_CURRENT_CONFIG")
- {
+ }
+ if (primary == "HKEY_CURRENT_CONFIG") {
primaryKey = HKEY_CURRENT_CONFIG;
- }
- if (primary == "HKEY_CLASSES_ROOT")
- {
+ }
+ if (primary == "HKEY_CLASSES_ROOT") {
primaryKey = HKEY_CLASSES_ROOT;
- }
- if (primary == "HKEY_LOCAL_MACHINE")
- {
+ }
+ if (primary == "HKEY_LOCAL_MACHINE") {
primaryKey = HKEY_LOCAL_MACHINE;
- }
- if (primary == "HKEY_USERS")
- {
+ }
+ if (primary == "HKEY_USERS") {
primaryKey = HKEY_USERS;
- }
+ }
return true;
}
@@ -993,69 +905,56 @@ static DWORD SystemToolsMakeRegistryMode(DWORD mode,
SystemTools::KeyWOW64 view)
{
// only add the modes when on a system that supports Wow64.
- static FARPROC wow64p = GetProcAddress(GetModuleHandleW(L"kernel32"),
- "IsWow64Process");
- if(wow64p == NULL)
- {
+ static FARPROC wow64p =
+ GetProcAddress(GetModuleHandleW(L"kernel32"), "IsWow64Process");
+ if (wow64p == NULL) {
return mode;
- }
+ }
- if(view == SystemTools::KeyWOW64_32)
- {
+ if (view == SystemTools::KeyWOW64_32) {
return mode | KWSYS_ST_KEY_WOW64_32KEY;
- }
- else if(view == SystemTools::KeyWOW64_64)
- {
+ } else if (view == SystemTools::KeyWOW64_64) {
return mode | KWSYS_ST_KEY_WOW64_64KEY;
- }
+ }
return mode;
}
#endif
#if defined(_WIN32) && !defined(__CYGWIN__)
-bool
-SystemTools::GetRegistrySubKeys(const std::string& key,
- std::vector<std::string>& subkeys,
- KeyWOW64 view)
+bool SystemTools::GetRegistrySubKeys(const std::string& key,
+ std::vector<std::string>& subkeys,
+ KeyWOW64 view)
{
HKEY primaryKey = HKEY_CURRENT_USER;
std::string second;
std::string valuename;
- if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
- {
+ if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
return false;
- }
+ }
HKEY hKey;
- if(RegOpenKeyExW(primaryKey,
- Encoding::ToWide(second).c_str(),
- 0,
- SystemToolsMakeRegistryMode(KEY_READ, view),
- &hKey) != ERROR_SUCCESS)
- {
+ if (RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0,
+ SystemToolsMakeRegistryMode(KEY_READ, view),
+ &hKey) != ERROR_SUCCESS) {
return false;
- }
- else
- {
+ } else {
wchar_t name[1024];
- DWORD dwNameSize = sizeof(name)/sizeof(name[0]);
+ DWORD dwNameSize = sizeof(name) / sizeof(name[0]);
DWORD i = 0;
- while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS)
- {
+ while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS) {
subkeys.push_back(Encoding::ToNarrow(name));
++i;
- }
+ }
RegCloseKey(hKey);
- }
+ }
return true;
}
#else
bool SystemTools::GetRegistrySubKeys(const std::string&,
- std::vector<std::string>&,
- KeyWOW64)
+ std::vector<std::string>&, KeyWOW64)
{
return false;
}
@@ -1069,71 +968,53 @@ bool SystemTools::GetRegistrySubKeys(const std::string&,
// => will return the data of the "Root" value of the key
#if defined(_WIN32) && !defined(__CYGWIN__)
-bool SystemTools::ReadRegistryValue(const std::string& key, std::string &value,
+bool SystemTools::ReadRegistryValue(const std::string& key, std::string& value,
KeyWOW64 view)
{
bool valueset = false;
HKEY primaryKey = HKEY_CURRENT_USER;
std::string second;
std::string valuename;
- if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
- {
+ if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
return false;
- }
+ }
HKEY hKey;
- if(RegOpenKeyExW(primaryKey,
- Encoding::ToWide(second).c_str(),
- 0,
- SystemToolsMakeRegistryMode(KEY_READ, view),
- &hKey) != ERROR_SUCCESS)
- {
+ if (RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0,
+ SystemToolsMakeRegistryMode(KEY_READ, view),
+ &hKey) != ERROR_SUCCESS) {
return false;
- }
- else
- {
+ } else {
DWORD dwType, dwSize;
dwSize = 1023;
wchar_t data[1024];
- if(RegQueryValueExW(hKey,
- Encoding::ToWide(valuename).c_str(),
- NULL,
- &dwType,
- (BYTE *)data,
- &dwSize) == ERROR_SUCCESS)
- {
- if (dwType == REG_SZ)
- {
+ if (RegQueryValueExW(hKey, Encoding::ToWide(valuename).c_str(), NULL,
+ &dwType, (BYTE*)data, &dwSize) == ERROR_SUCCESS) {
+ if (dwType == REG_SZ) {
value = Encoding::ToNarrow(data);
valueset = true;
- }
- else if (dwType == REG_EXPAND_SZ)
- {
+ } else if (dwType == REG_EXPAND_SZ) {
wchar_t expanded[1024];
- DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
- if(ExpandEnvironmentStringsW(data, expanded,
- dwExpandedSize))
- {
+ DWORD dwExpandedSize = sizeof(expanded) / sizeof(expanded[0]);
+ if (ExpandEnvironmentStringsW(data, expanded, dwExpandedSize)) {
value = Encoding::ToNarrow(expanded);
valueset = true;
- }
}
}
+ }
RegCloseKey(hKey);
- }
+ }
return valueset;
}
#else
-bool SystemTools::ReadRegistryValue(const std::string&, std::string &,
- KeyWOW64)
+bool SystemTools::ReadRegistryValue(const std::string&, std::string&, KeyWOW64)
{
return false;
}
#endif
-
// Write a registry value.
// Example :
// HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
@@ -1143,47 +1024,37 @@ bool SystemTools::ReadRegistryValue(const std::string&, std::string &,
#if defined(_WIN32) && !defined(__CYGWIN__)
bool SystemTools::WriteRegistryValue(const std::string& key,
- const std::string& value,
- KeyWOW64 view)
+ const std::string& value, KeyWOW64 view)
{
HKEY primaryKey = HKEY_CURRENT_USER;
std::string second;
std::string valuename;
- if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
- {
+ if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
return false;
- }
+ }
HKEY hKey;
DWORD dwDummy;
wchar_t lpClass[] = L"";
- if(RegCreateKeyExW(primaryKey,
- Encoding::ToWide(second).c_str(),
- 0,
- lpClass,
- REG_OPTION_NON_VOLATILE,
- SystemToolsMakeRegistryMode(KEY_WRITE, view),
- NULL,
- &hKey,
- &dwDummy) != ERROR_SUCCESS)
- {
+ if (RegCreateKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0, lpClass,
+ REG_OPTION_NON_VOLATILE,
+ SystemToolsMakeRegistryMode(KEY_WRITE, view), NULL,
+ &hKey, &dwDummy) != ERROR_SUCCESS) {
return false;
- }
+ }
std::wstring wvalue = Encoding::ToWide(value);
- if(RegSetValueExW(hKey,
- Encoding::ToWide(valuename).c_str(),
- 0,
- REG_SZ,
- (CONST BYTE *)wvalue.c_str(),
- (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) == ERROR_SUCCESS)
- {
+ if (RegSetValueExW(hKey, Encoding::ToWide(valuename).c_str(), 0, REG_SZ,
+ (CONST BYTE*)wvalue.c_str(),
+ (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) ==
+ ERROR_SUCCESS) {
return true;
- }
+ }
return false;
}
#else
-bool SystemTools::WriteRegistryValue(const std::string&, const std::string&, KeyWOW64)
+bool SystemTools::WriteRegistryValue(const std::string&, const std::string&,
+ KeyWOW64)
{
return false;
}
@@ -1202,29 +1073,21 @@ bool SystemTools::DeleteRegistryValue(const std::string& key, KeyWOW64 view)
HKEY primaryKey = HKEY_CURRENT_USER;
std::string second;
std::string valuename;
- if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
- {
+ if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
return false;
- }
+ }
HKEY hKey;
- if(RegOpenKeyExW(primaryKey,
- Encoding::ToWide(second).c_str(),
- 0,
- SystemToolsMakeRegistryMode(KEY_WRITE, view),
- &hKey) != ERROR_SUCCESS)
- {
+ if (RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0,
+ SystemToolsMakeRegistryMode(KEY_WRITE, view),
+ &hKey) != ERROR_SUCCESS) {
return false;
- }
- else
- {
- if(RegDeleteValue(hKey,
- (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
- {
+ } else {
+ if (RegDeleteValue(hKey, (LPTSTR)valuename.c_str()) == ERROR_SUCCESS) {
RegCloseKey(hKey);
return true;
- }
}
+ }
return false;
}
#else
@@ -1239,58 +1102,45 @@ bool SystemTools::SameFile(const std::string& file1, const std::string& file2)
#ifdef _WIN32
HANDLE hFile1, hFile2;
- hFile1 = CreateFileW( Encoding::ToWide(file1).c_str(),
- GENERIC_READ,
- FILE_SHARE_READ ,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL
- );
- hFile2 = CreateFileW( Encoding::ToWide(file2).c_str(),
- GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS,
- NULL
- );
- if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
- {
- if(hFile1 != INVALID_HANDLE_VALUE)
- {
+ hFile1 =
+ CreateFileW(Encoding::ToWide(file1).c_str(), GENERIC_READ, FILE_SHARE_READ,
+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+ hFile2 =
+ CreateFileW(Encoding::ToWide(file2).c_str(), GENERIC_READ, FILE_SHARE_READ,
+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+ if (hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE) {
+ if (hFile1 != INVALID_HANDLE_VALUE) {
CloseHandle(hFile1);
- }
- if(hFile2 != INVALID_HANDLE_VALUE)
- {
+ }
+ if (hFile2 != INVALID_HANDLE_VALUE) {
CloseHandle(hFile2);
- }
- return false;
}
+ return false;
+ }
- BY_HANDLE_FILE_INFORMATION fiBuf1;
- BY_HANDLE_FILE_INFORMATION fiBuf2;
- GetFileInformationByHandle( hFile1, &fiBuf1 );
- GetFileInformationByHandle( hFile2, &fiBuf2 );
- CloseHandle(hFile1);
- CloseHandle(hFile2);
- return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
- fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
- fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
+ BY_HANDLE_FILE_INFORMATION fiBuf1;
+ BY_HANDLE_FILE_INFORMATION fiBuf2;
+ GetFileInformationByHandle(hFile1, &fiBuf1);
+ GetFileInformationByHandle(hFile2, &fiBuf2);
+ CloseHandle(hFile1);
+ CloseHandle(hFile2);
+ return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
+ fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
+ fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
#else
struct stat fileStat1, fileStat2;
- if (stat(file1.c_str(), &fileStat1) == 0 && stat(file2.c_str(), &fileStat2) == 0)
- {
+ if (stat(file1.c_str(), &fileStat1) == 0 &&
+ stat(file2.c_str(), &fileStat2) == 0) {
// see if the files are the same file
// check the device inode and size
- if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
- memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
- fileStat2.st_size == fileStat1.st_size
- )
- {
+ if (memcmp(&fileStat2.st_dev, &fileStat1.st_dev,
+ sizeof(fileStat1.st_dev)) == 0 &&
+ memcmp(&fileStat2.st_ino, &fileStat1.st_ino,
+ sizeof(fileStat1.st_ino)) == 0 &&
+ fileStat2.st_size == fileStat1.st_size) {
return true;
- }
}
+ }
return false;
#endif
}
@@ -1298,23 +1148,21 @@ bool SystemTools::SameFile(const std::string& file1, const std::string& file2)
//----------------------------------------------------------------------------
bool SystemTools::PathExists(const std::string& path)
{
- if(path.empty())
- {
+ if (path.empty()) {
return false;
- }
+ }
#if defined(__CYGWIN__)
// Convert path to native windows path if possible.
char winpath[MAX_PATH];
- if(SystemTools::PathCygwinToWin32(path.c_str(), winpath))
- {
+ if (SystemTools::PathCygwinToWin32(path.c_str(), winpath)) {
return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
- }
+ }
struct stat st;
return lstat(path.c_str(), &st) == 0;
#elif defined(_WIN32)
return (GetFileAttributesW(
- SystemTools::ConvertToWindowsExtendedPath(path).c_str())
- != INVALID_FILE_ATTRIBUTES);
+ SystemTools::ConvertToWindowsExtendedPath(path).c_str()) !=
+ INVALID_FILE_ATTRIBUTES);
#else
struct stat st;
return lstat(path.c_str(), &st) == 0;
@@ -1324,32 +1172,29 @@ bool SystemTools::PathExists(const std::string& path)
//----------------------------------------------------------------------------
bool SystemTools::FileExists(const char* filename)
{
- if(!filename)
- {
+ if (!filename) {
return false;
- }
+ }
return SystemTools::FileExists(std::string(filename));
}
//----------------------------------------------------------------------------
bool SystemTools::FileExists(const std::string& filename)
{
- if(filename.empty())
- {
+ if (filename.empty()) {
return false;
- }
+ }
#if defined(__CYGWIN__)
// Convert filename to native windows path if possible.
char winpath[MAX_PATH];
- if(SystemTools::PathCygwinToWin32(filename.c_str(), winpath))
- {
+ if (SystemTools::PathCygwinToWin32(filename.c_str(), winpath)) {
return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
- }
+ }
return access(filename.c_str(), R_OK) == 0;
#elif defined(_WIN32)
return (GetFileAttributesW(
- SystemTools::ConvertToWindowsExtendedPath(filename).c_str())
- != INVALID_FILE_ATTRIBUTES);
+ SystemTools::ConvertToWindowsExtendedPath(filename).c_str()) !=
+ INVALID_FILE_ATTRIBUTES);
#else
// SCO OpenServer 5.0.7/3.2's command has 711 permission.
#if defined(_SCO_DS)
@@ -1363,22 +1208,20 @@ bool SystemTools::FileExists(const std::string& filename)
//----------------------------------------------------------------------------
bool SystemTools::FileExists(const char* filename, bool isFile)
{
- if(!filename)
- {
+ if (!filename) {
return false;
- }
+ }
return SystemTools::FileExists(std::string(filename), isFile);
}
//----------------------------------------------------------------------------
bool SystemTools::FileExists(const std::string& filename, bool isFile)
{
- if(SystemTools::FileExists(filename))
- {
+ if (SystemTools::FileExists(filename)) {
// If isFile is set return not FileIsDirectory,
// so this will only be true if it is a file
return !isFile || !SystemTools::FileIsDirectory(filename);
- }
+ }
return false;
}
@@ -1386,34 +1229,29 @@ bool SystemTools::FileExists(const std::string& filename, bool isFile)
bool SystemTools::TestFileAccess(const char* filename,
TestFilePermissions permissions)
{
- if(!filename)
- {
+ if (!filename) {
return false;
- }
- return SystemTools::TestFileAccess(std::string(filename),
- permissions);
+ }
+ return SystemTools::TestFileAccess(std::string(filename), permissions);
}
//----------------------------------------------------------------------------
bool SystemTools::TestFileAccess(const std::string& filename,
TestFilePermissions permissions)
{
- if(filename.empty())
- {
+ if (filename.empty()) {
return false;
- }
+ }
#if defined(_WIN32) && !defined(__CYGWIN__)
// If execute set, change to read permission (all files on Windows
// are executable if they are readable). The CRT will always fail
// if you pass an execute bit.
- if(permissions & TEST_FILE_EXECUTE)
- {
+ if (permissions & TEST_FILE_EXECUTE) {
permissions &= ~TEST_FILE_EXECUTE;
permissions |= TEST_FILE_READ;
- }
- return _waccess(
- SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
- permissions) == 0;
+ }
+ return _waccess(SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+ permissions) == 0;
#else
return access(filename.c_str(), permissions) == 0;
#endif
@@ -1421,109 +1259,93 @@ bool SystemTools::TestFileAccess(const std::string& filename,
//----------------------------------------------------------------------------
#ifdef __CYGWIN__
-bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
+bool SystemTools::PathCygwinToWin32(const char* path, char* win32_path)
{
SystemToolsTranslationMap::iterator i =
SystemTools::Cyg2Win32Map->find(path);
- if (i != SystemTools::Cyg2Win32Map->end())
- {
+ if (i != SystemTools::Cyg2Win32Map->end()) {
strncpy(win32_path, i->second.c_str(), MAX_PATH);
- }
- else
- {
- if(cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) != 0)
- {
+ } else {
+ if (cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) !=
+ 0) {
win32_path[0] = 0;
- }
+ }
SystemToolsTranslationMap::value_type entry(path, win32_path);
SystemTools::Cyg2Win32Map->insert(entry);
- }
+ }
return win32_path[0] != 0;
}
#endif
bool SystemTools::Touch(const std::string& filename, bool create)
{
- if (!SystemTools::FileExists(filename))
- {
- if(create)
- {
+ if (!SystemTools::FileExists(filename)) {
+ if (create) {
FILE* file = Fopen(filename, "a+b");
- if(file)
- {
+ if (file) {
fclose(file);
return true;
- }
- return false;
}
- else
- {
+ return false;
+ } else {
return true;
- }
}
+ }
#if defined(_WIN32) && !defined(__CYGWIN__)
- HANDLE h = CreateFileW(
- SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
- FILE_WRITE_ATTRIBUTES,
- FILE_SHARE_WRITE, 0, OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS, 0);
- if(!h)
- {
+ HANDLE h =
+ CreateFileW(SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+ FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS, 0);
+ if (!h) {
return false;
- }
+ }
FILETIME mtime;
GetSystemTimeAsFileTime(&mtime);
- if(!SetFileTime(h, 0, 0, &mtime))
- {
+ if (!SetFileTime(h, 0, 0, &mtime)) {
CloseHandle(h);
return false;
- }
+ }
CloseHandle(h);
#elif KWSYS_CXX_HAS_UTIMENSAT
- struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
- if(utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0)
- {
+ struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } };
+ if (utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0) {
return false;
- }
+ }
#else
struct stat st;
- if(stat(filename.c_str(), &st) < 0)
- {
+ if (stat(filename.c_str(), &st) < 0) {
return false;
- }
+ }
struct timeval mtime;
gettimeofday(&mtime, 0);
-# if KWSYS_CXX_HAS_UTIMES
+#if KWSYS_CXX_HAS_UTIMES
struct timeval atime;
-# if KWSYS_CXX_STAT_HAS_ST_MTIM
+#if KWSYS_CXX_STAT_HAS_ST_MTIM
atime.tv_sec = st.st_atim.tv_sec;
- atime.tv_usec = st.st_atim.tv_nsec/1000;
-# elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
+ atime.tv_usec = st.st_atim.tv_nsec / 1000;
+#elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
atime.tv_sec = st.st_atimespec.tv_sec;
- atime.tv_usec = st.st_atimespec.tv_nsec/1000;
-# else
+ atime.tv_usec = st.st_atimespec.tv_nsec / 1000;
+#else
atime.tv_sec = st.st_atime;
atime.tv_usec = 0;
-# endif
+#endif
struct timeval times[2] = { atime, mtime };
- if(utimes(filename.c_str(), times) < 0)
- {
+ if (utimes(filename.c_str(), times) < 0) {
return false;
- }
-# else
- struct utimbuf times = {st.st_atime, mtime.tv_sec};
- if(utime(filename.c_str(), &times) < 0)
- {
+ }
+#else
+ struct utimbuf times = { st.st_atime, mtime.tv_sec };
+ if (utime(filename.c_str(), &times) < 0) {
return false;
- }
-# endif
+ }
+#endif
#endif
return true;
}
-bool SystemTools::FileTimeCompare(const std::string& f1,
- const std::string& f2,
+bool SystemTools::FileTimeCompare(const std::string& f1, const std::string& f2,
int* result)
{
// Default to same time.
@@ -1531,78 +1353,57 @@ bool SystemTools::FileTimeCompare(const std::string& f1,
#if !defined(_WIN32) || defined(__CYGWIN__)
// POSIX version. Use stat function to get file modification time.
struct stat s1;
- if(stat(f1.c_str(), &s1) != 0)
- {
+ if (stat(f1.c_str(), &s1) != 0) {
return false;
- }
+ }
struct stat s2;
- if(stat(f2.c_str(), &s2) != 0)
- {
+ if (stat(f2.c_str(), &s2) != 0) {
return false;
- }
-# if KWSYS_CXX_STAT_HAS_ST_MTIM
+ }
+#if KWSYS_CXX_STAT_HAS_ST_MTIM
// Compare using nanosecond resolution.
- if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
- {
+ if (s1.st_mtim.tv_sec < s2.st_mtim.tv_sec) {
*result = -1;
- }
- else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
- {
+ } else if (s1.st_mtim.tv_sec > s2.st_mtim.tv_sec) {
*result = 1;
- }
- else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
- {
+ } else if (s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec) {
*result = -1;
- }
- else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
- {
+ } else if (s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec) {
*result = 1;
- }
-# elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
+ }
+#elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
// Compare using nanosecond resolution.
- if(s1.st_mtimespec.tv_sec < s2.st_mtimespec.tv_sec)
- {
+ if (s1.st_mtimespec.tv_sec < s2.st_mtimespec.tv_sec) {
*result = -1;
- }
- else if(s1.st_mtimespec.tv_sec > s2.st_mtimespec.tv_sec)
- {
+ } else if (s1.st_mtimespec.tv_sec > s2.st_mtimespec.tv_sec) {
*result = 1;
- }
- else if(s1.st_mtimespec.tv_nsec < s2.st_mtimespec.tv_nsec)
- {
+ } else if (s1.st_mtimespec.tv_nsec < s2.st_mtimespec.tv_nsec) {
*result = -1;
- }
- else if(s1.st_mtimespec.tv_nsec > s2.st_mtimespec.tv_nsec)
- {
+ } else if (s1.st_mtimespec.tv_nsec > s2.st_mtimespec.tv_nsec) {
*result = 1;
- }
-# else
+ }
+#else
// Compare using 1 second resolution.
- if(s1.st_mtime < s2.st_mtime)
- {
+ if (s1.st_mtime < s2.st_mtime) {
*result = -1;
- }
- else if(s1.st_mtime > s2.st_mtime)
- {
+ } else if (s1.st_mtime > s2.st_mtime) {
*result = 1;
- }
-# endif
+ }
+#endif
#else
// Windows version. Get the modification time from extended file attributes.
WIN32_FILE_ATTRIBUTE_DATA f1d;
WIN32_FILE_ATTRIBUTE_DATA f2d;
- if(!GetFileAttributesExW(
- SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
- GetFileExInfoStandard, &f1d))
- {
+ if (!GetFileAttributesExW(
+ SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
+ GetFileExInfoStandard, &f1d)) {
return false;
- }
- if(!GetFileAttributesExW(
- SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
- GetFileExInfoStandard, &f2d))
- {
+ }
+ if (!GetFileAttributesExW(
+ SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
+ GetFileExInfoStandard, &f2d)) {
return false;
- }
+ }
// Compare the file times using resolution provided by system call.
*result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
@@ -1610,22 +1411,19 @@ bool SystemTools::FileTimeCompare(const std::string& f1,
return true;
}
-
// Return a capitalized string (i.e the first letter is uppercased, all other
// are lowercased)
std::string SystemTools::Capitalized(const std::string& s)
{
std::string n;
- if(s.empty())
- {
+ if (s.empty()) {
return n;
- }
+ }
n.resize(s.size());
n[0] = static_cast<std::string::value_type>(toupper(s[0]));
- for (size_t i = 1; i < s.size(); i++)
- {
+ for (size_t i = 1; i < s.size(); i++) {
n[i] = static_cast<std::string::value_type>(tolower(s[i]));
- }
+ }
return n;
}
@@ -1633,9 +1431,8 @@ std::string SystemTools::Capitalized(const std::string& s)
std::string SystemTools::CapitalizedWords(const std::string& s)
{
std::string n(s);
- for (size_t i = 0; i < s.size(); i++)
- {
-#if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
+ for (size_t i = 0; i < s.size(); i++) {
+#if defined(_MSC_VER) && defined(_MT) && defined(_DEBUG)
// MS has an assert that will fail if s[i] < 0; setting
// LC_CTYPE using setlocale() does *not* help. Painful.
if ((int)s[i] >= 0 && isalpha(s[i]) &&
@@ -1643,10 +1440,10 @@ std::string SystemTools::CapitalizedWords(const std::string& s)
#else
if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
#endif
- {
+ {
n[i] = static_cast<std::string::value_type>(toupper(s[i]));
- }
}
+ }
return n;
}
@@ -1654,9 +1451,8 @@ std::string SystemTools::CapitalizedWords(const std::string& s)
std::string SystemTools::UnCapitalizedWords(const std::string& s)
{
std::string n(s);
- for (size_t i = 0; i < s.size(); i++)
- {
-#if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
+ for (size_t i = 0; i < s.size(); i++) {
+#if defined(_MSC_VER) && defined(_MT) && defined(_DEBUG)
// MS has an assert that will fail if s[i] < 0; setting
// LC_CTYPE using setlocale() does *not* help. Painful.
if ((int)s[i] >= 0 && isalpha(s[i]) &&
@@ -1664,77 +1460,66 @@ std::string SystemTools::UnCapitalizedWords(const std::string& s)
#else
if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
#endif
- {
+ {
n[i] = static_cast<std::string::value_type>(tolower(s[i]));
- }
}
+ }
return n;
}
// only works for words with at least two letters
-std::string SystemTools::AddSpaceBetweenCapitalizedWords(
- const std::string& s)
+std::string SystemTools::AddSpaceBetweenCapitalizedWords(const std::string& s)
{
std::string n;
- if (!s.empty())
- {
+ if (!s.empty()) {
n.reserve(s.size());
n += s[0];
- for (size_t i = 1; i < s.size(); i++)
- {
- if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
- {
+ for (size_t i = 1; i < s.size(); i++) {
+ if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1])) {
n += ' ';
- }
- n += s[i];
}
+ n += s[i];
}
+ }
return n;
}
char* SystemTools::AppendStrings(const char* str1, const char* str2)
{
- if (!str1)
- {
+ if (!str1) {
return SystemTools::DuplicateString(str2);
- }
- if (!str2)
- {
+ }
+ if (!str2) {
return SystemTools::DuplicateString(str1);
- }
+ }
size_t len1 = strlen(str1);
- char *newstr = new char[len1 + strlen(str2) + 1];
- if (!newstr)
- {
+ char* newstr = new char[len1 + strlen(str2) + 1];
+ if (!newstr) {
return 0;
- }
+ }
strcpy(newstr, str1);
strcat(newstr + len1, str2);
return newstr;
}
-char* SystemTools::AppendStrings(
- const char* str1, const char* str2, const char* str3)
+char* SystemTools::AppendStrings(const char* str1, const char* str2,
+ const char* str3)
{
- if (!str1)
- {
+ if (!str1) {
return SystemTools::AppendStrings(str2, str3);
- }
- if (!str2)
- {
+ }
+ if (!str2) {
return SystemTools::AppendStrings(str1, str3);
- }
- if (!str3)
- {
+ }
+ if (!str3) {
return SystemTools::AppendStrings(str1, str2);
- }
+ }
size_t len1 = strlen(str1), len2 = strlen(str2);
- char *newstr = new char[len1 + len2 + strlen(str3) + 1];
- if (!newstr)
- {
+ char* newstr = new char[len1 + len2 + strlen(str3) + 1];
+ if (!newstr) {
return 0;
- }
+ }
strcpy(newstr, str1);
strcat(newstr + len1, str2);
strcat(newstr + len1 + len2, str3);
@@ -1746,10 +1531,9 @@ std::string SystemTools::LowerCase(const std::string& s)
{
std::string n;
n.resize(s.size());
- for (size_t i = 0; i < s.size(); i++)
- {
+ for (size_t i = 0; i < s.size(); i++) {
n[i] = static_cast<std::string::value_type>(tolower(s[i]));
- }
+ }
return n;
}
@@ -1758,10 +1542,9 @@ std::string SystemTools::UpperCase(const std::string& s)
{
std::string n;
n.resize(s.size());
- for (size_t i = 0; i < s.size(); i++)
- {
+ for (size_t i = 0; i < s.size(); i++) {
n[i] = static_cast<std::string::value_type>(toupper(s[i]));
- }
+ }
return n;
}
@@ -1770,42 +1553,35 @@ size_t SystemTools::CountChar(const char* str, char c)
{
size_t count = 0;
- if (str)
- {
- while (*str)
- {
- if (*str == c)
- {
+ if (str) {
+ while (*str) {
+ if (*str == c) {
++count;
- }
- ++str;
}
+ ++str;
}
+ }
return count;
}
// Remove chars in string
-char* SystemTools::RemoveChars(const char* str, const char *toremove)
+char* SystemTools::RemoveChars(const char* str, const char* toremove)
{
- if (!str)
- {
+ if (!str) {
return NULL;
- }
- char *clean_str = new char [strlen(str) + 1];
- char *ptr = clean_str;
- while (*str)
- {
- const char *str2 = toremove;
- while (*str2 && *str != *str2)
- {
+ }
+ char* clean_str = new char[strlen(str) + 1];
+ char* ptr = clean_str;
+ while (*str) {
+ const char* str2 = toremove;
+ while (*str2 && *str != *str2) {
++str2;
- }
- if (!*str2)
- {
+ }
+ if (!*str2) {
*ptr++ = *str;
- }
- ++str;
}
+ ++str;
+ }
*ptr = '\0';
return clean_str;
}
@@ -1813,54 +1589,47 @@ char* SystemTools::RemoveChars(const char* str, const char *toremove)
// Remove chars in string
char* SystemTools::RemoveCharsButUpperHex(const char* str)
{
- if (!str)
- {
+ if (!str) {
return 0;
- }
- char *clean_str = new char [strlen(str) + 1];
- char *ptr = clean_str;
- while (*str)
- {
- if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
- {
+ }
+ char* clean_str = new char[strlen(str) + 1];
+ char* ptr = clean_str;
+ while (*str) {
+ if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F')) {
*ptr++ = *str;
- }
- ++str;
}
+ ++str;
+ }
*ptr = '\0';
return clean_str;
}
// Replace chars in string
-char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
-{
- if (str)
- {
- char *ptr = str;
- while (*ptr)
- {
- const char *ptr2 = toreplace;
- while (*ptr2)
- {
- if (*ptr == *ptr2)
- {
+char* SystemTools::ReplaceChars(char* str, const char* toreplace,
+ char replacement)
+{
+ if (str) {
+ char* ptr = str;
+ while (*ptr) {
+ const char* ptr2 = toreplace;
+ while (*ptr2) {
+ if (*ptr == *ptr2) {
*ptr = replacement;
- }
- ++ptr2;
}
- ++ptr;
+ ++ptr2;
}
+ ++ptr;
}
+ }
return str;
}
// Returns if string starts with another string
bool SystemTools::StringStartsWith(const char* str1, const char* str2)
{
- if (!str1 || !str2)
- {
+ if (!str1 || !str2) {
return false;
- }
+ }
size_t len1 = strlen(str1), len2 = strlen(str2);
return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
}
@@ -1868,10 +1637,9 @@ bool SystemTools::StringStartsWith(const char* str1, const char* str2)
// Returns if string starts with another string
bool SystemTools::StringStartsWith(const std::string& str1, const char* str2)
{
- if (!str2)
- {
+ if (!str2) {
return false;
- }
+ }
size_t len1 = str1.size(), len2 = strlen(str2);
return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false;
}
@@ -1879,45 +1647,42 @@ bool SystemTools::StringStartsWith(const std::string& str1, const char* str2)
// Returns if string ends with another string
bool SystemTools::StringEndsWith(const char* str1, const char* str2)
{
- if (!str1 || !str2)
- {
+ if (!str1 || !str2) {
return false;
- }
+ }
size_t len1 = strlen(str1), len2 = strlen(str2);
- return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
+ return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true
+ : false;
}
// Returns if string ends with another string
bool SystemTools::StringEndsWith(const std::string& str1, const char* str2)
{
- if (!str2)
- {
+ if (!str2) {
return false;
- }
+ }
size_t len1 = str1.size(), len2 = strlen(str2);
- return len1 >= len2 && !strncmp(str1.c_str() + (len1 - len2), str2, len2) ? true : false;
+ return len1 >= len2 && !strncmp(str1.c_str() + (len1 - len2), str2, len2)
+ ? true
+ : false;
}
// Returns a pointer to the last occurence of str2 in str1
const char* SystemTools::FindLastString(const char* str1, const char* str2)
{
- if (!str1 || !str2)
- {
+ if (!str1 || !str2) {
return NULL;
- }
+ }
size_t len1 = strlen(str1), len2 = strlen(str2);
- if (len1 >= len2)
- {
- const char *ptr = str1 + len1 - len2;
- do
- {
- if (!strncmp(ptr, str2, len2))
- {
+ if (len1 >= len2) {
+ const char* ptr = str1 + len1 - len2;
+ do {
+ if (!strncmp(ptr, str2, len2)) {
return ptr;
- }
- } while (ptr-- != str1);
- }
+ }
+ } while (ptr-- != str1);
+ }
return NULL;
}
@@ -1925,22 +1690,19 @@ const char* SystemTools::FindLastString(const char* str1, const char* str2)
// Duplicate string
char* SystemTools::DuplicateString(const char* str)
{
- if (str)
- {
- char *newstr = new char [strlen(str) + 1];
+ if (str) {
+ char* newstr = new char[strlen(str) + 1];
return strcpy(newstr, str);
- }
+ }
return NULL;
}
// Return a cropped string
-std::string SystemTools::CropString(const std::string& s,
- size_t max_len)
+std::string SystemTools::CropString(const std::string& s, size_t max_len)
{
- if (!s.size() || max_len == 0 || max_len >= s.size())
- {
+ if (!s.size() || max_len == 0 || max_len >= s.size()) {
return s;
- }
+ }
std::string n;
n.reserve(max_len);
@@ -1950,56 +1712,50 @@ std::string SystemTools::CropString(const std::string& s,
n += s.substr(0, middle);
n += s.substr(s.size() - (max_len - middle), std::string::npos);
- if (max_len > 2)
- {
+ if (max_len > 2) {
n[middle] = '.';
- if (max_len > 3)
- {
+ if (max_len > 3) {
n[middle - 1] = '.';
- if (max_len > 4)
- {
+ if (max_len > 4) {
n[middle + 1] = '.';
- }
}
}
+ }
return n;
}
//----------------------------------------------------------------------------
-std::vector<kwsys::String> SystemTools::SplitString(const std::string& p, char sep, bool isPath)
+std::vector<kwsys::String> SystemTools::SplitString(const std::string& p,
+ char sep, bool isPath)
{
std::string path = p;
std::vector<kwsys::String> paths;
- if(path.empty())
- {
+ if (path.empty()) {
return paths;
- }
- if(isPath && path[0] == '/')
- {
+ }
+ if (isPath && path[0] == '/') {
path.erase(path.begin());
paths.push_back("/");
- }
+ }
std::string::size_type pos1 = 0;
- std::string::size_type pos2 = path.find(sep, pos1+1);
- while(pos2 != std::string::npos)
- {
- paths.push_back(path.substr(pos1, pos2-pos1));
- pos1 = pos2+1;
- pos2 = path.find(sep, pos1+1);
- }
- paths.push_back(path.substr(pos1, pos2-pos1));
+ std::string::size_type pos2 = path.find(sep, pos1 + 1);
+ while (pos2 != std::string::npos) {
+ paths.push_back(path.substr(pos1, pos2 - pos1));
+ pos1 = pos2 + 1;
+ pos2 = path.find(sep, pos1 + 1);
+ }
+ paths.push_back(path.substr(pos1, pos2 - pos1));
return paths;
}
//----------------------------------------------------------------------------
-int SystemTools::EstimateFormatLength(const char *format, va_list ap)
+int SystemTools::EstimateFormatLength(const char* format, va_list ap)
{
- if (!format)
- {
+ if (!format) {
return 0;
- }
+ }
// Quick-hack attempt at estimating the length of the string.
// Should never under-estimate.
@@ -2011,89 +1767,72 @@ int SystemTools::EstimateFormatLength(const char *format, va_list ap)
// Increase the length for every argument in the format.
const char* cur = format;
- while(*cur)
- {
- if(*cur++ == '%')
- {
+ while (*cur) {
+ if (*cur++ == '%') {
// Skip "%%" since it doesn't correspond to a va_arg.
- if(*cur != '%')
- {
- while(!int(isalpha(*cur)))
- {
+ if (*cur != '%') {
+ while (!int(isalpha(*cur))) {
++cur;
- }
- switch (*cur)
- {
- case 's':
- {
- // Check the length of the string.
- char* s = va_arg(ap, char*);
- if(s)
- {
- length += strlen(s);
+ }
+ switch (*cur) {
+ case 's': {
+ // Check the length of the string.
+ char* s = va_arg(ap, char*);
+ if (s) {
+ length += strlen(s);
}
} break;
case 'e':
case 'f':
- case 'g':
- {
- // Assume the argument contributes no more than 64 characters.
- length += 64;
+ case 'g': {
+ // Assume the argument contributes no more than 64 characters.
+ length += 64;
- // Eat the argument.
- static_cast<void>(va_arg(ap, double));
+ // Eat the argument.
+ static_cast<void>(va_arg(ap, double));
} break;
- default:
- {
- // Assume the argument contributes no more than 64 characters.
- length += 64;
+ default: {
+ // Assume the argument contributes no more than 64 characters.
+ length += 64;
- // Eat the argument.
- static_cast<void>(va_arg(ap, int));
+ // Eat the argument.
+ static_cast<void>(va_arg(ap, int));
} break;
- }
}
+ }
// Move past the characters just tested.
++cur;
- }
}
+ }
return static_cast<int>(length);
}
-std::string SystemTools::EscapeChars(
- const char *str,
- const char *chars_to_escape,
- char escape_char)
+std::string SystemTools::EscapeChars(const char* str,
+ const char* chars_to_escape,
+ char escape_char)
{
std::string n;
- if (str)
- {
- if (!chars_to_escape || !*chars_to_escape)
- {
+ if (str) {
+ if (!chars_to_escape || !*chars_to_escape) {
n.append(str);
- }
- else
- {
+ } else {
n.reserve(strlen(str));
- while (*str)
- {
- const char *ptr = chars_to_escape;
- while (*ptr)
- {
- if (*str == *ptr)
- {
+ while (*str) {
+ const char* ptr = chars_to_escape;
+ while (*ptr) {
+ if (*str == *ptr) {
n += escape_char;
break;
- }
- ++ptr;
}
+ ++ptr;
+ }
n += *str;
++str;
- }
}
}
+ }
return n;
}
@@ -2102,22 +1841,19 @@ static void ConvertVMSToUnix(std::string& path)
{
std::string::size_type rootEnd = path.find(":[");
std::string::size_type pathEnd = path.find("]");
- if(rootEnd != path.npos)
- {
+ if (rootEnd != path.npos) {
std::string root = path.substr(0, rootEnd);
- std::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
+ std::string pathPart = path.substr(rootEnd + 2, pathEnd - rootEnd - 2);
const char* pathCString = pathPart.c_str();
const char* pos0 = pathCString;
- for (std::string::size_type pos = 0; *pos0; ++ pos )
- {
- if ( *pos0 == '.' )
- {
+ for (std::string::size_type pos = 0; *pos0; ++pos) {
+ if (*pos0 == '.') {
pathPart[pos] = '/';
- }
- pos0 ++;
}
- path = "/"+ root + "/" + pathPart;
+ pos0++;
}
+ path = "/" + root + "/" + pathPart;
+ }
}
#endif
@@ -2130,83 +1866,72 @@ void SystemTools::ConvertToUnixSlashes(std::string& path)
ConvertVMSToUnix(path);
#else
const char* pos0 = pathCString;
- const char* pos1 = pathCString+1;
- for (std::string::size_type pos = 0; *pos0; ++ pos )
- {
+ const char* pos1 = pathCString + 1;
+ for (std::string::size_type pos = 0; *pos0; ++pos) {
// make sure we don't convert an escaped space to a unix slash
- if ( *pos0 == '\\' && *pos1 != ' ' )
- {
+ if (*pos0 == '\\' && *pos1 != ' ') {
path[pos] = '/';
- }
+ }
// Also, reuse the loop to check for slash followed by another slash
- if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
- {
+ if (*pos1 == '/' && *(pos1 + 1) == '/' && !hasDoubleSlash) {
#ifdef _WIN32
// However, on windows if the first characters are both slashes,
// then keep them that way, so that network paths can be handled.
- if ( pos > 0)
- {
+ if (pos > 0) {
hasDoubleSlash = true;
- }
+ }
#else
hasDoubleSlash = true;
#endif
- }
-
- pos0 ++;
- pos1 ++;
}
- if ( hasDoubleSlash )
- {
+ pos0++;
+ pos1++;
+ }
+
+ if (hasDoubleSlash) {
SystemTools::ReplaceString(path, "//", "/");
- }
+ }
#endif
// remove any trailing slash
- if(!path.empty())
- {
+ if (!path.empty()) {
// if there is a tilda ~ then replace it with HOME
pathCString = path.c_str();
- if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
- {
+ if (pathCString[0] == '~' &&
+ (pathCString[1] == '/' || pathCString[1] == '\0')) {
std::string homeEnv;
- if (SystemTools::GetEnv("HOME", homeEnv))
- {
- path.replace(0,1,homeEnv);
- }
+ if (SystemTools::GetEnv("HOME", homeEnv)) {
+ path.replace(0, 1, homeEnv);
}
+ }
#ifdef HAVE_GETPWNAM
- else if(pathCString[0] == '~')
- {
+ else if (pathCString[0] == '~') {
std::string::size_type idx = path.find_first_of("/\0");
- std::string user = path.substr(1, idx-1);
+ std::string user = path.substr(1, idx - 1);
passwd* pw = getpwnam(user.c_str());
- if(pw)
- {
+ if (pw) {
path.replace(0, idx, pw->pw_dir);
- }
}
+ }
#endif
// remove trailing slash if the path is more than
// a single /
pathCString = path.c_str();
size_t size = path.size();
- if(size > 1 && *path.rbegin() == '/')
- {
+ if (size > 1 && *path.rbegin() == '/') {
// if it is c:/ then do not remove the trailing slash
- if(!((size == 3 && pathCString[1] == ':')))
- {
+ if (!((size == 3 && pathCString[1] == ':'))) {
path.resize(size - 1);
- }
}
}
+ }
}
#ifdef _WIN32
// Convert local paths to UNC style paths
-std::wstring
-SystemTools::ConvertToWindowsExtendedPath(const std::string &source)
+std::wstring SystemTools::ConvertToWindowsExtendedPath(
+ const std::string& source)
{
std::wstring wsource = Encoding::ToWide(source);
@@ -2223,44 +1948,36 @@ SystemTools::ConvertToWindowsExtendedPath(const std::string &source)
* previous size workaround. */
wfull_len = static_cast<DWORD>(wcslen(&wfull[0]));
- if(wfull_len >= 2 && isalpha(wfull[0]) && wfull[1] == L':')
- { /* C:\Foo\bar\FooBar.txt */
+ if (wfull_len >= 2 && isalpha(wfull[0]) &&
+ wfull[1] == L':') { /* C:\Foo\bar\FooBar.txt */
return L"\\\\?\\" + std::wstring(&wfull[0]);
- }
- else if(wfull_len >= 2 && wfull[0] == L'\\' && wfull[1] == L'\\')
- { /* Starts with \\ */
- if(wfull_len >= 4 && wfull[2] == L'?' && wfull[3] == L'\\')
- { /* Starts with \\?\ */
- if(wfull_len >= 8 && wfull[4] == L'U' && wfull[5] == L'N' &&
- wfull[6] == L'C' && wfull[7] == L'\\')
- { /* \\?\UNC\Foo\bar\FooBar.txt */
+ } else if (wfull_len >= 2 && wfull[0] == L'\\' &&
+ wfull[1] == L'\\') { /* Starts with \\ */
+ if (wfull_len >= 4 && wfull[2] == L'?' &&
+ wfull[3] == L'\\') { /* Starts with \\?\ */
+ if (wfull_len >= 8 && wfull[4] == L'U' && wfull[5] == L'N' &&
+ wfull[6] == L'C' &&
+ wfull[7] == L'\\') { /* \\?\UNC\Foo\bar\FooBar.txt */
return std::wstring(&wfull[0]);
- }
- else if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
- { /* \\?\C:\Foo\bar\FooBar.txt */
+ } else if (wfull_len >= 6 && isalpha(wfull[4]) &&
+ wfull[5] == L':') { /* \\?\C:\Foo\bar\FooBar.txt */
return std::wstring(&wfull[0]);
- }
- else if(wfull_len >= 5)
- { /* \\?\Foo\bar\FooBar.txt */
+ } else if (wfull_len >= 5) { /* \\?\Foo\bar\FooBar.txt */
return L"\\\\?\\UNC\\" + std::wstring(&wfull[4]);
- }
}
- else if(wfull_len >= 4 && wfull[2] == L'.' && wfull[3] == L'\\')
- { /* Starts with \\.\ a device name */
- if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
- { /* \\.\C:\Foo\bar\FooBar.txt */
+ } else if (wfull_len >= 4 && wfull[2] == L'.' &&
+ wfull[3] == L'\\') { /* Starts with \\.\ a device name */
+ if (wfull_len >= 6 && isalpha(wfull[4]) &&
+ wfull[5] == L':') { /* \\.\C:\Foo\bar\FooBar.txt */
return L"\\\\?\\" + std::wstring(&wfull[4]);
- }
- else if(wfull_len >= 5)
- { /* \\.\Foo\bar\ Device name is left unchanged */
+ } else if (wfull_len >=
+ 5) { /* \\.\Foo\bar\ Device name is left unchanged */
return std::wstring(&wfull[0]);
- }
}
- else if(wfull_len >= 3)
- { /* \\Foo\bar\FooBar.txt */
+ } else if (wfull_len >= 3) { /* \\Foo\bar\FooBar.txt */
return L"\\\\?\\UNC\\" + std::wstring(&wfull[2]);
- }
}
+ }
// If this case has been reached, then the path is invalid. Leave it
// unchanged
@@ -2274,28 +1991,24 @@ std::string SystemTools::ConvertToUnixOutputPath(const std::string& path)
std::string ret = path;
// remove // except at the beginning might be a cygwin drive
- std::string::size_type pos=1;
- while((pos = ret.find("//", pos)) != std::string::npos)
- {
+ std::string::size_type pos = 1;
+ while ((pos = ret.find("//", pos)) != std::string::npos) {
ret.erase(pos, 1);
- }
+ }
// escape spaces and () in the path
- if(ret.find_first_of(" ") != std::string::npos)
- {
+ if (ret.find_first_of(" ") != std::string::npos) {
std::string result = "";
char lastch = 1;
- for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
- {
- // if it is already escaped then don't try to escape it again
- if((*ch == ' ') && lastch != '\\')
- {
+ for (const char* ch = ret.c_str(); *ch != '\0'; ++ch) {
+ // if it is already escaped then don't try to escape it again
+ if ((*ch == ' ') && lastch != '\\') {
result += '\\';
- }
+ }
result += *ch;
lastch = *ch;
- }
- ret = result;
}
+ ret = result;
+ }
return ret;
}
@@ -2313,46 +2026,39 @@ std::string SystemTools::ConvertToWindowsOutputPath(const std::string& path)
{
std::string ret;
// make it big enough for all of path and double quotes
- ret.reserve(path.size()+3);
+ ret.reserve(path.size() + 3);
// put path into the string
ret = path;
std::string::size_type pos = 0;
// first convert all of the slashes
- while((pos = ret.find('/', pos)) != std::string::npos)
- {
+ while ((pos = ret.find('/', pos)) != std::string::npos) {
ret[pos] = '\\';
pos++;
- }
+ }
// check for really small paths
- if(ret.size() < 2)
- {
+ if (ret.size() < 2) {
return ret;
- }
+ }
// now clean up a bit and remove double slashes
// Only if it is not the first position in the path which is a network
// path on windows
pos = 1; // start at position 1
- if(ret[0] == '\"')
- {
- pos = 2; // if the string is already quoted then start at 2
- if(ret.size() < 3)
- {
+ if (ret[0] == '\"') {
+ pos = 2; // if the string is already quoted then start at 2
+ if (ret.size() < 3) {
return ret;
- }
}
- while((pos = ret.find("\\\\", pos)) != std::string::npos)
- {
+ }
+ while ((pos = ret.find("\\\\", pos)) != std::string::npos) {
ret.erase(pos, 1);
- }
+ }
// now double quote the path if it has spaces in it
// and is not already double quoted
- if(ret.find(' ') != std::string::npos
- && ret[0] != '\"')
- {
+ if (ret.find(' ') != std::string::npos && ret[0] != '\"') {
ret.insert(static_cast<std::string::size_type>(0),
static_cast<std::string::size_type>(1), '\"');
ret.append(1, '\"');
- }
+ }
return ret;
}
@@ -2361,30 +2067,25 @@ bool SystemTools::CopyFileIfDifferent(const std::string& source,
{
// special check for a destination that is a directory
// FilesDiffer does not handle file to directory compare
- if(SystemTools::FileIsDirectory(destination))
- {
+ if (SystemTools::FileIsDirectory(destination)) {
std::string new_destination = destination;
SystemTools::ConvertToUnixSlashes(new_destination);
new_destination += '/';
std::string source_name = source;
new_destination += SystemTools::GetFilenameName(source_name);
- if(SystemTools::FilesDiffer(source, new_destination))
- {
+ if (SystemTools::FilesDiffer(source, new_destination)) {
return SystemTools::CopyFileAlways(source, destination);
- }
- else
- {
+ } else {
// the files are the same so the copy is done return
// true
return true;
- }
}
+ }
// source and destination are files so do a copy if they
// are different
- if(SystemTools::FilesDiffer(source, destination))
- {
+ if (SystemTools::FilesDiffer(source, destination)) {
return SystemTools::CopyFileAlways(source, destination);
- }
+ }
// at this point the files must be the same so return true
return true;
}
@@ -2399,131 +2100,112 @@ bool SystemTools::FilesDiffer(const std::string& source,
WIN32_FILE_ATTRIBUTE_DATA statSource;
if (GetFileAttributesExW(
SystemTools::ConvertToWindowsExtendedPath(source).c_str(),
- GetFileExInfoStandard,
- &statSource) == 0)
- {
+ GetFileExInfoStandard, &statSource) == 0) {
return true;
- }
+ }
WIN32_FILE_ATTRIBUTE_DATA statDestination;
if (GetFileAttributesExW(
SystemTools::ConvertToWindowsExtendedPath(destination).c_str(),
- GetFileExInfoStandard,
- &statDestination) == 0)
- {
+ GetFileExInfoStandard, &statDestination) == 0) {
return true;
- }
+ }
- if(statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
- statSource.nFileSizeLow != statDestination.nFileSizeLow)
- {
+ if (statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
+ statSource.nFileSizeLow != statDestination.nFileSizeLow) {
return true;
- }
+ }
- if(statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0)
- {
+ if (statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0) {
return false;
- }
- off_t nleft = ((__int64)statSource.nFileSizeHigh << 32) +
- statSource.nFileSizeLow;
+ }
+ off_t nleft =
+ ((__int64)statSource.nFileSizeHigh << 32) + statSource.nFileSizeLow;
#else
struct stat statSource;
- if (stat(source.c_str(), &statSource) != 0)
- {
+ if (stat(source.c_str(), &statSource) != 0) {
return true;
- }
+ }
struct stat statDestination;
- if (stat(destination.c_str(), &statDestination) != 0)
- {
+ if (stat(destination.c_str(), &statDestination) != 0) {
return true;
- }
+ }
- if(statSource.st_size != statDestination.st_size)
- {
+ if (statSource.st_size != statDestination.st_size) {
return true;
- }
+ }
- if(statSource.st_size == 0)
- {
+ if (statSource.st_size == 0) {
return false;
- }
+ }
off_t nleft = statSource.st_size;
#endif
#if defined(_WIN32)
- kwsys::ifstream finSource(source.c_str(),
- (std::ios::binary |
- std::ios::in));
+ kwsys::ifstream finSource(source.c_str(), (std::ios::binary | std::ios::in));
kwsys::ifstream finDestination(destination.c_str(),
- (std::ios::binary |
- std::ios::in));
+ (std::ios::binary | std::ios::in));
#else
kwsys::ifstream finSource(source.c_str());
kwsys::ifstream finDestination(destination.c_str());
#endif
- if(!finSource || !finDestination)
- {
+ if (!finSource || !finDestination) {
return true;
- }
+ }
// Compare the files a block at a time.
char source_buf[KWSYS_ST_BUFFER];
char dest_buf[KWSYS_ST_BUFFER];
- while(nleft > 0)
- {
+ while (nleft > 0) {
// Read a block from each file.
- std::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<std::streamsize>(nleft);
+ std::streamsize nnext = (nleft > KWSYS_ST_BUFFER)
+ ? KWSYS_ST_BUFFER
+ : static_cast<std::streamsize>(nleft);
finSource.read(source_buf, nnext);
finDestination.read(dest_buf, nnext);
// If either failed to read assume they are different.
- if(static_cast<std::streamsize>(finSource.gcount()) != nnext ||
- static_cast<std::streamsize>(finDestination.gcount()) != nnext)
- {
+ if (static_cast<std::streamsize>(finSource.gcount()) != nnext ||
+ static_cast<std::streamsize>(finDestination.gcount()) != nnext) {
return true;
- }
+ }
// If this block differs the file differs.
- if(memcmp(static_cast<const void*>(source_buf),
- static_cast<const void*>(dest_buf),
- static_cast<size_t>(nnext)) != 0)
- {
+ if (memcmp(static_cast<const void*>(source_buf),
+ static_cast<const void*>(dest_buf),
+ static_cast<size_t>(nnext)) != 0) {
return true;
- }
+ }
// Update the byte count remaining.
nleft -= nnext;
- }
+ }
// No differences found.
return false;
}
-
//----------------------------------------------------------------------------
/**
* Copy a file named by "source" to the file named by "destination".
*/
-bool SystemTools::CopyFileAlways(const std::string& source, const std::string& destination)
+bool SystemTools::CopyFileAlways(const std::string& source,
+ const std::string& destination)
{
// If files are the same do not copy
- if ( SystemTools::SameFile(source, destination) )
- {
+ if (SystemTools::SameFile(source, destination)) {
return true;
- }
+ }
mode_t perm = 0;
bool perms = SystemTools::GetPermissions(source, perm);
std::string real_destination = destination;
- if(SystemTools::FileIsDirectory(source))
- {
+ if (SystemTools::FileIsDirectory(source)) {
SystemTools::MakeDirectory(destination);
- }
- else
- {
+ } else {
const int bufferSize = 4096;
char buffer[bufferSize];
@@ -2531,36 +2213,32 @@ bool SystemTools::CopyFileAlways(const std::string& source, const std::string& d
// name as the source in that directory.
std::string destination_dir;
- if(SystemTools::FileIsDirectory(destination))
- {
+ if (SystemTools::FileIsDirectory(destination)) {
destination_dir = real_destination;
SystemTools::ConvertToUnixSlashes(real_destination);
real_destination += '/';
std::string source_name = source;
real_destination += SystemTools::GetFilenameName(source_name);
- }
- else
- {
+ } else {
destination_dir = SystemTools::GetFilenamePath(destination);
- }
+ }
// Create destination directory
SystemTools::MakeDirectory(destination_dir);
- // Open files
+// Open files
#if defined(_WIN32)
- kwsys::ifstream fin(Encoding::ToNarrow(
- SystemTools::ConvertToWindowsExtendedPath(source)).c_str(),
- std::ios::in | std::ios::binary);
+ kwsys::ifstream fin(
+ Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(source))
+ .c_str(),
+ std::ios::in | std::ios::binary);
#else
- kwsys::ifstream fin(source.c_str(),
- std::ios::in | std::ios::binary);
+ kwsys::ifstream fin(source.c_str(), std::ios::in | std::ios::binary);
#endif
- if(!fin)
- {
+ if (!fin) {
return false;
- }
+ }
// try and remove the destination file so that read only destination files
// can be written to.
@@ -2569,35 +2247,32 @@ bool SystemTools::CopyFileAlways(const std::string& source, const std::string& d
SystemTools::RemoveFile(real_destination);
#if defined(_WIN32)
- kwsys::ofstream fout(Encoding::ToNarrow(
- SystemTools::ConvertToWindowsExtendedPath(real_destination)).c_str(),
- std::ios::out | std::ios::trunc | std::ios::binary);
+ kwsys::ofstream fout(
+ Encoding::ToNarrow(
+ SystemTools::ConvertToWindowsExtendedPath(real_destination))
+ .c_str(),
+ std::ios::out | std::ios::trunc | std::ios::binary);
#else
kwsys::ofstream fout(real_destination.c_str(),
- std::ios::out | std::ios::trunc | std::ios::binary);
+ std::ios::out | std::ios::trunc | std::ios::binary);
#endif
- if(!fout)
- {
+ if (!fout) {
return false;
- }
+ }
// This copy loop is very sensitive on certain platforms with
// slightly broken stream libraries (like HPUX). Normally, it is
// incorrect to not check the error condition on the fin.read()
// before using the data, but the fin.gcount() will be zero if an
// error occurred. Therefore, the loop should be safe everywhere.
- while(fin)
- {
+ while (fin) {
fin.read(buffer, bufferSize);
- if(fin.gcount())
- {
+ if (fin.gcount()) {
fout.write(buffer, fin.gcount());
- }
- else
- {
+ } else {
break;
- }
}
+ }
// Make sure the operating system has finished writing the file
// before closing it. This will ensure the file is finished before
@@ -2607,88 +2282,71 @@ bool SystemTools::CopyFileAlways(const std::string& source, const std::string& d
fin.close();
fout.close();
- if(!fout)
- {
+ if (!fout) {
return false;
- }
}
- if ( perms )
- {
- if ( !SystemTools::SetPermissions(real_destination, perm) )
- {
+ }
+ if (perms) {
+ if (!SystemTools::SetPermissions(real_destination, perm)) {
return false;
- }
}
+ }
return true;
}
//----------------------------------------------------------------------------
-bool SystemTools::CopyAFile(const std::string& source, const std::string& destination,
- bool always)
+bool SystemTools::CopyAFile(const std::string& source,
+ const std::string& destination, bool always)
{
- if(always)
- {
+ if (always) {
return SystemTools::CopyFileAlways(source, destination);
- }
- else
- {
+ } else {
return SystemTools::CopyFileIfDifferent(source, destination);
- }
+ }
}
/**
* Copy a directory content from "source" directory to the directory named by
* "destination".
*/
-bool SystemTools::CopyADirectory(const std::string& source, const std::string& destination,
- bool always)
+bool SystemTools::CopyADirectory(const std::string& source,
+ const std::string& destination, bool always)
{
Directory dir;
#ifdef _WIN32
- dir.Load(Encoding::ToNarrow(
- SystemTools::ConvertToWindowsExtendedPath(source)));
+ dir.Load(
+ Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(source)));
#else
dir.Load(source);
#endif
size_t fileNum;
- if ( !SystemTools::MakeDirectory(destination) )
- {
+ if (!SystemTools::MakeDirectory(destination)) {
return false;
- }
- for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
- {
- if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
- strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
- {
+ }
+ for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
+ if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
+ strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
std::string fullPath = source;
fullPath += "/";
fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
- if(SystemTools::FileIsDirectory(fullPath))
- {
+ if (SystemTools::FileIsDirectory(fullPath)) {
std::string fullDestPath = destination;
fullDestPath += "/";
fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
- if (!SystemTools::CopyADirectory(fullPath,
- fullDestPath,
- always))
- {
+ if (!SystemTools::CopyADirectory(fullPath, fullDestPath, always)) {
return false;
- }
}
- else
- {
- if(!SystemTools::CopyAFile(fullPath, destination, always))
- {
+ } else {
+ if (!SystemTools::CopyAFile(fullPath, destination, always)) {
return false;
- }
}
}
}
+ }
return true;
}
-
// return size of file; also returns zero if no file exists
unsigned long SystemTools::FileLength(const std::string& filename)
{
@@ -2697,21 +2355,19 @@ unsigned long SystemTools::FileLength(const std::string& filename)
WIN32_FILE_ATTRIBUTE_DATA fs;
if (GetFileAttributesExW(
SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
- GetFileExInfoStandard, &fs) != 0)
- {
+ GetFileExInfoStandard, &fs) != 0) {
/* To support the full 64-bit file size, use fs.nFileSizeHigh
* and fs.nFileSizeLow to construct the 64 bit size
length = ((__int64)fs.nFileSizeHigh << 32) + fs.nFileSizeLow;
*/
length = static_cast<unsigned long>(fs.nFileSizeLow);
- }
+ }
#else
struct stat fs;
- if (stat(filename.c_str(), &fs) == 0)
- {
+ if (stat(filename.c_str(), &fs) == 0) {
length = static_cast<unsigned long>(fs.st_size);
- }
+ }
#endif
return length;
}
@@ -2723,7 +2379,7 @@ int SystemTools::Strucmp(const char* l, const char* r)
do {
lc = tolower(*l++);
rc = tolower(*r++);
- } while(lc == rc && lc);
+ } while (lc == rc && lc);
return lc - rc;
}
@@ -2735,17 +2391,14 @@ long int SystemTools::ModifiedTime(const std::string& filename)
WIN32_FILE_ATTRIBUTE_DATA fs;
if (GetFileAttributesExW(
SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
- GetFileExInfoStandard,
- &fs) != 0)
- {
+ GetFileExInfoStandard, &fs) != 0) {
mt = windows_filetime_to_posix_time(fs.ftLastWriteTime);
- }
+ }
#else
struct stat fs;
- if (stat(filename.c_str(), &fs) == 0)
- {
+ if (stat(filename.c_str(), &fs) == 0) {
mt = static_cast<long int>(fs.st_mtime);
- }
+ }
#endif
return mt;
}
@@ -2758,27 +2411,23 @@ long int SystemTools::CreationTime(const std::string& filename)
WIN32_FILE_ATTRIBUTE_DATA fs;
if (GetFileAttributesExW(
SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
- GetFileExInfoStandard,
- &fs) != 0)
- {
+ GetFileExInfoStandard, &fs) != 0) {
ct = windows_filetime_to_posix_time(fs.ftCreationTime);
- }
+ }
#else
struct stat fs;
- if (stat(filename.c_str(), &fs) == 0)
- {
+ if (stat(filename.c_str(), &fs) == 0) {
ct = fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
- }
+ }
#endif
return ct;
}
-bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
+bool SystemTools::ConvertDateMacroString(const char* str, time_t* tmt)
{
- if (!str || !tmt || strlen(str) > 11)
- {
+ if (!str || !tmt || strlen(str) > 11) {
return false;
- }
+ }
struct tm tmt2;
@@ -2797,36 +2446,34 @@ bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
strcpy(buffer, str);
buffer[3] = 0;
- char *ptr = strstr(month_names, buffer);
- if (!ptr)
- {
+ char* ptr = strstr(month_names, buffer);
+ if (!ptr) {
return false;
- }
+ }
int month = static_cast<int>((ptr - month_names) / 3);
int day = atoi(buffer + 4);
int year = atoi(buffer + 7);
tmt2.tm_isdst = -1;
- tmt2.tm_hour = 0;
- tmt2.tm_min = 0;
- tmt2.tm_sec = 0;
- tmt2.tm_wday = 0;
- tmt2.tm_yday = 0;
- tmt2.tm_mday = day;
- tmt2.tm_mon = month;
- tmt2.tm_year = year - 1900;
+ tmt2.tm_hour = 0;
+ tmt2.tm_min = 0;
+ tmt2.tm_sec = 0;
+ tmt2.tm_wday = 0;
+ tmt2.tm_yday = 0;
+ tmt2.tm_mday = day;
+ tmt2.tm_mon = month;
+ tmt2.tm_year = year - 1900;
*tmt = mktime(&tmt2);
return true;
}
-bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
+bool SystemTools::ConvertTimeStampMacroString(const char* str, time_t* tmt)
{
- if (!str || !tmt || strlen(str) > 26)
- {
+ if (!str || !tmt || strlen(str) > 26) {
return false;
- }
+ }
struct tm tmt2;
@@ -2848,11 +2495,10 @@ bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
strcpy(buffer, str);
buffer[7] = 0;
- char *ptr = strstr(month_names, buffer + 4);
- if (!ptr)
- {
+ char* ptr = strstr(month_names, buffer + 4);
+ if (!ptr) {
return false;
- }
+ }
int month = static_cast<int>((ptr - month_names) / 3);
int day = atoi(buffer + 8);
@@ -2862,14 +2508,14 @@ bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
int year = atoi(buffer + 20);
tmt2.tm_isdst = -1;
- tmt2.tm_hour = hour;
- tmt2.tm_min = min;
- tmt2.tm_sec = sec;
- tmt2.tm_wday = 0;
- tmt2.tm_yday = 0;
- tmt2.tm_mday = day;
- tmt2.tm_mon = month;
- tmt2.tm_year = year - 1900;
+ tmt2.tm_hour = hour;
+ tmt2.tm_min = min;
+ tmt2.tm_sec = sec;
+ tmt2.tm_wday = 0;
+ tmt2.tm_yday = 0;
+ tmt2.tm_mday = day;
+ tmt2.tm_mon = month;
+ tmt2.tm_year = year - 1900;
*tmt = mktime(&tmt2);
return true;
@@ -2886,17 +2532,15 @@ std::string SystemTools::GetLastSystemError()
static bool IsJunction(const std::wstring& source)
{
#ifdef FSCTL_GET_REPARSE_POINT
- const DWORD JUNCTION_ATTRS = FILE_ATTRIBUTE_DIRECTORY |
- FILE_ATTRIBUTE_REPARSE_POINT;
+ const DWORD JUNCTION_ATTRS =
+ FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT;
DWORD attrs = GetFileAttributesW(source.c_str());
- if (attrs == INVALID_FILE_ATTRIBUTES)
- {
+ if (attrs == INVALID_FILE_ATTRIBUTES) {
return false;
- }
- if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS)
- {
+ }
+ if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS) {
return false;
- }
+ }
// Adjust privileges so that we can succefully open junction points.
HANDLE token;
@@ -2905,32 +2549,30 @@ static bool IsJunction(const std::wstring& source)
LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &privs.Privileges[0].Luid);
privs.PrivilegeCount = 1;
privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
+ AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL,
+ NULL);
CloseHandle(token);
- HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ,
- 0, NULL, OPEN_EXISTING,
- FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
- if (dir == INVALID_HANDLE_VALUE)
- {
+ HANDLE dir = CreateFileW(
+ source.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING,
+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
+ if (dir == INVALID_HANDLE_VALUE) {
return false;
- }
+ }
// Query whether this is a reparse point or not.
BYTE buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
- REPARSE_GUID_DATA_BUFFER *reparse_buffer =
- (REPARSE_GUID_DATA_BUFFER*) buffer;
+ REPARSE_GUID_DATA_BUFFER* reparse_buffer = (REPARSE_GUID_DATA_BUFFER*)buffer;
DWORD sentinel;
- BOOL success = DeviceIoControl(
- dir, FSCTL_GET_REPARSE_POINT,
- NULL, 0,
- reparse_buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
- &sentinel, NULL);
+ BOOL success =
+ DeviceIoControl(dir, FSCTL_GET_REPARSE_POINT, NULL, 0, reparse_buffer,
+ MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &sentinel, NULL);
CloseHandle(dir);
- return (success && (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT));
+ return (success &&
+ (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT));
#else
return false;
#endif
@@ -2947,30 +2589,28 @@ static bool DeleteJunction(const std::wstring& source)
LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &privs.Privileges[0].Luid);
privs.PrivilegeCount = 1;
privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
- AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
+ AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL,
+ NULL);
CloseHandle(token);
- HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ | GENERIC_WRITE,
- 0, NULL, OPEN_EXISTING,
- FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
- if (dir == INVALID_HANDLE_VALUE)
- {
+ HANDLE dir = CreateFileW(
+ source.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
+ if (dir == INVALID_HANDLE_VALUE) {
return false;
- }
+ }
// Set up the structure so that we can delete the junction.
std::vector<BYTE> buffer(REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, 0);
- REPARSE_GUID_DATA_BUFFER *reparse_buffer =
- (REPARSE_GUID_DATA_BUFFER*) &buffer[0];
+ REPARSE_GUID_DATA_BUFFER* reparse_buffer =
+ (REPARSE_GUID_DATA_BUFFER*)&buffer[0];
DWORD sentinel;
reparse_buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
BOOL success = DeviceIoControl(
- dir, FSCTL_DELETE_REPARSE_POINT,
- reparse_buffer, REPARSE_GUID_DATA_BUFFER_HEADER_SIZE,
- NULL, 0,
- &sentinel, NULL);
+ dir, FSCTL_DELETE_REPARSE_POINT, reparse_buffer,
+ REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, NULL, 0, &sentinel, NULL);
CloseHandle(dir);
@@ -2985,40 +2625,31 @@ static bool DeleteJunction(const std::wstring& source)
bool SystemTools::RemoveFile(const std::string& source)
{
#ifdef _WIN32
- std::wstring const& ws =
- SystemTools::ConvertToWindowsExtendedPath(source);
- if (DeleteFileW(ws.c_str()))
- {
+ std::wstring const& ws = SystemTools::ConvertToWindowsExtendedPath(source);
+ if (DeleteFileW(ws.c_str())) {
return true;
- }
+ }
DWORD err = GetLastError();
- if (err == ERROR_FILE_NOT_FOUND ||
- err == ERROR_PATH_NOT_FOUND)
- {
+ if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
return true;
- }
- if (err != ERROR_ACCESS_DENIED)
- {
+ }
+ if (err != ERROR_ACCESS_DENIED) {
return false;
- }
+ }
/* The file may be read-only. Try adding write permission. */
mode_t mode;
if (!SystemTools::GetPermissions(source, mode) ||
- !SystemTools::SetPermissions(source, S_IWRITE))
- {
+ !SystemTools::SetPermissions(source, S_IWRITE)) {
SetLastError(err);
return false;
- }
- if (IsJunction(ws) && DeleteJunction(ws))
- {
+ }
+ if (IsJunction(ws) && DeleteJunction(ws)) {
return true;
- }
- if (DeleteFileW(ws.c_str()) ||
- GetLastError() == ERROR_FILE_NOT_FOUND ||
- GetLastError() == ERROR_PATH_NOT_FOUND)
- {
+ }
+ if (DeleteFileW(ws.c_str()) || GetLastError() == ERROR_FILE_NOT_FOUND ||
+ GetLastError() == ERROR_PATH_NOT_FOUND) {
return true;
- }
+ }
/* Try to restore the original permissions. */
SystemTools::SetPermissions(source, mode);
SetLastError(err);
@@ -3033,49 +2664,41 @@ bool SystemTools::RemoveADirectory(const std::string& source)
// Add write permission to the directory so we can modify its
// content to remove files and directories from it.
mode_t mode;
- if(SystemTools::GetPermissions(source, mode))
- {
+ if (SystemTools::GetPermissions(source, mode)) {
#if defined(_WIN32) && !defined(__CYGWIN__)
mode |= S_IWRITE;
#else
mode |= S_IWUSR;
#endif
SystemTools::SetPermissions(source, mode);
- }
+ }
Directory dir;
#ifdef _WIN32
- dir.Load(Encoding::ToNarrow(
- SystemTools::ConvertToWindowsExtendedPath(source)));
+ dir.Load(
+ Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(source)));
#else
dir.Load(source);
#endif
size_t fileNum;
- for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum)
- {
- if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
- strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
- {
+ for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
+ if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
+ strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
std::string fullPath = source;
fullPath += "/";
fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
- if(SystemTools::FileIsDirectory(fullPath) &&
- !SystemTools::FileIsSymlink(fullPath))
- {
- if (!SystemTools::RemoveADirectory(fullPath))
- {
+ if (SystemTools::FileIsDirectory(fullPath) &&
+ !SystemTools::FileIsSymlink(fullPath)) {
+ if (!SystemTools::RemoveADirectory(fullPath)) {
return false;
- }
}
- else
- {
- if(!SystemTools::RemoveFile(fullPath))
- {
+ } else {
+ if (!SystemTools::RemoveFile(fullPath)) {
return false;
- }
}
}
}
+ }
return (Rmdir(source) == 0);
}
@@ -3092,50 +2715,43 @@ size_t SystemTools::GetMaximumFilePathLength()
* the system search path. Returns the full path to the file if it is
* found. Otherwise, the empty string is returned.
*/
-std::string SystemTools
-::FindName(const std::string& name,
- const std::vector<std::string>& userPaths,
- bool no_system_path)
+std::string SystemTools::FindName(const std::string& name,
+ const std::vector<std::string>& userPaths,
+ bool no_system_path)
{
// Add the system search path to our path first
std::vector<std::string> path;
- if (!no_system_path)
- {
+ if (!no_system_path) {
SystemTools::GetPath(path, "CMAKE_FILE_PATH");
SystemTools::GetPath(path);
- }
+ }
// now add the additional paths
{
- for(std::vector<std::string>::const_iterator i = userPaths.begin();
- i != userPaths.end(); ++i)
- {
- path.push_back(*i);
+ for (std::vector<std::string>::const_iterator i = userPaths.begin();
+ i != userPaths.end(); ++i) {
+ path.push_back(*i);
}
}
// Add a trailing slash to all paths to aid the search process.
{
- for(std::vector<std::string>::iterator i = path.begin();
- i != path.end(); ++i)
- {
- std::string& p = *i;
- if(p.empty() || *p.rbegin() != '/')
- {
- p += "/";
+ for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
+ ++i) {
+ std::string& p = *i;
+ if (p.empty() || *p.rbegin() != '/') {
+ p += "/";
}
}
}
// now look for the file
std::string tryPath;
- for(std::vector<std::string>::const_iterator p = path.begin();
- p != path.end(); ++p)
- {
+ for (std::vector<std::string>::const_iterator p = path.begin();
+ p != path.end(); ++p) {
tryPath = *p;
tryPath += name;
- if(SystemTools::FileExists(tryPath))
- {
+ if (SystemTools::FileExists(tryPath)) {
return tryPath;
- }
}
+ }
// Couldn't find the file.
return "";
}
@@ -3145,16 +2761,14 @@ std::string SystemTools
* the system search path. Returns the full path to the file if it is
* found. Otherwise, the empty string is returned.
*/
-std::string SystemTools
-::FindFile(const std::string& name,
- const std::vector<std::string>& userPaths,
- bool no_system_path)
+std::string SystemTools::FindFile(const std::string& name,
+ const std::vector<std::string>& userPaths,
+ bool no_system_path)
{
std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
- if(!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath))
- {
+ if (!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
// Couldn't find the file.
return "";
}
@@ -3164,16 +2778,14 @@ std::string SystemTools
* the system search path. Returns the full path to the directory if it is
* found. Otherwise, the empty string is returned.
*/
-std::string SystemTools
-::FindDirectory(const std::string& name,
- const std::vector<std::string>& userPaths,
- bool no_system_path)
+std::string SystemTools::FindDirectory(
+ const std::string& name, const std::vector<std::string>& userPaths,
+ bool no_system_path)
{
std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
- if(!tryPath.empty() && SystemTools::FileIsDirectory(tryPath))
- {
+ if (!tryPath.empty() && SystemTools::FileIsDirectory(tryPath)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
// Couldn't find the file.
return "";
}
@@ -3183,132 +2795,113 @@ std::string SystemTools
* the system search path. Returns the full path to the executable if it is
* found. Otherwise, the empty string is returned.
*/
-std::string SystemTools::FindProgram(
- const char* nameIn,
- const std::vector<std::string>& userPaths,
- bool no_system_path)
+std::string SystemTools::FindProgram(const char* nameIn,
+ const std::vector<std::string>& userPaths,
+ bool no_system_path)
{
- if(!nameIn || !*nameIn)
- {
+ if (!nameIn || !*nameIn) {
return "";
- }
- return SystemTools::FindProgram(std::string(nameIn), userPaths, no_system_path);
+ }
+ return SystemTools::FindProgram(std::string(nameIn), userPaths,
+ no_system_path);
}
-std::string SystemTools::FindProgram(
- const std::string& name,
- const std::vector<std::string>& userPaths,
- bool no_system_path)
+std::string SystemTools::FindProgram(const std::string& name,
+ const std::vector<std::string>& userPaths,
+ bool no_system_path)
{
std::string tryPath;
-#if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
std::vector<std::string> extensions;
// check to see if the name already has a .xxx at
// the end of it
// on windows try .com then .exe
- if(name.size() <= 3 || name[name.size()-4] != '.')
- {
+ if (name.size() <= 3 || name[name.size() - 4] != '.') {
extensions.push_back(".com");
extensions.push_back(".exe");
// first try with extensions if the os supports them
- for(std::vector<std::string>::iterator i =
- extensions.begin(); i != extensions.end(); ++i)
- {
+ for (std::vector<std::string>::iterator i = extensions.begin();
+ i != extensions.end(); ++i) {
tryPath = name;
tryPath += *i;
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
}
}
+ }
#endif
// now try just the name
- if(SystemTools::FileExists(name, true))
- {
+ if (SystemTools::FileExists(name, true)) {
return SystemTools::CollapseFullPath(name);
- }
+ }
// now construct the path
std::vector<std::string> path;
// Add the system search path to our path.
- if (!no_system_path)
- {
+ if (!no_system_path) {
SystemTools::GetPath(path);
- }
+ }
// now add the additional paths
{
- for(std::vector<std::string>::const_iterator i =
- userPaths.begin(); i != userPaths.end(); ++i)
- {
- path.push_back(*i);
+ for (std::vector<std::string>::const_iterator i = userPaths.begin();
+ i != userPaths.end(); ++i) {
+ path.push_back(*i);
}
}
// Add a trailing slash to all paths to aid the search process.
{
- for(std::vector<std::string>::iterator i = path.begin();
- i != path.end(); ++i)
- {
- std::string& p = *i;
- if(p.empty() || *p.rbegin() != '/')
- {
- p += "/";
+ for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
+ ++i) {
+ std::string& p = *i;
+ if (p.empty() || *p.rbegin() != '/') {
+ p += "/";
}
}
}
// Try each path
- for(std::vector<std::string>::iterator p = path.begin();
- p != path.end(); ++p)
- {
+ for (std::vector<std::string>::iterator p = path.begin(); p != path.end();
+ ++p) {
#ifdef _WIN32
// Remove double quotes from the path on windows
SystemTools::ReplaceString(*p, "\"", "");
#endif
-#if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
// first try with extensions
- for(std::vector<std::string>::iterator ext
- = extensions.begin(); ext != extensions.end(); ++ext)
- {
+ for (std::vector<std::string>::iterator ext = extensions.begin();
+ ext != extensions.end(); ++ext) {
tryPath = *p;
tryPath += name;
tryPath += *ext;
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
}
+ }
#endif
// now try it without them
tryPath = *p;
tryPath += name;
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
}
+ }
// Couldn't find the program.
return "";
}
-std::string SystemTools::FindProgram(
- const std::vector<std::string>& names,
- const std::vector<std::string>& path,
- bool noSystemPath)
+std::string SystemTools::FindProgram(const std::vector<std::string>& names,
+ const std::vector<std::string>& path,
+ bool noSystemPath)
{
- for(std::vector<std::string>::const_iterator it = names.begin();
- it != names.end() ; ++it)
- {
+ for (std::vector<std::string>::const_iterator it = names.begin();
+ it != names.end(); ++it) {
// Try to find the program.
- std::string result = SystemTools::FindProgram(*it,
- path,
- noSystemPath);
- if ( !result.empty() )
- {
+ std::string result = SystemTools::FindProgram(*it, path, noSystemPath);
+ if (!result.empty()) {
return result;
- }
}
+ }
return "";
}
@@ -3317,110 +2910,97 @@ std::string SystemTools::FindProgram(
* the system search path. Returns the full path to the library if it is
* found. Otherwise, the empty string is returned.
*/
-std::string SystemTools
-::FindLibrary(const std::string& name,
- const std::vector<std::string>& userPaths)
+std::string SystemTools::FindLibrary(const std::string& name,
+ const std::vector<std::string>& userPaths)
{
// See if the executable exists as written.
- if(SystemTools::FileExists(name, true))
- {
+ if (SystemTools::FileExists(name, true)) {
return SystemTools::CollapseFullPath(name);
- }
+ }
// Add the system search path to our path.
std::vector<std::string> path;
SystemTools::GetPath(path);
- // now add the additional paths
+ // now add the additional paths
{
- for(std::vector<std::string>::const_iterator i = userPaths.begin();
- i != userPaths.end(); ++i)
- {
- path.push_back(*i);
+ for (std::vector<std::string>::const_iterator i = userPaths.begin();
+ i != userPaths.end(); ++i) {
+ path.push_back(*i);
}
}
// Add a trailing slash to all paths to aid the search process.
{
- for(std::vector<std::string>::iterator i = path.begin();
- i != path.end(); ++i)
- {
- std::string& p = *i;
- if(p.empty() || *p.rbegin() != '/')
- {
- p += "/";
+ for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
+ ++i) {
+ std::string& p = *i;
+ if (p.empty() || *p.rbegin() != '/') {
+ p += "/";
}
}
}
std::string tryPath;
- for(std::vector<std::string>::const_iterator p = path.begin();
- p != path.end(); ++p)
- {
+ for (std::vector<std::string>::const_iterator p = path.begin();
+ p != path.end(); ++p) {
#if defined(__APPLE__)
tryPath = *p;
tryPath += name;
tryPath += ".framework";
- if(SystemTools::FileIsDirectory(tryPath))
- {
+ if (SystemTools::FileIsDirectory(tryPath)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
#endif
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
tryPath = *p;
tryPath += name;
tryPath += ".lib";
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
#else
tryPath = *p;
tryPath += "lib";
tryPath += name;
tryPath += ".so";
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
tryPath = *p;
tryPath += "lib";
tryPath += name;
tryPath += ".a";
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
tryPath = *p;
tryPath += "lib";
tryPath += name;
tryPath += ".sl";
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
tryPath = *p;
tryPath += "lib";
tryPath += name;
tryPath += ".dylib";
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
+ }
tryPath = *p;
tryPath += "lib";
tryPath += name;
tryPath += ".dll";
- if(SystemTools::FileExists(tryPath, true))
- {
+ if (SystemTools::FileExists(tryPath, true)) {
return SystemTools::CollapseFullPath(tryPath);
- }
-#endif
}
+#endif
+ }
// Couldn't find the library.
return "";
}
std::string SystemTools::GetRealPath(const std::string& path,
- std::string* errorMessage)
+ std::string* errorMessage)
{
std::string ret;
Realpath(path, ret, errorMessage);
@@ -3429,76 +3009,61 @@ std::string SystemTools::GetRealPath(const std::string& path,
bool SystemTools::FileIsDirectory(const std::string& inName)
{
- if (inName.empty())
- {
+ if (inName.empty()) {
return false;
- }
+ }
size_t length = inName.size();
const char* name = inName.c_str();
// Remove any trailing slash from the name except in a root component.
char local_buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
std::string string_buffer;
- size_t last = length-1;
- if(last > 0 && (name[last] == '/' || name[last] == '\\')
- && strcmp(name, "/") != 0 && name[last-1] != ':')
- {
- if (last < sizeof(local_buffer))
- {
+ size_t last = length - 1;
+ if (last > 0 && (name[last] == '/' || name[last] == '\\') &&
+ strcmp(name, "/") != 0 && name[last - 1] != ':') {
+ if (last < sizeof(local_buffer)) {
memcpy(local_buffer, name, last);
local_buffer[last] = '\0';
name = local_buffer;
- }
- else
- {
+ } else {
string_buffer.append(name, last);
name = string_buffer.c_str();
- }
}
+ }
- // Now check the file node type.
-#if defined( _WIN32 )
+// Now check the file node type.
+#if defined(_WIN32)
DWORD attr = GetFileAttributesW(
SystemTools::ConvertToWindowsExtendedPath(name).c_str());
- if (attr != INVALID_FILE_ATTRIBUTES)
- {
+ if (attr != INVALID_FILE_ATTRIBUTES) {
return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
struct stat fs;
- if(stat(name, &fs) == 0)
- {
+ if (stat(name, &fs) == 0) {
return S_ISDIR(fs.st_mode);
#endif
- }
- else
- {
+ } else {
return false;
- }
+ }
}
bool SystemTools::FileIsSymlink(const std::string& name)
{
-#if defined( _WIN32 )
+#if defined(_WIN32)
DWORD attr = GetFileAttributesW(
SystemTools::ConvertToWindowsExtendedPath(name).c_str());
- if (attr != INVALID_FILE_ATTRIBUTES)
- {
+ if (attr != INVALID_FILE_ATTRIBUTES) {
return (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
- }
- else
- {
+ } else {
return false;
- }
+ }
#else
struct stat fs;
- if(lstat(name.c_str(), &fs) == 0)
- {
+ if (lstat(name.c_str(), &fs) == 0) {
return S_ISLNK(fs.st_mode);
- }
- else
- {
+ } else {
return false;
- }
+ }
#endif
}
@@ -3508,7 +3073,8 @@ bool SystemTools::CreateSymlink(const std::string&, const std::string&)
return false;
}
#else
-bool SystemTools::CreateSymlink(const std::string& origName, const std::string& newName)
+bool SystemTools::CreateSymlink(const std::string& origName,
+ const std::string& newName)
{
return symlink(origName.c_str(), newName.c_str()) >= 0;
}
@@ -3523,20 +3089,17 @@ bool SystemTools::ReadSymlink(const std::string&, std::string&)
bool SystemTools::ReadSymlink(const std::string& newName,
std::string& origName)
{
- char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1];
- int count =
- static_cast<int>(readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH));
- if(count >= 0)
- {
+ char buf[KWSYS_SYSTEMTOOLS_MAXPATH + 1];
+ int count = static_cast<int>(
+ readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH));
+ if (count >= 0) {
// Add null-terminator.
buf[count] = 0;
origName = buf;
return true;
- }
- else
- {
+ } else {
return false;
- }
+ }
}
#endif
@@ -3550,14 +3113,12 @@ std::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
char buf[2048];
const char* cwd = Getcwd(buf, 2048);
std::string path;
- if ( cwd )
- {
+ if (cwd) {
path = cwd;
- }
- if(collapse)
- {
+ }
+ if (collapse) {
return SystemTools::CollapseFullPath(path);
- }
+ }
return path;
}
@@ -3569,56 +3130,45 @@ std::string SystemTools::GetProgramPath(const std::string& in_name)
}
bool SystemTools::SplitProgramPath(const std::string& in_name,
- std::string& dir,
- std::string& file,
- bool)
+ std::string& dir, std::string& file, bool)
{
dir = in_name;
file = "";
SystemTools::ConvertToUnixSlashes(dir);
- if(!SystemTools::FileIsDirectory(dir))
- {
+ if (!SystemTools::FileIsDirectory(dir)) {
std::string::size_type slashPos = dir.rfind("/");
- if(slashPos != std::string::npos)
- {
- file = dir.substr(slashPos+1);
+ if (slashPos != std::string::npos) {
+ file = dir.substr(slashPos + 1);
dir = dir.substr(0, slashPos);
- }
- else
- {
+ } else {
file = dir;
dir = "";
- }
}
- if(!(dir.empty()) && !SystemTools::FileIsDirectory(dir))
- {
+ }
+ if (!(dir.empty()) && !SystemTools::FileIsDirectory(dir)) {
std::string oldDir = in_name;
SystemTools::ConvertToUnixSlashes(oldDir);
dir = in_name;
return false;
- }
+ }
return true;
}
-bool SystemTools::FindProgramPath(const char* argv0,
- std::string& pathOut,
- std::string& errorMsg,
- const char* exeName,
+bool SystemTools::FindProgramPath(const char* argv0, std::string& pathOut,
+ std::string& errorMsg, const char* exeName,
const char* buildDir,
- const char* installPrefix )
+ const char* installPrefix)
{
std::vector<std::string> failures;
std::string self = argv0 ? argv0 : "";
failures.push_back(self);
SystemTools::ConvertToUnixSlashes(self);
self = SystemTools::FindProgram(self);
- if(!SystemTools::FileExists(self))
- {
- if(buildDir)
- {
+ if (!SystemTools::FileExists(self)) {
+ if (buildDir) {
std::string intdir = ".";
-#ifdef CMAKE_INTDIR
+#ifdef CMAKE_INTDIR
intdir = CMAKE_INTDIR;
#endif
self = buildDir;
@@ -3627,52 +3177,46 @@ bool SystemTools::FindProgramPath(const char* argv0,
self += "/";
self += exeName;
self += SystemTools::GetExecutableExtension();
- }
}
- if(installPrefix)
- {
- if(!SystemTools::FileExists(self))
- {
+ }
+ if (installPrefix) {
+ if (!SystemTools::FileExists(self)) {
failures.push_back(self);
self = installPrefix;
self += "/bin/";
- self += exeName;
- }
+ self += exeName;
}
- if(!SystemTools::FileExists(self))
- {
+ }
+ if (!SystemTools::FileExists(self)) {
failures.push_back(self);
std::ostringstream msg;
msg << "Can not find the command line program ";
- if (exeName)
- {
+ if (exeName) {
msg << exeName;
- }
+ }
msg << "\n";
- if (argv0)
- {
+ if (argv0) {
msg << " argv[0] = \"" << argv0 << "\"\n";
- }
+ }
msg << " Attempted paths:\n";
std::vector<std::string>::iterator i;
- for(i=failures.begin(); i != failures.end(); ++i)
- {
+ for (i = failures.begin(); i != failures.end(); ++i) {
msg << " \"" << *i << "\"\n";
- }
+ }
errorMsg = msg.str();
return false;
- }
+ }
pathOut = self;
return true;
}
-
std::string SystemTools::CollapseFullPath(const std::string& in_relative)
{
return SystemTools::CollapseFullPath(in_relative, 0);
}
-void SystemTools::AddTranslationPath(const std::string& a, const std::string& b)
+void SystemTools::AddTranslationPath(const std::string& a,
+ const std::string& b)
{
std::string path_a = a;
std::string path_b = b;
@@ -3680,30 +3224,25 @@ void SystemTools::AddTranslationPath(const std::string& a, const std::string& b)
SystemTools::ConvertToUnixSlashes(path_b);
// First check this is a directory path, since we don't want the table to
// grow too fat
- if( SystemTools::FileIsDirectory( path_a ) )
- {
+ if (SystemTools::FileIsDirectory(path_a)) {
// Make sure the path is a full path and does not contain no '..'
// Ken--the following code is incorrect. .. can be in a valid path
// for example /home/martink/MyHubba...Hubba/Src
- if( SystemTools::FileIsFullPath(path_b) && path_b.find("..")
- == std::string::npos )
- {
+ if (SystemTools::FileIsFullPath(path_b) &&
+ path_b.find("..") == std::string::npos) {
// Before inserting make sure path ends with '/'
- if(!path_a.empty() && *path_a.rbegin() != '/')
- {
+ if (!path_a.empty() && *path_a.rbegin() != '/') {
path_a += '/';
- }
- if(!path_b.empty() && *path_b.rbegin() != '/')
- {
+ }
+ if (!path_b.empty() && *path_b.rbegin() != '/') {
path_b += '/';
- }
- if( !(path_a == path_b) )
- {
+ }
+ if (!(path_a == path_b)) {
SystemTools::TranslationMap->insert(
SystemToolsTranslationMap::value_type(path_a, path_b));
- }
}
}
+ }
}
void SystemTools::AddKeepPath(const std::string& dir)
@@ -3713,14 +3252,13 @@ void SystemTools::AddKeepPath(const std::string& dir)
SystemTools::AddTranslationPath(cdir, dir);
}
-void SystemTools::CheckTranslationPath(std::string & path)
+void SystemTools::CheckTranslationPath(std::string& path)
{
// Do not translate paths that are too short to have meaningful
// translations.
- if(path.size() < 2)
- {
+ if (path.size() < 2) {
return;
- }
+ }
// Always add a trailing slash before translation. It does not
// matter if this adds an extra slash, but we do not want to
@@ -3729,49 +3267,39 @@ void SystemTools::CheckTranslationPath(std::string & path)
// In case a file was specified we still have to go through this:
// Now convert any path found in the table back to the one desired:
- std::map<std::string,std::string>::const_iterator it;
- for(it = SystemTools::TranslationMap->begin();
- it != SystemTools::TranslationMap->end();
- ++it )
- {
+ std::map<std::string, std::string>::const_iterator it;
+ for (it = SystemTools::TranslationMap->begin();
+ it != SystemTools::TranslationMap->end(); ++it) {
// We need to check of the path is a substring of the other path
- if(path.find( it->first ) == 0)
- {
- path = path.replace( 0, it->first.size(), it->second);
- }
+ if (path.find(it->first) == 0) {
+ path = path.replace(0, it->first.size(), it->second);
}
+ }
// Remove the trailing slash we added before.
- path.erase(path.end()-1, path.end());
+ path.erase(path.end() - 1, path.end());
}
-static void
-SystemToolsAppendComponents(
+static void SystemToolsAppendComponents(
std::vector<std::string>& out_components,
std::vector<std::string>::const_iterator first,
std::vector<std::string>::const_iterator last)
{
static const std::string up = "..";
static const std::string cur = ".";
- for(std::vector<std::string>::const_iterator i = first;
- i != last; ++i)
- {
- if(*i == up)
- {
- if(out_components.size() > 1)
- {
- out_components.resize(out_components.size()-1);
- }
+ for (std::vector<std::string>::const_iterator i = first; i != last; ++i) {
+ if (*i == up) {
+ if (out_components.size() > 1) {
+ out_components.resize(out_components.size() - 1);
}
- else if(!i->empty() && *i != cur)
- {
+ } else if (!i->empty() && *i != cur) {
out_components.push_back(*i);
- }
}
+ }
}
std::string SystemTools::CollapseFullPath(const std::string& in_path,
- const char* in_base)
+ const char* in_base)
{
// Collect the output path components.
std::vector<std::string> out_components;
@@ -3781,38 +3309,29 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
SystemTools::SplitPath(in_path, path_components);
// If the input path is relative, start with a base path.
- if(path_components[0].length() == 0)
- {
+ if (path_components[0].length() == 0) {
std::vector<std::string> base_components;
- if(in_base)
- {
+ if (in_base) {
// Use the given base path.
SystemTools::SplitPath(in_base, base_components);
- }
- else
- {
+ } else {
// Use the current working directory as a base path.
char buf[2048];
- if(const char* cwd = Getcwd(buf, 2048))
- {
+ if (const char* cwd = Getcwd(buf, 2048)) {
SystemTools::SplitPath(cwd, base_components);
- }
- else
- {
+ } else {
base_components.push_back("");
- }
}
+ }
// Append base path components to the output path.
out_components.push_back(base_components[0]);
- SystemToolsAppendComponents(out_components,
- base_components.begin()+1,
+ SystemToolsAppendComponents(out_components, base_components.begin() + 1,
base_components.end());
- }
+ }
// Append input path components to the output path.
- SystemToolsAppendComponents(out_components,
- path_components.begin(),
+ SystemToolsAppendComponents(out_components, path_components.begin(),
path_components.end());
// Transform the path back to a string.
@@ -3830,7 +3349,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
// collapsed, so I am going to try to comment it out, and see what hits the
// fan, hopefully quickly.
// Commented out line below:
- //SystemTools::AddTranslationPath(newPath, in_path);
+ // SystemTools::AddTranslationPath(newPath, in_path);
SystemTools::CheckTranslationPath(newPath);
#ifdef _WIN32
@@ -3842,7 +3361,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
}
std::string SystemTools::CollapseFullPath(const std::string& in_path,
- const std::string& in_base)
+ const std::string& in_base)
{
// Collect the output path components.
std::vector<std::string> out_components;
@@ -3852,22 +3371,19 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
SystemTools::SplitPath(in_path, path_components);
// If the input path is relative, start with a base path.
- if(path_components[0].length() == 0)
- {
+ if (path_components[0].length() == 0) {
std::vector<std::string> base_components;
// Use the given base path.
SystemTools::SplitPath(in_base, base_components);
// Append base path components to the output path.
out_components.push_back(base_components[0]);
- SystemToolsAppendComponents(out_components,
- base_components.begin()+1,
+ SystemToolsAppendComponents(out_components, base_components.begin() + 1,
base_components.end());
- }
+ }
// Append input path components to the output path.
- SystemToolsAppendComponents(out_components,
- path_components.begin(),
+ SystemToolsAppendComponents(out_components, path_components.begin(),
path_components.end());
// Transform the path back to a string.
@@ -3885,7 +3401,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
// collapsed, so I am going to try to comment it out, and see what hits the
// fan, hopefully quickly.
// Commented out line below:
- //SystemTools::AddTranslationPath(newPath, in_path);
+ // SystemTools::AddTranslationPath(newPath, in_path);
SystemTools::CheckTranslationPath(newPath);
#ifdef _WIN32
@@ -3897,89 +3413,82 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
}
// compute the relative path from here to there
-std::string SystemTools::RelativePath(const std::string& local, const std::string& remote)
+std::string SystemTools::RelativePath(const std::string& local,
+ const std::string& remote)
{
- if(!SystemTools::FileIsFullPath(local))
- {
+ if (!SystemTools::FileIsFullPath(local)) {
return "";
- }
- if(!SystemTools::FileIsFullPath(remote))
- {
+ }
+ if (!SystemTools::FileIsFullPath(remote)) {
return "";
- }
+ }
std::string l = SystemTools::CollapseFullPath(local);
std::string r = SystemTools::CollapseFullPath(remote);
// split up both paths into arrays of strings using / as a separator
- std::vector<kwsys::String> localSplit = SystemTools::SplitString(l, '/', true);
- std::vector<kwsys::String> remoteSplit = SystemTools::SplitString(r, '/', true);
- std::vector<kwsys::String> commonPath; // store shared parts of path in this array
- std::vector<kwsys::String> finalPath; // store the final relative path here
+ std::vector<kwsys::String> localSplit =
+ SystemTools::SplitString(l, '/', true);
+ std::vector<kwsys::String> remoteSplit =
+ SystemTools::SplitString(r, '/', true);
+ std::vector<kwsys::String>
+ commonPath; // store shared parts of path in this array
+ std::vector<kwsys::String> finalPath; // store the final relative path here
// count up how many matching directory names there are from the start
unsigned int sameCount = 0;
- while(
- ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
- &&
+ while (((sameCount <= (localSplit.size() - 1)) &&
+ (sameCount <= (remoteSplit.size() - 1))) &&
// for windows and apple do a case insensitive string compare
#if defined(_WIN32) || defined(__APPLE__)
- SystemTools::Strucmp(localSplit[sameCount].c_str(),
- remoteSplit[sameCount].c_str()) == 0
+ SystemTools::Strucmp(localSplit[sameCount].c_str(),
+ remoteSplit[sameCount].c_str()) == 0
#else
- localSplit[sameCount] == remoteSplit[sameCount]
+ localSplit[sameCount] == remoteSplit[sameCount]
#endif
- )
- {
+ ) {
// put the common parts of the path into the commonPath array
commonPath.push_back(localSplit[sameCount]);
// erase the common parts of the path from the original path arrays
localSplit[sameCount] = "";
remoteSplit[sameCount] = "";
sameCount++;
- }
+ }
// If there is nothing in common at all then just return the full
// path. This is the case only on windows when the paths have
// different drive letters. On unix two full paths always at least
// have the root "/" in common so we will return a relative path
// that passes through the root directory.
- if(sameCount == 0)
- {
+ if (sameCount == 0) {
return remote;
- }
+ }
// for each entry that is not common in the local path
// add a ../ to the finalpath array, this gets us out of the local
// path into the remote dir
- for(unsigned int i = 0; i < localSplit.size(); ++i)
- {
- if(!localSplit[i].empty())
- {
+ for (unsigned int i = 0; i < localSplit.size(); ++i) {
+ if (!localSplit[i].empty()) {
finalPath.push_back("../");
- }
}
+ }
// for each entry that is not common in the remote path add it
// to the final path.
- for(std::vector<String>::iterator vit = remoteSplit.begin();
- vit != remoteSplit.end(); ++vit)
- {
- if(!vit->empty())
- {
+ for (std::vector<String>::iterator vit = remoteSplit.begin();
+ vit != remoteSplit.end(); ++vit) {
+ if (!vit->empty()) {
finalPath.push_back(*vit);
- }
}
- std::string relativePath; // result string
+ }
+ std::string relativePath; // result string
// now turn the array of directories into a unix path by puttint /
// between each entry that does not already have one
- for(std::vector<String>::iterator vit1 = finalPath.begin();
- vit1 != finalPath.end(); ++vit1)
- {
- if(!relativePath.empty() && *relativePath.rbegin() != '/')
- {
+ for (std::vector<String>::iterator vit1 = finalPath.begin();
+ vit1 != finalPath.end(); ++vit1) {
+ if (!relativePath.empty() && *relativePath.rbegin() != '/') {
relativePath += "/";
- }
- relativePath += *vit1;
}
+ relativePath += *vit1;
+ }
return relativePath;
}
@@ -3989,77 +3498,66 @@ static std::string GetCasePathName(std::string const& pathIn)
std::string casePath;
std::vector<std::string> path_components;
SystemTools::SplitPath(pathIn, path_components);
- if(path_components[0].empty()) // First component always exists.
- {
+ if (path_components[0].empty()) // First component always exists.
+ {
// Relative paths cannot be converted.
casePath = pathIn;
return casePath;
- }
+ }
// Start with root component.
std::vector<std::string>::size_type idx = 0;
casePath = path_components[idx++];
// make sure drive letter is always upper case
- if(casePath.size() > 1 && casePath[1] == ':')
- {
+ if (casePath.size() > 1 && casePath[1] == ':') {
casePath[0] = toupper(casePath[0]);
- }
+ }
const char* sep = "";
// If network path, fill casePath with server/share so FindFirstFile
// will work after that. Maybe someday call other APIs to get
// actual case of servers and shares.
- if(path_components.size() > 2 && path_components[0] == "//")
- {
+ if (path_components.size() > 2 && path_components[0] == "//") {
casePath += path_components[idx++];
casePath += "/";
casePath += path_components[idx++];
sep = "/";
- }
+ }
// Convert case of all components that exist.
bool converting = true;
- for(; idx < path_components.size(); idx++)
- {
+ for (; idx < path_components.size(); idx++) {
casePath += sep;
sep = "/";
- if (converting)
- {
+ if (converting) {
// If path component contains wildcards, we skip matching
// because these filenames are not allowed on windows,
// and we do not want to match a different file.
- if(path_components[idx].find('*') != std::string::npos ||
- path_components[idx].find('?') != std::string::npos)
- {
+ if (path_components[idx].find('*') != std::string::npos ||
+ path_components[idx].find('?') != std::string::npos) {
converting = false;
- }
- else
- {
+ } else {
std::string test_str = casePath;
test_str += path_components[idx];
WIN32_FIND_DATAW findData;
- HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
- &findData);
- if (INVALID_HANDLE_VALUE != hFind)
- {
+ HANDLE hFind =
+ ::FindFirstFileW(Encoding::ToWide(test_str).c_str(), &findData);
+ if (INVALID_HANDLE_VALUE != hFind) {
path_components[idx] = Encoding::ToNarrow(findData.cFileName);
::FindClose(hFind);
- }
- else
- {
+ } else {
converting = false;
- }
}
}
+ }
casePath += path_components[idx];
- }
+ }
return casePath;
}
#endif
-
//----------------------------------------------------------------------------
std::string SystemTools::GetActualCaseForPath(const std::string& p)
{
@@ -4068,17 +3566,14 @@ std::string SystemTools::GetActualCaseForPath(const std::string& p)
#else
// Check to see if actual case has already been called
// for this path, and the result is stored in the PathCaseMap
- SystemToolsPathCaseMap::iterator i =
- SystemTools::PathCaseMap->find(p);
- if(i != SystemTools::PathCaseMap->end())
- {
+ SystemToolsPathCaseMap::iterator i = SystemTools::PathCaseMap->find(p);
+ if (i != SystemTools::PathCaseMap->end()) {
return i->second;
- }
+ }
std::string casePath = GetCasePathName(p);
- if (casePath.size() > MAX_PATH)
- {
+ if (casePath.size() > MAX_PATH) {
return casePath;
- }
+ }
(*SystemTools::PathCaseMap)[p] = casePath;
return casePath;
#endif
@@ -4090,46 +3585,33 @@ const char* SystemTools::SplitPathRootComponent(const std::string& p,
{
// Identify the root component.
const char* c = p.c_str();
- if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
- {
+ if ((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\')) {
// Network path.
- if(root)
- {
+ if (root) {
*root = "//";
- }
- c += 2;
}
- else if(c[0] == '/' || c[0] == '\\')
- {
+ c += 2;
+ } else if (c[0] == '/' || c[0] == '\\') {
// Unix path (or Windows path w/out drive letter).
- if(root)
- {
+ if (root) {
*root = "/";
- }
- c += 1;
}
- else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
- {
+ c += 1;
+ } else if (c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\')) {
// Windows path.
- if(root)
- {
+ if (root) {
(*root) = "_:/";
(*root)[0] = c[0];
- }
- c += 3;
}
- else if(c[0] && c[1] == ':')
- {
+ c += 3;
+ } else if (c[0] && c[1] == ':') {
// Path relative to a windows drive working directory.
- if(root)
- {
+ if (root) {
(*root) = "_:";
(*root)[0] = c[0];
- }
- c += 2;
}
- else if(c[0] == '~')
- {
+ c += 2;
+ } else if (c[0] == '~') {
// Home directory. The returned root should always have a
// trailing slash so that appending components as
// c[0]c[1]/c[2]/... works. The remaining path returned should
@@ -4142,29 +3624,23 @@ const char* SystemTools::SplitPathRootComponent(const std::string& p,
// "~u/" : root = "~u/", return ""
// "~u/x" : root = "~u/", return "x"
size_t n = 1;
- while(c[n] && c[n] != '/')
- {
+ while (c[n] && c[n] != '/') {
++n;
- }
- if(root)
- {
+ }
+ if (root) {
root->assign(c, n);
*root += '/';
- }
- if(c[n] == '/')
- {
+ }
+ if (c[n] == '/') {
++n;
- }
- c += n;
}
- else
- {
+ c += n;
+ } else {
// Relative path.
- if(root)
- {
+ if (root) {
*root = "";
- }
}
+ }
// Return the remaining path.
return c;
@@ -4180,102 +3656,86 @@ void SystemTools::SplitPath(const std::string& p,
// Identify the root component.
{
- std::string root;
- c = SystemTools::SplitPathRootComponent(p, &root);
-
- // Expand home directory references if requested.
- if(expand_home_dir && !root.empty() && root[0] == '~')
- {
- std::string homedir;
- root = root.substr(0, root.size()-1);
- if(root.size() == 1)
- {
+ std::string root;
+ c = SystemTools::SplitPathRootComponent(p, &root);
+
+ // Expand home directory references if requested.
+ if (expand_home_dir && !root.empty() && root[0] == '~') {
+ std::string homedir;
+ root = root.substr(0, root.size() - 1);
+ if (root.size() == 1) {
#if defined(_WIN32) && !defined(__CYGWIN__)
- if (!SystemTools::GetEnv("USERPROFILE", homedir))
+ if (!SystemTools::GetEnv("USERPROFILE", homedir))
#endif
- SystemTools::GetEnv("HOME", homedir);
+ SystemTools::GetEnv("HOME", homedir);
}
#ifdef HAVE_GETPWNAM
- else if(passwd* pw = getpwnam(root.c_str()+1))
- {
- if(pw->pw_dir)
- {
- homedir = pw->pw_dir;
+ else if (passwd* pw = getpwnam(root.c_str() + 1)) {
+ if (pw->pw_dir) {
+ homedir = pw->pw_dir;
}
}
#endif
- if(!homedir.empty() && (*homedir.rbegin() == '/' ||
- *homedir.rbegin() == '\\'))
- {
- homedir.resize(homedir.size() - 1);
+ if (!homedir.empty() &&
+ (*homedir.rbegin() == '/' || *homedir.rbegin() == '\\')) {
+ homedir.resize(homedir.size() - 1);
}
- SystemTools::SplitPath(homedir, components);
- }
- else
- {
- components.push_back(root);
+ SystemTools::SplitPath(homedir, components);
+ } else {
+ components.push_back(root);
}
}
// Parse the remaining components.
const char* first = c;
const char* last = first;
- for(;*last; ++last)
- {
- if(*last == '/' || *last == '\\')
- {
+ for (; *last; ++last) {
+ if (*last == '/' || *last == '\\') {
// End of a component. Save it.
components.push_back(std::string(first, last));
- first = last+1;
- }
+ first = last + 1;
}
+ }
// Save the last component unless there were no components.
- if(last != c)
- {
+ if (last != c) {
components.push_back(std::string(first, last));
- }
+ }
}
//----------------------------------------------------------------------------
-std::string
-SystemTools::JoinPath(const std::vector<std::string>& components)
+std::string SystemTools::JoinPath(const std::vector<std::string>& components)
{
return SystemTools::JoinPath(components.begin(), components.end());
}
//----------------------------------------------------------------------------
-std::string
-SystemTools
-::JoinPath(std::vector<std::string>::const_iterator first,
- std::vector<std::string>::const_iterator last)
+std::string SystemTools::JoinPath(
+ std::vector<std::string>::const_iterator first,
+ std::vector<std::string>::const_iterator last)
{
// Construct result in a single string.
std::string result;
size_t len = 0;
std::vector<std::string>::const_iterator i;
- for(i = first; i != last; ++i)
- {
+ for (i = first; i != last; ++i) {
len += 1 + i->size();
- }
+ }
result.reserve(len);
// The first two components do not add a slash.
- if(first != last)
- {
+ if (first != last) {
result.append(*first++);
- }
- if(first != last)
- {
+ }
+ if (first != last) {
result.append(*first++);
- }
+ }
// All remaining components are always separated with a slash.
- while(first != last)
- {
+ while (first != last) {
result.append("/");
result.append((*first++));
- }
+ }
// Return the concatenated result.
return result;
@@ -4285,68 +3745,61 @@ SystemTools
bool SystemTools::ComparePath(const std::string& c1, const std::string& c2)
{
#if defined(_WIN32) || defined(__APPLE__)
-# ifdef _MSC_VER
+#ifdef _MSC_VER
return _stricmp(c1.c_str(), c2.c_str()) == 0;
-# elif defined(__APPLE__) || defined(__GNUC__)
+#elif defined(__APPLE__) || defined(__GNUC__)
return strcasecmp(c1.c_str(), c2.c_str()) == 0;
#else
return SystemTools::Strucmp(c1.c_str(), c2.c_str()) == 0;
-# endif
+#endif
#else
return c1 == c2;
#endif
}
//----------------------------------------------------------------------------
-bool SystemTools::Split(const std::string& str, std::vector<std::string>& lines, char separator)
+bool SystemTools::Split(const std::string& str,
+ std::vector<std::string>& lines, char separator)
{
std::string data(str);
std::string::size_type lpos = 0;
- while(lpos < data.length())
- {
+ while (lpos < data.length()) {
std::string::size_type rpos = data.find_first_of(separator, lpos);
- if(rpos == std::string::npos)
- {
+ if (rpos == std::string::npos) {
// Line ends at end of string without a newline.
lines.push_back(data.substr(lpos));
return false;
- }
- else
- {
+ } else {
// Line ends in a "\n", remove the character.
- lines.push_back(data.substr(lpos, rpos-lpos));
- }
- lpos = rpos+1;
+ lines.push_back(data.substr(lpos, rpos - lpos));
}
+ lpos = rpos + 1;
+ }
return true;
}
//----------------------------------------------------------------------------
-bool SystemTools::Split(const std::string& str, std::vector<std::string>& lines)
+bool SystemTools::Split(const std::string& str,
+ std::vector<std::string>& lines)
{
std::string data(str);
std::string::size_type lpos = 0;
- while(lpos < data.length())
- {
+ while (lpos < data.length()) {
std::string::size_type rpos = data.find_first_of("\n", lpos);
- if(rpos == std::string::npos)
- {
+ if (rpos == std::string::npos) {
// Line ends at end of string without a newline.
lines.push_back(data.substr(lpos));
return false;
- }
- if((rpos > lpos) && (data[rpos-1] == '\r'))
- {
+ }
+ if ((rpos > lpos) && (data[rpos - 1] == '\r')) {
// Line ends in a "\r\n" pair, remove both characters.
- lines.push_back(data.substr(lpos, (rpos-1)-lpos));
- }
- else
- {
+ lines.push_back(data.substr(lpos, (rpos - 1) - lpos));
+ } else {
// Line ends in a "\n", remove the character.
- lines.push_back(data.substr(lpos, rpos-lpos));
- }
- lpos = rpos+1;
+ lines.push_back(data.substr(lpos, rpos - lpos));
}
+ lpos = rpos + 1;
+ }
return true;
}
@@ -4360,26 +3813,20 @@ std::string SystemTools::GetFilenamePath(const std::string& filename)
SystemTools::ConvertToUnixSlashes(fn);
std::string::size_type slash_pos = fn.rfind("/");
- if(slash_pos != std::string::npos)
- {
- std::string ret = fn.substr(0, slash_pos);
- if(ret.size() == 2 && ret[1] == ':')
- {
+ if (slash_pos != std::string::npos) {
+ std::string ret = fn.substr(0, slash_pos);
+ if (ret.size() == 2 && ret[1] == ':') {
return ret + '/';
- }
- if(ret.empty())
- {
+ }
+ if (ret.empty()) {
return "/";
- }
- return ret;
}
- else
- {
+ return ret;
+ } else {
return "";
- }
+ }
}
-
/**
* Return file name of a full filename (i.e. file name without path).
*/
@@ -4390,17 +3837,13 @@ std::string SystemTools::GetFilenameName(const std::string& filename)
#else
std::string::size_type slash_pos = filename.rfind('/');
#endif
- if(slash_pos != std::string::npos)
- {
+ if (slash_pos != std::string::npos) {
return filename.substr(slash_pos + 1);
- }
- else
- {
+ } else {
return filename;
- }
+ }
}
-
/**
* Return file extension of a full filename (dot included).
* Warning: this is the longest extension (for example: .tar.gz)
@@ -4409,14 +3852,11 @@ std::string SystemTools::GetFilenameExtension(const std::string& filename)
{
std::string name = SystemTools::GetFilenameName(filename);
std::string::size_type dot_pos = name.find('.');
- if(dot_pos != std::string::npos)
- {
+ if (dot_pos != std::string::npos) {
return name.substr(dot_pos);
- }
- else
- {
+ } else {
return "";
- }
+ }
}
/**
@@ -4427,161 +3867,135 @@ std::string SystemTools::GetFilenameLastExtension(const std::string& filename)
{
std::string name = SystemTools::GetFilenameName(filename);
std::string::size_type dot_pos = name.rfind('.');
- if(dot_pos != std::string::npos)
- {
+ if (dot_pos != std::string::npos) {
return name.substr(dot_pos);
- }
- else
- {
+ } else {
return "";
- }
+ }
}
/**
* Return file name without extension of a full filename (i.e. without path).
* Warning: it considers the longest extension (for example: .tar.gz)
*/
-std::string SystemTools::GetFilenameWithoutExtension(const std::string& filename)
+std::string SystemTools::GetFilenameWithoutExtension(
+ const std::string& filename)
{
std::string name = SystemTools::GetFilenameName(filename);
std::string::size_type dot_pos = name.find('.');
- if(dot_pos != std::string::npos)
- {
+ if (dot_pos != std::string::npos) {
return name.substr(0, dot_pos);
- }
- else
- {
+ } else {
return name;
- }
+ }
}
-
/**
* Return file name without extension of a full filename (i.e. without path).
* Warning: it considers the last extension (for example: removes .gz
* from .tar.gz)
*/
-std::string
-SystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
+std::string SystemTools::GetFilenameWithoutLastExtension(
+ const std::string& filename)
{
std::string name = SystemTools::GetFilenameName(filename);
std::string::size_type dot_pos = name.rfind('.');
- if(dot_pos != std::string::npos)
- {
+ if (dot_pos != std::string::npos) {
return name.substr(0, dot_pos);
- }
- else
- {
+ } else {
return name;
- }
+ }
}
-bool SystemTools::FileHasSignature(const char *filename,
- const char *signature,
+bool SystemTools::FileHasSignature(const char* filename, const char* signature,
long offset)
{
- if (!filename || !signature)
- {
+ if (!filename || !signature) {
return false;
- }
+ }
- FILE *fp = Fopen(filename, "rb");
- if (!fp)
- {
+ FILE* fp = Fopen(filename, "rb");
+ if (!fp) {
return false;
- }
+ }
fseek(fp, offset, SEEK_SET);
bool res = false;
size_t signature_len = strlen(signature);
- char *buffer = new char [signature_len];
+ char* buffer = new char[signature_len];
- if (fread(buffer, 1, signature_len, fp) == signature_len)
- {
+ if (fread(buffer, 1, signature_len, fp) == signature_len) {
res = (!strncmp(buffer, signature, signature_len) ? true : false);
- }
+ }
- delete [] buffer;
+ delete[] buffer;
fclose(fp);
return res;
}
-SystemTools::FileTypeEnum
-SystemTools::DetectFileType(const char *filename,
- unsigned long length,
- double percent_bin)
+SystemTools::FileTypeEnum SystemTools::DetectFileType(const char* filename,
+ unsigned long length,
+ double percent_bin)
{
- if (!filename || percent_bin < 0)
- {
+ if (!filename || percent_bin < 0) {
return SystemTools::FileTypeUnknown;
- }
+ }
- if (SystemTools::FileIsDirectory(filename))
- {
+ if (SystemTools::FileIsDirectory(filename)) {
return SystemTools::FileTypeUnknown;
- }
+ }
- FILE *fp = Fopen(filename, "rb");
- if (!fp)
- {
+ FILE* fp = Fopen(filename, "rb");
+ if (!fp) {
return SystemTools::FileTypeUnknown;
- }
+ }
// Allocate buffer and read bytes
- unsigned char *buffer = new unsigned char [length];
+ unsigned char* buffer = new unsigned char[length];
size_t read_length = fread(buffer, 1, length, fp);
fclose(fp);
- if (read_length == 0)
- {
- delete [] buffer;
+ if (read_length == 0) {
+ delete[] buffer;
return SystemTools::FileTypeUnknown;
- }
+ }
// Loop over contents and count
size_t text_count = 0;
- const unsigned char *ptr = buffer;
- const unsigned char *buffer_end = buffer + read_length;
+ const unsigned char* ptr = buffer;
+ const unsigned char* buffer_end = buffer + read_length;
- while (ptr != buffer_end)
- {
- if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
- *ptr == '\n' ||
- *ptr == '\r' ||
- *ptr == '\t')
- {
+ while (ptr != buffer_end) {
+ if ((*ptr >= 0x20 && *ptr <= 0x7F) || *ptr == '\n' || *ptr == '\r' ||
+ *ptr == '\t') {
text_count++;
- }
- ptr++;
}
+ ptr++;
+ }
- delete [] buffer;
+ delete[] buffer;
- double current_percent_bin =
- (static_cast<double>(read_length - text_count) /
- static_cast<double>(read_length));
+ double current_percent_bin = (static_cast<double>(read_length - text_count) /
+ static_cast<double>(read_length));
- if (current_percent_bin >= percent_bin)
- {
+ if (current_percent_bin >= percent_bin) {
return SystemTools::FileTypeBinary;
- }
+ }
return SystemTools::FileTypeText;
}
-bool SystemTools::LocateFileInDir(const char *filename,
- const char *dir,
+bool SystemTools::LocateFileInDir(const char* filename, const char* dir,
std::string& filename_found,
int try_filename_dirs)
{
- if (!filename || !dir)
- {
+ if (!filename || !dir) {
return false;
- }
+ }
// Get the basename of 'filename'
@@ -4591,81 +4005,72 @@ bool SystemTools::LocateFileInDir(const char *filename,
// If win32 and matches something like C:, accept it as a dir
std::string real_dir;
- if (!SystemTools::FileIsDirectory(dir))
- {
-#if defined( _WIN32 )
+ if (!SystemTools::FileIsDirectory(dir)) {
+#if defined(_WIN32)
size_t dir_len = strlen(dir);
- if (dir_len < 2 || dir[dir_len - 1] != ':')
- {
+ if (dir_len < 2 || dir[dir_len - 1] != ':') {
#endif
real_dir = SystemTools::GetFilenamePath(dir);
dir = real_dir.c_str();
-#if defined( _WIN32 )
- }
-#endif
+#if defined(_WIN32)
}
+#endif
+ }
// Try to find the file in 'dir'
bool res = false;
- if (!filename_base.empty() && dir)
- {
+ if (!filename_base.empty() && dir) {
size_t dir_len = strlen(dir);
int need_slash =
(dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
std::string temp = dir;
- if (need_slash)
- {
+ if (need_slash) {
temp += "/";
- }
+ }
temp += filename_base;
- if (SystemTools::FileExists(temp))
- {
+ if (SystemTools::FileExists(temp)) {
res = true;
filename_found = temp;
- }
+ }
// If not found, we can try harder by appending part of the file to
// to the directory to look inside.
// Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
// try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
- else if (try_filename_dirs)
- {
+ else if (try_filename_dirs) {
std::string filename_dir(filename);
std::string filename_dir_base;
std::string filename_dir_bases;
- do
- {
+ do {
filename_dir = SystemTools::GetFilenamePath(filename_dir);
filename_dir_base = SystemTools::GetFilenameName(filename_dir);
-#if defined( _WIN32 )
- if (filename_dir_base.empty() ||
- *filename_dir_base.rbegin() == ':')
+#if defined(_WIN32)
+ if (filename_dir_base.empty() || *filename_dir_base.rbegin() == ':')
#else
if (filename_dir_base.empty())
#endif
- {
+ {
break;
- }
+ }
filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
temp = dir;
- if (need_slash)
- {
+ if (need_slash) {
temp += "/";
- }
+ }
temp += filename_dir_bases;
- res = SystemTools::LocateFileInDir(
- filename_base.c_str(), temp.c_str(), filename_found, 0);
+ res = SystemTools::LocateFileInDir(filename_base.c_str(), temp.c_str(),
+ filename_found, 0);
- } while (!res && !filename_dir_base.empty());
- }
+ } while (!res && !filename_dir_base.empty());
}
+ }
return res;
}
@@ -4677,77 +4082,67 @@ bool SystemTools::FileIsFullPath(const std::string& in_name)
bool SystemTools::FileIsFullPath(const char* in_name)
{
- return SystemTools::FileIsFullPath(in_name, in_name[0] ? (in_name[1] ? 2 : 1) : 0);
+ return SystemTools::FileIsFullPath(in_name,
+ in_name[0] ? (in_name[1] ? 2 : 1) : 0);
}
bool SystemTools::FileIsFullPath(const char* in_name, size_t len)
{
#if defined(_WIN32) || defined(__CYGWIN__)
// On Windows, the name must be at least two characters long.
- if(len < 2)
- {
+ if (len < 2) {
return false;
- }
- if(in_name[1] == ':')
- {
+ }
+ if (in_name[1] == ':') {
return true;
- }
- if(in_name[0] == '\\')
- {
+ }
+ if (in_name[0] == '\\') {
return true;
- }
+ }
#else
// On UNIX, the name must be at least one character long.
- if(len < 1)
- {
+ if (len < 1) {
return false;
- }
+ }
#endif
#if !defined(_WIN32)
- if(in_name[0] == '~')
- {
+ if (in_name[0] == '~') {
return true;
- }
+ }
#endif
// On UNIX, the name must begin in a '/'.
// On Windows, if the name begins in a '/', then it is a full
// network path.
- if(in_name[0] == '/')
- {
+ if (in_name[0] == '/') {
return true;
- }
+ }
return false;
}
bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
- std::string tempPath = path; // create a buffer
+ std::string tempPath = path; // create a buffer
// if the path passed in has quotes around it, first remove the quotes
- if (!path.empty() && path[0] == '"' && *path.rbegin() == '"')
- {
- tempPath = path.substr(1, path.length()-2);
- }
+ if (!path.empty() && path[0] == '"' && *path.rbegin() == '"') {
+ tempPath = path.substr(1, path.length() - 2);
+ }
std::wstring wtempPath = Encoding::ToWide(tempPath);
DWORD ret = GetShortPathNameW(wtempPath.c_str(), NULL, 0);
std::vector<wchar_t> buffer(ret);
- if (ret != 0)
- {
- ret = GetShortPathNameW(wtempPath.c_str(),
- &buffer[0], static_cast<DWORD>(buffer.size()));
- }
+ if (ret != 0) {
+ ret = GetShortPathNameW(wtempPath.c_str(), &buffer[0],
+ static_cast<DWORD>(buffer.size()));
+ }
- if (ret == 0)
- {
+ if (ret == 0) {
return false;
- }
- else
- {
+ } else {
shortPath = Encoding::ToNarrow(&buffer[0]);
return true;
- }
+ }
#else
shortPath = path;
return true;
@@ -4759,63 +4154,56 @@ void SystemTools::SplitProgramFromArgs(const std::string& path,
{
// see if this is a full path to a program
// if so then set program to path and args to nothing
- if(SystemTools::FileExists(path))
- {
+ if (SystemTools::FileExists(path)) {
program = path;
args = "";
return;
- }
+ }
// Try to find the program in the path, note the program
// may have spaces in its name so we have to look for it
std::vector<std::string> e;
std::string findProg = SystemTools::FindProgram(path, e);
- if(!findProg.empty())
- {
+ if (!findProg.empty()) {
program = findProg;
args = "";
return;
- }
+ }
// Now try and peel off space separated chunks from the end of the string
// so the largest path possible is found allowing for spaces in the path
std::string dir = path;
std::string::size_type spacePos = dir.rfind(' ');
- while(spacePos != std::string::npos)
- {
+ while (spacePos != std::string::npos) {
std::string tryProg = dir.substr(0, spacePos);
// See if the file exists
- if(SystemTools::FileExists(tryProg))
- {
+ if (SystemTools::FileExists(tryProg)) {
program = tryProg;
// remove trailing spaces from program
- std::string::size_type pos = program.size()-1;
- while(program[pos] == ' ')
- {
+ std::string::size_type pos = program.size() - 1;
+ while (program[pos] == ' ') {
program.erase(pos);
pos--;
- }
- args = dir.substr(spacePos, dir.size()-spacePos);
- return;
}
+ args = dir.substr(spacePos, dir.size() - spacePos);
+ return;
+ }
// Now try and find the program in the path
findProg = SystemTools::FindProgram(tryProg, e);
- if(!findProg.empty())
- {
+ if (!findProg.empty()) {
program = findProg;
// remove trailing spaces from program
- std::string::size_type pos = program.size()-1;
- while(program[pos] == ' ')
- {
+ std::string::size_type pos = program.size() - 1;
+ while (program[pos] == ' ') {
program.erase(pos);
pos--;
- }
- args = dir.substr(spacePos, dir.size()-spacePos);
- return;
}
+ args = dir.substr(spacePos, dir.size() - spacePos);
+ return;
+ }
// move past the space for the next search
spacePos--;
spacePos = dir.rfind(' ', spacePos);
- }
+ }
program = "";
args = "";
@@ -4833,28 +4221,26 @@ std::string SystemTools::GetCurrentDateTime(const char* format)
std::string SystemTools::MakeCidentifier(const std::string& s)
{
std::string str(s);
- if (str.find_first_of("0123456789") == 0)
- {
+ if (str.find_first_of("0123456789") == 0) {
str = "_" + str;
- }
+ }
std::string permited_chars("_"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789");
std::string::size_type pos = 0;
- while ((pos = str.find_first_not_of(permited_chars, pos)) != std::string::npos)
- {
+ while ((pos = str.find_first_not_of(permited_chars, pos)) !=
+ std::string::npos) {
str[pos] = '_';
- }
+ }
return str;
}
// Due to a buggy stream library on the HP and another on Mac OS X, we
// need this very carefully written version of getline. Returns true
// if any data were read before the end-of-file was reached.
-bool SystemTools::GetLineFromStream(std::istream& is,
- std::string& line,
+bool SystemTools::GetLineFromStream(std::istream& is, std::string& line,
bool* has_newline /* = 0 */,
long sizeLimit /* = -1 */)
{
@@ -4872,63 +4258,52 @@ bool SystemTools::GetLineFromStream(std::istream& is,
// false and the empty line. (Probably means caller tried to
// create a file stream with a non-existent file name...)
//
- if(!is)
- {
- if(has_newline)
- {
+ if (!is) {
+ if (has_newline) {
*has_newline = false;
- }
- return false;
}
+ return false;
+ }
// If no characters are read from the stream, the end of file has
// been reached. Clear the fail bit just before reading.
- while(!haveNewline &&
- leftToRead != 0 &&
- (static_cast<void>(is.clear(is.rdstate() & ~std::ios::failbit)),
- static_cast<void>(is.getline(buffer, bufferSize)),
- is.gcount() > 0))
- {
+ while (!haveNewline && leftToRead != 0 &&
+ (static_cast<void>(is.clear(is.rdstate() & ~std::ios::failbit)),
+ static_cast<void>(is.getline(buffer, bufferSize)),
+ is.gcount() > 0)) {
// We have read at least one byte.
haveData = true;
// If newline character was read the gcount includes the character
// but the buffer does not: the end of line has been reached.
size_t length = strlen(buffer);
- if(length < static_cast<size_t>(is.gcount()))
- {
+ if (length < static_cast<size_t>(is.gcount())) {
haveNewline = true;
- }
+ }
// Avoid storing a carriage return character.
- if(length > 0 && buffer[length-1] == '\r')
- {
- buffer[length-1] = 0;
- }
+ if (length > 0 && buffer[length - 1] == '\r') {
+ buffer[length - 1] = 0;
+ }
// if we read too much then truncate the buffer
- if (leftToRead > 0)
- {
- if (static_cast<long>(length) > leftToRead)
- {
- buffer[leftToRead-1] = 0;
+ if (leftToRead > 0) {
+ if (static_cast<long>(length) > leftToRead) {
+ buffer[leftToRead - 1] = 0;
leftToRead = 0;
- }
- else
- {
+ } else {
leftToRead -= static_cast<long>(length);
- }
}
+ }
// Append the data read to the line.
line.append(buffer);
- }
+ }
// Return the results.
- if(has_newline)
- {
+ if (has_newline) {
*has_newline = haveNewline;
- }
+ }
return haveData;
}
@@ -4938,38 +4313,32 @@ int SystemTools::GetTerminalWidth()
#ifdef HAVE_TTY_INFO
struct winsize ws;
std::string columns; /* Unix98 environment variable */
- if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
- {
+ if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0 && ws.ws_row > 0) {
width = ws.ws_col;
- }
- if(!isatty(STDOUT_FILENO))
- {
+ }
+ if (!isatty(STDOUT_FILENO)) {
width = -1;
- }
- if(SystemTools::GetEnv("COLUMNS", columns) && !columns.empty())
- {
+ }
+ if (SystemTools::GetEnv("COLUMNS", columns) && !columns.empty()) {
long t;
- char *endptr;
+ char* endptr;
t = strtol(columns.c_str(), &endptr, 0);
- if(endptr && !*endptr && (t>0) && (t<1000))
- {
+ if (endptr && !*endptr && (t > 0) && (t < 1000)) {
width = static_cast<int>(t);
- }
}
- if ( width < 9 )
- {
+ }
+ if (width < 9) {
width = -1;
- }
+ }
#endif
return width;
}
bool SystemTools::GetPermissions(const char* file, mode_t& mode)
{
- if ( !file )
- {
+ if (!file) {
return false;
- }
+ }
return SystemTools::GetPermissions(std::string(file), mode);
}
@@ -4978,85 +4347,68 @@ bool SystemTools::GetPermissions(const std::string& file, mode_t& mode)
#if defined(_WIN32)
DWORD attr = GetFileAttributesW(
SystemTools::ConvertToWindowsExtendedPath(file).c_str());
- if(attr == INVALID_FILE_ATTRIBUTES)
- {
+ if (attr == INVALID_FILE_ATTRIBUTES) {
return false;
- }
- if((attr & FILE_ATTRIBUTE_READONLY) != 0)
- {
- mode = (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
- }
- else
- {
+ }
+ if ((attr & FILE_ATTRIBUTE_READONLY) != 0) {
+ mode = (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
+ } else {
mode = (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6)) |
- (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
- }
- if((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
- {
- mode |= S_IFDIR | (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
- }
- else
- {
+ (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
+ }
+ if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
+ mode |= S_IFDIR | (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
+ } else {
mode |= S_IFREG;
- }
+ }
size_t dotPos = file.rfind('.');
const char* ext = dotPos == file.npos ? 0 : (file.c_str() + dotPos);
- if(ext && (Strucmp(ext, ".exe") == 0 ||
- Strucmp(ext, ".com") == 0 ||
- Strucmp(ext, ".cmd") == 0 ||
- Strucmp(ext, ".bat") == 0))
- {
- mode |= (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
- }
+ if (ext && (Strucmp(ext, ".exe") == 0 || Strucmp(ext, ".com") == 0 ||
+ Strucmp(ext, ".cmd") == 0 || Strucmp(ext, ".bat") == 0)) {
+ mode |= (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
+ }
#else
struct stat st;
- if ( stat(file.c_str(), &st) < 0 )
- {
+ if (stat(file.c_str(), &st) < 0) {
return false;
- }
+ }
mode = st.st_mode;
#endif
return true;
}
-bool SystemTools::SetPermissions(const char* file,
- mode_t mode,
+bool SystemTools::SetPermissions(const char* file, mode_t mode,
bool honor_umask)
{
- if ( !file )
- {
+ if (!file) {
return false;
- }
- return SystemTools::SetPermissions(
- std::string(file), mode, honor_umask);
+ }
+ return SystemTools::SetPermissions(std::string(file), mode, honor_umask);
}
-bool SystemTools::SetPermissions(const std::string& file,
- mode_t mode,
+bool SystemTools::SetPermissions(const std::string& file, mode_t mode,
bool honor_umask)
{
// TEMPORARY / TODO: After FileExists calls lstat() instead of
// access(), change this call to FileExists instead of
// TestFileAccess so that we don't follow symlinks.
- if ( !SystemTools::TestFileAccess(file, TEST_FILE_OK) )
- {
+ if (!SystemTools::TestFileAccess(file, TEST_FILE_OK)) {
return false;
- }
- if (honor_umask)
- {
+ }
+ if (honor_umask) {
mode_t currentMask = umask(0);
umask(currentMask);
mode &= ~currentMask;
- }
+ }
#ifdef _WIN32
- if ( _wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
- mode) < 0 )
+ if (_wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(), mode) <
+ 0)
#else
- if ( chmod(file.c_str(), mode) < 0 )
+ if (chmod(file.c_str(), mode) < 0)
#endif
- {
+ {
return false;
- }
+ }
return true;
}
@@ -5066,21 +4418,20 @@ std::string SystemTools::GetParentDirectory(const std::string& fileOrDir)
return SystemTools::GetFilenamePath(fileOrDir);
}
-bool SystemTools::IsSubDirectory(const std::string& cSubdir, const std::string& cDir)
+bool SystemTools::IsSubDirectory(const std::string& cSubdir,
+ const std::string& cDir)
{
- if(cDir.empty())
- {
+ if (cDir.empty()) {
return false;
- }
+ }
std::string subdir = cSubdir;
std::string dir = cDir;
SystemTools::ConvertToUnixSlashes(subdir);
SystemTools::ConvertToUnixSlashes(dir);
- if(subdir.size() > dir.size() && subdir[dir.size()] == '/')
- {
+ if (subdir.size() > dir.size() && subdir[dir.size()] == '/') {
std::string s = subdir.substr(0, dir.size());
return SystemTools::ComparePath(s, dir);
- }
+ }
return false;
}
@@ -5096,15 +4447,12 @@ void SystemTools::Delay(unsigned int msec)
// atomically. If select is given empty sets and zero as the max
// file descriptor but a non-zero timeout it can be used to block
// for a precise amount of time.
- if(msec >= 1000)
- {
+ if (msec >= 1000) {
sleep(msec / 1000);
usleep((msec % 1000) * 1000);
- }
- else
- {
+ } else {
usleep(msec * 1000);
- }
+ }
#endif
}
@@ -5122,229 +4470,171 @@ std::string SystemTools::GetOperatingSystemNameAndVersion()
osvi.dwOSVersionInfoSize = sizeof(osvi);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-# pragma warning (disable:1478)
-# else
-# pragma warning (disable:4996)
-# endif
-#endif
- bOsVersionInfoEx = GetVersionExA((OSVERSIONINFOA *)&osvi);
- if (!bOsVersionInfoEx)
- {
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
+#endif
+ bOsVersionInfoEx = GetVersionExA((OSVERSIONINFOA*)&osvi);
+ if (!bOsVersionInfoEx) {
return 0;
- }
+ }
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
#endif
- switch (osvi.dwPlatformId)
- {
+ switch (osvi.dwPlatformId) {
// Test for the Windows NT product family.
case VER_PLATFORM_WIN32_NT:
// Test for the specific product family.
- if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0)
- {
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
+ if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0) {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
res += "Microsoft Windows 10";
- }
- else
- {
+ } else {
res += "Microsoft Windows Server 2016 family";
- }
}
+ }
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3)
- {
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
+ if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3) {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
res += "Microsoft Windows 8.1";
- }
- else
- {
+ } else {
res += "Microsoft Windows Server 2012 R2 family";
- }
}
+ }
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2)
- {
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
+ if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2) {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
res += "Microsoft Windows 8";
- }
- else
- {
+ } else {
res += "Microsoft Windows Server 2012 family";
- }
}
+ }
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
- {
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
+ if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
res += "Microsoft Windows 7";
- }
- else
- {
+ } else {
res += "Microsoft Windows Server 2008 R2 family";
- }
}
+ }
- if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
- {
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
+ if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
res += "Microsoft Windows Vista";
- }
- else
- {
+ } else {
res += "Microsoft Windows Server 2008 family";
- }
}
+ }
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
- {
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
res += "Microsoft Windows Server 2003 family";
- }
+ }
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
- {
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
res += "Microsoft Windows XP";
- }
+ }
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
- {
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
res += "Microsoft Windows 2000";
- }
+ }
- if (osvi.dwMajorVersion <= 4)
- {
+ if (osvi.dwMajorVersion <= 4) {
res += "Microsoft Windows NT";
- }
+ }
// Test for specific product on Windows NT 4.0 SP6 and later.
- if (bOsVersionInfoEx)
- {
+ if (bOsVersionInfoEx) {
// Test for the workstation type.
- if (osvi.wProductType == VER_NT_WORKSTATION)
- {
- if (osvi.dwMajorVersion == 4)
- {
+ if (osvi.wProductType == VER_NT_WORKSTATION) {
+ if (osvi.dwMajorVersion == 4) {
res += " Workstation 4.0";
- }
- else if (osvi.dwMajorVersion == 5)
- {
- if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
- {
+ } else if (osvi.dwMajorVersion == 5) {
+ if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
res += " Home Edition";
- }
- else
- {
+ } else {
res += " Professional";
- }
}
}
+ }
// Test for the server type.
- else if (osvi.wProductType == VER_NT_SERVER)
- {
- if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
- {
- if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
- {
+ else if (osvi.wProductType == VER_NT_SERVER) {
+ if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
+ if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
res += " Datacenter Edition";
- }
- else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
- {
+ } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
res += " Enterprise Edition";
- }
- else if (osvi.wSuiteMask == VER_SUITE_BLADE)
- {
+ } else if (osvi.wSuiteMask == VER_SUITE_BLADE) {
res += " Web Edition";
- }
- else
- {
+ } else {
res += " Standard Edition";
- }
}
+ }
- else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
- {
- if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
- {
+ else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
+ if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
res += " Datacenter Server";
- }
- else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
- {
+ } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
res += " Advanced Server";
- }
- else
- {
+ } else {
res += " Server";
- }
}
+ }
- else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
- {
- if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
- {
+ else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
+ {
+ if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
res += " Server 4.0, Enterprise Edition";
- }
- else
- {
+ } else {
res += " Server 4.0";
- }
}
}
}
+ }
// Test for specific product on Windows NT 4.0 SP5 and earlier
- else
- {
+ else {
HKEY hKey;
- #define BUFSIZE 80
+#define BUFSIZE 80
wchar_t szProductType[BUFSIZE];
- DWORD dwBufLen=BUFSIZE;
+ DWORD dwBufLen = BUFSIZE;
LONG lRet;
- lRet = RegOpenKeyExW(
- HKEY_LOCAL_MACHINE,
- L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
- 0, KEY_QUERY_VALUE, &hKey);
- if (lRet != ERROR_SUCCESS)
- {
+ lRet =
+ RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+ L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
+ 0, KEY_QUERY_VALUE, &hKey);
+ if (lRet != ERROR_SUCCESS) {
return 0;
- }
+ }
lRet = RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
- (LPBYTE) szProductType, &dwBufLen);
+ (LPBYTE)szProductType, &dwBufLen);
- if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
- {
+ if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE)) {
return 0;
- }
+ }
RegCloseKey(hKey);
- if (lstrcmpiW(L"WINNT", szProductType) == 0)
- {
+ if (lstrcmpiW(L"WINNT", szProductType) == 0) {
res += " Workstation";
- }
- if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
- {
+ }
+ if (lstrcmpiW(L"LANMANNT", szProductType) == 0) {
res += " Server";
- }
- if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
- {
+ }
+ if (lstrcmpiW(L"SERVERNT", szProductType) == 0) {
res += " Advanced Server";
- }
+ }
res += " ";
sprintf(buffer, "%ld", osvi.dwMajorVersion);
@@ -5352,13 +4642,12 @@ std::string SystemTools::GetOperatingSystemNameAndVersion()
res += ".";
sprintf(buffer, "%ld", osvi.dwMinorVersion);
res += buffer;
- }
+ }
// Display service pack (if any) and build number.
if (osvi.dwMajorVersion == 4 &&
- lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0)
- {
+ lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0) {
HKEY hKey;
LONG lRet;
@@ -5369,104 +4658,95 @@ std::string SystemTools::GetOperatingSystemNameAndVersion()
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
0, KEY_QUERY_VALUE, &hKey);
- if (lRet == ERROR_SUCCESS)
- {
+ if (lRet == ERROR_SUCCESS) {
res += " Service Pack 6a (Build ";
sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
res += buffer;
res += ")";
- }
- else // Windows NT 4.0 prior to SP6a
- {
+ } else // Windows NT 4.0 prior to SP6a
+ {
res += " ";
res += osvi.szCSDVersion;
res += " (Build ";
sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
res += buffer;
res += ")";
- }
+ }
RegCloseKey(hKey);
- }
- else // Windows NT 3.51 and earlier or Windows 2000 and later
- {
+ } else // Windows NT 3.51 and earlier or Windows 2000 and later
+ {
res += " ";
res += osvi.szCSDVersion;
res += " (Build ";
sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
res += buffer;
res += ")";
- }
+ }
break;
- // Test for the Windows 95 product family.
+ // Test for the Windows 95 product family.
case VER_PLATFORM_WIN32_WINDOWS:
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
- {
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
res += "Microsoft Windows 95";
- if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
- {
+ if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') {
res += " OSR2";
- }
}
+ }
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
- {
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
res += "Microsoft Windows 98";
- if (osvi.szCSDVersion[1] == 'A')
- {
+ if (osvi.szCSDVersion[1] == 'A') {
res += " SE";
- }
}
+ }
- if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
- {
+ if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) {
res += "Microsoft Windows Millennium Edition";
- }
+ }
break;
case VER_PLATFORM_WIN32s:
- res += "Microsoft Win32s";
+ res += "Microsoft Win32s";
break;
- }
+ }
#endif
return res;
}
// ----------------------------------------------------------------------
-bool SystemTools::ParseURLProtocol( const std::string& URL,
- std::string& protocol,
- std::string& dataglom )
+bool SystemTools::ParseURLProtocol(const std::string& URL,
+ std::string& protocol,
+ std::string& dataglom)
{
// match 0 entire url
// match 1 protocol
// match 2 dataglom following protocol://
- kwsys::RegularExpression urlRe( VTK_URL_PROTOCOL_REGEX );
+ kwsys::RegularExpression urlRe(VTK_URL_PROTOCOL_REGEX);
- if ( ! urlRe.find( URL ) ) return false;
+ if (!urlRe.find(URL))
+ return false;
- protocol = urlRe.match( 1 );
- dataglom = urlRe.match( 2 );
+ protocol = urlRe.match(1);
+ dataglom = urlRe.match(2);
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 )
+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)
{
- kwsys::RegularExpression urlRe( VTK_URL_REGEX );
- if ( ! urlRe.find( URL ) ) return false;
+ kwsys::RegularExpression urlRe(VTK_URL_REGEX);
+ if (!urlRe.find(URL))
+ return false;
// match 0 URL
// match 1 protocol
@@ -5479,12 +4759,12 @@ bool SystemTools::ParseURL( const std::string& URL,
// match 8 dataport
// match 9 database name
- protocol = urlRe.match( 1 );
- username = urlRe.match( 3 );
- password = urlRe.match( 5 );
- hostname = urlRe.match( 6 );
- dataport = urlRe.match( 8 );
- database = urlRe.match( 9 );
+ protocol = urlRe.match(1);
+ username = urlRe.match(3);
+ password = urlRe.match(5);
+ hostname = urlRe.match(6);
+ dataport = urlRe.match(8);
+ database = urlRe.match(9);
return true;
}
@@ -5493,13 +4773,13 @@ bool SystemTools::ParseURL( const std::string& URL,
// These must NOT be initialized. Default initialization to zero is
// necessary.
static unsigned int SystemToolsManagerCount;
-SystemToolsTranslationMap *SystemTools::TranslationMap;
+SystemToolsTranslationMap* SystemTools::TranslationMap;
#ifdef _WIN32
-SystemToolsPathCaseMap *SystemTools::PathCaseMap;
-SystemToolsEnvMap *SystemTools::EnvMap;
+SystemToolsPathCaseMap* SystemTools::PathCaseMap;
+SystemToolsEnvMap* SystemTools::EnvMap;
#endif
#ifdef __CYGWIN__
-SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
+SystemToolsTranslationMap* SystemTools::Cyg2Win32Map;
#endif
// SystemToolsManager manages the SystemTools singleton.
@@ -5510,24 +4790,22 @@ SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
SystemToolsManager::SystemToolsManager()
{
- if(++SystemToolsManagerCount == 1)
- {
+ if (++SystemToolsManagerCount == 1) {
SystemTools::ClassInitialize();
- }
+ }
}
SystemToolsManager::~SystemToolsManager()
{
- if(--SystemToolsManagerCount == 0)
- {
+ if (--SystemToolsManagerCount == 0) {
SystemTools::ClassFinalize();
- }
+ }
}
#if defined(__VMS)
// On VMS we configure the run time C library to be more UNIX like.
// http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html
-extern "C" int decc$feature_get_index(char *name);
+extern "C" int decc$feature_get_index(char* name);
extern "C" int decc$feature_set_value(int index, int mode, int value);
static int SetVMSFeature(char* name, int value)
{
@@ -5553,9 +4831,9 @@ void SystemTools::ClassInitialize()
SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
#endif
- // Add some special translation paths for unix. These are not added
- // for windows because drive letters need to be maintained. Also,
- // there are not sym-links and mount points on windows anyway.
+// Add some special translation paths for unix. These are not added
+// for windows because drive letters need to be maintained. Also,
+// there are not sym-links and mount points on windows anyway.
#if !defined(_WIN32) || defined(__CYGWIN__)
// The tmp path is frequently a logical path so always keep it:
SystemTools::AddKeepPath("/tmp/");
@@ -5563,11 +4841,9 @@ void SystemTools::ClassInitialize()
// If the current working directory is a logical path then keep the
// logical name.
std::string pwd_str;
- if(SystemTools::GetEnv("PWD", pwd_str))
- {
+ if (SystemTools::GetEnv("PWD", pwd_str)) {
char buf[2048];
- if(const char* cwd = Getcwd(buf, 2048))
- {
+ if (const char* cwd = Getcwd(buf, 2048)) {
// The current working directory may be a logical path. Find
// the shortest logical path that still produces the correct
// physical path.
@@ -5578,8 +4854,7 @@ void SystemTools::ClassInitialize()
std::string cwd_str = cwd;
std::string pwd_path;
Realpath(pwd_str.c_str(), pwd_path);
- while(cwd_str == pwd_path && cwd_str != pwd_str)
- {
+ while (cwd_str == pwd_path && cwd_str != pwd_str) {
// The current pair of paths is a working logical mapping.
cwd_changed = cwd_str;
pwd_changed = pwd_str;
@@ -5589,16 +4864,14 @@ void SystemTools::ClassInitialize()
pwd_str = SystemTools::GetFilenamePath(pwd_str);
cwd_str = SystemTools::GetFilenamePath(cwd_str);
Realpath(pwd_str.c_str(), pwd_path);
- }
+ }
// Add the translation to keep the logical path name.
- if(!cwd_changed.empty() && !pwd_changed.empty())
- {
- SystemTools::AddTranslationPath(cwd_changed,
- pwd_changed);
- }
+ if (!cwd_changed.empty() && !pwd_changed.empty()) {
+ SystemTools::AddTranslationPath(cwd_changed, pwd_changed);
}
}
+ }
#endif
}
@@ -5614,15 +4887,13 @@ void SystemTools::ClassFinalize()
#endif
}
-
} // namespace KWSYS_NAMESPACE
#if defined(_MSC_VER) && defined(_DEBUG)
-# include <crtdbg.h>
-# include <stdio.h>
-# include <stdlib.h>
-namespace KWSYS_NAMESPACE
-{
+#include <crtdbg.h>
+#include <stdio.h>
+#include <stdlib.h>
+namespace KWSYS_NAMESPACE {
static int SystemToolsDebugReport(int, char* message, int*)
{
@@ -5634,16 +4905,16 @@ static int SystemToolsDebugReport(int, char* message, int*)
void SystemTools::EnableMSVCDebugHook()
{
if (SystemTools::HasEnv("DART_TEST_FROM_DART") ||
- SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST"))
- {
+ SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST")) {
_CrtSetReportHook(SystemToolsDebugReport);
- }
+ }
}
} // namespace KWSYS_NAMESPACE
#else
-namespace KWSYS_NAMESPACE
+namespace KWSYS_NAMESPACE {
+void SystemTools::EnableMSVCDebugHook()
{
-void SystemTools::EnableMSVCDebugHook() {}
+}
} // namespace KWSYS_NAMESPACE
#endif
diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in
index 5849145..f3d06fe 100644
--- a/Source/kwsys/SystemTools.hxx.in
+++ b/Source/kwsys/SystemTools.hxx.in
@@ -1,29 +1,20 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_SystemTools_hxx
#define @KWSYS_NAMESPACE@_SystemTools_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#include <iosfwd>
+#include <map>
#include <string>
#include <vector>
-#include <map>
#include <@KWSYS_NAMESPACE@/String.hxx>
#include <sys/types.h>
#if !defined(_WIN32) || defined(__CYGWIN__)
-# include <unistd.h> // For access permissions for use with access()
+#include <unistd.h> // For access permissions for use with access()
#endif
// Required for va_list
@@ -36,20 +27,18 @@
// after stdarg.h does not solve things because we do not have control over
// what the user does. This hack solves this problem by moving va_list to our
// own namespace that is local for kwsys.
-namespace std {} // Required for platforms that do not have std namespace
-namespace @KWSYS_NAMESPACE@_VA_LIST
-{
- using namespace std;
- typedef va_list hack_va_list;
+namespace std {
+} // Required for platforms that do not have std namespace
+namespace @KWSYS_NAMESPACE@_VA_LIST {
+using namespace std;
+typedef va_list hack_va_list;
}
-namespace @KWSYS_NAMESPACE@
-{
- typedef @KWSYS_NAMESPACE@_VA_LIST::hack_va_list va_list;
+namespace @KWSYS_NAMESPACE@ {
+typedef @KWSYS_NAMESPACE@_VA_LIST::hack_va_list va_list;
}
#endif // va_list
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
class SystemToolsTranslationMap;
class SystemToolsPathCaseMap;
@@ -76,17 +65,17 @@ static SystemToolsManager SystemToolsManagerInstance;
// combined using the | operator.
typedef int TestFilePermissions;
#if defined(_WIN32) && !defined(__CYGWIN__)
- // On Windows (VC and Borland), no system header defines these constants...
- static const TestFilePermissions TEST_FILE_OK = 0;
- static const TestFilePermissions TEST_FILE_READ = 4;
- static const TestFilePermissions TEST_FILE_WRITE = 2;
- static const TestFilePermissions TEST_FILE_EXECUTE = 1;
+// On Windows (VC and Borland), no system header defines these constants...
+static const TestFilePermissions TEST_FILE_OK = 0;
+static const TestFilePermissions TEST_FILE_READ = 4;
+static const TestFilePermissions TEST_FILE_WRITE = 2;
+static const TestFilePermissions TEST_FILE_EXECUTE = 1;
#else
- // Standard POSIX constants
- static const TestFilePermissions TEST_FILE_OK = F_OK;
- static const TestFilePermissions TEST_FILE_READ = R_OK;
- static const TestFilePermissions TEST_FILE_WRITE = W_OK;
- static const TestFilePermissions TEST_FILE_EXECUTE = X_OK;
+// Standard POSIX constants
+static const TestFilePermissions TEST_FILE_OK = F_OK;
+static const TestFilePermissions TEST_FILE_READ = R_OK;
+static const TestFilePermissions TEST_FILE_WRITE = W_OK;
+static const TestFilePermissions TEST_FILE_EXECUTE = X_OK;
#endif
/** \class SystemTools
@@ -95,7 +84,6 @@ typedef int TestFilePermissions;
class @KWSYS_NAMESPACE@_EXPORT SystemTools
{
public:
-
/** -----------------------------------------------------------------
* String Manipulation Routines
* -----------------------------------------------------------------
@@ -118,11 +106,9 @@ public:
/**
* Replace replace all occurences of the string in the source string.
*/
- static void ReplaceString(std::string& source,
- const char* replace,
+ static void ReplaceString(std::string& source, const char* replace,
const char* with);
- static void ReplaceString(std::string& source,
- const std::string& replace,
+ static void ReplaceString(std::string& source, const std::string& replace,
const std::string& with);
/**
@@ -162,7 +148,7 @@ public:
* Remove some characters from a string.
* Return a pointer to the new resulting string (allocated with 'new')
*/
- static char* RemoveChars(const char* str, const char *toremove);
+ static char* RemoveChars(const char* str, const char* toremove);
/**
* Remove remove all but 0->9, A->F characters from a string.
@@ -174,7 +160,8 @@ public:
* Replace some characters by another character in a string (in-place)
* Return a pointer to string
*/
- static char* ReplaceChars(char* str, const char *toreplace,char replacement);
+ static char* ReplaceChars(char* str, const char* toreplace,
+ char replacement);
/**
* Returns true if str1 starts (respectively ends) with str2
@@ -200,41 +187,42 @@ public:
* Return the string cropped to a given length by removing chars in the
* center of the string and replacing them with an ellipsis (...)
*/
- static std::string CropString(const std::string&,size_t max_len);
+ static std::string CropString(const std::string&, size_t max_len);
/** split a path by separator into an array of strings, default is /.
If isPath is true then the string is treated like a path and if
s starts with a / then the first element of the returned array will
be /, so /foo/bar will be [/, foo, bar]
*/
- static std::vector<String> SplitString(const std::string& s, char separator = '/',
- bool isPath = false);
+ static std::vector<String> SplitString(const std::string& s,
+ char separator = '/',
+ bool isPath = false);
/**
* Perform a case-independent string comparison
*/
- static int Strucmp(const char *s1, const char *s2);
+ static int Strucmp(const char* s1, const char* s2);
/**
* Convert a string in __DATE__ or __TIMESTAMP__ format into a time_t.
* Return false on error, true on success
*/
- static bool ConvertDateMacroString(const char *str, time_t *tmt);
- static bool ConvertTimeStampMacroString(const char *str, time_t *tmt);
+ static bool ConvertDateMacroString(const char* str, time_t* tmt);
+ static bool ConvertTimeStampMacroString(const char* str, time_t* tmt);
/**
* Split a string on its newlines into multiple lines
* Return false only if the last line stored had no newline
*/
static bool Split(const std::string& s, std::vector<std::string>& l);
- static bool Split(const std::string& s, std::vector<std::string>& l, char separator);
+ static bool Split(const std::string& s, std::vector<std::string>& l,
+ char separator);
/**
* Return string with space added between capitalized words
* (i.e. EatMyShorts becomes Eat My Shorts )
* (note that IEatShorts becomes IEat Shorts)
*/
- static std::string AddSpaceBetweenCapitalizedWords(
- const std::string&);
+ static std::string AddSpaceBetweenCapitalizedWords(const std::string&);
/**
* Append two or more strings and produce new one.
@@ -242,10 +230,9 @@ public:
* with 'new'.
* Return 0 if inputs are empty or there was an error
*/
- static char* AppendStrings(
- const char* str1, const char* str2);
- static char* AppendStrings(
- const char* str1, const char* str2, const char* str3);
+ static char* AppendStrings(const char* str1, const char* str2);
+ static char* AppendStrings(const char* str1, const char* str2,
+ const char* str3);
/**
* Estimate the length of the string that will be produced
@@ -256,13 +243,13 @@ public:
* you will not be able to use this 'ap' anymore from the beginning.
* It's up to you to call va_end though.
*/
- static int EstimateFormatLength(const char *format, va_list ap);
+ static int EstimateFormatLength(const char* format, va_list ap);
/**
* Escape specific characters in 'str'.
*/
- static std::string EscapeChars(
- const char *str, const char *chars_to_escape, char escape_char = '\\');
+ static std::string EscapeChars(const char* str, const char* chars_to_escape,
+ char escape_char = '\\');
/** -----------------------------------------------------------------
* Filename Manipulation Routines
@@ -338,13 +325,13 @@ public:
static bool TestFileAccess(const std::string& filename,
TestFilePermissions permissions);
- /**
- * Converts Cygwin path to Win32 path. Uses dictionary container for
- * caching and calls to cygwin_conv_to_win32_path from Cygwin dll
- * for actual translation. Returns true on success, else false.
- */
+/**
+ * Converts Cygwin path to Win32 path. Uses dictionary container for
+ * caching and calls to cygwin_conv_to_win32_path from Cygwin dll
+ * for actual translation. Returns true on success, else false.
+ */
#ifdef __CYGWIN__
- static bool PathCygwinToWin32(const char *path, char *win32_path);
+ static bool PathCygwinToWin32(const char* path, char* win32_path);
#endif
/**
@@ -363,8 +350,7 @@ public:
* When true is returned, result has -1, 0, +1 for
* f1 older, same, or newer than f2.
*/
- static bool FileTimeCompare(const std::string& f1,
- const std::string& f2,
+ static bool FileTimeCompare(const std::string& f1, const std::string& f2,
int* result);
/**
@@ -388,10 +374,8 @@ public:
* part, the empty string is returned.
*/
static std::string GetProgramPath(const std::string&);
- static bool SplitProgramPath(const std::string& in_name,
- std::string& dir,
- std::string& file,
- bool errorReport = true);
+ static bool SplitProgramPath(const std::string& in_name, std::string& dir,
+ std::string& file, bool errorReport = true);
/**
* Given argv[0] for a unix program find the full path to a running
@@ -405,10 +389,8 @@ public:
* buildDir is a possibly null path to the build directory.
* installPrefix is a possibly null pointer to the install directory.
*/
- static bool FindProgramPath(const char* argv0,
- std::string& pathOut,
- std::string& errorMsg,
- const char* exeName = 0,
+ static bool FindProgramPath(const char* argv0, std::string& pathOut,
+ std::string& errorMsg, const char* exeName = 0,
const char* buildDir = 0,
const char* installPrefix = 0);
@@ -420,9 +402,9 @@ public:
*/
static std::string CollapseFullPath(const std::string& in_relative);
static std::string CollapseFullPath(const std::string& in_relative,
- const char* in_base);
+ const char* in_base);
static std::string CollapseFullPath(const std::string& in_relative,
- const std::string& in_base);
+ const std::string& in_base);
/**
* Get the real path for a given path, removing all symlinks. In
@@ -432,7 +414,7 @@ public:
* contains error description.
*/
static std::string GetRealPath(const std::string& path,
- std::string* errorMessage = 0);
+ std::string* errorMessage = 0);
/**
* Split a path name into its root component and the rest of the
@@ -450,7 +432,7 @@ public:
* given.
*/
static const char* SplitPathRootComponent(const std::string& p,
- std::string* root=0);
+ std::string* root = 0);
/**
* Split a path name into its basic components. The first component
@@ -470,18 +452,15 @@ public:
* Join components of a path name into a single string. See
* SplitPath for the format of the components.
*/
- static std::string JoinPath(
- const std::vector<std::string>& components);
- static std::string JoinPath(
- std::vector<std::string>::const_iterator first,
- std::vector<std::string>::const_iterator last);
+ static std::string JoinPath(const std::vector<std::string>& components);
+ static std::string JoinPath(std::vector<std::string>::const_iterator first,
+ std::vector<std::string>::const_iterator last);
/**
* Compare a path or components of a path.
*/
static bool ComparePath(const std::string& c1, const std::string& c2);
-
/**
* Return path of a full filename (no trailing slashes)
*/
@@ -495,9 +474,8 @@ public:
/**
* Split a program from its arguments and handle spaces in the paths
*/
- static void SplitProgramFromArgs(
- const std::string& path,
- std::string& program, std::string& args);
+ static void SplitProgramFromArgs(const std::string& path,
+ std::string& program, std::string& args);
/**
* Return longest file extension of a full filename (dot included)
@@ -507,20 +485,17 @@ public:
/**
* Return shortest file extension of a full filename (dot included)
*/
- static std::string GetFilenameLastExtension(
- const std::string& filename);
+ static std::string GetFilenameLastExtension(const std::string& filename);
/**
* Return file name without extension of a full filename
*/
- static std::string GetFilenameWithoutExtension(
- const std::string&);
+ static std::string GetFilenameWithoutExtension(const std::string&);
/**
* Return file name without its last (shortest) extension
*/
- static std::string GetFilenameWithoutLastExtension(
- const std::string&);
+ static std::string GetFilenameWithoutLastExtension(const std::string&);
/**
* Return whether the path represents a full path (not relative)
@@ -541,10 +516,8 @@ public:
* end-of-file was reached. If the has_newline argument is specified, it will
* be true when the line read had a newline character.
*/
- static bool GetLineFromStream(std::istream& istr,
- std::string& line,
- bool* has_newline=0,
- long sizeLimit=-1);
+ static bool GetLineFromStream(std::istream& istr, std::string& line,
+ bool* has_newline = 0, long sizeLimit = -1);
/**
* Get the parent directory of the directory or file
@@ -554,7 +527,8 @@ public:
/**
* Check if the given file or directory is in subdirectory of dir
*/
- static bool IsSubDirectory(const std::string& fileOrDir, const std::string& dir);
+ static bool IsSubDirectory(const std::string& fileOrDir,
+ const std::string& dir);
/** -----------------------------------------------------------------
* File Manipulation Routines
@@ -584,7 +558,8 @@ public:
/**
* Compare the contents of two files. Return true if different
*/
- static bool FilesDiffer(const std::string& source, const std::string& destination);
+ static bool FilesDiffer(const std::string& source,
+ const std::string& destination);
/**
* Return true if the two files are the same file
@@ -594,15 +569,16 @@ public:
/**
* Copy a file.
*/
- static bool CopyFileAlways(const std::string& source, const std::string& destination);
+ static bool CopyFileAlways(const std::string& source,
+ const std::string& destination);
/**
* Copy a file. If the "always" argument is true the file is always
* copied. If it is false, the file is copied only if it is new or
* has changed.
*/
- static bool CopyAFile(const std::string& source, const std::string& destination,
- bool always = true);
+ static bool CopyAFile(const std::string& source,
+ const std::string& destination, bool always = true);
/**
* Copy content directory to another directory with all files and
@@ -610,7 +586,8 @@ public:
* always copied. If it is false, only files that have changed or
* are new are copied.
*/
- static bool CopyADirectory(const std::string& source, const std::string& destination,
+ static bool CopyADirectory(const std::string& source,
+ const std::string& destination,
bool always = true);
/**
@@ -633,8 +610,7 @@ public:
*/
static std::string FindFile(
const std::string& name,
- const std::vector<std::string>& path =
- std::vector<std::string>(),
+ const std::vector<std::string>& path = std::vector<std::string>(),
bool no_system_path = false);
/**
@@ -642,8 +618,7 @@ public:
*/
static std::string FindDirectory(
const std::string& name,
- const std::vector<std::string>& path =
- std::vector<std::string>(),
+ const std::vector<std::string>& path = std::vector<std::string>(),
bool no_system_path = false);
/**
@@ -651,26 +626,22 @@ public:
*/
static std::string FindProgram(
const char* name,
- const std::vector<std::string>& path =
- std::vector<std::string>(),
+ const std::vector<std::string>& path = std::vector<std::string>(),
bool no_system_path = false);
static std::string FindProgram(
const std::string& name,
- const std::vector<std::string>& path =
- std::vector<std::string>(),
+ const std::vector<std::string>& path = std::vector<std::string>(),
bool no_system_path = false);
static std::string FindProgram(
const std::vector<std::string>& names,
- const std::vector<std::string>& path =
- std::vector<std::string>(),
+ const std::vector<std::string>& path = std::vector<std::string>(),
bool no_system_path = false);
/**
* Find a library in the system PATH, with optional extra paths
*/
- static std::string FindLibrary(
- const std::string& name,
- const std::vector<std::string>& path);
+ static std::string FindLibrary(const std::string& name,
+ const std::vector<std::string>& path);
/**
* Return true if the file is a directory
@@ -685,8 +656,8 @@ public:
/**
* Return true if the file has a given signature (first set of bytes)
*/
- static bool FileHasSignature(
- const char* filename, const char *signature, long offset = 0);
+ static bool FileHasSignature(const char* filename, const char* signature,
+ long offset = 0);
/**
* Attempt to detect and return the type of a file.
@@ -703,16 +674,16 @@ public:
FileTypeBinary,
FileTypeText
};
- static SystemTools::FileTypeEnum DetectFileType(
- const char* filename,
- unsigned long length = 256,
- double percent_bin = 0.05);
+ static SystemTools::FileTypeEnum DetectFileType(const char* filename,
+ unsigned long length = 256,
+ double percent_bin = 0.05);
/**
* Create a symbolic link if the platform supports it. Returns whether
* creation succeeded.
*/
- static bool CreateSymlink(const std::string& origName, const std::string& newName);
+ static bool CreateSymlink(const std::string& origName,
+ const std::string& newName);
/**
* Read the contents of a symbolic link. Returns whether reading
@@ -735,8 +706,7 @@ public:
* etc.
* Return true if the file was found, false otherwise.
*/
- static bool LocateFileInDir(const char *filename,
- const char *dir,
+ static bool LocateFileInDir(const char* filename, const char* dir,
std::string& filename_found,
int try_filename_dirs = 0);
@@ -748,7 +718,8 @@ public:
/a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
*/
- static std::string RelativePath(const std::string& local, const std::string& remote);
+ static std::string RelativePath(const std::string& local,
+ const std::string& remote);
/**
* Return file's modified time
@@ -760,12 +731,12 @@ public:
*/
static long int CreationTime(const std::string& filename);
- /**
- * Visual C++ does not define mode_t (note that Borland does, however).
- */
- #if defined( _MSC_VER )
+/**
+ * Visual C++ does not define mode_t (note that Borland does, however).
+ */
+#if defined(_MSC_VER)
typedef unsigned short mode_t;
- #endif
+#endif
/**
* Get and set permissions of the file. If honor_umask is set, the umask
@@ -777,8 +748,10 @@ public:
*/
static bool GetPermissions(const char* file, mode_t& mode);
static bool GetPermissions(const std::string& file, mode_t& mode);
- static bool SetPermissions(const char* file, mode_t mode, bool honor_umask = false);
- static bool SetPermissions(const std::string& file, mode_t mode, bool honor_umask = false);
+ static bool SetPermissions(const char* file, mode_t mode,
+ bool honor_umask = false);
+ static bool SetPermissions(const std::string& file, mode_t mode,
+ bool honor_umask = false);
/** -----------------------------------------------------------------
* Time Manipulation Routines
@@ -803,7 +776,12 @@ public:
* registry values. The default is to match the currently running
* binary type.
*/
- enum KeyWOW64 { KeyWOW64_Default, KeyWOW64_32, KeyWOW64_64 };
+ enum KeyWOW64
+ {
+ KeyWOW64_Default,
+ KeyWOW64_32,
+ KeyWOW64_64
+ };
/**
* Get a list of subkeys.
@@ -815,13 +793,14 @@ public:
/**
* Read a registry value
*/
- static bool ReadRegistryValue(const std::string& key, std::string &value,
+ static bool ReadRegistryValue(const std::string& key, std::string& value,
KeyWOW64 view = KeyWOW64_Default);
/**
* Write a registry value
*/
- static bool WriteRegistryValue(const std::string& key, const std::string& value,
+ static bool WriteRegistryValue(const std::string& key,
+ const std::string& value,
KeyWOW64 view = KeyWOW64_Default);
/**
@@ -840,8 +819,7 @@ public:
* string vector passed in. If env is set then the value
* of env will be used instead of PATH.
*/
- static void GetPath(std::vector<std::string>& path,
- const char* env=0);
+ static void GetPath(std::vector<std::string>& path, const char* env = 0);
/**
* Read an environment variable
@@ -864,7 +842,7 @@ public:
/**
* Get current working directory CWD
*/
- static std::string GetCurrentWorkingDirectory(bool collapse =true);
+ static std::string GetCurrentWorkingDirectory(bool collapse = true);
/**
* Change directory to the directory specified
@@ -893,7 +871,8 @@ public:
/**
* Add an entry in the path translation table.
*/
- static void AddTranslationPath(const std::string& dir, const std::string& refdir);
+ static void AddTranslationPath(const std::string& dir,
+ const std::string& refdir);
/**
* If dir is different after CollapseFullPath is called,
@@ -904,7 +883,7 @@ public:
/**
* Update path by going through the Path Translation table;
*/
- static void CheckTranslationPath(std::string & path);
+ static void CheckTranslationPath(std::string& path);
/**
* Delay the execution for a specified amount of time specified
@@ -929,9 +908,8 @@ public:
* and fill protocol as appropriate.
* 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 );
+ static bool ParseURLProtocol(const std::string& URL, std::string& protocol,
+ std::string& dataglom);
/**
* Parse a string (a URL without protocol prefix) with the form:
@@ -940,13 +918,10 @@ public:
* when values are found.
* 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 );
+ 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);
private:
/**
@@ -963,17 +938,15 @@ private:
* This method prevents warning on SGI
*/
SystemToolsManager* GetSystemToolsManager()
- {
+ {
return &SystemToolsManagerInstance;
- }
+ }
/**
* Actual implementation of ReplaceString.
*/
- static void ReplaceString(std::string& source,
- const char* replace,
- size_t replaceSize,
- const std::string& with);
+ static void ReplaceString(std::string& source, const char* replace,
+ size_t replaceSize, const std::string& with);
/**
* Actual implementation of FileIsFullPath.
@@ -986,8 +959,7 @@ private:
*/
static std::string FindName(
const std::string& name,
- const std::vector<std::string>& path =
- std::vector<std::string>(),
+ const std::vector<std::string>& path = std::vector<std::string>(),
bool no_system_path = false);
static const char* GetEnvImpl(const char* key);
@@ -996,13 +968,13 @@ private:
* Path translation table from dir to refdir
* Each time 'dir' will be found it will be replace by 'refdir'
*/
- static SystemToolsTranslationMap *TranslationMap;
+ static SystemToolsTranslationMap* TranslationMap;
#ifdef _WIN32
- static SystemToolsPathCaseMap *PathCaseMap;
- static SystemToolsEnvMap *EnvMap;
+ static SystemToolsPathCaseMap* PathCaseMap;
+ static SystemToolsEnvMap* EnvMap;
#endif
#ifdef __CYGWIN__
- static SystemToolsTranslationMap *Cyg2Win32Map;
+ static SystemToolsTranslationMap* Cyg2Win32Map;
#endif
friend class SystemToolsManager;
};
diff --git a/Source/kwsys/Terminal.c b/Source/kwsys/Terminal.c
index a8abb6c..c0b7f45 100644
--- a/Source/kwsys/Terminal.c
+++ b/Source/kwsys/Terminal.c
@@ -1,48 +1,39 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Terminal.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Terminal.h.in"
+#include "Terminal.h.in"
#endif
/*--------------------------------------------------------------------------*/
/* Configure support for this platform. */
#if defined(_WIN32) || defined(__CYGWIN__)
-# define KWSYS_TERMINAL_SUPPORT_CONSOLE
+#define KWSYS_TERMINAL_SUPPORT_CONSOLE
#endif
#if !defined(_WIN32)
-# define KWSYS_TERMINAL_ISATTY_WORKS
+#define KWSYS_TERMINAL_ISATTY_WORKS
#endif
/*--------------------------------------------------------------------------*/
/* Include needed system APIs. */
+#include <stdarg.h> /* va_list */
#include <stdlib.h> /* getenv */
#include <string.h> /* strcmp */
-#include <stdarg.h> /* va_list */
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
-# include <windows.h> /* SetConsoleTextAttribute */
-# include <io.h> /* _get_osfhandle */
+#include <io.h> /* _get_osfhandle */
+#include <windows.h> /* SetConsoleTextAttribute */
#endif
#if defined(KWSYS_TERMINAL_ISATTY_WORKS)
-# include <unistd.h> /* isatty */
+#include <unistd.h> /* isatty */
#else
-# include <sys/stat.h> /* fstat */
+#include <sys/stat.h> /* fstat */
#endif
/*--------------------------------------------------------------------------*/
@@ -53,8 +44,7 @@ static void kwsysTerminalSetVT100Color(FILE* stream, int color);
static HANDLE kwsysTerminalGetStreamHandle(FILE* stream);
static void kwsysTerminalSetConsoleColor(HANDLE hOut,
CONSOLE_SCREEN_BUFFER_INFO* hOutInfo,
- FILE* stream,
- int color);
+ FILE* stream, int color);
#endif
/*--------------------------------------------------------------------------*/
@@ -68,39 +58,35 @@ void kwsysTerminal_cfprintf(int color, FILE* stream, const char* format, ...)
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
HANDLE hOut = kwsysTerminalGetStreamHandle(stream);
- if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
- {
+ if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
pipeIsConsole = 1;
kwsysTerminalSetConsoleColor(hOut, &hOutInfo, stream, color);
- }
+ }
#endif
- if(!pipeIsConsole && kwsysTerminalStreamIsVT100(stream,
- default_vt100, default_tty))
- {
+ if (!pipeIsConsole &&
+ kwsysTerminalStreamIsVT100(stream, default_vt100, default_tty)) {
pipeIsVT100 = 1;
kwsysTerminalSetVT100Color(stream, color);
- }
+ }
/* Format the text into the stream. */
{
- va_list var_args;
- va_start(var_args, format);
- vfprintf(stream, format, var_args);
- va_end(var_args);
+ va_list var_args;
+ va_start(var_args, format);
+ vfprintf(stream, format, var_args);
+ va_end(var_args);
}
- /* Restore the normal color state for the stream. */
+/* Restore the normal color state for the stream. */
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
- if(pipeIsConsole)
- {
+ if (pipeIsConsole) {
kwsysTerminalSetConsoleColor(hOut, &hOutInfo, stream,
kwsysTerminal_Color_Normal);
- }
+ }
#endif
- if(pipeIsVT100)
- {
+ if (pipeIsVT100) {
kwsysTerminalSetVT100Color(stream, kwsysTerminal_Color_Normal);
- }
+ }
}
/*--------------------------------------------------------------------------*/
@@ -111,73 +97,70 @@ static int kwsysTerminalStreamIsNotInteractive(FILE* stream)
/* The given stream is definitely not interactive if it is a regular
file. */
struct stat stream_stat;
- if(fstat(fileno(stream), &stream_stat) == 0)
- {
- if(stream_stat.st_mode & S_IFREG)
- {
+ if (fstat(fileno(stream), &stream_stat) == 0) {
+ if (stream_stat.st_mode & S_IFREG) {
return 1;
- }
}
+ }
return 0;
}
#endif
/*--------------------------------------------------------------------------*/
/* List of terminal names known to support VT100 color escape sequences. */
-static const char* kwsysTerminalVT100Names[] =
-{
- "Eterm",
- "ansi",
- "color-xterm",
- "con132x25",
- "con132x30",
- "con132x43",
- "con132x60",
- "con80x25",
- "con80x28",
- "con80x30",
- "con80x43",
- "con80x50",
- "con80x60",
- "cons25",
- "console",
- "cygwin",
- "dtterm",
- "eterm-color",
- "gnome",
- "gnome-256color",
- "konsole",
- "konsole-256color",
- "kterm",
- "linux",
- "msys",
- "linux-c",
- "mach-color",
- "mlterm",
- "putty",
- "putty-256color",
- "rxvt",
- "rxvt-256color",
- "rxvt-cygwin",
- "rxvt-cygwin-native",
- "rxvt-unicode",
- "rxvt-unicode-256color",
- "screen",
- "screen-256color",
- "screen-256color-bce",
- "screen-bce",
- "screen-w",
- "screen.linux",
- "vt100",
- "xterm",
- "xterm-16color",
- "xterm-256color",
- "xterm-88color",
- "xterm-color",
- "xterm-debian",
- "xterm-termite",
- 0
-};
+static const char* kwsysTerminalVT100Names[] = { "Eterm",
+ "ansi",
+ "color-xterm",
+ "con132x25",
+ "con132x30",
+ "con132x43",
+ "con132x60",
+ "con80x25",
+ "con80x28",
+ "con80x30",
+ "con80x43",
+ "con80x50",
+ "con80x60",
+ "cons25",
+ "console",
+ "cygwin",
+ "dtterm",
+ "eterm-color",
+ "gnome",
+ "gnome-256color",
+ "konsole",
+ "konsole-256color",
+ "kterm",
+ "linux",
+ "msys",
+ "linux-c",
+ "mach-color",
+ "mlterm",
+ "putty",
+ "putty-256color",
+ "rxvt",
+ "rxvt-256color",
+ "rxvt-cygwin",
+ "rxvt-cygwin-native",
+ "rxvt-unicode",
+ "rxvt-unicode-256color",
+ "screen",
+ "screen-256color",
+ "screen-256color-bce",
+ "screen-bce",
+ "screen-w",
+ "screen.linux",
+ "tmux",
+ "tmux-256color",
+ "vt100",
+ "xterm",
+ "xterm-16color",
+ "xterm-256color",
+ "xterm-88color",
+ "xterm-color",
+ "xterm-debian",
+ "xterm-termite",
+ 0 };
/*--------------------------------------------------------------------------*/
/* Detect whether a stream is displayed in a VT100-compatible terminal. */
@@ -186,10 +169,10 @@ static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
{
/* Force color according to http://bixense.com/clicolors/ convention. */
{
- const char* clicolor_force = getenv("CLICOLOR_FORCE");
- if (clicolor_force && *clicolor_force && strcmp(clicolor_force, "0") != 0)
- {
- return 1;
+ const char* clicolor_force = getenv("CLICOLOR_FORCE");
+ if (clicolor_force && *clicolor_force &&
+ strcmp(clicolor_force, "0") != 0) {
+ return 1;
}
}
@@ -197,38 +180,34 @@ static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
seem to claim the TERM is xterm even though they do not support
VT100 escapes. */
{
- const char* emacs = getenv("EMACS");
- if(emacs && *emacs == 't')
- {
- return 0;
+ const char* emacs = getenv("EMACS");
+ if (emacs && *emacs == 't') {
+ return 0;
}
}
/* Check for a valid terminal. */
- if(!default_vt100)
- {
+ if (!default_vt100) {
const char** t = 0;
const char* term = getenv("TERM");
- if(term)
- {
- for(t = kwsysTerminalVT100Names; *t && strcmp(term, *t) != 0; ++t) {}
+ if (term) {
+ for (t = kwsysTerminalVT100Names; *t && strcmp(term, *t) != 0; ++t) {
}
- if(!(t && *t))
- {
+ }
+ if (!(t && *t)) {
return 0;
- }
}
+ }
#if defined(KWSYS_TERMINAL_ISATTY_WORKS)
/* Make sure the stream is a tty. */
(void)default_tty;
- return isatty(fileno(stream))? 1:0;
+ return isatty(fileno(stream)) ? 1 : 0;
#else
/* Check for cases in which the stream is definitely not a tty. */
- if(kwsysTerminalStreamIsNotInteractive(stream))
- {
+ if (kwsysTerminalStreamIsNotInteractive(stream)) {
return 0;
- }
+ }
/* Use the provided default for whether this is a tty. */
return default_tty;
@@ -237,40 +216,38 @@ static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
/*--------------------------------------------------------------------------*/
/* VT100 escape sequence strings. */
-#define KWSYS_TERMINAL_VT100_NORMAL "\33[0m"
-#define KWSYS_TERMINAL_VT100_BOLD "\33[1m"
-#define KWSYS_TERMINAL_VT100_UNDERLINE "\33[4m"
-#define KWSYS_TERMINAL_VT100_BLINK "\33[5m"
-#define KWSYS_TERMINAL_VT100_INVERSE "\33[7m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_BLACK "\33[30m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_RED "\33[31m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_GREEN "\33[32m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_YELLOW "\33[33m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_BLUE "\33[34m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_MAGENTA "\33[35m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_CYAN "\33[36m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_WHITE "\33[37m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_BLACK "\33[40m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_RED "\33[41m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_GREEN "\33[42m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_YELLOW "\33[43m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_BLUE "\33[44m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_MAGENTA "\33[45m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_CYAN "\33[46m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_WHITE "\33[47m"
+#define KWSYS_TERMINAL_VT100_NORMAL "\33[0m"
+#define KWSYS_TERMINAL_VT100_BOLD "\33[1m"
+#define KWSYS_TERMINAL_VT100_UNDERLINE "\33[4m"
+#define KWSYS_TERMINAL_VT100_BLINK "\33[5m"
+#define KWSYS_TERMINAL_VT100_INVERSE "\33[7m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_BLACK "\33[30m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_RED "\33[31m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_GREEN "\33[32m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_YELLOW "\33[33m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_BLUE "\33[34m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_MAGENTA "\33[35m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_CYAN "\33[36m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_WHITE "\33[37m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_BLACK "\33[40m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_RED "\33[41m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_GREEN "\33[42m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_YELLOW "\33[43m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_BLUE "\33[44m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_MAGENTA "\33[45m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_CYAN "\33[46m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_WHITE "\33[47m"
/*--------------------------------------------------------------------------*/
/* Write VT100 escape sequences to the stream for the given color. */
static void kwsysTerminalSetVT100Color(FILE* stream, int color)
{
- if(color == kwsysTerminal_Color_Normal)
- {
+ if (color == kwsysTerminal_Color_Normal) {
fprintf(stream, KWSYS_TERMINAL_VT100_NORMAL);
return;
- }
+ }
- switch(color & kwsysTerminal_Color_ForegroundMask)
- {
+ switch (color & kwsysTerminal_Color_ForegroundMask) {
case kwsysTerminal_Color_Normal:
fprintf(stream, KWSYS_TERMINAL_VT100_NORMAL);
break;
@@ -298,9 +275,8 @@ static void kwsysTerminalSetVT100Color(FILE* stream, int color)
case kwsysTerminal_Color_ForegroundWhite:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_WHITE);
break;
- }
- switch(color & kwsysTerminal_Color_BackgroundMask)
- {
+ }
+ switch (color & kwsysTerminal_Color_BackgroundMask) {
case kwsysTerminal_Color_BackgroundBlack:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_BLACK);
break;
@@ -325,19 +301,18 @@ static void kwsysTerminalSetVT100Color(FILE* stream, int color)
case kwsysTerminal_Color_BackgroundWhite:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_WHITE);
break;
- }
- if(color & kwsysTerminal_Color_ForegroundBold)
- {
+ }
+ if (color & kwsysTerminal_Color_ForegroundBold) {
fprintf(stream, KWSYS_TERMINAL_VT100_BOLD);
- }
+ }
}
/*--------------------------------------------------------------------------*/
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
-# define KWSYS_TERMINAL_MASK_FOREGROUND \
+#define KWSYS_TERMINAL_MASK_FOREGROUND \
(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
-# define KWSYS_TERMINAL_MASK_BACKGROUND \
+#define KWSYS_TERMINAL_MASK_BACKGROUND \
(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
/* Get the Windows handle for a FILE stream. */
@@ -346,19 +321,16 @@ static HANDLE kwsysTerminalGetStreamHandle(FILE* stream)
/* Get the C-library file descriptor from the stream. */
int fd = fileno(stream);
-# if defined(__CYGWIN__)
+#if defined(__CYGWIN__)
/* Cygwin seems to have an extra pipe level. If the file descriptor
corresponds to stdout or stderr then obtain the matching windows
handle directly. */
- if(fd == fileno(stdout))
- {
+ if (fd == fileno(stdout)) {
return GetStdHandle(STD_OUTPUT_HANDLE);
- }
- else if(fd == fileno(stderr))
- {
+ } else if (fd == fileno(stderr)) {
return GetStdHandle(STD_ERROR_HANDLE);
- }
-# endif
+ }
+#endif
/* Get the underlying Windows handle for the descriptor. */
return (HANDLE)_get_osfhandle(fd);
@@ -367,12 +339,10 @@ static HANDLE kwsysTerminalGetStreamHandle(FILE* stream)
/* Set color attributes in a Windows console. */
static void kwsysTerminalSetConsoleColor(HANDLE hOut,
CONSOLE_SCREEN_BUFFER_INFO* hOutInfo,
- FILE* stream,
- int color)
+ FILE* stream, int color)
{
WORD attributes = 0;
- switch(color & kwsysTerminal_Color_ForegroundMask)
- {
+ switch (color & kwsysTerminal_Color_ForegroundMask) {
case kwsysTerminal_Color_Normal:
attributes |= hOutInfo->wAttributes & KWSYS_TERMINAL_MASK_FOREGROUND;
break;
@@ -400,9 +370,8 @@ static void kwsysTerminalSetConsoleColor(HANDLE hOut,
case kwsysTerminal_Color_ForegroundWhite:
attributes |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
break;
- }
- switch(color & kwsysTerminal_Color_BackgroundMask)
- {
+ }
+ switch (color & kwsysTerminal_Color_BackgroundMask) {
case kwsysTerminal_Color_Normal:
attributes |= hOutInfo->wAttributes & KWSYS_TERMINAL_MASK_BACKGROUND;
break;
@@ -430,15 +399,13 @@ static void kwsysTerminalSetConsoleColor(HANDLE hOut,
case kwsysTerminal_Color_BackgroundWhite:
attributes |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
break;
- }
- if(color & kwsysTerminal_Color_ForegroundBold)
- {
+ }
+ if (color & kwsysTerminal_Color_ForegroundBold) {
attributes |= FOREGROUND_INTENSITY;
- }
- if(color & kwsysTerminal_Color_BackgroundBold)
- {
+ }
+ if (color & kwsysTerminal_Color_BackgroundBold) {
attributes |= BACKGROUND_INTENSITY;
- }
+ }
fflush(stream);
SetConsoleTextAttribute(hOut, attributes);
}
diff --git a/Source/kwsys/Terminal.h.in b/Source/kwsys/Terminal.h.in
index 108cba0..5d29830 100644
--- a/Source/kwsys/Terminal.h.in
+++ b/Source/kwsys/Terminal.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_Terminal_h
#define @KWSYS_NAMESPACE@_Terminal_h
@@ -21,41 +12,61 @@
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysTerminal_cfprintf kwsys_ns(Terminal_cfprintf)
-# define kwsysTerminal_Color_e kwsys_ns(Terminal_Color_e)
-# define kwsysTerminal_Color_Normal kwsys_ns(Terminal_Color_Normal)
-# define kwsysTerminal_Color_ForegroundBlack kwsys_ns(Terminal_Color_ForegroundBlack)
-# define kwsysTerminal_Color_ForegroundRed kwsys_ns(Terminal_Color_ForegroundRed)
-# define kwsysTerminal_Color_ForegroundGreen kwsys_ns(Terminal_Color_ForegroundGreen)
-# define kwsysTerminal_Color_ForegroundYellow kwsys_ns(Terminal_Color_ForegroundYellow)
-# define kwsysTerminal_Color_ForegroundBlue kwsys_ns(Terminal_Color_ForegroundBlue)
-# define kwsysTerminal_Color_ForegroundMagenta kwsys_ns(Terminal_Color_ForegroundMagenta)
-# define kwsysTerminal_Color_ForegroundCyan kwsys_ns(Terminal_Color_ForegroundCyan)
-# define kwsysTerminal_Color_ForegroundWhite kwsys_ns(Terminal_Color_ForegroundWhite)
-# define kwsysTerminal_Color_ForegroundMask kwsys_ns(Terminal_Color_ForegroundMask)
-# define kwsysTerminal_Color_BackgroundBlack kwsys_ns(Terminal_Color_BackgroundBlack)
-# define kwsysTerminal_Color_BackgroundRed kwsys_ns(Terminal_Color_BackgroundRed)
-# define kwsysTerminal_Color_BackgroundGreen kwsys_ns(Terminal_Color_BackgroundGreen)
-# define kwsysTerminal_Color_BackgroundYellow kwsys_ns(Terminal_Color_BackgroundYellow)
-# define kwsysTerminal_Color_BackgroundBlue kwsys_ns(Terminal_Color_BackgroundBlue)
-# define kwsysTerminal_Color_BackgroundMagenta kwsys_ns(Terminal_Color_BackgroundMagenta)
-# define kwsysTerminal_Color_BackgroundCyan kwsys_ns(Terminal_Color_BackgroundCyan)
-# define kwsysTerminal_Color_BackgroundWhite kwsys_ns(Terminal_Color_BackgroundWhite)
-# define kwsysTerminal_Color_BackgroundMask kwsys_ns(Terminal_Color_BackgroundMask)
-# define kwsysTerminal_Color_ForegroundBold kwsys_ns(Terminal_Color_ForegroundBold)
-# define kwsysTerminal_Color_BackgroundBold kwsys_ns(Terminal_Color_BackgroundBold)
-# define kwsysTerminal_Color_AssumeTTY kwsys_ns(Terminal_Color_AssumeTTY)
-# define kwsysTerminal_Color_AssumeVT100 kwsys_ns(Terminal_Color_AssumeVT100)
-# define kwsysTerminal_Color_AttributeMask kwsys_ns(Terminal_Color_AttributeMask)
+#define kwsysTerminal_cfprintf kwsys_ns(Terminal_cfprintf)
+#define kwsysTerminal_Color_e kwsys_ns(Terminal_Color_e)
+#define kwsysTerminal_Color_Normal kwsys_ns(Terminal_Color_Normal)
+#define kwsysTerminal_Color_ForegroundBlack \
+ kwsys_ns(Terminal_Color_ForegroundBlack)
+#define kwsysTerminal_Color_ForegroundRed \
+ kwsys_ns(Terminal_Color_ForegroundRed)
+#define kwsysTerminal_Color_ForegroundGreen \
+ kwsys_ns(Terminal_Color_ForegroundGreen)
+#define kwsysTerminal_Color_ForegroundYellow \
+ kwsys_ns(Terminal_Color_ForegroundYellow)
+#define kwsysTerminal_Color_ForegroundBlue \
+ kwsys_ns(Terminal_Color_ForegroundBlue)
+#define kwsysTerminal_Color_ForegroundMagenta \
+ kwsys_ns(Terminal_Color_ForegroundMagenta)
+#define kwsysTerminal_Color_ForegroundCyan \
+ kwsys_ns(Terminal_Color_ForegroundCyan)
+#define kwsysTerminal_Color_ForegroundWhite \
+ kwsys_ns(Terminal_Color_ForegroundWhite)
+#define kwsysTerminal_Color_ForegroundMask \
+ kwsys_ns(Terminal_Color_ForegroundMask)
+#define kwsysTerminal_Color_BackgroundBlack \
+ kwsys_ns(Terminal_Color_BackgroundBlack)
+#define kwsysTerminal_Color_BackgroundRed \
+ kwsys_ns(Terminal_Color_BackgroundRed)
+#define kwsysTerminal_Color_BackgroundGreen \
+ kwsys_ns(Terminal_Color_BackgroundGreen)
+#define kwsysTerminal_Color_BackgroundYellow \
+ kwsys_ns(Terminal_Color_BackgroundYellow)
+#define kwsysTerminal_Color_BackgroundBlue \
+ kwsys_ns(Terminal_Color_BackgroundBlue)
+#define kwsysTerminal_Color_BackgroundMagenta \
+ kwsys_ns(Terminal_Color_BackgroundMagenta)
+#define kwsysTerminal_Color_BackgroundCyan \
+ kwsys_ns(Terminal_Color_BackgroundCyan)
+#define kwsysTerminal_Color_BackgroundWhite \
+ kwsys_ns(Terminal_Color_BackgroundWhite)
+#define kwsysTerminal_Color_BackgroundMask \
+ kwsys_ns(Terminal_Color_BackgroundMask)
+#define kwsysTerminal_Color_ForegroundBold \
+ kwsys_ns(Terminal_Color_ForegroundBold)
+#define kwsysTerminal_Color_BackgroundBold \
+ kwsys_ns(Terminal_Color_BackgroundBold)
+#define kwsysTerminal_Color_AssumeTTY kwsys_ns(Terminal_Color_AssumeTTY)
+#define kwsysTerminal_Color_AssumeVT100 kwsys_ns(Terminal_Color_AssumeVT100)
+#define kwsysTerminal_Color_AttributeMask \
+ kwsys_ns(Terminal_Color_AttributeMask)
#endif
#if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
#endif
/**
@@ -88,33 +99,33 @@ enum kwsysTerminal_Color_e
kwsysTerminal_Color_Normal = 0,
/* Foreground Color */
- kwsysTerminal_Color_ForegroundBlack = 0x1,
- kwsysTerminal_Color_ForegroundRed = 0x2,
- kwsysTerminal_Color_ForegroundGreen = 0x3,
- kwsysTerminal_Color_ForegroundYellow = 0x4,
- kwsysTerminal_Color_ForegroundBlue = 0x5,
+ kwsysTerminal_Color_ForegroundBlack = 0x1,
+ kwsysTerminal_Color_ForegroundRed = 0x2,
+ kwsysTerminal_Color_ForegroundGreen = 0x3,
+ kwsysTerminal_Color_ForegroundYellow = 0x4,
+ kwsysTerminal_Color_ForegroundBlue = 0x5,
kwsysTerminal_Color_ForegroundMagenta = 0x6,
- kwsysTerminal_Color_ForegroundCyan = 0x7,
- kwsysTerminal_Color_ForegroundWhite = 0x8,
- kwsysTerminal_Color_ForegroundMask = 0xF,
+ kwsysTerminal_Color_ForegroundCyan = 0x7,
+ kwsysTerminal_Color_ForegroundWhite = 0x8,
+ kwsysTerminal_Color_ForegroundMask = 0xF,
/* Background Color */
- kwsysTerminal_Color_BackgroundBlack = 0x10,
- kwsysTerminal_Color_BackgroundRed = 0x20,
- kwsysTerminal_Color_BackgroundGreen = 0x30,
- kwsysTerminal_Color_BackgroundYellow = 0x40,
- kwsysTerminal_Color_BackgroundBlue = 0x50,
+ kwsysTerminal_Color_BackgroundBlack = 0x10,
+ kwsysTerminal_Color_BackgroundRed = 0x20,
+ kwsysTerminal_Color_BackgroundGreen = 0x30,
+ kwsysTerminal_Color_BackgroundYellow = 0x40,
+ kwsysTerminal_Color_BackgroundBlue = 0x50,
kwsysTerminal_Color_BackgroundMagenta = 0x60,
- kwsysTerminal_Color_BackgroundCyan = 0x70,
- kwsysTerminal_Color_BackgroundWhite = 0x80,
- kwsysTerminal_Color_BackgroundMask = 0xF0,
+ kwsysTerminal_Color_BackgroundCyan = 0x70,
+ kwsysTerminal_Color_BackgroundWhite = 0x80,
+ kwsysTerminal_Color_BackgroundMask = 0xF0,
/* Attributes */
kwsysTerminal_Color_ForegroundBold = 0x100,
kwsysTerminal_Color_BackgroundBold = 0x200,
- kwsysTerminal_Color_AssumeTTY = 0x400,
- kwsysTerminal_Color_AssumeVT100 = 0x800,
- kwsysTerminal_Color_AttributeMask = 0xF00
+ kwsysTerminal_Color_AssumeTTY = 0x400,
+ kwsysTerminal_Color_AssumeVT100 = 0x800,
+ kwsysTerminal_Color_AttributeMask = 0xF00
};
#if defined(__cplusplus)
@@ -124,36 +135,36 @@ enum kwsysTerminal_Color_e
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysTerminal_cfprintf
-# undef kwsysTerminal_Color_e
-# undef kwsysTerminal_Color_Normal
-# undef kwsysTerminal_Color_ForegroundBlack
-# undef kwsysTerminal_Color_ForegroundRed
-# undef kwsysTerminal_Color_ForegroundGreen
-# undef kwsysTerminal_Color_ForegroundYellow
-# undef kwsysTerminal_Color_ForegroundBlue
-# undef kwsysTerminal_Color_ForegroundMagenta
-# undef kwsysTerminal_Color_ForegroundCyan
-# undef kwsysTerminal_Color_ForegroundWhite
-# undef kwsysTerminal_Color_ForegroundMask
-# undef kwsysTerminal_Color_BackgroundBlack
-# undef kwsysTerminal_Color_BackgroundRed
-# undef kwsysTerminal_Color_BackgroundGreen
-# undef kwsysTerminal_Color_BackgroundYellow
-# undef kwsysTerminal_Color_BackgroundBlue
-# undef kwsysTerminal_Color_BackgroundMagenta
-# undef kwsysTerminal_Color_BackgroundCyan
-# undef kwsysTerminal_Color_BackgroundWhite
-# undef kwsysTerminal_Color_BackgroundMask
-# undef kwsysTerminal_Color_ForegroundBold
-# undef kwsysTerminal_Color_BackgroundBold
-# undef kwsysTerminal_Color_AssumeTTY
-# undef kwsysTerminal_Color_AssumeVT100
-# undef kwsysTerminal_Color_AttributeMask
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+#undef kwsysTerminal_cfprintf
+#undef kwsysTerminal_Color_e
+#undef kwsysTerminal_Color_Normal
+#undef kwsysTerminal_Color_ForegroundBlack
+#undef kwsysTerminal_Color_ForegroundRed
+#undef kwsysTerminal_Color_ForegroundGreen
+#undef kwsysTerminal_Color_ForegroundYellow
+#undef kwsysTerminal_Color_ForegroundBlue
+#undef kwsysTerminal_Color_ForegroundMagenta
+#undef kwsysTerminal_Color_ForegroundCyan
+#undef kwsysTerminal_Color_ForegroundWhite
+#undef kwsysTerminal_Color_ForegroundMask
+#undef kwsysTerminal_Color_BackgroundBlack
+#undef kwsysTerminal_Color_BackgroundRed
+#undef kwsysTerminal_Color_BackgroundGreen
+#undef kwsysTerminal_Color_BackgroundYellow
+#undef kwsysTerminal_Color_BackgroundBlue
+#undef kwsysTerminal_Color_BackgroundMagenta
+#undef kwsysTerminal_Color_BackgroundCyan
+#undef kwsysTerminal_Color_BackgroundWhite
+#undef kwsysTerminal_Color_BackgroundMask
+#undef kwsysTerminal_Color_ForegroundBold
+#undef kwsysTerminal_Color_BackgroundBold
+#undef kwsysTerminal_Color_AssumeTTY
+#undef kwsysTerminal_Color_AssumeVT100
+#undef kwsysTerminal_Color_AttributeMask
+#endif
#endif
#endif
diff --git a/Source/kwsys/hash_fun.hxx.in b/Source/kwsys/hash_fun.hxx.in
index 4872b51..8626c2a 100644
--- a/Source/kwsys/hash_fun.hxx.in
+++ b/Source/kwsys/hash_fun.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
@@ -38,108 +29,134 @@
#define @KWSYS_NAMESPACE@_hash_fun_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
-#include <stddef.h> // size_t
+
+#include <stddef.h> // size_t
#include <string>
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
-template <class _Key> struct hash { };
+template <class _Key>
+struct hash
+{
+};
inline size_t _stl_hash_string(const char* __s)
{
unsigned long __h = 0;
- for ( ; *__s; ++__s)
- __h = 5*__h + *__s;
+ for (; *__s; ++__s)
+ __h = 5 * __h + *__s;
return size_t(__h);
}
template <>
-struct hash<char*> {
+struct hash<char*>
+{
size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
};
template <>
-struct hash<const char*> {
+struct hash<const char*>
+{
size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
};
template <>
- struct hash<std::string> {
- size_t operator()(const std::string & __s) const { return _stl_hash_string(__s.c_str()); }
+struct hash<std::string>
+{
+ size_t operator()(const std::string& __s) const
+ {
+ return _stl_hash_string(__s.c_str());
+ }
};
#if !defined(__BORLANDC__)
template <>
- struct hash<const std::string> {
- size_t operator()(const std::string & __s) const { return _stl_hash_string(__s.c_str()); }
+struct hash<const std::string>
+{
+ size_t operator()(const std::string& __s) const
+ {
+ return _stl_hash_string(__s.c_str());
+ }
};
#endif
template <>
-struct hash<char> {
+struct hash<char>
+{
size_t operator()(char __x) const { return __x; }
};
template <>
-struct hash<unsigned char> {
+struct hash<unsigned char>
+{
size_t operator()(unsigned char __x) const { return __x; }
};
template <>
-struct hash<signed char> {
+struct hash<signed char>
+{
size_t operator()(unsigned char __x) const { return __x; }
};
template <>
-struct hash<short> {
+struct hash<short>
+{
size_t operator()(short __x) const { return __x; }
};
template <>
-struct hash<unsigned short> {
+struct hash<unsigned short>
+{
size_t operator()(unsigned short __x) const { return __x; }
};
template <>
-struct hash<int> {
+struct hash<int>
+{
size_t operator()(int __x) const { return __x; }
};
template <>
-struct hash<unsigned int> {
+struct hash<unsigned int>
+{
size_t operator()(unsigned int __x) const { return __x; }
};
template <>
-struct hash<long> {
+struct hash<long>
+{
size_t operator()(long __x) const { return __x; }
};
template <>
-struct hash<unsigned long> {
+struct hash<unsigned long>
+{
size_t operator()(unsigned long __x) const { return __x; }
};
// use long long or __int64
#if @KWSYS_USE_LONG_LONG@
template <>
-struct hash<long long> {
+struct hash<long long>
+{
size_t operator()(long long __x) const { return __x; }
};
template <>
-struct hash<unsigned long long> {
+struct hash<unsigned long long>
+{
size_t operator()(unsigned long long __x) const { return __x; }
};
#elif @KWSYS_USE___INT64@
template <>
-struct hash<__int64> {
+struct hash<__int64>
+{
size_t operator()(__int64 __x) const { return __x; }
};
template <>
-struct hash<unsigned __int64> {
+struct hash<unsigned __int64>
+{
size_t operator()(unsigned __int64 __x) const { return __x; }
};
#endif // use long long or __int64
diff --git a/Source/kwsys/hash_map.hxx.in b/Source/kwsys/hash_map.hxx.in
index 60c7086..3f9174f 100644
--- a/Source/kwsys/hash_map.hxx.in
+++ b/Source/kwsys/hash_map.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
@@ -38,36 +29,37 @@
#define @KWSYS_NAMESPACE@_hash_map_hxx
#include <@KWSYS_NAMESPACE@/hashtable.hxx>
+
#include <@KWSYS_NAMESPACE@/hash_fun.hxx>
+
#include <functional> // equal_to
#if defined(_MSC_VER)
-# pragma warning (push)
-# pragma warning (disable:4284)
-# pragma warning (disable:4786)
+#pragma warning(push)
+#pragma warning(disable : 4284)
+#pragma warning(disable : 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma set woff 1174
-# pragma set woff 1375
+#pragma set woff 1174
+#pragma set woff 1375
#endif
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
// select1st is an extension: it is not part of the standard.
template <class T1, class T2>
-struct hash_select1st:
- public std::unary_function<std::pair<T1, T2>, T1>
+struct hash_select1st : public std::unary_function<std::pair<T1, T2>, T1>
{
const T1& operator()(const std::pair<T1, T2>& __x) const
- { return __x.first; }
+ {
+ return __x.first;
+ }
};
// Forward declaration of equality operator; needed for friend declaration.
-template <class _Key, class _Tp,
- class _HashFcn = hash<_Key>,
+template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
class _EqualKey = std::equal_to<_Key>,
class _Alloc = std::allocator<char> >
class hash_map;
@@ -76,13 +68,13 @@ template <class _Key, class _Tp, class _HashFn, class _EqKey, class _Alloc>
bool operator==(const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&,
const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&);
-template <class _Key, class _Tp, class _HashFcn, class _EqualKey,
- class _Alloc>
+template <class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
class hash_map
{
private:
- typedef hashtable<std::pair<const _Key,_Tp>,_Key,_HashFcn,
- hash_select1st<const _Key,_Tp>,_EqualKey,_Alloc> _Ht;
+ typedef hashtable<std::pair<const _Key, _Tp>, _Key, _HashFcn,
+ hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
+ _Ht;
_Ht _M_ht;
public:
@@ -110,34 +102,51 @@ public:
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
- hash_map() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+ hash_map()
+ : _M_ht(100, hasher(), key_equal(), allocator_type())
+ {
+ }
explicit hash_map(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+ : _M_ht(__n, hasher(), key_equal(), allocator_type())
+ {
+ }
hash_map(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+ : _M_ht(__n, __hf, key_equal(), allocator_type())
+ {
+ }
hash_map(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a) {}
+ : _M_ht(__n, __hf, __eql, __a)
+ {
+ }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
public:
size_type size() const { return _M_ht.size(); }
@@ -145,8 +154,7 @@ public:
bool empty() const { return _M_ht.empty(); }
void swap(hash_map& __hs) { _M_ht.swap(__hs._M_ht); }
- friend bool operator==<>(const hash_map&,
- const hash_map&);
+ friend bool operator==<>(const hash_map&, const hash_map&);
iterator begin() { return _M_ht.begin(); }
iterator end() { return _M_ht.end(); }
@@ -154,31 +162,44 @@ public:
const_iterator end() const { return _M_ht.end(); }
public:
- std::pair<iterator,bool> insert(const value_type& __obj)
- { return _M_ht.insert_unique(__obj); }
+ std::pair<iterator, bool> insert(const value_type& __obj)
+ {
+ return _M_ht.insert_unique(__obj);
+ }
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
- { _M_ht.insert_unique(__f,__l); }
- std::pair<iterator,bool> insert_noresize(const value_type& __obj)
- { return _M_ht.insert_unique_noresize(__obj); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
+ std::pair<iterator, bool> insert_noresize(const value_type& __obj)
+ {
+ return _M_ht.insert_unique_noresize(__obj);
+ }
iterator find(const key_type& __key) { return _M_ht.find(__key); }
const_iterator find(const key_type& __key) const
- { return _M_ht.find(__key); }
+ {
+ return _M_ht.find(__key);
+ }
- _Tp& operator[](const key_type& __key) {
+ _Tp& operator[](const key_type& __key)
+ {
return _M_ht.find_or_insert(value_type(__key, _Tp())).second;
}
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
std::pair<iterator, iterator> equal_range(const key_type& __key)
- { return _M_ht.equal_range(__key); }
- std::pair<const_iterator, const_iterator>
- equal_range(const key_type& __key) const
- { return _M_ht.equal_range(__key); }
+ {
+ return _M_ht.equal_range(__key);
+ }
+ std::pair<const_iterator, const_iterator> equal_range(
+ const key_type& __key) const
+ {
+ return _M_ht.equal_range(__key);
+ }
- size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+ size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
@@ -187,53 +208,51 @@ public:
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
- { return _M_ht.elems_in_bucket(__n); }
+ {
+ return _M_ht.elems_in_bucket(__n);
+ }
};
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-bool
-operator==(const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
- const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
+bool operator==(const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+ const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
{
return __hm1._M_ht == __hm2._M_ht;
}
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline bool
-operator!=(const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
- const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2) {
+inline bool operator!=(
+ const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+ const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
+{
return !(__hm1 == __hm2);
}
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline void
-swap(hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
- hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
+inline void swap(hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+ hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
{
__hm1.swap(__hm2);
}
// Forward declaration of equality operator; needed for friend declaration.
-template <class _Key, class _Tp,
- class _HashFcn = hash<_Key>,
+template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
class _EqualKey = std::equal_to<_Key>,
class _Alloc = std::allocator<char> >
class hash_multimap;
template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-bool
-operator==(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
- const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2);
+bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
+ const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2);
-template <class _Key, class _Tp, class _HashFcn, class _EqualKey,
- class _Alloc>
+template <class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
class hash_multimap
{
private:
typedef hashtable<std::pair<const _Key, _Tp>, _Key, _HashFcn,
hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
- _Ht;
+ _Ht;
_Ht _M_ht;
public:
@@ -261,34 +280,51 @@ public:
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
- hash_multimap() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+ hash_multimap()
+ : _M_ht(100, hasher(), key_equal(), allocator_type())
+ {
+ }
explicit hash_multimap(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+ : _M_ht(__n, hasher(), key_equal(), allocator_type())
+ {
+ }
hash_multimap(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+ : _M_ht(__n, __hf, key_equal(), allocator_type())
+ {
+ }
hash_multimap(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a) {}
+ : _M_ht(__n, __hf, __eql, __a)
+ {
+ }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
public:
size_type size() const { return _M_ht.size(); }
@@ -296,8 +332,7 @@ public:
bool empty() const { return _M_ht.empty(); }
void swap(hash_multimap& __hs) { _M_ht.swap(__hs._M_ht); }
- friend bool operator==<>(const hash_multimap&,
- const hash_multimap&);
+ friend bool operator==<>(const hash_multimap&, const hash_multimap&);
iterator begin() { return _M_ht.begin(); }
iterator end() { return _M_ht.end(); }
@@ -306,26 +341,38 @@ public:
public:
iterator insert(const value_type& __obj)
- { return _M_ht.insert_equal(__obj); }
+ {
+ return _M_ht.insert_equal(__obj);
+ }
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
- { _M_ht.insert_equal(__f,__l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
iterator insert_noresize(const value_type& __obj)
- { return _M_ht.insert_equal_noresize(__obj); }
+ {
+ return _M_ht.insert_equal_noresize(__obj);
+ }
iterator find(const key_type& __key) { return _M_ht.find(__key); }
const_iterator find(const key_type& __key) const
- { return _M_ht.find(__key); }
+ {
+ return _M_ht.find(__key);
+ }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
std::pair<iterator, iterator> equal_range(const key_type& __key)
- { return _M_ht.equal_range(__key); }
- std::pair<const_iterator, const_iterator>
- equal_range(const key_type& __key) const
- { return _M_ht.equal_range(__key); }
+ {
+ return _M_ht.equal_range(__key);
+ }
+ std::pair<const_iterator, const_iterator> equal_range(
+ const key_type& __key) const
+ {
+ return _M_ht.equal_range(__key);
+ }
- size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+ size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
@@ -335,28 +382,29 @@ public:
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
- { return _M_ht.elems_in_bucket(__n); }
+ {
+ return _M_ht.elems_in_bucket(__n);
+ }
};
template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-bool
-operator==(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
- const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2)
+bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
+ const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2)
{
return __hm1._M_ht == __hm2._M_ht;
}
template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-inline bool
-operator!=(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
- const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2) {
+inline bool operator!=(
+ const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
+ const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2)
+{
return !(__hm1 == __hm2);
}
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline void
-swap(hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
- hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
+inline void swap(hash_multimap<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+ hash_multimap<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
{
__hm1.swap(__hm2);
}
@@ -364,12 +412,12 @@ swap(hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
} // namespace @KWSYS_NAMESPACE@
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma reset woff 1174
-# pragma reset woff 1375
+#pragma reset woff 1174
+#pragma reset woff 1375
#endif
#if defined(_MSC_VER)
-# pragma warning (pop)
+#pragma warning(pop)
#endif
#endif
diff --git a/Source/kwsys/hash_set.hxx.in b/Source/kwsys/hash_set.hxx.in
index c314979..e3a0c6c 100644
--- a/Source/kwsys/hash_set.hxx.in
+++ b/Source/kwsys/hash_set.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
@@ -38,49 +29,49 @@
#define @KWSYS_NAMESPACE@_hash_set_hxx
#include <@KWSYS_NAMESPACE@/hashtable.hxx>
+
#include <@KWSYS_NAMESPACE@/hash_fun.hxx>
+
#include <functional> // equal_to
#if defined(_MSC_VER)
-# pragma warning (push)
-# pragma warning (disable:4284)
-# pragma warning (disable:4786)
+#pragma warning(push)
+#pragma warning(disable : 4284)
+#pragma warning(disable : 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma set woff 1174
-# pragma set woff 1375
+#pragma set woff 1174
+#pragma set woff 1375
#endif
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
// identity is an extension: it is not part of the standard.
template <class _Tp>
-struct _Identity : public std::unary_function<_Tp,_Tp>
+struct _Identity : public std::unary_function<_Tp, _Tp>
{
const _Tp& operator()(const _Tp& __x) const { return __x; }
};
// Forward declaration of equality operator; needed for friend declaration.
-template <class _Value,
- class _HashFcn = hash<_Value>,
+template <class _Value, class _HashFcn = hash<_Value>,
class _EqualKey = std::equal_to<_Value>,
class _Alloc = std::allocator<char> >
class hash_set;
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
- const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2);
+bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2);
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class hash_set
{
private:
- typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
- _EqualKey, _Alloc> _Ht;
+ typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey,
+ _Alloc>
+ _Ht;
_Ht _M_ht;
public:
@@ -107,34 +98,50 @@ public:
public:
hash_set()
- : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+ : _M_ht(100, hasher(), key_equal(), allocator_type())
+ {
+ }
explicit hash_set(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+ : _M_ht(__n, hasher(), key_equal(), allocator_type())
+ {
+ }
hash_set(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+ : _M_ht(__n, __hf, key_equal(), allocator_type())
+ {
+ }
hash_set(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a) {}
+ : _M_ht(__n, __hf, __eql, __a)
+ {
+ }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
- { _M_ht.insert_unique(__f, __l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
public:
size_type size() const { return _M_ht.size(); }
@@ -142,27 +149,27 @@ public:
bool empty() const { return _M_ht.empty(); }
void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); }
- friend bool operator==<>(const hash_set&,
- const hash_set&);
+ friend bool operator==<>(const hash_set&, const hash_set&);
iterator begin() const { return _M_ht.begin(); }
iterator end() const { return _M_ht.end(); }
public:
std::pair<iterator, bool> insert(const value_type& __obj)
- {
- typedef typename _Ht::iterator _Ht_iterator;
- std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique(__obj);
- return std::pair<iterator,bool>(__p.first, __p.second);
- }
+ {
+ typedef typename _Ht::iterator _Ht_iterator;
+ std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique(__obj);
+ return std::pair<iterator, bool>(__p.first, __p.second);
+ }
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
- { _M_ht.insert_unique(__f,__l); }
+ {
+ _M_ht.insert_unique(__f, __l);
+ }
std::pair<iterator, bool> insert_noresize(const value_type& __obj)
{
typedef typename _Ht::iterator _Ht_iterator;
- std::pair<_Ht_iterator, bool> __p =
- _M_ht.insert_unique_noresize(__obj);
+ std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique_noresize(__obj);
return std::pair<iterator, bool>(__p.first, __p.second);
}
@@ -171,9 +178,11 @@ public:
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
std::pair<iterator, iterator> equal_range(const key_type& __key) const
- { return _M_ht.equal_range(__key); }
+ {
+ return _M_ht.equal_range(__key);
+ }
- size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+ size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
@@ -183,50 +192,49 @@ public:
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
- { return _M_ht.elems_in_bucket(__n); }
+ {
+ return _M_ht.elems_in_bucket(__n);
+ }
};
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
- const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2)
+bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2)
{
return __hs1._M_ht == __hs2._M_ht;
}
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-inline bool
-operator!=(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
- const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2) {
+inline bool operator!=(
+ const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2)
+{
return !(__hs1 == __hs2);
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline void
-swap(hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
- hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
+inline void swap(hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
{
__hs1.swap(__hs2);
}
-template <class _Value,
- class _HashFcn = hash<_Value>,
+template <class _Value, class _HashFcn = hash<_Value>,
class _EqualKey = std::equal_to<_Value>,
class _Alloc = std::allocator<char> >
class hash_multiset;
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
- const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2);
-
+bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2);
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class hash_multiset
{
private:
- typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
- _EqualKey, _Alloc> _Ht;
+ typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey,
+ _Alloc>
+ _Ht;
_Ht _M_ht;
public:
@@ -253,34 +261,50 @@ public:
public:
hash_multiset()
- : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+ : _M_ht(100, hasher(), key_equal(), allocator_type())
+ {
+ }
explicit hash_multiset(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+ : _M_ht(__n, hasher(), key_equal(), allocator_type())
+ {
+ }
hash_multiset(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+ : _M_ht(__n, __hf, key_equal(), allocator_type())
+ {
+ }
hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a) {}
+ : _M_ht(__n, __hf, __eql, __a)
+ {
+ }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
- { _M_ht.insert_equal(__f, __l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
public:
size_type size() const { return _M_ht.size(); }
@@ -288,29 +312,36 @@ public:
bool empty() const { return _M_ht.empty(); }
void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); }
- friend bool operator==<>(const hash_multiset&,
- const hash_multiset&);
+ friend bool operator==<>(const hash_multiset&, const hash_multiset&);
iterator begin() const { return _M_ht.begin(); }
iterator end() const { return _M_ht.end(); }
public:
iterator insert(const value_type& __obj)
- { return _M_ht.insert_equal(__obj); }
+ {
+ return _M_ht.insert_equal(__obj);
+ }
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
- { _M_ht.insert_equal(__f,__l); }
+ {
+ _M_ht.insert_equal(__f, __l);
+ }
iterator insert_noresize(const value_type& __obj)
- { return _M_ht.insert_equal_noresize(__obj); }
+ {
+ return _M_ht.insert_equal_noresize(__obj);
+ }
iterator find(const key_type& __key) const { return _M_ht.find(__key); }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
std::pair<iterator, iterator> equal_range(const key_type& __key) const
- { return _M_ht.equal_range(__key); }
+ {
+ return _M_ht.equal_range(__key);
+ }
- size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+ size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
@@ -320,40 +351,42 @@ public:
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
- { return _M_ht.elems_in_bucket(__n); }
+ {
+ return _M_ht.elems_in_bucket(__n);
+ }
};
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
- const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
+bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
{
return __hs1._M_ht == __hs2._M_ht;
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline bool
-operator!=(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
- const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
+inline bool operator!=(
+ const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
+{
return !(__hs1 == __hs2);
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline void
-swap(hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
- hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
+inline void swap(hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+ hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
+{
__hs1.swap(__hs2);
}
} // namespace @KWSYS_NAMESPACE@
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma reset woff 1174
-# pragma reset woff 1375
+#pragma reset woff 1174
+#pragma reset woff 1375
#endif
#if defined(_MSC_VER)
-# pragma warning (pop)
+#pragma warning(pop)
#endif
#endif
diff --git a/Source/kwsys/hashtable.hxx.in b/Source/kwsys/hashtable.hxx.in
index 9a20226..dd92cb9 100644
--- a/Source/kwsys/hashtable.hxx.in
+++ b/Source/kwsys/hashtable.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
@@ -35,31 +26,31 @@
*
*/
#ifdef __BORLANDC__
-# pragma warn -8027 /* 'for' not inlined. */
-# pragma warn -8026 /* 'exception' not inlined. */
-#endif
+#pragma warn - 8027 /* 'for' not inlined. */
+#pragma warn - 8026 /* 'exception' not inlined. */
+#endif
#ifndef @KWSYS_NAMESPACE@_hashtable_hxx
#define @KWSYS_NAMESPACE@_hashtable_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
-#include <stddef.h> // size_t
#include <algorithm> // lower_bound
#include <functional> // unary_function
#include <iterator> // iterator_traits
#include <memory> // allocator
+#include <stddef.h> // size_t
#include <utility> // pair
#include <vector> // vector
#if defined(_MSC_VER)
-# pragma warning (push)
-# pragma warning (disable:4284)
-# pragma warning (disable:4786)
-# pragma warning (disable:4512) /* no assignment operator for class */
+#pragma warning(push)
+#pragma warning(disable : 4284)
+#pragma warning(disable : 4786)
+#pragma warning(disable : 4512) /* no assignment operator for class */
#endif
#if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 3970 /* pointer to int conversion */ 3321 3968
+#pragma set woff 3970 /* pointer to int conversion */ 3321 3968
#endif
// In C++11, clang will warn about using dynamic exception specifications
@@ -67,14 +58,13 @@
// mimic unordered_set and unordered_map, we want to keep the 'throw()'
// decorations below. So we suppress the warning.
#if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wdeprecated"
-# endif
+#if __has_warning("-Wdeprecated")
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated"
+#endif
#endif
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
template <class _Val>
struct _Hashtable_node
@@ -82,34 +72,35 @@ struct _Hashtable_node
_Hashtable_node* _M_next;
_Val _M_val;
void public_method_to_quiet_warning_about_all_methods_private();
+
private:
void operator=(_Hashtable_node<_Val> const&); // poison node assignment
};
-template <class _Val, class _Key, class _HashFcn,
- class _ExtractKey, class _EqualKey,
- class _Alloc = std::allocator<char> >
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+ class _EqualKey, class _Alloc = std::allocator<char> >
class hashtable;
-template <class _Val, class _Key, class _HashFcn,
- class _ExtractKey, class _EqualKey, class _Alloc>
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+ class _EqualKey, class _Alloc>
struct _Hashtable_iterator;
-template <class _Val, class _Key, class _HashFcn,
- class _ExtractKey, class _EqualKey, class _Alloc>
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+ class _EqualKey, class _Alloc>
struct _Hashtable_const_iterator;
-template <class _Val, class _Key, class _HashFcn,
- class _ExtractKey, class _EqualKey, class _Alloc>
-struct _Hashtable_iterator {
- typedef hashtable<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>
- _Hashtable;
- typedef _Hashtable_iterator<_Val, _Key, _HashFcn,
- _ExtractKey, _EqualKey, _Alloc>
- iterator;
- typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn,
- _ExtractKey, _EqualKey, _Alloc>
- const_iterator;
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+ class _EqualKey, class _Alloc>
+struct _Hashtable_iterator
+{
+ typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>
+ _Hashtable;
+ typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
+ _Alloc>
+ iterator;
+ typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+ _EqualKey, _Alloc>
+ const_iterator;
typedef _Hashtable_node<_Val> _Node;
typedef std::forward_iterator_tag iterator_category;
@@ -123,30 +114,31 @@ struct _Hashtable_iterator {
_Hashtable* _M_ht;
_Hashtable_iterator(_Node* __n, _Hashtable* __tab)
- : _M_cur(__n), _M_ht(__tab) {}
+ : _M_cur(__n)
+ , _M_ht(__tab)
+ {
+ }
_Hashtable_iterator() {}
reference operator*() const { return _M_cur->_M_val; }
pointer operator->() const { return &(operator*()); }
iterator& operator++();
iterator operator++(int);
- bool operator==(const iterator& __it) const
- { return _M_cur == __it._M_cur; }
- bool operator!=(const iterator& __it) const
- { return _M_cur != __it._M_cur; }
+ bool operator==(const iterator& __it) const { return _M_cur == __it._M_cur; }
+ bool operator!=(const iterator& __it) const { return _M_cur != __it._M_cur; }
};
-
-template <class _Val, class _Key, class _HashFcn,
- class _ExtractKey, class _EqualKey, class _Alloc>
-struct _Hashtable_const_iterator {
- typedef hashtable<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>
- _Hashtable;
- typedef _Hashtable_iterator<_Val,_Key,_HashFcn,
- _ExtractKey,_EqualKey,_Alloc>
- iterator;
- typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn,
- _ExtractKey, _EqualKey, _Alloc>
- const_iterator;
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+ class _EqualKey, class _Alloc>
+struct _Hashtable_const_iterator
+{
+ typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>
+ _Hashtable;
+ typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
+ _Alloc>
+ iterator;
+ typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+ _EqualKey, _Alloc>
+ const_iterator;
typedef _Hashtable_node<_Val> _Node;
typedef std::forward_iterator_tag iterator_category;
@@ -160,39 +152,53 @@ struct _Hashtable_const_iterator {
const _Hashtable* _M_ht;
_Hashtable_const_iterator(const _Node* __n, const _Hashtable* __tab)
- : _M_cur(__n), _M_ht(__tab) {}
+ : _M_cur(__n)
+ , _M_ht(__tab)
+ {
+ }
_Hashtable_const_iterator() {}
_Hashtable_const_iterator(const iterator& __it)
- : _M_cur(__it._M_cur), _M_ht(__it._M_ht) {}
+ : _M_cur(__it._M_cur)
+ , _M_ht(__it._M_ht)
+ {
+ }
reference operator*() const { return _M_cur->_M_val; }
pointer operator->() const { return &(operator*()); }
const_iterator& operator++();
const_iterator operator++(int);
bool operator==(const const_iterator& __it) const
- { return _M_cur == __it._M_cur; }
+ {
+ return _M_cur == __it._M_cur;
+ }
bool operator!=(const const_iterator& __it) const
- { return _M_cur != __it._M_cur; }
+ {
+ return _M_cur != __it._M_cur;
+ }
};
// Note: assumes long is at least 32 bits.
-enum { _stl_num_primes = 31 };
+enum
+{
+ _stl_num_primes = 31
+};
// create a function with a static local to that function that returns
// the static
-static inline const unsigned long* get_stl_prime_list() {
-
-static const unsigned long _stl_prime_list[_stl_num_primes] =
+static inline const unsigned long* get_stl_prime_list()
{
- 5ul, 11ul, 23ul,
- 53ul, 97ul, 193ul, 389ul, 769ul,
- 1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
- 49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
- 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
- 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
- 1610612741ul, 3221225473ul, 4294967291ul
-};
-return &_stl_prime_list[0]; }
+ static const unsigned long _stl_prime_list[_stl_num_primes] = {
+ 5ul, 11ul, 23ul, 53ul, 97ul,
+ 193ul, 389ul, 769ul, 1543ul, 3079ul,
+ 6151ul, 12289ul, 24593ul, 49157ul, 98317ul,
+ 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul,
+ 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul,
+ 201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul,
+ 4294967291ul
+ };
+
+ return &_stl_prime_list[0];
+}
static inline size_t _stl_next_prime(size_t __n)
{
@@ -208,8 +214,8 @@ template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
class hashtable;
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
- const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2);
+bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
+ const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2);
// Hashtables handle allocators a bit differently than other containers
// do. If we're using standard-conforming allocators, then a hashtable
@@ -219,20 +225,21 @@ bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
// Additionally, a base class wouldn't serve any other purposes; it
// wouldn't, for example, simplify the exception-handling code.
-template <class _Val, class _Key, class _HashFcn,
- class _ExtractKey, class _EqualKey, class _Alloc>
-class hashtable {
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+ class _EqualKey, class _Alloc>
+class hashtable
+{
public:
typedef _Key key_type;
typedef _Val value_type;
typedef _HashFcn hasher;
typedef _EqualKey key_equal;
- typedef size_t size_type;
- typedef ptrdiff_t difference_type;
- typedef value_type* pointer;
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef value_type* pointer;
typedef const value_type* const_pointer;
- typedef value_type& reference;
+ typedef value_type& reference;
typedef const value_type& const_reference;
hasher hash_funct() const { return _M_hash; }
@@ -245,75 +252,74 @@ public:
typedef typename _Alloc::template rebind<_Val>::other allocator_type;
allocator_type get_allocator() const { return _M_node_allocator; }
private:
- typedef typename _Alloc::template rebind<_Node>::other _M_node_allocator_type;
- typedef typename _Alloc::template rebind<_Node*>::other _M_node_ptr_allocator_type;
- typedef std::vector<_Node*,_M_node_ptr_allocator_type> _M_buckets_type;
+ typedef
+ typename _Alloc::template rebind<_Node>::other _M_node_allocator_type;
+ typedef
+ typename _Alloc::template rebind<_Node*>::other _M_node_ptr_allocator_type;
+ typedef std::vector<_Node*, _M_node_ptr_allocator_type> _M_buckets_type;
private:
_M_node_allocator_type _M_node_allocator;
- hasher _M_hash;
- key_equal _M_equals;
- _ExtractKey _M_get_key;
- _M_buckets_type _M_buckets;
- size_type _M_num_elements;
+ hasher _M_hash;
+ key_equal _M_equals;
+ _ExtractKey _M_get_key;
+ _M_buckets_type _M_buckets;
+ size_type _M_num_elements;
_Node* _M_get_node() { return _M_node_allocator.allocate(1); }
void _M_put_node(_Node* __p) { _M_node_allocator.deallocate(__p, 1); }
public:
- typedef _Hashtable_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>
- iterator;
- typedef _Hashtable_const_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,
- _Alloc>
- const_iterator;
-
- friend struct
- _Hashtable_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>;
- friend struct
- _Hashtable_const_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>;
+ typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
+ _Alloc>
+ iterator;
+ typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+ _EqualKey, _Alloc>
+ const_iterator;
+
+ friend struct _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+ _EqualKey, _Alloc>;
+ friend struct _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+ _EqualKey, _Alloc>;
public:
- hashtable(size_type __n,
- const _HashFcn& __hf,
- const _EqualKey& __eql,
+ hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql,
const _ExtractKey& __ext,
const allocator_type& __a = allocator_type())
- : _M_node_allocator(__a),
- _M_hash(__hf),
- _M_equals(__eql),
- _M_get_key(__ext),
- _M_buckets(__a),
- _M_num_elements(0)
+ : _M_node_allocator(__a)
+ , _M_hash(__hf)
+ , _M_equals(__eql)
+ , _M_get_key(__ext)
+ , _M_buckets(__a)
+ , _M_num_elements(0)
{
_M_initialize_buckets(__n);
}
- hashtable(size_type __n,
- const _HashFcn& __hf,
- const _EqualKey& __eql,
+ hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql,
const allocator_type& __a = allocator_type())
- : _M_node_allocator(__a),
- _M_hash(__hf),
- _M_equals(__eql),
- _M_get_key(_ExtractKey()),
- _M_buckets(__a),
- _M_num_elements(0)
+ : _M_node_allocator(__a)
+ , _M_hash(__hf)
+ , _M_equals(__eql)
+ , _M_get_key(_ExtractKey())
+ , _M_buckets(__a)
+ , _M_num_elements(0)
{
_M_initialize_buckets(__n);
}
hashtable(const hashtable& __ht)
- : _M_node_allocator(__ht.get_allocator()),
- _M_hash(__ht._M_hash),
- _M_equals(__ht._M_equals),
- _M_get_key(__ht._M_get_key),
- _M_buckets(__ht.get_allocator()),
- _M_num_elements(0)
+ : _M_node_allocator(__ht.get_allocator())
+ , _M_hash(__ht._M_hash)
+ , _M_equals(__ht._M_equals)
+ , _M_get_key(__ht._M_get_key)
+ , _M_buckets(__ht.get_allocator())
+ , _M_num_elements(0)
{
_M_copy_from(__ht);
}
- hashtable& operator= (const hashtable& __ht)
+ hashtable& operator=(const hashtable& __ht)
{
if (&__ht != this) {
clear();
@@ -360,15 +366,15 @@ public:
const_iterator end() const { return const_iterator(0, this); }
- friend bool operator==<>(const hashtable&,
- const hashtable&);
+ friend bool operator==<>(const hashtable&, const hashtable&);
public:
-
size_type bucket_count() const { return _M_buckets.size(); }
size_type max_bucket_count() const
- { return get_stl_prime_list()[(int)_stl_num_primes - 1]; }
+ {
+ return get_stl_prime_list()[(int)_stl_num_primes - 1];
+ }
size_type elems_in_bucket(size_type __bucket) const
{
@@ -396,14 +402,16 @@ public:
template <class _InputIterator>
void insert_unique(_InputIterator __f, _InputIterator __l)
{
- insert_unique(__f, __l,
+ insert_unique(
+ __f, __l,
typename std::iterator_traits<_InputIterator>::iterator_category());
}
template <class _InputIterator>
void insert_equal(_InputIterator __f, _InputIterator __l)
{
- insert_equal(__f, __l,
+ insert_equal(
+ __f, __l,
typename std::iterator_traits<_InputIterator>::iterator_category());
}
@@ -411,7 +419,7 @@ public:
void insert_unique(_InputIterator __f, _InputIterator __l,
std::input_iterator_tag)
{
- for ( ; __f != __l; ++__f)
+ for (; __f != __l; ++__f)
insert_unique(*__f);
}
@@ -419,7 +427,7 @@ public:
void insert_equal(_InputIterator __f, _InputIterator __l,
std::input_iterator_tag)
{
- for ( ; __f != __l; ++__f)
+ for (; __f != __l; ++__f)
insert_equal(*__f);
}
@@ -430,7 +438,7 @@ public:
size_type __n = 0;
std::distance(__f, __l, __n);
resize(_M_num_elements + __n);
- for ( ; __n > 0; --__n, ++__f)
+ for (; __n > 0; --__n, ++__f)
insert_unique_noresize(*__f);
}
@@ -441,7 +449,7 @@ public:
size_type __n = 0;
std::distance(__f, __l, __n);
resize(_M_num_elements + __n);
- for ( ; __n > 0; --__n, ++__f)
+ for (; __n > 0; --__n, ++__f)
insert_equal_noresize(*__f);
}
@@ -451,10 +459,10 @@ public:
{
size_type __n = _M_bkt_num_key(__key);
_Node* __first;
- for ( __first = _M_buckets[__n];
- __first && !_M_equals(_M_get_key(__first->_M_val), __key);
- __first = __first->_M_next)
- {}
+ for (__first = _M_buckets[__n];
+ __first && !_M_equals(_M_get_key(__first->_M_val), __key);
+ __first = __first->_M_next) {
+ }
return iterator(__first, this);
}
@@ -462,10 +470,10 @@ public:
{
size_type __n = _M_bkt_num_key(__key);
const _Node* __first;
- for ( __first = _M_buckets[__n];
- __first && !_M_equals(_M_get_key(__first->_M_val), __key);
- __first = __first->_M_next)
- {}
+ for (__first = _M_buckets[__n];
+ __first && !_M_equals(_M_get_key(__first->_M_val), __key);
+ __first = __first->_M_next) {
+ }
return const_iterator(__first, this);
}
@@ -480,11 +488,10 @@ public:
return __result;
}
- std::pair<iterator, iterator>
- equal_range(const key_type& __key);
+ std::pair<iterator, iterator> equal_range(const key_type& __key);
- std::pair<const_iterator, const_iterator>
- equal_range(const key_type& __key) const;
+ std::pair<const_iterator, const_iterator> equal_range(
+ const key_type& __key) const;
size_type erase(const key_type& __key);
void erase(const iterator& __it);
@@ -497,14 +504,13 @@ public:
void clear();
private:
- size_type _M_next_size(size_type __n) const
- { return _stl_next_prime(__n); }
+ size_type _M_next_size(size_type __n) const { return _stl_next_prime(__n); }
void _M_initialize_buckets(size_type __n)
{
const size_type __n_buckets = _M_next_size(__n);
_M_buckets.reserve(__n_buckets);
- _M_buckets.insert(_M_buckets.end(), __n_buckets, (_Node*) 0);
+ _M_buckets.insert(_M_buckets.end(), __n_buckets, (_Node*)0);
_M_num_elements = 0;
}
@@ -528,15 +534,12 @@ private:
return _M_bkt_num_key(_M_get_key(__obj), __n);
}
- void construct(_Val* p, const _Val& v)
- {
- new (p) _Val(v);
- }
+ void construct(_Val* p, const _Val& v) { new (p) _Val(v); }
void destroy(_Val* p)
- {
+ {
(void)p;
p->~_Val();
- }
+ }
_Node* _M_new_node(const value_type& __obj)
{
@@ -545,8 +548,10 @@ private:
try {
construct(&__n->_M_val, __obj);
return __n;
+ } catch (...) {
+ _M_put_node(__n);
+ throw;
}
- catch(...) {_M_put_node(__n); throw;}
}
void _M_delete_node(_Node* __n)
@@ -559,13 +564,12 @@ private:
void _M_erase_bucket(const size_type __n, _Node* __last);
void _M_copy_from(const hashtable& __ht);
-
};
template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
class _All>
-_Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>&
-_Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
+_Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>&
+ _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++()
{
const _Node* __old = _M_cur;
_M_cur = _M_cur->_M_next;
@@ -579,8 +583,8 @@ _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
class _All>
-inline _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>
-_Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
+inline _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>
+ _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++(int)
{
iterator __tmp = *this;
++*this;
@@ -589,8 +593,8 @@ _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
class _All>
-_Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>&
-_Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
+_Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>&
+ _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++()
{
const _Node* __old = _M_cur;
_M_cur = _M_cur->_M_next;
@@ -604,8 +608,8 @@ _Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
class _All>
-inline _Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>
-_Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
+inline _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>
+ _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++(int)
{
const_iterator __tmp = *this;
++*this;
@@ -613,18 +617,18 @@ _Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
- const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2)
+bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
+ const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2)
{
- typedef typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::_Node _Node;
+ typedef typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_Node _Node;
if (__ht1._M_buckets.size() != __ht2._M_buckets.size())
return false;
for (int __n = 0; __n < __ht1._M_buckets.size(); ++__n) {
_Node* __cur1 = __ht1._M_buckets[__n];
_Node* __cur2 = __ht2._M_buckets[__n];
- for ( ; __cur1 && __cur2 && __cur1->_M_val == __cur2->_M_val;
- __cur1 = __cur1->_M_next, __cur2 = __cur2->_M_next)
- {}
+ for (; __cur1 && __cur2 && __cur1->_M_val == __cur2->_M_val;
+ __cur1 = __cur1->_M_next, __cur2 = __cur2->_M_next) {
+ }
if (__cur1 || __cur2)
return false;
}
@@ -632,22 +636,24 @@ bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline bool operator!=(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
- const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2) {
+inline bool operator!=(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
+ const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2)
+{
return !(__ht1 == __ht2);
}
template <class _Val, class _Key, class _HF, class _Extract, class _EqKey,
class _All>
inline void swap(hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht1,
- hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht2) {
+ hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht2)
+{
__ht1.swap(__ht2);
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator, bool>
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::insert_unique_noresize(const value_type& __obj)
+std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator, bool>
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::insert_unique_noresize(
+ const value_type& __obj)
{
const size_type __n = _M_bkt_num(__obj);
_Node* __first = _M_buckets[__n];
@@ -664,9 +670,9 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::insert_equal_noresize(const value_type& __obj)
+typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::insert_equal_noresize(
+ const value_type& __obj)
{
const size_type __n = _M_bkt_num(__obj);
_Node* __first = _M_buckets[__n];
@@ -688,8 +694,8 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::reference
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::find_or_insert(const value_type& __obj)
+typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::reference hashtable<
+ _Val, _Key, _HF, _Ex, _Eq, _All>::find_or_insert(const value_type& __obj)
{
resize(_M_num_elements + 1);
@@ -708,9 +714,9 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::find_or_insert(const value_type& __obj)
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator,
- typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator>
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::equal_range(const key_type& __key)
+std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator,
+ typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator>
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::equal_range(const key_type& __key)
{
typedef std::pair<iterator, iterator> _Pii;
const size_type __n = _M_bkt_num_key(__key);
@@ -723,27 +729,25 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::equal_range(const key_type& __key)
for (size_type __m = __n + 1; __m < _M_buckets.size(); ++__m)
if (_M_buckets[__m])
return _Pii(iterator(__first, this),
- iterator(_M_buckets[__m], this));
+ iterator(_M_buckets[__m], this));
return _Pii(iterator(__first, this), end());
}
return _Pii(end(), end());
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::const_iterator,
- typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::const_iterator>
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::equal_range(const key_type& __key) const
+std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator,
+ typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator>
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::equal_range(
+ const key_type& __key) const
{
typedef std::pair<const_iterator, const_iterator> _Pii;
const size_type __n = _M_bkt_num_key(__key);
- for (const _Node* __first = _M_buckets[__n] ;
- __first;
+ for (const _Node* __first = _M_buckets[__n]; __first;
__first = __first->_M_next) {
if (_M_equals(_M_get_key(__first->_M_val), __key)) {
- for (const _Node* __cur = __first->_M_next;
- __cur;
+ for (const _Node* __cur = __first->_M_next; __cur;
__cur = __cur->_M_next)
if (!_M_equals(_M_get_key(__cur->_M_val), __key))
return _Pii(const_iterator(__first, this),
@@ -759,8 +763,8 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::size_type
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
+typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::size_type
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(const key_type& __key)
{
const size_type __n = _M_bkt_num_key(__key);
_Node* __first = _M_buckets[__n];
@@ -776,8 +780,7 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
__next = __cur->_M_next;
++__erased;
--_M_num_elements;
- }
- else {
+ } else {
__cur = __next;
__next = __cur->_M_next;
}
@@ -793,7 +796,7 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(const iterator& __it)
{
_Node* __p = __it._M_cur;
if (__p) {
@@ -804,8 +807,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
_M_buckets[__n] = __cur->_M_next;
_M_delete_node(__cur);
--_M_num_elements;
- }
- else {
+ } else {
_Node* __next = __cur->_M_next;
while (__next) {
if (__next == __p) {
@@ -813,8 +815,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
_M_delete_node(__next);
--_M_num_elements;
break;
- }
- else {
+ } else {
__cur = __next;
__next = __cur->_M_next;
}
@@ -824,13 +825,13 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::erase(iterator __first, iterator __last)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(iterator __first,
+ iterator __last)
{
- size_type __f_bucket = __first._M_cur ?
- _M_bkt_num(__first._M_cur->_M_val) : _M_buckets.size();
- size_type __l_bucket = __last._M_cur ?
- _M_bkt_num(__last._M_cur->_M_val) : _M_buckets.size();
+ size_type __f_bucket =
+ __first._M_cur ? _M_bkt_num(__first._M_cur->_M_val) : _M_buckets.size();
+ size_type __l_bucket =
+ __last._M_cur ? _M_bkt_num(__last._M_cur->_M_val) : _M_buckets.size();
if (__first._M_cur == __last._M_cur)
return;
@@ -846,9 +847,8 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline void
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const_iterator __first,
- const_iterator __last)
+inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(
+ const_iterator __first, const_iterator __last)
{
erase(iterator(const_cast<_Node*>(__first._M_cur),
const_cast<hashtable*>(__first._M_ht)),
@@ -857,24 +857,22 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const_iterator __first,
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline void
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const const_iterator& __it)
+inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(
+ const const_iterator& __it)
{
erase(iterator(const_cast<_Node*>(__it._M_cur),
const_cast<hashtable*>(__it._M_ht)));
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::resize(size_type __num_elements_hint)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::resize(
+ size_type __num_elements_hint)
{
const size_type __old_n = _M_buckets.size();
if (__num_elements_hint > __old_n) {
const size_type __n = _M_next_size(__num_elements_hint);
if (__n > __old_n) {
- _M_buckets_type __tmp(
- __n, (_Node*)(0),
- _M_buckets.get_allocator());
+ _M_buckets_type __tmp(__n, (_Node*)(0), _M_buckets.get_allocator());
try {
for (size_type __bucket = 0; __bucket < __old_n; ++__bucket) {
_Node* __first = _M_buckets[__bucket];
@@ -887,8 +885,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
}
_M_buckets.swap(__tmp);
- }
- catch(...) {
+ } catch (...) {
for (size_type __bucket = 0; __bucket < __tmp.size(); ++__bucket) {
while (__tmp[__bucket]) {
_Node* __next = __tmp[__bucket]->_M_next;
@@ -903,16 +900,15 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::_M_erase_bucket(const size_type __n, _Node* __first, _Node* __last)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_erase_bucket(
+ const size_type __n, _Node* __first, _Node* __last)
{
_Node* __cur = _M_buckets[__n];
if (__cur == __first)
_M_erase_bucket(__n, __last);
else {
_Node* __next;
- for (__next = __cur->_M_next;
- __next != __first;
+ for (__next = __cur->_M_next; __next != __first;
__cur = __next, __next = __cur->_M_next)
;
while (__next != __last) {
@@ -925,8 +921,8 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::_M_erase_bucket(const size_type __n, _Node* __last)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_erase_bucket(
+ const size_type __n, _Node* __last)
{
_Node* __cur = _M_buckets[__n];
while (__cur != __last) {
@@ -939,7 +935,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::clear()
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::clear()
{
for (size_type __i = 0; __i < _M_buckets.size(); ++__i) {
_Node* __cur = _M_buckets[__i];
@@ -953,14 +949,13 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::clear()
_M_num_elements = 0;
}
-
template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
- ::_M_copy_from(const hashtable& __ht)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_copy_from(
+ const hashtable& __ht)
{
_M_buckets.clear();
_M_buckets.reserve(__ht._M_buckets.size());
- _M_buckets.insert(_M_buckets.end(), __ht._M_buckets.size(), (_Node*) 0);
+ _M_buckets.insert(_M_buckets.end(), __ht._M_buckets.size(), (_Node*)0);
try {
for (size_type __i = 0; __i < __ht._M_buckets.size(); ++__i) {
const _Node* __cur = __ht._M_buckets[__i];
@@ -968,8 +963,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
_Node* __copy = _M_new_node(__cur->_M_val);
_M_buckets[__i] = __copy;
- for (_Node* __next = __cur->_M_next;
- __next;
+ for (_Node *__next = __cur->_M_next; __next;
__cur = __next, __next = __cur->_M_next) {
__copy->_M_next = _M_new_node(__next->_M_val);
__copy = __copy->_M_next;
@@ -977,21 +971,23 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
}
}
_M_num_elements = __ht._M_num_elements;
+ } catch (...) {
+ clear();
+ throw;
}
- catch(...) {clear(); throw;}
}
} // namespace @KWSYS_NAMESPACE@
// Undo warning suppression.
#if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-# pragma clang diagnostic pop
-# endif
+#if __has_warning("-Wdeprecated")
+#pragma clang diagnostic pop
+#endif
#endif
#if defined(_MSC_VER)
-# pragma warning (pop)
+#pragma warning(pop)
#endif
#endif
diff --git a/Source/kwsys/kwsysHeaderDump.pl b/Source/kwsys/kwsysHeaderDump.pl
index 0dc4a52..e3391e7 100755
--- a/Source/kwsys/kwsysHeaderDump.pl
+++ b/Source/kwsys/kwsysHeaderDump.pl
@@ -1,15 +1,6 @@
#!/usr/bin/perl
-#=============================================================================
-# KWSys - Kitware System Library
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
if ( $#ARGV+1 < 2 )
{
diff --git a/Source/kwsys/kwsysPlatformTests.cmake b/Source/kwsys/kwsysPlatformTests.cmake
index 0da0f63..5386a49 100644
--- a/Source/kwsys/kwsysPlatformTests.cmake
+++ b/Source/kwsys/kwsysPlatformTests.cmake
@@ -1,14 +1,6 @@
-#=============================================================================
-# KWSys - Kitware System Library
-# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
+# 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)
diff --git a/Source/kwsys/kwsysPlatformTestsC.c b/Source/kwsys/kwsysPlatformTestsC.c
index e602964..d12fac0 100644
--- a/Source/kwsys/kwsysPlatformTestsC.c
+++ b/Source/kwsys/kwsysPlatformTestsC.c
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
/*
Macros to define main() in a cross-platform way.
@@ -26,21 +17,23 @@
}
*/
#if defined(__CLASSIC_C__)
-# define KWSYS_PLATFORM_TEST_C_MAIN() \
- main()
-# define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
- main(argc,argv) int argc; char* argv[];
+#define KWSYS_PLATFORM_TEST_C_MAIN() main()
+#define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
+ main(argc, argv) int argc; \
+ char* argv[];
#else
-# define KWSYS_PLATFORM_TEST_C_MAIN() \
- main(void)
-# define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
+#define KWSYS_PLATFORM_TEST_C_MAIN() main(void)
+#define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
main(int argc, char* argv[])
#endif
/*--------------------------------------------------------------------------*/
#ifdef TEST_KWSYS_C_HAS_PTRDIFF_T
#include <stddef.h>
-int f(ptrdiff_t n) { return n > 0; }
+int f(ptrdiff_t n)
+{
+ return n > 0;
+}
int KWSYS_PLATFORM_TEST_C_MAIN()
{
char* p = 0;
@@ -53,7 +46,10 @@ int KWSYS_PLATFORM_TEST_C_MAIN()
/*--------------------------------------------------------------------------*/
#ifdef TEST_KWSYS_C_HAS_SSIZE_T
#include <unistd.h>
-int f(ssize_t n) { return (int)n; }
+int f(ssize_t n)
+{
+ return (int)n;
+}
int KWSYS_PLATFORM_TEST_C_MAIN()
{
ssize_t n = 0;
@@ -65,28 +61,28 @@ int KWSYS_PLATFORM_TEST_C_MAIN()
#ifdef TEST_KWSYS_C_TYPE_MACROS
char* info_macros =
#if defined(__SIZEOF_SHORT__)
-"INFO:macro[__SIZEOF_SHORT__]\n"
+ "INFO:macro[__SIZEOF_SHORT__]\n"
#endif
#if defined(__SIZEOF_INT__)
-"INFO:macro[__SIZEOF_INT__]\n"
+ "INFO:macro[__SIZEOF_INT__]\n"
#endif
#if defined(__SIZEOF_LONG__)
-"INFO:macro[__SIZEOF_LONG__]\n"
+ "INFO:macro[__SIZEOF_LONG__]\n"
#endif
#if defined(__SIZEOF_LONG_LONG__)
-"INFO:macro[__SIZEOF_LONG_LONG__]\n"
+ "INFO:macro[__SIZEOF_LONG_LONG__]\n"
#endif
#if defined(__SHORT_MAX__)
-"INFO:macro[__SHORT_MAX__]\n"
+ "INFO:macro[__SHORT_MAX__]\n"
#endif
#if defined(__INT_MAX__)
-"INFO:macro[__INT_MAX__]\n"
+ "INFO:macro[__INT_MAX__]\n"
#endif
#if defined(__LONG_MAX__)
-"INFO:macro[__LONG_MAX__]\n"
+ "INFO:macro[__LONG_MAX__]\n"
#endif
#if defined(__LONG_LONG_MAX__)
-"INFO:macro[__LONG_LONG_MAX__]\n"
+ "INFO:macro[__LONG_LONG_MAX__]\n"
#endif
"";
diff --git a/Source/kwsys/kwsysPlatformTestsCXX.cxx b/Source/kwsys/kwsysPlatformTestsCXX.cxx
index b35808b..01c6951 100644
--- a/Source/kwsys/kwsysPlatformTestsCXX.cxx
+++ b/Source/kwsys/kwsysPlatformTestsCXX.cxx
@@ -1,21 +1,18 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifdef TEST_KWSYS_CXX_HAS_CSTDIO
#include <cstdio>
-int main() { return 0; }
+int main()
+{
+ return 0;
+}
#endif
#ifdef TEST_KWSYS_CXX_HAS_LONG_LONG
-long long f(long long n) { return n; }
+long long f(long long n)
+{
+ return n;
+}
int main()
{
long long n = 0;
@@ -24,7 +21,10 @@ int main()
#endif
#ifdef TEST_KWSYS_CXX_HAS___INT64
-__int64 f(__int64 n) { return n; }
+__int64 f(__int64 n)
+{
+ return n;
+}
int main()
{
__int64 n = 0;
@@ -34,6 +34,7 @@ int main()
#ifdef TEST_KWSYS_CXX_STAT_HAS_ST_MTIM
#include <sys/types.h>
+
#include <sys/stat.h>
#include <unistd.h>
int main()
@@ -47,6 +48,7 @@ int main()
#ifdef TEST_KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
#include <sys/types.h>
+
#include <sys/stat.h>
#include <unistd.h>
int main()
@@ -59,7 +61,9 @@ int main()
#endif
#ifdef TEST_KWSYS_CXX_SAME_LONG_AND___INT64
-void function(long**) {}
+void function(long**)
+{
+}
int main()
{
__int64** p = 0;
@@ -69,7 +73,9 @@ int main()
#endif
#ifdef TEST_KWSYS_CXX_SAME_LONG_LONG_AND___INT64
-void function(long long**) {}
+void function(long long**)
+{
+}
int main()
{
__int64** p = 0;
@@ -79,10 +85,10 @@ int main()
#endif
#ifdef TEST_KWSYS_IOS_HAS_ISTREAM_LONG_LONG
-# include <iostream>
+#include <iostream>
int test_istream(std::istream& is, long long& x)
{
- return (is >> x)? 1:0;
+ return (is >> x) ? 1 : 0;
}
int main()
{
@@ -92,10 +98,10 @@ int main()
#endif
#ifdef TEST_KWSYS_IOS_HAS_OSTREAM_LONG_LONG
-# include <iostream>
+#include <iostream>
int test_ostream(std::ostream& os, long long x)
{
- return (os << x)? 1:0;
+ return (os << x) ? 1 : 0;
}
int main()
{
@@ -105,10 +111,10 @@ int main()
#endif
#ifdef TEST_KWSYS_IOS_HAS_ISTREAM___INT64
-# include <iostream>
+#include <iostream>
int test_istream(std::istream& is, __int64& x)
{
- return (is >> x)? 1:0;
+ return (is >> x) ? 1 : 0;
}
int main()
{
@@ -118,10 +124,10 @@ int main()
#endif
#ifdef TEST_KWSYS_IOS_HAS_OSTREAM___INT64
-# include <iostream>
+#include <iostream>
int test_ostream(std::ostream& os, __int64 x)
{
- return (os << x)? 1:0;
+ return (os << x) ? 1 : 0;
}
int main()
{
@@ -137,30 +143,31 @@ int main()
#define _LARGE_FILES
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
-#include <sys/stat.h>
+
#include <assert.h>
+#include <sys/stat.h>
#if KWSYS_CXX_HAS_CSTDIO
-# include <cstdio>
+#include <cstdio>
#endif
#include <stdio.h>
-int main(int, char **argv)
+int main(int, char** argv)
{
- /* check that off_t can hold 2^63 - 1 and perform basic operations... */
-#define OFF_T_64 (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+/* check that off_t can hold 2^63 - 1 and perform basic operations... */
+#define OFF_T_64 (((off_t)1 << 62) - 1 + ((off_t)1 << 62))
if (OFF_T_64 % 2147483647 != 1)
return 1;
// stat breaks on SCO OpenServer
struct stat buf;
- stat( argv[0], &buf );
+ stat(argv[0], &buf);
if (!S_ISREG(buf.st_mode))
return 2;
- FILE *file = fopen( argv[0], "r" );
- off_t offset = ftello( file );
- fseek( file, offset, SEEK_CUR );
- fclose( file );
+ FILE* file = fopen(argv[0], "r");
+ off_t offset = ftello(file);
+ fseek(file, offset, SEEK_CUR);
+ fclose(file);
return 0;
}
#endif
@@ -187,14 +194,14 @@ int main()
int main()
{
char* e = environ[0];
- return e? 0:1;
+ return e ? 0 : 1;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_GETLOADAVG
// Match feature definitions from SystemInformation.cxx
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
#endif
#include <stdlib.h>
int main()
@@ -205,17 +212,17 @@ int main()
#endif
#ifdef TEST_KWSYS_CXX_HAS_RLIMIT64
-# if defined(KWSYS_HAS_LFS)
-# define _LARGEFILE_SOURCE
-# define _LARGEFILE64_SOURCE
-# define _LARGE_FILES
-# define _FILE_OFFSET_BITS 64
-# endif
-# include <sys/resource.h>
+#if defined(KWSYS_HAS_LFS)
+#define _LARGEFILE_SOURCE
+#define _LARGEFILE64_SOURCE
+#define _LARGE_FILES
+#define _FILE_OFFSET_BITS 64
+#endif
+#include <sys/resource.h>
int main()
{
struct rlimit64 rlim;
- return getrlimit64(0,&rlim);
+ return getrlimit64(0, &rlim);
}
#endif
@@ -223,7 +230,7 @@ int main()
#include <stdlib.h>
int main()
{
- const char *str="1024";
+ const char* str = "1024";
return static_cast<int>(atoll(str));
}
#endif
@@ -232,7 +239,7 @@ int main()
#include <stdlib.h>
int main()
{
- const char *str="1024";
+ const char* str = "1024";
return static_cast<int>(atol(str));
}
#endif
@@ -241,7 +248,7 @@ int main()
#include <stdlib.h>
int main()
{
- const char *str="1024";
+ const char* str = "1024";
return static_cast<int>(_atoi64(str));
}
#endif
@@ -260,58 +267,58 @@ int main()
#include <sys/stat.h>
int main()
{
- struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
+ struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } };
return utimensat(AT_FDCWD, "/example", times, AT_SYMLINK_NOFOLLOW);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_BACKTRACE
-#if defined(__PATHSCALE__) || defined(__PATHCC__) \
- || (defined(__LSB_VERSION__) && (__LSB_VERSION__ < 41))
+#if defined(__PATHSCALE__) || defined(__PATHCC__) || \
+ (defined(__LSB_VERSION__) && (__LSB_VERSION__ < 41))
backtrace doesnt work with this compiler or os
#endif
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
#endif
#include <execinfo.h>
int main()
{
- void *stackSymbols[256];
- backtrace(stackSymbols,256);
- backtrace_symbols(&stackSymbols[0],1);
+ void* stackSymbols[256];
+ backtrace(stackSymbols, 256);
+ backtrace_symbols(&stackSymbols[0], 1);
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_DLADDR
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
#endif
#include <dlfcn.h>
int main()
{
Dl_info info;
- int ierr=dladdr((void*)main,&info);
+ int ierr = dladdr((void*)main, &info);
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_CXXABI
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
#endif
-#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5130 \
- && __linux && __SUNPRO_CC_COMPAT == 'G'
-# include <iostream>
+#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5130 && __linux && \
+ __SUNPRO_CC_COMPAT == 'G'
+#include <iostream>
#endif
#include <cxxabi.h>
int main()
{
int status = 0;
size_t bufferLen = 512;
- char buffer[512] = {'\0'};
- const char *function="_ZN5kwsys17SystemInformation15GetProgramStackEii";
- char *demangledFunction =
+ char buffer[512] = { '\0' };
+ const char* function = "_ZN5kwsys17SystemInformation15GetProgramStackEii";
+ char* demangledFunction =
abi::__cxa_demangle(function, buffer, &bufferLen, &status);
return status;
}
@@ -346,11 +353,19 @@ int main()
#ifdef TEST_KWSYS_STL_HAS_WSTRING
#include <string>
-void f(std ::wstring*) {}
-int main() { return 0; }
+void f(std::wstring*)
+{
+}
+int main()
+{
+ return 0;
+}
#endif
#ifdef TEST_KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H
#include <ext/stdio_filebuf.h>
-int main() { return 0; }
+int main()
+{
+ return 0;
+}
#endif
diff --git a/Source/kwsys/kwsysPrivate.h b/Source/kwsys/kwsysPrivate.h
index 3a26c26..ce1b53e 100644
--- a/Source/kwsys/kwsysPrivate.h
+++ b/Source/kwsys/kwsysPrivate.h
@@ -1,16 +1,7 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef KWSYS_NAMESPACE
-# error "Do not include kwsysPrivate.h outside of kwsys c and cxx files."
+#error "Do not include kwsysPrivate.h outside of kwsys c and cxx files."
#endif
#ifndef _kwsysPrivate_h
@@ -24,7 +15,9 @@
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(std/vector)
*/
+/* clang-format off */
#define KWSYS_HEADER(x) KWSYS_HEADER0(KWSYS_NAMESPACE/x)
+/* clang-format on */
#define KWSYS_HEADER0(x) KWSYS_HEADER1(x)
#define KWSYS_HEADER1(x) <x>
@@ -37,5 +30,5 @@
#define KWSYS_NAMESPACE_STRING1(x) #x
#else
-# error "kwsysPrivate.h included multiple times."
+#error "kwsysPrivate.h included multiple times."
#endif
diff --git a/Source/kwsys/testCommandLineArguments.cxx b/Source/kwsys/testCommandLineArguments.cxx
index 525522d..d2215d6 100644
--- a/Source/kwsys/testCommandLineArguments.cxx
+++ b/Source/kwsys/testCommandLineArguments.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(CommandLineArguments.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "CommandLineArguments.hxx.in"
+#include "CommandLineArguments.hxx.in"
#endif
#include <iostream>
@@ -28,33 +19,45 @@ static void* random_ptr = reinterpret_cast<void*>(0x123);
static int argument(const char* arg, const char* value, void* call_data)
{
- std::cout << "Got argument: \"" << arg << "\" value: \"" << (value?value:"(null)") << "\"" << std::endl;
- if ( call_data != random_ptr )
- {
+ std::cout << "Got argument: \"" << arg << "\" value: \""
+ << (value ? value : "(null)") << "\"" << std::endl;
+ if (call_data != random_ptr) {
std::cerr << "Problem processing call_data" << std::endl;
return 0;
- }
+ }
return 1;
}
static int unknown_argument(const char* argument, void* call_data)
{
std::cout << "Got unknown argument: \"" << argument << "\"" << std::endl;
- if ( call_data != random_ptr )
- {
+ if (call_data != random_ptr) {
std::cerr << "Problem processing call_data" << std::endl;
return 0;
- }
+ }
return 1;
}
-static bool CompareTwoItemsOnList(bool i1, bool i2) { return i1 == i2; }
-static bool CompareTwoItemsOnList(int i1, int i2) { return i1 == i2; }
-static bool CompareTwoItemsOnList(double i1, double i2) { return i1 == i2; }
-static bool CompareTwoItemsOnList(const char* i1,
- const char* i2) { return strcmp(i1, i2) == 0; }
-static bool CompareTwoItemsOnList(const std::string& i1,
- const std::string& i2) { return i1 == i2; }
+static bool CompareTwoItemsOnList(bool i1, bool i2)
+{
+ return i1 == i2;
+}
+static bool CompareTwoItemsOnList(int i1, int i2)
+{
+ return i1 == i2;
+}
+static bool CompareTwoItemsOnList(double i1, double i2)
+{
+ return i1 == i2;
+}
+static bool CompareTwoItemsOnList(const char* i1, const char* i2)
+{
+ return strcmp(i1, i2) == 0;
+}
+static bool CompareTwoItemsOnList(const std::string& i1, const std::string& i2)
+{
+ return i1 == i2;
+}
int testCommandLineArguments(int argc, char* argv[])
{
@@ -97,73 +100,89 @@ int testCommandLineArguments(int argc, char* argv[])
typedef kwsys::CommandLineArguments argT;
- arg.AddArgument("--some-int-variable", argT::SPACE_ARGUMENT, &some_int_variable, "Set some random int variable");
- arg.AddArgument("--some-double-variable", argT::CONCAT_ARGUMENT, &some_double_variable, "Set some random double variable");
- arg.AddArgument("--some-string-variable", argT::EQUAL_ARGUMENT, &some_string_variable, "Set some random string variable");
- arg.AddArgument("--some-stl-string-variable", argT::EQUAL_ARGUMENT, &some_stl_string_variable, "Set some random stl string variable");
- arg.AddArgument("--some-bool-variable", argT::EQUAL_ARGUMENT, &some_bool_variable, "Set some random bool variable");
- arg.AddArgument("--another-bool-variable", argT::NO_ARGUMENT, &some_bool_variable1, "Set some random bool variable 1");
- arg.AddBooleanArgument("--set-bool-arg1", &bool_arg1, "Test AddBooleanArgument 1");
- arg.AddBooleanArgument("--set-bool-arg2", &bool_arg2, "Test AddBooleanArgument 2");
- arg.AddArgument("--some-multi-argument", argT::MULTI_ARGUMENT, &numbers_argument, "Some multiple values variable");
- arg.AddArgument("-N", argT::SPACE_ARGUMENT, &doubles_argument, "Some explicit multiple values variable");
- arg.AddArgument("-BB", argT::CONCAT_ARGUMENT, &bools_argument, "Some explicit multiple values variable");
- arg.AddArgument("-SS", argT::EQUAL_ARGUMENT, &strings_argument, "Some explicit multiple values variable");
- arg.AddArgument("-SSS", argT::MULTI_ARGUMENT, &stl_strings_argument, "Some explicit multiple values variable");
-
- arg.AddCallback("-A", argT::NO_ARGUMENT, argument, random_ptr, "Some option -A. This option has a multiline comment. It should demonstrate how the code splits lines.");
- arg.AddCallback("-B", argT::SPACE_ARGUMENT, argument, random_ptr, "Option -B takes argument with space");
- arg.AddCallback("-C", argT::EQUAL_ARGUMENT, argument, random_ptr, "Option -C takes argument after =");
- arg.AddCallback("-D", argT::CONCAT_ARGUMENT, argument, random_ptr, "This option takes concatinated argument");
+ arg.AddArgument("--some-int-variable", argT::SPACE_ARGUMENT,
+ &some_int_variable, "Set some random int variable");
+ arg.AddArgument("--some-double-variable", argT::CONCAT_ARGUMENT,
+ &some_double_variable, "Set some random double variable");
+ arg.AddArgument("--some-string-variable", argT::EQUAL_ARGUMENT,
+ &some_string_variable, "Set some random string variable");
+ arg.AddArgument("--some-stl-string-variable", argT::EQUAL_ARGUMENT,
+ &some_stl_string_variable,
+ "Set some random stl string variable");
+ arg.AddArgument("--some-bool-variable", argT::EQUAL_ARGUMENT,
+ &some_bool_variable, "Set some random bool variable");
+ arg.AddArgument("--another-bool-variable", argT::NO_ARGUMENT,
+ &some_bool_variable1, "Set some random bool variable 1");
+ arg.AddBooleanArgument("--set-bool-arg1", &bool_arg1,
+ "Test AddBooleanArgument 1");
+ arg.AddBooleanArgument("--set-bool-arg2", &bool_arg2,
+ "Test AddBooleanArgument 2");
+ arg.AddArgument("--some-multi-argument", argT::MULTI_ARGUMENT,
+ &numbers_argument, "Some multiple values variable");
+ arg.AddArgument("-N", argT::SPACE_ARGUMENT, &doubles_argument,
+ "Some explicit multiple values variable");
+ arg.AddArgument("-BB", argT::CONCAT_ARGUMENT, &bools_argument,
+ "Some explicit multiple values variable");
+ arg.AddArgument("-SS", argT::EQUAL_ARGUMENT, &strings_argument,
+ "Some explicit multiple values variable");
+ arg.AddArgument("-SSS", argT::MULTI_ARGUMENT, &stl_strings_argument,
+ "Some explicit multiple values variable");
+
+ arg.AddCallback("-A", argT::NO_ARGUMENT, argument, random_ptr,
+ "Some option -A. This option has a multiline comment. It "
+ "should demonstrate how the code splits lines.");
+ arg.AddCallback("-B", argT::SPACE_ARGUMENT, argument, random_ptr,
+ "Option -B takes argument with space");
+ arg.AddCallback("-C", argT::EQUAL_ARGUMENT, argument, random_ptr,
+ "Option -C takes argument after =");
+ arg.AddCallback("-D", argT::CONCAT_ARGUMENT, argument, random_ptr,
+ "This option takes concatinated argument");
arg.AddCallback("--long1", argT::NO_ARGUMENT, argument, random_ptr, "-A");
arg.AddCallback("--long2", argT::SPACE_ARGUMENT, argument, random_ptr, "-B");
- arg.AddCallback("--long3", argT::EQUAL_ARGUMENT, argument, random_ptr, "Same as -C but a bit different");
- arg.AddCallback("--long4", argT::CONCAT_ARGUMENT, argument, random_ptr, "-C");
+ arg.AddCallback("--long3", argT::EQUAL_ARGUMENT, argument, random_ptr,
+ "Same as -C but a bit different");
+ arg.AddCallback("--long4", argT::CONCAT_ARGUMENT, argument, random_ptr,
+ "-C");
- if ( !arg.Parse() )
- {
+ if (!arg.Parse()) {
std::cerr << "Problem parsing arguments" << std::endl;
res = 1;
- }
+ }
std::cout << "Help: " << arg.GetHelp() << std::endl;
- std::cout << "Some int variable was set to: " << some_int_variable << std::endl;
- std::cout << "Some double variable was set to: " << some_double_variable << std::endl;
- if ( some_string_variable && strcmp(some_string_variable, "test string with space") == 0)
- {
- std::cout << "Some string variable was set to: " << some_string_variable << std::endl;
- delete [] some_string_variable;
- }
- else
- {
+ std::cout << "Some int variable was set to: " << some_int_variable
+ << std::endl;
+ std::cout << "Some double variable was set to: " << some_double_variable
+ << std::endl;
+ if (some_string_variable &&
+ strcmp(some_string_variable, "test string with space") == 0) {
+ std::cout << "Some string variable was set to: " << some_string_variable
+ << std::endl;
+ delete[] some_string_variable;
+ } else {
std::cerr << "Problem setting string variable" << std::endl;
res = 1;
- }
+ }
size_t cc;
-#define CompareTwoLists(list1, list_valid, lsize) \
- if ( list1.size() != lsize ) \
- { \
- std::cerr << "Problem setting " #list1 ". Size is: " << list1.size() \
- << " should be: " << lsize << std::endl; \
- res = 1; \
- } \
- else \
- { \
- std::cout << #list1 " argument set:"; \
- for ( cc =0; cc < lsize; ++ cc ) \
- { \
- std::cout << " " << list1[cc]; \
- if ( !CompareTwoItemsOnList(list1[cc], list_valid[cc]) ) \
- { \
- std::cerr << "Problem setting " #list1 ". Value of " \
- << cc << " is: [" << list1[cc] << "] <> [" \
- << list_valid[cc] << "]" << std::endl; \
- res = 1; \
- break; \
- } \
- } \
- std::cout << std::endl; \
- }
+#define CompareTwoLists(list1, list_valid, lsize) \
+ if (list1.size() != lsize) { \
+ std::cerr << "Problem setting " #list1 ". Size is: " << list1.size() \
+ << " should be: " << lsize << std::endl; \
+ res = 1; \
+ } else { \
+ std::cout << #list1 " argument set:"; \
+ for (cc = 0; cc < lsize; ++cc) { \
+ std::cout << " " << list1[cc]; \
+ if (!CompareTwoItemsOnList(list1[cc], list_valid[cc])) { \
+ std::cerr << "Problem setting " #list1 ". Value of " << cc \
+ << " is: [" << list1[cc] << "] <> [" << list_valid[cc] \
+ << "]" << std::endl; \
+ res = 1; \
+ break; \
+ } \
+ } \
+ std::cout << std::endl; \
+ }
CompareTwoLists(numbers_argument, valid_numbers, 10);
CompareTwoLists(doubles_argument, valid_doubles, 3);
@@ -171,17 +190,19 @@ int testCommandLineArguments(int argc, char* argv[])
CompareTwoLists(strings_argument, valid_strings, 4);
CompareTwoLists(stl_strings_argument, valid_stl_strings, 4);
- std::cout << "Some STL String variable was set to: " << some_stl_string_variable << std::endl;
- std::cout << "Some bool variable was set to: " << some_bool_variable << std::endl;
- std::cout << "Some bool variable was set to: " << some_bool_variable1 << std::endl;
+ std::cout << "Some STL String variable was set to: "
+ << some_stl_string_variable << std::endl;
+ std::cout << "Some bool variable was set to: " << some_bool_variable
+ << std::endl;
+ std::cout << "Some bool variable was set to: " << some_bool_variable1
+ << std::endl;
std::cout << "bool_arg1 variable was set to: " << bool_arg1 << std::endl;
std::cout << "bool_arg2 variable was set to: " << bool_arg2 << std::endl;
std::cout << std::endl;
- for ( cc = 0; cc < strings_argument.size(); ++ cc )
- {
- delete [] strings_argument[cc];
+ for (cc = 0; cc < strings_argument.size(); ++cc) {
+ delete[] strings_argument[cc];
strings_argument[cc] = 0;
- }
+ }
return res;
}
diff --git a/Source/kwsys/testCommandLineArguments1.cxx b/Source/kwsys/testCommandLineArguments1.cxx
index 6eb465d..5a03401 100644
--- a/Source/kwsys/testCommandLineArguments1.cxx
+++ b/Source/kwsys/testCommandLineArguments1.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(CommandLineArguments.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "CommandLineArguments.hxx.in"
+#include "CommandLineArguments.hxx.in"
#endif
#include <iostream>
@@ -41,68 +32,62 @@ int testCommandLineArguments1(int argc, char* argv[])
arg.StoreUnusedArguments(true);
- if ( !arg.Parse() )
- {
+ if (!arg.Parse()) {
std::cerr << "Problem parsing arguments" << std::endl;
res = 1;
- }
- if ( n != 24 )
- {
+ }
+ if (n != 24) {
std::cout << "Problem setting N. Value of N: " << n << std::endl;
res = 1;
- }
- if ( !m || strcmp(m, "test value") != 0 )
- {
+ }
+ if (!m || strcmp(m, "test value") != 0) {
std::cout << "Problem setting M. Value of M: " << m << std::endl;
res = 1;
- }
- if ( p != "1" )
- {
+ }
+ if (p != "1") {
std::cout << "Problem setting P. Value of P: " << p << std::endl;
res = 1;
- }
+ }
std::cout << "Value of N: " << n << std::endl;
std::cout << "Value of M: " << m << std::endl;
std::cout << "Value of P: " << p << std::endl;
- if ( m )
- {
- delete [] m;
- }
+ if (m) {
+ delete[] m;
+ }
char** newArgv = 0;
int newArgc = 0;
arg.GetUnusedArguments(&newArgc, &newArgv);
int cc;
- const char* valid_unused_args[9] = {
- 0, "--ignored", "--second-ignored", "third-ignored",
- "some", "junk", "at", "the", "end"
- };
- if ( newArgc != 9 )
- {
+ const char* valid_unused_args[9] = { 0,
+ "--ignored",
+ "--second-ignored",
+ "third-ignored",
+ "some",
+ "junk",
+ "at",
+ "the",
+ "end" };
+ if (newArgc != 9) {
std::cerr << "Bad number of unused arguments: " << newArgc << std::endl;
res = 1;
- }
- for ( cc = 0; cc < newArgc; ++ cc )
- {
+ }
+ for (cc = 0; cc < newArgc; ++cc) {
assert(newArgv[cc]); /* Quiet Clang scan-build. */
std::cout << "Unused argument[" << cc << "] = [" << newArgv[cc] << "]"
- << std::endl;
- if ( cc >= 9 )
- {
+ << std::endl;
+ if (cc >= 9) {
std::cerr << "Too many unused arguments: " << cc << std::endl;
res = 1;
- }
- else if ( valid_unused_args[cc] &&
- strcmp(valid_unused_args[cc], newArgv[cc]) != 0 )
- {
- std::cerr << "Bad unused argument [" << cc << "] \""
- << newArgv[cc] << "\" should be: \"" << valid_unused_args[cc] << "\""
- << std::endl;
+ } else if (valid_unused_args[cc] &&
+ strcmp(valid_unused_args[cc], newArgv[cc]) != 0) {
+ std::cerr << "Bad unused argument [" << cc << "] \"" << newArgv[cc]
+ << "\" should be: \"" << valid_unused_args[cc] << "\""
+ << std::endl;
res = 1;
- }
}
+ }
arg.DeleteRemainingArguments(newArgc, &newArgv);
return res;
}
-
diff --git a/Source/kwsys/testConsoleBuf.cxx b/Source/kwsys/testConsoleBuf.cxx
index d7775e6..bd58fb6 100644
--- a/Source/kwsys/testConsoleBuf.cxx
+++ b/Source/kwsys/testConsoleBuf.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
// Ignore Windows version levels defined by command-line flags. This
@@ -22,24 +13,26 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Encoding.hxx.in"
+#include "Encoding.hxx.in"
#endif
#if defined(_WIN32)
-#include <windows.h>
-#include <string.h>
-#include <wchar.h>
-#include <iostream>
#include <iomanip>
+#include <iostream>
#include <stdexcept>
+#include <string.h>
+#include <wchar.h>
+#include <windows.h>
+
#include "testConsoleBuf.hxx"
#if defined(_MSC_VER) && _MSC_VER >= 1800
-# define KWSYS_WINDOWS_DEPRECATED_GetVersion
+#define KWSYS_WINDOWS_DEPRECATED_GetVersion
#endif
// ŁŠŁˆŁ†ŁŠŁƒŁˆŲÆ
-static const WCHAR UnicodeInputTestString[] = L"\u064A\u0648\u0646\u064A\u0643\u0648\u062F!";
+static const WCHAR UnicodeInputTestString[] =
+ L"\u064A\u0648\u0646\u064A\u0643\u0648\u062F!";
static UINT TestCodepage = KWSYS_ENCODING_DEFAULT_CODEPAGE;
static const DWORD waitTimeout = 10 * 1000;
@@ -50,55 +43,62 @@ static HANDLE afterOutputEvent;
static std::string encodedInputTestString;
static std::string encodedTestString;
-static void displayError(DWORD errorCode) {
+static void displayError(DWORD errorCode)
+{
std::cerr.setf(std::ios::hex, std::ios::basefield);
std::cerr << "Failed with error: 0x" << errorCode << "!" << std::endl;
LPWSTR message;
- if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- errorCode,
- 0,
- (LPWSTR)&message, 0,
- NULL)
- ) {
- std::cerr << "Error message: " << kwsys::Encoding::ToNarrow(message) << std::endl;
+ if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL, errorCode, 0, (LPWSTR)&message, 0, NULL)) {
+ std::cerr << "Error message: " << kwsys::Encoding::ToNarrow(message)
+ << std::endl;
HeapFree(GetProcessHeap(), 0, message);
} else {
- std::cerr << "FormatMessage() failed with error: 0x" << GetLastError() << "!" << std::endl;
+ std::cerr << "FormatMessage() failed with error: 0x" << GetLastError()
+ << "!" << std::endl;
}
std::cerr.unsetf(std::ios::hex);
}
-std::basic_streambuf<char> *errstream(const char *unused) {
+std::basic_streambuf<char>* errstream(const char* unused)
+{
static_cast<void>(unused);
return std::cerr.rdbuf();
}
-std::basic_streambuf<wchar_t> *errstream(const wchar_t *unused) {
+std::basic_streambuf<wchar_t>* errstream(const wchar_t* unused)
+{
static_cast<void>(unused);
return std::wcerr.rdbuf();
}
//----------------------------------------------------------------------------
-template<typename T>
-static void dumpBuffers(const T *expected, const T *received, size_t size) {
+template <typename T>
+static void dumpBuffers(const T* expected, const T* received, size_t size)
+{
std::basic_ostream<T> err(errstream(expected));
- err << "Expected output: '" << std::basic_string<T>(expected, size) << "'" << std::endl;
+ err << "Expected output: '" << std::basic_string<T>(expected, size) << "'"
+ << std::endl;
if (err.fail()) {
err.clear();
err << "--- Error while outputting ---" << std::endl;
}
- err << "Received output: '" << std::basic_string<T>(received, size) << "'" << std::endl;
+ err << "Received output: '" << std::basic_string<T>(received, size) << "'"
+ << std::endl;
if (err.fail()) {
err.clear();
err << "--- Error while outputting ---" << std::endl;
}
std::cerr << "Expected output | Received output" << std::endl;
for (size_t i = 0; i < size; i++) {
- std::cerr << std::setbase(16) << std::setfill('0') << " " <<
- "0x" << std::setw(8) << static_cast<unsigned int>(expected[i]) << " | " <<
- "0x" << std::setw(8) << static_cast<unsigned int>(received[i]);
- if (static_cast<unsigned int>(expected[i]) != static_cast<unsigned int>(received[i])) {
+ std::cerr << std::setbase(16) << std::setfill('0') << " "
+ << "0x" << std::setw(8) << static_cast<unsigned int>(expected[i])
+ << " | "
+ << "0x" << std::setw(8)
+ << static_cast<unsigned int>(received[i]);
+ if (static_cast<unsigned int>(expected[i]) !=
+ static_cast<unsigned int>(received[i])) {
std::cerr << " MISMATCH!";
}
std::cerr << std::endl;
@@ -129,25 +129,29 @@ static bool createProcess(HANDLE hIn, HANDLE hOut, HANDLE hErr)
std::cerr << "GetModuleFileName failed!" << std::endl;
return false;
}
- WCHAR *p = cmd + wcslen(cmd);
- while (p > cmd && *p != L'\\') p--;
- *(p+1) = 0;
+ WCHAR* p = cmd + wcslen(cmd);
+ while (p > cmd && *p != L'\\')
+ p--;
+ *(p + 1) = 0;
wcscat(cmd, cmdConsoleBufChild);
wcscat(cmd, L".exe");
- bool success = CreateProcessW(NULL, // No module name (use command line)
- cmd, // Command line
- NULL, // Process handle not inheritable
- NULL, // Thread handle not inheritable
- bInheritHandles, // Set handle inheritance
- dwCreationFlags,
- NULL, // Use parent's environment block
- NULL, // Use parent's starting directory
- &startupInfo, // Pointer to STARTUPINFO structure
- &processInfo) != 0; // Pointer to PROCESS_INFORMATION structure
+ bool success =
+ CreateProcessW(NULL, // No module name (use command line)
+ cmd, // Command line
+ NULL, // Process handle not inheritable
+ NULL, // Thread handle not inheritable
+ bInheritHandles, // Set handle inheritance
+ dwCreationFlags,
+ NULL, // Use parent's environment block
+ NULL, // Use parent's starting directory
+ &startupInfo, // Pointer to STARTUPINFO structure
+ &processInfo) !=
+ 0; // Pointer to PROCESS_INFORMATION structure
if (!success) {
DWORD lastError = GetLastError();
- std::cerr << "CreateProcess(" << kwsys::Encoding::ToNarrow(cmd) << ")" << std::endl;
+ std::cerr << "CreateProcess(" << kwsys::Encoding::ToNarrow(cmd) << ")"
+ << std::endl;
displayError(lastError);
}
return success;
@@ -157,8 +161,8 @@ static bool createProcess(HANDLE hIn, HANDLE hOut, HANDLE hErr)
static void finishProcess(bool success)
{
if (success) {
- success = WaitForSingleObject(processInfo.hProcess, waitTimeout)
- == WAIT_OBJECT_0;
+ success =
+ WaitForSingleObject(processInfo.hProcess, waitTimeout) == WAIT_OBJECT_0;
};
if (!success) {
TerminateProcess(processInfo.hProcess, 1);
@@ -174,8 +178,8 @@ static bool createPipe(PHANDLE readPipe, PHANDLE writePipe)
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.bInheritHandle = TRUE;
securityAttributes.lpSecurityDescriptor = NULL;
- return CreatePipe(readPipe, writePipe, &securityAttributes, 0) == 0
- ? false : true;
+ return CreatePipe(readPipe, writePipe, &securityAttributes, 0) == 0 ? false
+ : true;
}
//----------------------------------------------------------------------------
@@ -197,16 +201,17 @@ static HANDLE createFile(LPCWSTR fileName)
securityAttributes.bInheritHandle = TRUE;
securityAttributes.lpSecurityDescriptor = NULL;
- HANDLE file = CreateFileW(fileName,
- GENERIC_READ | GENERIC_WRITE,
- 0, // do not share
- &securityAttributes,
- CREATE_ALWAYS, // overwrite existing
- FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
- NULL); // no template
+ HANDLE file =
+ CreateFileW(fileName, GENERIC_READ | GENERIC_WRITE,
+ 0, // do not share
+ &securityAttributes,
+ CREATE_ALWAYS, // overwrite existing
+ FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
+ NULL); // no template
if (file == INVALID_HANDLE_VALUE) {
DWORD lastError = GetLastError();
- std::cerr << "CreateFile(" << kwsys::Encoding::ToNarrow(fileName) << ")" << std::endl;
+ std::cerr << "CreateFile(" << kwsys::Encoding::ToNarrow(fileName) << ")"
+ << std::endl;
displayError(lastError);
}
return file;
@@ -223,7 +228,7 @@ static void finishFile(HANDLE file)
//----------------------------------------------------------------------------
#ifndef MAPVK_VK_TO_VSC
-# define MAPVK_VK_TO_VSC (0)
+#define MAPVK_VK_TO_VSC (0)
#endif
static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
@@ -238,9 +243,8 @@ static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
keyCode = 'K';
}
inputBuffer[0].Event.KeyEvent.wVirtualKeyCode = LOBYTE(keyCode);
- inputBuffer[0].Event.KeyEvent.wVirtualScanCode =
- MapVirtualKey(inputBuffer[0].Event.KeyEvent.wVirtualKeyCode,
- MAPVK_VK_TO_VSC);
+ inputBuffer[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(
+ inputBuffer[0].Event.KeyEvent.wVirtualKeyCode, MAPVK_VK_TO_VSC);
inputBuffer[0].Event.KeyEvent.uChar.UnicodeChar = chr;
inputBuffer[0].Event.KeyEvent.dwControlKeyState = 0;
if ((HIBYTE(keyCode) & 1) == 1) {
@@ -255,12 +259,12 @@ static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
inputBuffer[1].EventType = inputBuffer[0].EventType;
inputBuffer[1].Event.KeyEvent.bKeyDown = FALSE;
inputBuffer[1].Event.KeyEvent.wRepeatCount = 1;
- inputBuffer[1].Event.KeyEvent.wVirtualKeyCode = inputBuffer[0].Event.
- KeyEvent.wVirtualKeyCode;
- inputBuffer[1].Event.KeyEvent.wVirtualScanCode = inputBuffer[0].Event.
- KeyEvent.wVirtualScanCode;
- inputBuffer[1].Event.KeyEvent.uChar.UnicodeChar = inputBuffer[0].Event.
- KeyEvent.uChar.UnicodeChar;
+ inputBuffer[1].Event.KeyEvent.wVirtualKeyCode =
+ inputBuffer[0].Event.KeyEvent.wVirtualKeyCode;
+ inputBuffer[1].Event.KeyEvent.wVirtualScanCode =
+ inputBuffer[0].Event.KeyEvent.wVirtualScanCode;
+ inputBuffer[1].Event.KeyEvent.uChar.UnicodeChar =
+ inputBuffer[0].Event.KeyEvent.uChar.UnicodeChar;
inputBuffer[1].Event.KeyEvent.dwControlKeyState = 0;
}
@@ -292,29 +296,33 @@ static int testPipe()
DWORD bytesWritten = 0;
if (!WriteFile(inPipeWrite, encodedInputTestString.c_str(),
- (DWORD)encodedInputTestString.size(), &bytesWritten, NULL)
- || bytesWritten == 0) {
+ (DWORD)encodedInputTestString.size(), &bytesWritten,
+ NULL) ||
+ bytesWritten == 0) {
throw std::runtime_error("WriteFile failed!");
}
if (createProcess(inPipeRead, outPipeWrite, errPipeWrite)) {
try {
DWORD status;
- if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+ if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) !=
+ WAIT_OBJECT_0) {
std::cerr.setf(std::ios::hex, std::ios::basefield);
- std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+ std::cerr << "WaitForSingleObject returned unexpected status 0x"
+ << status << std::endl;
std::cerr.unsetf(std::ios::hex);
throw std::runtime_error("WaitForSingleObject failed!");
}
DWORD bytesRead = 0;
- if (!ReadFile(outPipeRead, buffer, sizeof(buffer), &bytesRead, NULL)
- || bytesRead == 0) {
+ if (!ReadFile(outPipeRead, buffer, sizeof(buffer), &bytesRead, NULL) ||
+ bytesRead == 0) {
throw std::runtime_error("ReadFile#1 failed!");
}
- if ((bytesRead < encodedTestString.size() + 1 + encodedInputTestString.size()
- && !ReadFile(outPipeRead, buffer + bytesRead,
- sizeof(buffer) - bytesRead, &bytesRead, NULL))
- || bytesRead == 0) {
+ if ((bytesRead <
+ encodedTestString.size() + 1 + encodedInputTestString.size() &&
+ !ReadFile(outPipeRead, buffer + bytesRead,
+ sizeof(buffer) - bytesRead, &bytesRead, NULL)) ||
+ bytesRead == 0) {
throw std::runtime_error("ReadFile#2 failed!");
}
if (memcmp(buffer, encodedTestString.c_str(),
@@ -323,31 +331,37 @@ static int testPipe()
encodedInputTestString.c_str(),
encodedInputTestString.size()) == 0) {
bytesRead = 0;
- if (!ReadFile(errPipeRead, buffer2, sizeof(buffer2), &bytesRead, NULL)
- || bytesRead == 0) {
+ if (!ReadFile(errPipeRead, buffer2, sizeof(buffer2), &bytesRead,
+ NULL) ||
+ bytesRead == 0) {
throw std::runtime_error("ReadFile#3 failed!");
}
buffer2[bytesRead - 1] = 0;
didFail = encodedTestString.compare(buffer2) == 0 ? 0 : 1;
}
if (didFail != 0) {
- std::cerr << "Pipe's output didn't match expected output!" << std::endl;
- dumpBuffers<char>(encodedTestString.c_str(), buffer, encodedTestString.size());
- dumpBuffers<char>(encodedInputTestString.c_str(), buffer + encodedTestString.size() + 1, encodedInputTestString.size());
- dumpBuffers<char>(encodedTestString.c_str(), buffer2, encodedTestString.size());
+ std::cerr << "Pipe's output didn't match expected output!"
+ << std::endl;
+ dumpBuffers<char>(encodedTestString.c_str(), buffer,
+ encodedTestString.size());
+ dumpBuffers<char>(encodedInputTestString.c_str(),
+ buffer + encodedTestString.size() + 1,
+ encodedInputTestString.size());
+ dumpBuffers<char>(encodedTestString.c_str(), buffer2,
+ encodedTestString.size());
}
- } catch (const std::runtime_error &ex) {
+ } catch (const std::runtime_error& ex) {
DWORD lastError = GetLastError();
- std::cerr << "In function testPipe, line " << __LINE__ << ": "
+ std::cerr << "In function testPipe, line " << __LINE__ << ": "
<< ex.what() << std::endl;
displayError(lastError);
}
finishProcess(didFail == 0);
}
- } catch (const std::runtime_error &ex) {
+ } catch (const std::runtime_error& ex) {
DWORD lastError = GetLastError();
- std::cerr << "In function testPipe, line " << __LINE__ << ": "
- << ex.what() << std::endl;
+ std::cerr << "In function testPipe, line " << __LINE__ << ": " << ex.what()
+ << std::endl;
displayError(lastError);
}
finishPipe(inPipeRead, inPipeWrite);
@@ -375,14 +389,14 @@ static int testFile()
char buffer2[200];
int length;
- if ((length = WideCharToMultiByte(TestCodepage, 0, UnicodeInputTestString, -1,
- buffer, sizeof(buffer),
- NULL, NULL)) == 0) {
+ if ((length =
+ WideCharToMultiByte(TestCodepage, 0, UnicodeInputTestString, -1,
+ buffer, sizeof(buffer), NULL, NULL)) == 0) {
throw std::runtime_error("WideCharToMultiByte failed!");
}
buffer[length - 1] = '\n';
- if (!WriteFile(inFile, buffer, length, &bytesWritten, NULL)
- || bytesWritten == 0) {
+ if (!WriteFile(inFile, buffer, length, &bytesWritten, NULL) ||
+ bytesWritten == 0) {
throw std::runtime_error("WriteFile failed!");
}
if (SetFilePointer(inFile, 0, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
@@ -393,18 +407,20 @@ static int testFile()
DWORD bytesRead = 0;
try {
DWORD status;
- if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+ if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) !=
+ WAIT_OBJECT_0) {
std::cerr.setf(std::ios::hex, std::ios::basefield);
- std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+ std::cerr << "WaitForSingleObject returned unexpected status 0x"
+ << status << std::endl;
std::cerr.unsetf(std::ios::hex);
throw std::runtime_error("WaitForSingleObject failed!");
}
- if (SetFilePointer(outFile, 0, 0, FILE_BEGIN)
- == INVALID_SET_FILE_POINTER) {
+ if (SetFilePointer(outFile, 0, 0, FILE_BEGIN) ==
+ INVALID_SET_FILE_POINTER) {
throw std::runtime_error("SetFilePointer#1 failed!");
}
- if (!ReadFile(outFile, buffer, sizeof(buffer), &bytesRead, NULL)
- || bytesRead == 0) {
+ if (!ReadFile(outFile, buffer, sizeof(buffer), &bytesRead, NULL) ||
+ bytesRead == 0) {
throw std::runtime_error("ReadFile#1 failed!");
}
buffer[bytesRead - 1] = 0;
@@ -414,35 +430,40 @@ static int testFile()
encodedInputTestString.c_str(),
encodedInputTestString.size() - 1) == 0) {
bytesRead = 0;
- if (SetFilePointer(errFile, 0, 0, FILE_BEGIN)
- == INVALID_SET_FILE_POINTER) {
+ if (SetFilePointer(errFile, 0, 0, FILE_BEGIN) ==
+ INVALID_SET_FILE_POINTER) {
throw std::runtime_error("SetFilePointer#2 failed!");
}
- if (!ReadFile(errFile, buffer2, sizeof(buffer2), &bytesRead, NULL)
- || bytesRead == 0) {
+ if (!ReadFile(errFile, buffer2, sizeof(buffer2), &bytesRead, NULL) ||
+ bytesRead == 0) {
throw std::runtime_error("ReadFile#2 failed!");
}
buffer2[bytesRead - 1] = 0;
didFail = encodedTestString.compare(buffer2) == 0 ? 0 : 1;
}
if (didFail != 0) {
- std::cerr << "File's output didn't match expected output!" << std::endl;
- dumpBuffers<char>(encodedTestString.c_str(), buffer, encodedTestString.size());
- dumpBuffers<char>(encodedInputTestString.c_str(), buffer + encodedTestString.size() + 1, encodedInputTestString.size() - 1);
- dumpBuffers<char>(encodedTestString.c_str(), buffer2, encodedTestString.size());
+ std::cerr << "File's output didn't match expected output!"
+ << std::endl;
+ dumpBuffers<char>(encodedTestString.c_str(), buffer,
+ encodedTestString.size());
+ dumpBuffers<char>(encodedInputTestString.c_str(),
+ buffer + encodedTestString.size() + 1,
+ encodedInputTestString.size() - 1);
+ dumpBuffers<char>(encodedTestString.c_str(), buffer2,
+ encodedTestString.size());
}
- } catch (const std::runtime_error &ex) {
+ } catch (const std::runtime_error& ex) {
DWORD lastError = GetLastError();
- std::cerr << "In function testFile, line " << __LINE__ << ": "
+ std::cerr << "In function testFile, line " << __LINE__ << ": "
<< ex.what() << std::endl;
displayError(lastError);
}
finishProcess(didFail == 0);
}
- } catch (const std::runtime_error &ex) {
+ } catch (const std::runtime_error& ex) {
DWORD lastError = GetLastError();
- std::cerr << "In function testFile, line " << __LINE__ << ": "
- << ex.what() << std::endl;
+ std::cerr << "In function testFile, line " << __LINE__ << ": " << ex.what()
+ << std::endl;
displayError(lastError);
}
finishFile(inFile);
@@ -452,7 +473,7 @@ static int testFile()
}
#ifndef _WIN32_WINNT_VISTA
-# define _WIN32_WINNT_VISTA 0x0600
+#define _WIN32_WINNT_VISTA 0x0600
#endif
//----------------------------------------------------------------------------
@@ -478,16 +499,17 @@ static int testConsole()
DWORD FontFamily = TestFontFamily;
DWORD FontSize = TestFontSize;
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersion
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-# pragma warning (disable:1478)
-# else
-# pragma warning (disable:4996)
-# endif
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
#endif
- const bool isVistaOrGreater = LOBYTE(LOWORD(GetVersion())) >= HIBYTE(_WIN32_WINNT_VISTA);
+ const bool isVistaOrGreater =
+ LOBYTE(LOWORD(GetVersion())) >= HIBYTE(_WIN32_WINNT_VISTA);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersion
-# pragma warning (pop)
+#pragma warning(pop)
#endif
if (!isVistaOrGreater) {
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0, KEY_READ | KEY_WRITE,
@@ -502,11 +524,12 @@ static int testConsole()
(LPBYTE)&FontSize, &dwordSize);
RegSetValueExW(hConsoleKey, L"FontFamily", 0, REG_DWORD,
- (BYTE *)&TestFontFamily, sizeof(TestFontFamily));
+ (BYTE*)&TestFontFamily, sizeof(TestFontFamily));
RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ,
- (BYTE *)TestFaceName, (DWORD)((wcslen(TestFaceName) + 1) * sizeof(WCHAR)));
+ (BYTE*)TestFaceName,
+ (DWORD)((wcslen(TestFaceName) + 1) * sizeof(WCHAR)));
RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD,
- (BYTE *)&TestFontSize, sizeof(TestFontSize));
+ (BYTE*)&TestFontSize, sizeof(TestFontSize));
restoreConsole = true;
forceNewConsole = true;
@@ -516,7 +539,8 @@ static int testConsole()
}
RegCloseKey(hConsoleKey);
} else {
- std::cerr << "RegOpenKeyExW(HKEY_CURRENT_USER\\Console) failed!" << std::endl;
+ std::cerr << "RegOpenKeyExW(HKEY_CURRENT_USER\\Console) failed!"
+ << std::endl;
}
}
if (forceNewConsole || GetConsoleMode(parentOut, &consoleMode) == 0) {
@@ -530,15 +554,17 @@ static int testConsole()
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.bInheritHandle = TRUE;
securityAttributes.lpSecurityDescriptor = NULL;
- hIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
- &securityAttributes, OPEN_EXISTING, 0, NULL);
+ hIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, &securityAttributes,
+ OPEN_EXISTING, 0, NULL);
if (hIn == INVALID_HANDLE_VALUE) {
DWORD lastError = GetLastError();
std::cerr << "CreateFile(CONIN$)" << std::endl;
displayError(lastError);
}
- hOut = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
- &securityAttributes, OPEN_EXISTING, 0, NULL);
+ hOut = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, &securityAttributes,
+ OPEN_EXISTING, 0, NULL);
if (hOut == INVALID_HANDLE_VALUE) {
DWORD lastError = GetLastError();
std::cerr << "CreateFile(CONOUT$)" << std::endl;
@@ -556,10 +582,18 @@ static int testConsole()
memset(&consoleFont, 0, sizeof(consoleFont));
consoleFont.cbSize = sizeof(consoleFont);
HMODULE kernel32 = LoadLibraryW(L"kernel32.dll");
- typedef BOOL (WINAPI *GetCurrentConsoleFontExFunc)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
- typedef BOOL (WINAPI *SetCurrentConsoleFontExFunc)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
- GetCurrentConsoleFontExFunc getConsoleFont = (GetCurrentConsoleFontExFunc)GetProcAddress(kernel32, "GetCurrentConsoleFontEx");
- SetCurrentConsoleFontExFunc setConsoleFont = (SetCurrentConsoleFontExFunc)GetProcAddress(kernel32, "SetCurrentConsoleFontEx");
+ typedef BOOL(WINAPI * GetCurrentConsoleFontExFunc)(
+ HANDLE hConsoleOutput, BOOL bMaximumWindow,
+ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
+ typedef BOOL(WINAPI * SetCurrentConsoleFontExFunc)(
+ HANDLE hConsoleOutput, BOOL bMaximumWindow,
+ PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
+ GetCurrentConsoleFontExFunc getConsoleFont =
+ (GetCurrentConsoleFontExFunc)GetProcAddress(kernel32,
+ "GetCurrentConsoleFontEx");
+ SetCurrentConsoleFontExFunc setConsoleFont =
+ (SetCurrentConsoleFontExFunc)GetProcAddress(kernel32,
+ "SetCurrentConsoleFontEx");
if (getConsoleFont(hOut, FALSE, &consoleFont)) {
if (consoleFont.FontFamily != TestFontFamily) {
consoleFont.FontFamily = TestFontFamily;
@@ -573,18 +607,19 @@ static int testConsole()
}
} else {
#endif
- if (restoreConsole && RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0,
- KEY_WRITE, &hConsoleKey) == ERROR_SUCCESS) {
+ if (restoreConsole &&
+ RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0, KEY_WRITE,
+ &hConsoleKey) == ERROR_SUCCESS) {
RegSetValueExW(hConsoleKey, L"FontFamily", 0, REG_DWORD,
- (BYTE *)&FontFamily, sizeof(FontFamily));
+ (BYTE*)&FontFamily, sizeof(FontFamily));
if (FaceName[0] != 0) {
- RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ,
- (BYTE *)FaceName, FaceNameSize);
+ RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ, (BYTE*)FaceName,
+ FaceNameSize);
} else {
RegDeleteValueW(hConsoleKey, L"FaceName");
}
- RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD,
- (BYTE *)&FontSize, sizeof(FontSize));
+ RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD, (BYTE*)&FontSize,
+ sizeof(FontSize));
RegCloseKey(hConsoleKey);
}
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
@@ -594,32 +629,41 @@ static int testConsole()
if (createProcess(NULL, NULL, NULL)) {
try {
DWORD status;
- if ((status = WaitForSingleObject(beforeInputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+ if ((status = WaitForSingleObject(beforeInputEvent, waitTimeout)) !=
+ WAIT_OBJECT_0) {
std::cerr.setf(std::ios::hex, std::ios::basefield);
- std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+ std::cerr << "WaitForSingleObject returned unexpected status 0x"
+ << status << std::endl;
std::cerr.unsetf(std::ios::hex);
throw std::runtime_error("WaitForSingleObject#1 failed!");
}
INPUT_RECORD inputBuffer[(sizeof(UnicodeInputTestString) /
- sizeof(UnicodeInputTestString[0])) * 2];
+ sizeof(UnicodeInputTestString[0])) *
+ 2];
memset(&inputBuffer, 0, sizeof(inputBuffer));
unsigned int i;
for (i = 0; i < (sizeof(UnicodeInputTestString) /
- sizeof(UnicodeInputTestString[0]) - 1); i++) {
- writeInputKeyEvent(&inputBuffer[i*2], UnicodeInputTestString[i]);
+ sizeof(UnicodeInputTestString[0]) -
+ 1);
+ i++) {
+ writeInputKeyEvent(&inputBuffer[i * 2], UnicodeInputTestString[i]);
}
- writeInputKeyEvent(&inputBuffer[i*2], VK_RETURN);
+ writeInputKeyEvent(&inputBuffer[i * 2], VK_RETURN);
DWORD eventsWritten = 0;
- // We need to wait a bit before writing to console so child process have started waiting for input on stdin.
+ // We need to wait a bit before writing to console so child process have
+ // started waiting for input on stdin.
Sleep(300);
- if (!WriteConsoleInputW(hIn, inputBuffer, sizeof(inputBuffer) /
- sizeof(inputBuffer[0]),
- &eventsWritten) || eventsWritten == 0) {
+ if (!WriteConsoleInputW(hIn, inputBuffer,
+ sizeof(inputBuffer) / sizeof(inputBuffer[0]),
+ &eventsWritten) ||
+ eventsWritten == 0) {
throw std::runtime_error("WriteConsoleInput failed!");
}
- if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+ if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) !=
+ WAIT_OBJECT_0) {
std::cerr.setf(std::ios::hex, std::ios::basefield);
- std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+ std::cerr << "WaitForSingleObject returned unexpected status 0x"
+ << status << std::endl;
std::cerr.unsetf(std::ios::hex);
throw std::runtime_error("WaitForSingleObject#2 failed!");
}
@@ -632,38 +676,48 @@ static int testConsole()
DWORD charsRead = 0;
coord.X = 0;
coord.Y = screenBufferInfo.dwCursorPosition.Y - 4;
- WCHAR *outputBuffer = new WCHAR[screenBufferInfo.dwSize.X * 4];
+ WCHAR* outputBuffer = new WCHAR[screenBufferInfo.dwSize.X * 4];
if (!ReadConsoleOutputCharacterW(hOut, outputBuffer,
- screenBufferInfo.dwSize.X * 4, coord, &charsRead)
- || charsRead == 0) {
+ screenBufferInfo.dwSize.X * 4, coord,
+ &charsRead) ||
+ charsRead == 0) {
delete[] outputBuffer;
throw std::runtime_error("ReadConsoleOutputCharacter failed!");
}
std::wstring wideTestString = kwsys::Encoding::ToWide(encodedTestString);
- std::wstring wideInputTestString = kwsys::Encoding::ToWide(encodedInputTestString);
+ std::wstring wideInputTestString =
+ kwsys::Encoding::ToWide(encodedInputTestString);
if (memcmp(outputBuffer, wideTestString.c_str(),
wideTestString.size() * sizeof(wchar_t)) == 0 &&
memcmp(outputBuffer + screenBufferInfo.dwSize.X * 1,
- wideTestString.c_str(), wideTestString.size() * sizeof(wchar_t)) == 0 &&
+ wideTestString.c_str(),
+ wideTestString.size() * sizeof(wchar_t)) == 0 &&
memcmp(outputBuffer + screenBufferInfo.dwSize.X * 2,
- UnicodeInputTestString, sizeof(UnicodeInputTestString) -
- sizeof(WCHAR)) == 0 &&
+ UnicodeInputTestString,
+ sizeof(UnicodeInputTestString) - sizeof(WCHAR)) == 0 &&
memcmp(outputBuffer + screenBufferInfo.dwSize.X * 3,
wideInputTestString.c_str(),
- (wideInputTestString.size() - 1) * sizeof(wchar_t)) == 0
- ) {
+ (wideInputTestString.size() - 1) * sizeof(wchar_t)) == 0) {
didFail = 0;
} else {
- std::cerr << "Console's output didn't match expected output!" << std::endl;
- dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer, wideTestString.size());
- dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer + screenBufferInfo.dwSize.X * 1, wideTestString.size());
- dumpBuffers<wchar_t>(UnicodeInputTestString, outputBuffer + screenBufferInfo.dwSize.X * 2, (sizeof(UnicodeInputTestString) - 1) / sizeof(WCHAR));
- dumpBuffers<wchar_t>(wideInputTestString.c_str(), outputBuffer + screenBufferInfo.dwSize.X * 3, wideInputTestString.size() - 1);
+ std::cerr << "Console's output didn't match expected output!"
+ << std::endl;
+ dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer,
+ wideTestString.size());
+ dumpBuffers<wchar_t>(wideTestString.c_str(),
+ outputBuffer + screenBufferInfo.dwSize.X * 1,
+ wideTestString.size());
+ dumpBuffers<wchar_t>(
+ UnicodeInputTestString, outputBuffer + screenBufferInfo.dwSize.X * 2,
+ (sizeof(UnicodeInputTestString) - 1) / sizeof(WCHAR));
+ dumpBuffers<wchar_t>(wideInputTestString.c_str(),
+ outputBuffer + screenBufferInfo.dwSize.X * 3,
+ wideInputTestString.size() - 1);
}
delete[] outputBuffer;
- } catch (const std::runtime_error &ex) {
+ } catch (const std::runtime_error& ex) {
DWORD lastError = GetLastError();
- std::cerr << "In function testConsole, line " << __LINE__ << ": "
+ std::cerr << "In function testConsole, line " << __LINE__ << ": "
<< ex.what() << std::endl;
displayError(lastError);
}
@@ -683,15 +737,15 @@ static int testConsole()
#endif
//----------------------------------------------------------------------------
-int testConsoleBuf(int, char*[])
+int testConsoleBuf(int, char* [])
{
int ret = 0;
#if defined(_WIN32)
beforeInputEvent = CreateEventW(NULL,
- FALSE, // auto-reset event
- FALSE, // initial state is nonsignaled
- BeforeInputEventName); // object name
+ FALSE, // auto-reset event
+ FALSE, // initial state is nonsignaled
+ BeforeInputEventName); // object name
if (!beforeInputEvent) {
std::cerr << "CreateEvent#1 failed " << GetLastError() << std::endl;
return 1;
diff --git a/Source/kwsys/testConsoleBuf.hxx b/Source/kwsys/testConsoleBuf.hxx
index 7c2f4c6..8891960 100644
--- a/Source/kwsys/testConsoleBuf.hxx
+++ b/Source/kwsys/testConsoleBuf.hxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef testConsoleBuf_hxx
#define testConsoleBuf_hxx
@@ -18,8 +9,9 @@ static const wchar_t BeforeInputEventName[] = L"BeforeInputEvent";
static const wchar_t AfterOutputEventName[] = L"AfterOutputEvent";
// ą¤Æą„‚ą¤Øą¤æą¤•ą„‹ą¤” είναι зГорово!
-static const wchar_t UnicodeTestString[] = L"\u092F\u0942\u0928\u093F\u0915\u094B\u0921 "
- L"\u03B5\u03AF\u03BD\u03B1\u03B9 "
- L"\u0437\u0434\u043E\u0440\u043E\u0432\u043E!";
+static const wchar_t UnicodeTestString[] =
+ L"\u092F\u0942\u0928\u093F\u0915\u094B\u0921 "
+ L"\u03B5\u03AF\u03BD\u03B1\u03B9 "
+ L"\u0437\u0434\u043E\u0440\u043E\u0432\u043E!";
#endif
diff --git a/Source/kwsys/testConsoleBufChild.cxx b/Source/kwsys/testConsoleBufChild.cxx
index 2da39f2..313323e 100644
--- a/Source/kwsys/testConsoleBufChild.cxx
+++ b/Source/kwsys/testConsoleBufChild.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2016 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(ConsoleBuf.hxx)
@@ -17,11 +8,12 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "ConsoleBuf.hxx.in"
-# include "Encoding.hxx.in"
+#include "ConsoleBuf.hxx.in"
+#include "Encoding.hxx.in"
#endif
#include <iostream>
+
#include "testConsoleBuf.hxx"
//----------------------------------------------------------------------------
diff --git a/Source/kwsys/testDynamicLoader.cxx b/Source/kwsys/testDynamicLoader.cxx
index 7c58769..b52ddda 100644
--- a/Source/kwsys/testDynamicLoader.cxx
+++ b/Source/kwsys/testDynamicLoader.cxx
@@ -1,30 +1,21 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#if defined(__BEOS__) || defined(__HAIKU__)
-#include <be/kernel/OS.h> /* disable_debugger() API. */
+#include <be/kernel/OS.h> /* disable_debugger() API. */
#endif
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "DynamicLoader.hxx.in"
+#include "DynamicLoader.hxx.in"
#endif
-#include <string>
#include <iostream>
+#include <string>
// Include with <> instead of "" to avoid getting any in-source copy
// left on disk.
@@ -53,41 +44,36 @@ static std::string GetLibName(const char* lname)
* r2: should GetSymbolAddress succeed ?
* r3: should CloseLibrary succeed ?
*/
-static int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3)
+static int TestDynamicLoader(const char* libname, const char* symbol, int r1,
+ int r2, int r3)
{
std::cerr << "Testing: " << libname << std::endl;
- kwsys::DynamicLoader::LibraryHandle l
- = kwsys::DynamicLoader::OpenLibrary(libname);
+ kwsys::DynamicLoader::LibraryHandle l =
+ kwsys::DynamicLoader::OpenLibrary(libname);
// If result is incompatible with expectation just fails (xor):
- if( (r1 && !l) || (!r1 && l) )
- {
- std::cerr
- << kwsys::DynamicLoader::LastError() << std::endl;
+ if ((r1 && !l) || (!r1 && l)) {
+ std::cerr << kwsys::DynamicLoader::LastError() << std::endl;
return 1;
- }
- kwsys::DynamicLoader::SymbolPointer f
- = kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
- if( (r2 && !f) || (!r2 && f) )
- {
- std::cerr
- << kwsys::DynamicLoader::LastError() << std::endl;
+ }
+ kwsys::DynamicLoader::SymbolPointer f =
+ kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
+ if ((r2 && !f) || (!r2 && f)) {
+ std::cerr << kwsys::DynamicLoader::LastError() << std::endl;
return 1;
- }
+ }
#ifndef __APPLE__
int s = kwsys::DynamicLoader::CloseLibrary(l);
- if( (r3 && !s) || (!r3 && s) )
- {
- std::cerr
- << kwsys::DynamicLoader::LastError() << std::endl;
+ if ((r3 && !s) || (!r3 && s)) {
+ std::cerr << kwsys::DynamicLoader::LastError() << std::endl;
return 1;
- }
+ }
#else
(void)r3;
#endif
return 0;
}
-int testDynamicLoader(int argc, char *argv[])
+int testDynamicLoader(int argc, char* argv[])
{
#if defined(_WIN32)
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
@@ -95,34 +81,37 @@ int testDynamicLoader(int argc, char *argv[])
disable_debugger(1);
#endif
int res = 0;
- if( argc == 3 )
- {
+ if (argc == 3) {
// User specify a libname and symbol to check.
- res = TestDynamicLoader(argv[1], argv[2],1,1,1);
+ res = TestDynamicLoader(argv[1], argv[2], 1, 1, 1);
return res;
- }
+ }
// dlopen() on Syllable before 11/22/2007 doesn't return 0 on error
#ifndef __SYLLABLE__
// Make sure that inexistent lib is giving correct result
- res += TestDynamicLoader("azerty_", "foo_bar",0,0,0);
+ res += TestDynamicLoader("azerty_", "foo_bar", 0, 0, 0);
// Make sure that random binary file cannot be assimilated as dylib
- res += TestDynamicLoader(TEST_SYSTEMTOOLS_SOURCE_DIR "/testSystemTools.bin", "wp",0,0,0);
+ res += TestDynamicLoader(TEST_SYSTEMTOOLS_SOURCE_DIR "/testSystemTools.bin",
+ "wp", 0, 0, 0);
#endif
#ifdef __linux__
- // This one is actually fun to test, since dlopen is by default loaded...wonder why :)
- res += TestDynamicLoader("foobar.lib", "dlopen",0,1,0);
- res += TestDynamicLoader("libdl.so", "dlopen",1,1,1);
- res += TestDynamicLoader("libdl.so", "TestDynamicLoader",1,0,1);
+ // This one is actually fun to test, since dlopen is by default
+ // loaded...wonder why :)
+ res += TestDynamicLoader("foobar.lib", "dlopen", 0, 1, 0);
+ res += TestDynamicLoader("libdl.so", "dlopen", 1, 1, 1);
+ res += TestDynamicLoader("libdl.so", "TestDynamicLoader", 1, 0, 1);
#endif
// Now try on the generated library
std::string libname = GetLibName(KWSYS_NAMESPACE_STRING "TestDynload");
- res += TestDynamicLoader(libname.c_str(), "dummy",1,0,1);
- res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderSymbolPointer",1,1,1);
- res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderSymbolPointer",1,0,1);
- res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData",1,1,1);
- res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData",1,0,1);
+ res += TestDynamicLoader(libname.c_str(), "dummy", 1, 0, 1);
+ res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderSymbolPointer",
+ 1, 1, 1);
+ res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderSymbolPointer",
+ 1, 0, 1);
+ res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData", 1, 1, 1);
+ res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData", 1, 0, 1);
return res;
}
diff --git a/Source/kwsys/testDynload.c b/Source/kwsys/testDynload.c
index ba60bec..cdb9e5c 100644
--- a/Source/kwsys/testDynload.c
+++ b/Source/kwsys/testDynload.c
@@ -1,16 +1,7 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifdef _WIN32
-#define DL_EXPORT __declspec( dllexport )
+#define DL_EXPORT __declspec(dllexport)
#else
#define DL_EXPORT
#endif
diff --git a/Source/kwsys/testEncode.c b/Source/kwsys/testEncode.c
index 26d483b..a20d46f 100644
--- a/Source/kwsys/testEncode.c
+++ b/Source/kwsys/testEncode.c
@@ -1,29 +1,20 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(MD5.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "MD5.h.in"
+#include "MD5.h.in"
#endif
#include <stdio.h>
#include <string.h>
static const unsigned char testMD5input1[] =
-" A quick brown fox jumps over the lazy dog.\n"
-" This is sample text for MD5 sum input.\n";
+ " A quick brown fox jumps over the lazy dog.\n"
+ " This is sample text for MD5 sum input.\n";
static const char testMD5output1[] = "8f146af46ed4f267921bb937d4d3500c";
static const int testMD5input2len = 28;
@@ -40,7 +31,7 @@ static int testMD5_1(kwsysMD5* md5)
printf("md5sum 1: expected [%s]\n"
" got [%s]\n",
testMD5output1, md5out);
- return (strcmp(md5out, testMD5output1) != 0)? 1:0;
+ return (strcmp(md5out, testMD5output1) != 0) ? 1 : 0;
}
static int testMD5_2(kwsysMD5* md5)
@@ -55,7 +46,7 @@ static int testMD5_2(kwsysMD5* md5)
printf("md5sum 2: expected [%s]\n"
" got [%s]\n",
testMD5output2, md5out);
- return (strcmp(md5out, testMD5output2) != 0)? 1:0;
+ return (strcmp(md5out, testMD5output2) != 0) ? 1 : 0;
}
int testEncode(int argc, char* argv[])
@@ -66,10 +57,10 @@ int testEncode(int argc, char* argv[])
/* Test MD5 digest. */
{
- kwsysMD5* md5 = kwsysMD5_New();
- result |= testMD5_1(md5);
- result |= testMD5_2(md5);
- kwsysMD5_Delete(md5);
+ kwsysMD5* md5 = kwsysMD5_New();
+ result |= testMD5_1(md5);
+ result |= testMD5_2(md5);
+ kwsysMD5_Delete(md5);
}
return result;
diff --git a/Source/kwsys/testEncoding.cxx b/Source/kwsys/testEncoding.cxx
index 80ec040..996976f 100644
--- a/Source/kwsys/testEncoding.cxx
+++ b/Source/kwsys/testEncoding.cxx
@@ -1,18 +1,9 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
#endif
#include KWSYS_HEADER(Encoding.hxx)
@@ -20,68 +11,63 @@
#include <iostream>
#include <locale.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Encoding.hxx.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Encoding.hxx.in"
#endif
//----------------------------------------------------------------------------
-static const unsigned char helloWorldStrings[][32] =
-{
+static const unsigned char helloWorldStrings[][32] = {
// English
- {'H','e','l','l','o',' ','W','o','r','l','d',0},
+ { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', 0 },
// Japanese
- {0xE3, 0x81, 0x93, 0xE3, 0x82, 0x93, 0xE3, 0x81, 0xAB, 0xE3,
- 0x81, 0xA1, 0xE3, 0x81, 0xAF, 0xE4, 0xB8, 0x96, 0xE7, 0x95,
- 0x8C, 0},
- // Arabic
- {0xD9, 0x85, 0xD8, 0xB1, 0xD8, 0xAD, 0xD8, 0xA8, 0xD8, 0xA7,
- 0x20, 0xD8, 0xA7, 0xD9, 0x84, 0xD8, 0xB9, 0xD8, 0xA7, 0xD9,
- 0x84, 0xD9, 0x85, 0},
+ { 0xE3, 0x81, 0x93, 0xE3, 0x82, 0x93, 0xE3, 0x81, 0xAB, 0xE3, 0x81,
+ 0xA1, 0xE3, 0x81, 0xAF, 0xE4, 0xB8, 0x96, 0xE7, 0x95, 0x8C, 0 },
+ // Arabic
+ { 0xD9, 0x85, 0xD8, 0xB1, 0xD8, 0xAD, 0xD8, 0xA8, 0xD8, 0xA7, 0x20, 0xD8,
+ 0xA7, 0xD9, 0x84, 0xD8, 0xB9, 0xD8, 0xA7, 0xD9, 0x84, 0xD9, 0x85, 0 },
// Yiddish
- {0xD7, 0x94, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x90, 0x20, 0xD7,
- 0x95, 0xD7, 0x95, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x98, 0},
+ { 0xD7, 0x94, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x90, 0x20, 0xD7,
+ 0x95, 0xD7, 0x95, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x98, 0 },
// Russian
- {0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5,
- 0xD1, 0x82, 0x20, 0xD0, 0xBC, 0xD0, 0xB8, 0xD1, 0x80, 0},
+ { 0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5,
+ 0xD1, 0x82, 0x20, 0xD0, 0xBC, 0xD0, 0xB8, 0xD1, 0x80, 0 },
// Latin
- {0x4D, 0x75, 0x6E, 0x64, 0x75, 0x73, 0x20, 0x73, 0x61, 0x6C,
- 0x76, 0x65, 0},
+ { 0x4D, 0x75, 0x6E, 0x64, 0x75, 0x73, 0x20, 0x73, 0x61, 0x6C, 0x76, 0x65,
+ 0 },
// Swahili
- {0x68, 0x75, 0x6A, 0x61, 0x6D, 0x62, 0x6F, 0x20, 0x44, 0x75,
- 0x6E, 0x69, 0x61, 0},
+ { 0x68, 0x75, 0x6A, 0x61, 0x6D, 0x62, 0x6F, 0x20, 0x44, 0x75, 0x6E, 0x69,
+ 0x61, 0 },
// Icelandic
- {0x48, 0x61, 0x6C, 0x6C, 0xC3, 0xB3, 0x20, 0x68, 0x65, 0x69,
- 0x6D, 0x75, 0x72, 0},
- {0}
+ { 0x48, 0x61, 0x6C, 0x6C, 0xC3, 0xB3, 0x20, 0x68, 0x65, 0x69, 0x6D, 0x75,
+ 0x72, 0 },
+ { 0 }
};
//----------------------------------------------------------------------------
static int testHelloWorldEncoding()
{
int ret = 0;
- for(int i=0; helloWorldStrings[i][0] != 0; i++)
- {
+ for (int i = 0; helloWorldStrings[i][0] != 0; i++) {
std::string str = reinterpret_cast<const char*>(helloWorldStrings[i]);
std::cout << str << std::endl;
std::wstring wstr = kwsys::Encoding::ToWide(str);
std::string str2 = kwsys::Encoding::ToNarrow(wstr);
wchar_t* c_wstr = kwsysEncoding_DupToWide(str.c_str());
char* c_str2 = kwsysEncoding_DupToNarrow(c_wstr);
- if(!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str())))
- {
+ if (!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str()))) {
std::cout << "converted string was different: " << str2 << std::endl;
std::cout << "converted string was different: " << c_str2 << std::endl;
ret++;
- }
+ }
free(c_wstr);
free(c_str2);
- }
+ }
return ret;
}
@@ -91,55 +77,49 @@ static int testRobustEncoding()
// unicode correctly/gracefully
int ret = 0;
- char cstr[] = {(char)-1, 0};
+ char cstr[] = { (char)-1, 0 };
// this conversion could fail
std::wstring wstr = kwsys::Encoding::ToWide(cstr);
wstr = kwsys::Encoding::ToWide(NULL);
- if(wstr != L"")
- {
+ if (wstr != L"") {
const wchar_t* wcstr = wstr.c_str();
std::cout << "ToWide(NULL) returned";
- for(size_t i=0; i<wstr.size(); i++)
- {
+ for (size_t i = 0; i < wstr.size(); i++) {
std::cout << " " << std::hex << (int)wcstr[i];
- }
+ }
std::cout << std::endl;
ret++;
- }
+ }
wstr = kwsys::Encoding::ToWide("");
- if(wstr != L"")
- {
+ if (wstr != L"") {
const wchar_t* wcstr = wstr.c_str();
std::cout << "ToWide(\"\") returned";
- for(size_t i=0; i<wstr.size(); i++)
- {
+ for (size_t i = 0; i < wstr.size(); i++) {
std::cout << " " << std::hex << (int)wcstr[i];
- }
+ }
std::cout << std::endl;
ret++;
- }
+ }
#ifdef _WIN32
// 16 bit wchar_t - we make an invalid surrogate pair
- wchar_t cwstr[] = {0xD801, 0xDA00, 0};
+ wchar_t cwstr[] = { 0xD801, 0xDA00, 0 };
// this conversion could fail
std::string win_str = kwsys::Encoding::ToNarrow(cwstr);
#endif
std::string str = kwsys::Encoding::ToNarrow(NULL);
- if(str != "")
- {
+ if (str != "") {
std::cout << "ToNarrow(NULL) returned " << str << std::endl;
ret++;
- }
+ }
str = kwsys::Encoding::ToNarrow(L"");
- if(wstr != L"")
- {
+ if (wstr != L"") {
std::cout << "ToNarrow(\"\") returned " << str << std::endl;
ret++;
- }
+ }
return ret;
}
@@ -148,23 +128,18 @@ static int testCommandLineArguments()
{
int status = 0;
- char const* argv[2] = {
- "./app.exe",
- (char const*)helloWorldStrings[1]
- };
+ char const* argv[2] = { "./app.exe", (char const*)helloWorldStrings[1] };
kwsys::Encoding::CommandLineArguments args(2, argv);
kwsys::Encoding::CommandLineArguments arg2 =
kwsys::Encoding::CommandLineArguments(args);
char const* const* u8_argv = args.argv();
- for(int i=0; i<args.argc(); i++)
- {
+ for (int i = 0; i < args.argc(); i++) {
char const* u8_arg = u8_argv[i];
- if(strcmp(argv[i], u8_arg) != 0)
- {
- std::cout << "argv[" << i << "] " << argv[i] << " != "
- << u8_arg << std::endl;
+ if (strcmp(argv[i], u8_arg) != 0) {
+ std::cout << "argv[" << i << "] " << argv[i] << " != " << u8_arg
+ << std::endl;
status++;
}
}
@@ -176,17 +151,14 @@ static int testCommandLineArguments()
}
//----------------------------------------------------------------------------
-int testEncoding(int, char*[])
+int testEncoding(int, char* [])
{
const char* loc = setlocale(LC_ALL, "");
- if(loc)
- {
+ if (loc) {
std::cout << "Locale: " << loc << std::endl;
- }
- else
- {
+ } else {
std::cout << "Locale: None" << std::endl;
- }
+ }
int ret = 0;
diff --git a/Source/kwsys/testFStream.cxx b/Source/kwsys/testFStream.cxx
index 5e53725..670f5e7 100644
--- a/Source/kwsys/testFStream.cxx
+++ b/Source/kwsys/testFStream.cxx
@@ -1,30 +1,21 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
#endif
#include KWSYS_HEADER(FStream.hxx)
#include <string.h>
#ifdef __BORLANDC__
-# include <mem.h> /* memcmp */
+#include <mem.h> /* memcmp */
#endif
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "FStream.hxx.in"
+#include "FStream.hxx.in"
#endif
#include <iostream>
@@ -33,10 +24,9 @@
static int testNoFile()
{
kwsys::ifstream in_file("NoSuchFile.txt");
- if(in_file)
- {
+ if (in_file) {
return 1;
- }
+ }
return 0;
}
@@ -44,90 +34,78 @@ static int testNoFile()
static const int num_test_files = 7;
static const int max_test_file_size = 45;
-static kwsys::FStream::BOM expected_bom[num_test_files] =
-{
- kwsys::FStream::BOM_None,
- kwsys::FStream::BOM_None,
- kwsys::FStream::BOM_UTF8,
- kwsys::FStream::BOM_UTF16LE,
- kwsys::FStream::BOM_UTF16BE,
- kwsys::FStream::BOM_UTF32LE,
+static kwsys::FStream::BOM expected_bom[num_test_files] = {
+ kwsys::FStream::BOM_None, kwsys::FStream::BOM_None,
+ kwsys::FStream::BOM_UTF8, kwsys::FStream::BOM_UTF16LE,
+ kwsys::FStream::BOM_UTF16BE, kwsys::FStream::BOM_UTF32LE,
kwsys::FStream::BOM_UTF32BE
};
-static unsigned char expected_bom_data[num_test_files][5] =
-{
- {0},
- {0},
- {3, 0xEF, 0xBB, 0xBF},
- {2, 0xFF, 0xFE},
- {2, 0xFE, 0xFF},
- {4, 0xFF, 0xFE, 0x00, 0x00},
- {4, 0x00, 0x00, 0xFE, 0xFF},
+static unsigned char expected_bom_data[num_test_files][5] = {
+ { 0 },
+ { 0 },
+ { 3, 0xEF, 0xBB, 0xBF },
+ { 2, 0xFF, 0xFE },
+ { 2, 0xFE, 0xFF },
+ { 4, 0xFF, 0xFE, 0x00, 0x00 },
+ { 4, 0x00, 0x00, 0xFE, 0xFF },
};
-static unsigned char file_data[num_test_files][max_test_file_size] =
-{
- {1, 'H'},
- {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'},
- {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'},
- {22, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20, 0x00,
- 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64, 0x00},
- {22, 0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20,
- 0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64},
- {44, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00,
- 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
- 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00,
- 0x6C, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00},
- {44, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C,
- 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20,
- 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72,
- 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x64},
+static unsigned char file_data[num_test_files][max_test_file_size] = {
+ { 1, 'H' },
+ { 11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' },
+ { 11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' },
+ { 22, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20,
+ 0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64, 0x00 },
+ { 22, 0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00,
+ 0x20, 0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64 },
+ { 44, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00,
+ 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,
+ 0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00,
+ 0x00, 0x6C, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00 },
+ { 44, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00,
+ 0x6C, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00,
+ 0x20, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00,
+ 0x72, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x64 },
};
//----------------------------------------------------------------------------
static int testBOM()
{
// test various encodings in binary mode
- for(int i=0; i<num_test_files; i++)
+ for (int i = 0; i < num_test_files; i++) {
{
- {
kwsys::ofstream out("bom.txt", kwsys::ofstream::binary);
- out.write(reinterpret_cast<const char*>(expected_bom_data[i]+1),
+ out.write(reinterpret_cast<const char*>(expected_bom_data[i] + 1),
*expected_bom_data[i]);
- out.write(reinterpret_cast<const char*>(file_data[i]+1),
+ out.write(reinterpret_cast<const char*>(file_data[i] + 1),
file_data[i][0]);
- }
+ }
kwsys::ifstream in("bom.txt", kwsys::ofstream::binary);
kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(in);
- if(bom != expected_bom[i])
- {
+ if (bom != expected_bom[i]) {
std::cout << "Unexpected BOM " << i << std::endl;
return 1;
- }
+ }
char data[max_test_file_size];
in.read(data, file_data[i][0]);
- if(!in.good())
- {
+ if (!in.good()) {
std::cout << "Unable to read data " << i << std::endl;
return 1;
- }
+ }
- if(memcmp(data, file_data[i]+1, file_data[i][0]) != 0)
- {
+ if (memcmp(data, file_data[i] + 1, file_data[i][0]) != 0) {
std::cout << "Incorrect read data " << i << std::endl;
return 1;
- }
-
}
+ }
return 0;
}
-
//----------------------------------------------------------------------------
-int testFStream(int, char*[])
+int testFStream(int, char* [])
{
int ret = 0;
diff --git a/Source/kwsys/testFail.c b/Source/kwsys/testFail.c
index 7e062c1..82caeac 100644
--- a/Source/kwsys/testFail.c
+++ b/Source/kwsys/testFail.c
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -17,19 +8,17 @@ int testFail(int argc, char* argv[])
{
char* env = getenv("DASHBOARD_TEST_FROM_CTEST");
int oldCtest = 0;
- if(env)
- {
- if(strcmp(env, "1") == 0)
- {
+ if (env) {
+ if (strcmp(env, "1") == 0) {
oldCtest = 1;
- }
- printf("DASHBOARD_TEST_FROM_CTEST = %s\n", env);
}
+ printf("DASHBOARD_TEST_FROM_CTEST = %s\n", env);
+ }
printf("%s: This test intentionally fails\n", argv[0]);
- if(oldCtest)
- {
- printf("The version of ctest is not able to handle intentionally failing tests, so pass.\n");
+ if (oldCtest) {
+ printf("The version of ctest is not able to handle intentionally failing "
+ "tests, so pass.\n");
return 0;
- }
+ }
return argc;
}
diff --git a/Source/kwsys/testHashSTL.cxx b/Source/kwsys/testHashSTL.cxx
index ae66ceb..0444874 100644
--- a/Source/kwsys/testHashSTL.cxx
+++ b/Source/kwsys/testHashSTL.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(hash_map.hxx)
#include KWSYS_HEADER(hash_set.hxx)
@@ -16,18 +7,18 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "hash_map.hxx.in"
-# include "hash_set.hxx.in"
+#include "hash_map.hxx.in"
+#include "hash_set.hxx.in"
#endif
#include <iostream>
#if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1468 /* inline function cannot be explicitly instantiated */
+#pragma set woff 1468 /* inline function cannot be explicitly instantiated */
#endif
template class kwsys::hash_map<const char*, int>;
@@ -37,16 +28,15 @@ static bool test_hash_map()
{
typedef kwsys::hash_map<const char*, int> mtype;
mtype m;
- const char* keys[] = {"hello", "world"};
+ 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)
- {
+ for (mtype::iterator mi = m.begin(); mi != m.end(); ++mi) {
std::cout << "Found entry [" << mi->first << "," << mi->second << "]"
<< std::endl;
sum += mi->second;
- }
+ }
return sum == 3;
}
@@ -57,18 +47,17 @@ static bool test_hash_set()
s.insert(1);
s.insert(2);
int sum = 0;
- for(stype::iterator si = s.begin(); si != s.end(); ++si)
- {
+ for (stype::iterator si = s.begin(); si != s.end(); ++si) {
std::cout << "Found entry [" << *si << "]" << std::endl;
sum += *si;
- }
+ }
return sum == 3;
}
-int testHashSTL(int, char*[])
+int testHashSTL(int, char* [])
{
bool result = true;
result = test_hash_map() && result;
result = test_hash_set() && result;
- return result? 0:1;
+ return result ? 0 : 1;
}
diff --git a/Source/kwsys/testIOS.cxx b/Source/kwsys/testIOS.cxx
index 5ff7955..3e4c325 100644
--- a/Source/kwsys/testIOS.cxx
+++ b/Source/kwsys/testIOS.cxx
@@ -1,163 +1,138 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Configure.hxx)
-#include <sstream>
#include <fstream>
#include <iostream>
-#include <vector>
+#include <sstream>
#include <string.h> /* strlen */
+#include <vector>
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "Configure.hxx.in"
+#include "Configure.hxx.in"
#endif
-int testIOS(int, char*[])
+int testIOS(int, char* [])
{
std::ostringstream ostr;
const char hello[] = "hello";
ostr << hello;
- if(ostr.str() != hello)
- {
+ if (ostr.str() != hello) {
std::cerr << "failed to write hello to ostr" << std::endl;
return 1;
- }
+ }
const char world[] = "world";
std::ostringstream ostr2;
- ostr2.write( hello, strlen(hello) ); /* I could do sizeof */
- ostr2.put( '\0' );
- ostr2.write( world, strlen(world) );
- if(ostr2.str().size() != strlen(hello) + 1 + strlen(world) )
- {
+ ostr2.write(hello, strlen(hello)); /* I could do sizeof */
+ ostr2.put('\0');
+ ostr2.write(world, strlen(world));
+ if (ostr2.str().size() != strlen(hello) + 1 + strlen(world)) {
std::cerr << "failed to write hello to ostr2" << std::endl;
return 1;
- }
- static const unsigned char array[] = { 0xff,0x4f,0xff,0x51,0x00,0x29,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x07,0x01,0x01,0xff,0x52,0x00,0x0c,0x00,0x00,0x00,0x01,0x00,0x05,0x04,0x04,0x00,0x01,0xff,0x5c,0x00,0x13,0x40,0x40,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0xff,0x64,0x00,0x2c,0x00,0x00,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x62,0x79,0x20,0x49,0x54,0x4b,0x2f,0x47,0x44,0x43,0x4d,0x2f,0x4f,0x70,0x65,0x6e,0x4a,0x50,0x45,0x47,0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,0x31,0x2e,0x30,0xff,0x90,0x00,0x0a,0x00,0x00,0x00,0x00,0x06,0x2c,0x00,0x01,0xff,0x93,0xcf,0xb0,0x18,0x08,0x7f,0xc6,0x99,0xbf,0xff,0xc0,0xf8,0xc1,0xc1,0xf3,0x05,0x81,0xf2,0x83,0x0a,0xa5,0xff,0x10,0x90,0xbf,0x2f,0xff,0x04,0xa8,0x7f,0xc0,0xf8,0xc4,0xc1,0xf3,0x09,0x81,0xf3,0x0c,0x19,0x34 };
+ }
+ static const unsigned char array[] = {
+ 0xff, 0x4f, 0xff, 0x51, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30,
+ 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x01, 0xff, 0x52, 0x00,
+ 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x04, 0x04, 0x00, 0x01, 0xff,
+ 0x5c, 0x00, 0x13, 0x40, 0x40, 0x48, 0x48, 0x50, 0x48, 0x48, 0x50, 0x48,
+ 0x48, 0x50, 0x48, 0x48, 0x50, 0x48, 0x48, 0x50, 0xff, 0x64, 0x00, 0x2c,
+ 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79,
+ 0x20, 0x49, 0x54, 0x4b, 0x2f, 0x47, 0x44, 0x43, 0x4d, 0x2f, 0x4f, 0x70,
+ 0x65, 0x6e, 0x4a, 0x50, 0x45, 0x47, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
+ 0x6f, 0x6e, 0x20, 0x31, 0x2e, 0x30, 0xff, 0x90, 0x00, 0x0a, 0x00, 0x00,
+ 0x00, 0x00, 0x06, 0x2c, 0x00, 0x01, 0xff, 0x93, 0xcf, 0xb0, 0x18, 0x08,
+ 0x7f, 0xc6, 0x99, 0xbf, 0xff, 0xc0, 0xf8, 0xc1, 0xc1, 0xf3, 0x05, 0x81,
+ 0xf2, 0x83, 0x0a, 0xa5, 0xff, 0x10, 0x90, 0xbf, 0x2f, 0xff, 0x04, 0xa8,
+ 0x7f, 0xc0, 0xf8, 0xc4, 0xc1, 0xf3, 0x09, 0x81, 0xf3, 0x0c, 0x19, 0x34
+ };
const size_t narray = sizeof(array); // 180
std::stringstream strstr;
- strstr.write( (char*)array, narray );
- //strstr.seekp( narray / 2 ); // set position of put pointer in mid string
- if(strstr.str().size() != narray )
- {
+ strstr.write((char*)array, narray);
+ // strstr.seekp( narray / 2 ); // set position of put pointer in mid string
+ if (strstr.str().size() != narray) {
std::cerr << "failed to write array to strstr" << std::endl;
return 1;
- }
+ }
std::istringstream istr(" 10 20 str ");
std::string s;
int x;
- if(istr >> x)
- {
- if(x != 10)
- {
+ if (istr >> x) {
+ if (x != 10) {
std::cerr << "x != 10" << std::endl;
return 1;
- }
}
- else
- {
+ } else {
std::cerr << "Failed to read 10 from istr" << std::endl;
return 1;
- }
- if(istr >> x)
- {
- if(x != 20)
- {
+ }
+ if (istr >> x) {
+ if (x != 20) {
std::cerr << "x != 20" << std::endl;
return 1;
- }
}
- else
- {
+ } else {
std::cerr << "Failed to read 20 from istr" << std::endl;
return 1;
- }
- if(istr >> s)
- {
- if(s != "str")
- {
+ }
+ if (istr >> s) {
+ if (s != "str") {
std::cerr << "s != \"str\"" << std::endl;
return 1;
- }
}
- else
- {
+ } else {
std::cerr << "Failed to read str from istr" << std::endl;
return 1;
- }
- if(istr >> s)
- {
+ }
+ if (istr >> s) {
std::cerr << "Able to read past end of stream" << std::endl;
return 1;
- }
- else
- {
+ } else {
// Clear the failure.
istr.clear(istr.rdstate() & ~std::ios::eofbit);
istr.clear(istr.rdstate() & ~std::ios::failbit);
- }
+ }
istr.str("30");
- if(istr >> x)
- {
- if(x != 30)
- {
+ if (istr >> x) {
+ if (x != 30) {
std::cerr << "x != 30" << std::endl;
return 1;
- }
}
- else
- {
+ } else {
std::cerr << "Failed to read 30 from istr" << std::endl;
return 1;
- }
+ }
std::stringstream sstr;
sstr << "40 str2";
- if(sstr >> x)
- {
- if(x != 40)
- {
+ if (sstr >> x) {
+ if (x != 40) {
std::cerr << "x != 40" << std::endl;
return 1;
- }
}
- else
- {
+ } else {
std::cerr << "Failed to read 40 from sstr" << std::endl;
return 1;
- }
- if(sstr >> s)
- {
- if(s != "str2")
- {
+ }
+ if (sstr >> s) {
+ if (s != "str2") {
std::cerr << "s != \"str2\"" << std::endl;
return 1;
- }
}
- else
- {
+ } else {
std::cerr << "Failed to read str2 from sstr" << std::endl;
return 1;
- }
+ }
// Just try to compile this.
- if(x == 12345)
- {
- std::ifstream fin("/does_not_exist",
- std::ios::in | std::ios::binary);
- }
+ if (x == 12345) {
+ std::ifstream fin("/does_not_exist", std::ios::in | std::ios::binary);
+ }
std::cout << "IOS tests passed" << std::endl;
return 0;
diff --git a/Source/kwsys/testProcess.c b/Source/kwsys/testProcess.c
index 8fd3382..092dd03 100644
--- a/Source/kwsys/testProcess.c
+++ b/Source/kwsys/testProcess.c
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
#include KWSYS_HEADER(Encoding.h)
@@ -16,8 +7,8 @@
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Process.h.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Process.h.in"
#endif
#include <assert.h>
@@ -27,21 +18,21 @@
#include <string.h>
#if defined(_WIN32)
-# include <windows.h>
+#include <windows.h>
#else
-# include <unistd.h>
-# include <signal.h>
+#include <signal.h>
+#include <unistd.h>
#endif
#if defined(__BORLANDC__)
-# pragma warn -8060 /* possibly incorrect assignment */
+#pragma warn - 8060 /* possibly incorrect assignment */
#endif
/* Platform-specific sleep functions. */
#if defined(__BEOS__) && !defined(__ZETA__)
/* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
-# include <be/kernel/OS.h>
+#include <be/kernel/OS.h>
static inline void testProcess_usleep(unsigned int usec)
{
snooze(usec);
@@ -53,13 +44,13 @@ static void testProcess_usleep(unsigned int usec)
Sleep(usec / 1000);
}
#else
-# define testProcess_usleep usleep
+#define testProcess_usleep usleep
#endif
#if defined(_WIN32)
static void testProcess_sleep(unsigned int sec)
{
- Sleep(sec*1000);
+ Sleep(sec * 1000);
}
#else
static void testProcess_sleep(unsigned int sec)
@@ -68,10 +59,9 @@ static void testProcess_sleep(unsigned int sec)
}
#endif
-int runChild(const char* cmd[], int state, int exception, int value,
- int share, int output, int delay, double timeout, int poll,
- int repeat, int disown, int createNewGroup,
- unsigned int interruptDelay);
+int runChild(const char* cmd[], int state, int exception, int value, int share,
+ int output, int delay, double timeout, int poll, int repeat,
+ int disown, int createNewGroup, unsigned int interruptDelay);
static int test1(int argc, const char* argv[])
{
@@ -85,7 +75,8 @@ static int test1(int argc, const char* argv[])
If you have problems with this test timing out on your system, or want to
run more than 257 iterations, you can change the number of iterations by
setting the KWSYS_TEST_PROCESS_1_COUNT environment variable. */
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output on stdout from test returning 0.\n");
fprintf(stderr, "Output on stderr from test returning 0.\n");
return 0;
@@ -93,7 +84,8 @@ static int test1(int argc, const char* argv[])
static int test2(int argc, const char* argv[])
{
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output on stdout from test returning 123.\n");
fprintf(stderr, "Output on stderr from test returning 123.\n");
return 123;
@@ -101,7 +93,8 @@ static int test2(int argc, const char* argv[])
static int test3(int argc, const char* argv[])
{
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output before sleep on stdout from timeout test.\n");
fprintf(stderr, "Output before sleep on stderr from timeout test.\n");
fflush(stdout);
@@ -120,7 +113,7 @@ static int test4(int argc, const char* argv[])
optimize away the write. We hope to 'outsmart' them by using
'volatile' and a slightly larger address, based on a runtime value. */
volatile int* invalidAddress = 0;
- invalidAddress += argc?1:2;
+ invalidAddress += argc ? 1 : 2;
#if defined(_WIN32)
/* Avoid error diagnostic popups since we are crashing on purpose. */
@@ -129,7 +122,8 @@ static int test4(int argc, const char* argv[])
/* Avoid error diagnostic popups since we are crashing on purpose. */
disable_debugger(1);
#endif
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output before crash on stdout from crash test.\n");
fprintf(stderr, "Output before crash on stderr from crash test.\n");
fflush(stdout);
@@ -155,8 +149,8 @@ static int test5(int argc, const char* argv[])
fprintf(stderr, "Output on stderr before recursive test.\n");
fflush(stdout);
fflush(stderr);
- r = runChild(cmd, kwsysProcess_State_Exception,
- kwsysProcess_Exception_Fault, 1, 1, 1, 0, 15, 0, 1, 0, 0, 0);
+ r = runChild(cmd, kwsysProcess_State_Exception, kwsysProcess_Exception_Fault,
+ 1, 1, 1, 0, 15, 0, 1, 0, 0, 0);
fprintf(stdout, "Output on stdout after recursive test.\n");
fprintf(stderr, "Output on stderr after recursive test.\n");
fflush(stdout);
@@ -164,24 +158,23 @@ static int test5(int argc, const char* argv[])
return r;
}
-#define TEST6_SIZE (4096*2)
+#define TEST6_SIZE (4096 * 2)
static void test6(int argc, const char* argv[])
{
int i;
- char runaway[TEST6_SIZE+1];
- (void)argc; (void)argv;
- for(i=0;i < TEST6_SIZE;++i)
- {
+ char runaway[TEST6_SIZE + 1];
+ (void)argc;
+ (void)argv;
+ for (i = 0; i < TEST6_SIZE; ++i) {
runaway[i] = '.';
- }
+ }
runaway[TEST6_SIZE] = '\n';
/* Generate huge amounts of output to test killing. */
- for(;;)
- {
- fwrite(runaway, 1, TEST6_SIZE+1, stdout);
+ for (;;) {
+ fwrite(runaway, 1, TEST6_SIZE + 1, stdout);
fflush(stdout);
- }
+ }
}
/* Define MINPOLL to be one more than the number of times output is
@@ -191,7 +184,8 @@ static void test6(int argc, const char* argv[])
#define MAXPOLL 20
static int test7(int argc, const char* argv[])
{
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output on stdout before sleep.\n");
fprintf(stderr, "Output on stderr before sleep.\n");
fflush(stdout);
@@ -231,7 +225,8 @@ static int test8(int argc, const char* argv[])
static int test8_grandchild(int argc, const char* argv[])
{
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
fflush(stdout);
@@ -266,9 +261,8 @@ static int test9(int argc, const char* argv[])
fprintf(stderr, "Output on stderr before grandchild test.\n");
fflush(stdout);
fflush(stderr);
- r = runChild(cmd, kwsysProcess_State_Exited,
- kwsysProcess_Exception_None,
- 0, 1, 1, 0, 30, 0, 1, 0, 0, 0);
+ r = runChild(cmd, kwsysProcess_State_Exited, kwsysProcess_Exception_None, 0,
+ 1, 1, 0, 30, 0, 1, 0, 0, 0);
/* This sleep will avoid a race condition between this function exiting
normally and our Ctrl+C handler exiting abnormally after the process
exits. */
@@ -294,21 +288,20 @@ static BOOL WINAPI test9_grandchild_handler(DWORD dwCtrlType)
static int test9_grandchild(int argc, const char* argv[])
{
/* The grandchild just sleeps for a few seconds while ignoring signals. */
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
#if defined(_WIN32)
- if(!SetConsoleCtrlHandler(test9_grandchild_handler, TRUE))
- {
+ if (!SetConsoleCtrlHandler(test9_grandchild_handler, TRUE)) {
return 1;
- }
+ }
#else
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
- if(sigaction(SIGINT, &sa, 0) < 0)
- {
+ if (sigaction(SIGINT, &sa, 0) < 0) {
return 1;
- }
+ }
#endif
fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
@@ -341,9 +334,9 @@ static int test10(int argc, const char* argv[])
fprintf(stderr, "Output on stderr before grandchild test.\n");
fflush(stdout);
fflush(stderr);
- r = runChild(cmd, kwsysProcess_State_Exception,
- kwsysProcess_Exception_Interrupt,
- 0, 1, 1, 0, 30, 0, 1, 0, 1, 0);
+ r =
+ runChild(cmd, kwsysProcess_State_Exception,
+ kwsysProcess_Exception_Interrupt, 0, 1, 1, 0, 30, 0, 1, 0, 1, 0);
fprintf(stdout, "Output on stdout after grandchild test.\n");
fprintf(stderr, "Output on stderr after grandchild test.\n");
fflush(stdout);
@@ -354,7 +347,8 @@ static int test10(int argc, const char* argv[])
static int test10_grandchild(int argc, const char* argv[])
{
/* The grandchild just sleeps for a few seconds and handles signals. */
- (void)argc; (void)argv;
+ (void)argc;
+ (void)argv;
fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
fflush(stdout);
@@ -368,11 +362,10 @@ static int test10_grandchild(int argc, const char* argv[])
return 0;
}
-static int runChild2(kwsysProcess* kp,
- const char* cmd[], int state, int exception, int value,
- int share, int output, int delay, double timeout,
- int poll, int disown, int createNewGroup,
- unsigned int interruptDelay)
+static int runChild2(kwsysProcess* kp, const char* cmd[], int state,
+ int exception, int value, int share, int output,
+ int delay, double timeout, int poll, int disown,
+ int createNewGroup, unsigned int interruptDelay)
{
int result = 0;
char* data = 0;
@@ -380,146 +373,128 @@ static int runChild2(kwsysProcess* kp,
double userTimeout = 0;
double* pUserTimeout = 0;
kwsysProcess_SetCommand(kp, cmd);
- if(timeout >= 0)
- {
+ if (timeout >= 0) {
kwsysProcess_SetTimeout(kp, timeout);
- }
- if(share)
- {
+ }
+ if (share) {
kwsysProcess_SetPipeShared(kp, kwsysProcess_Pipe_STDOUT, 1);
kwsysProcess_SetPipeShared(kp, kwsysProcess_Pipe_STDERR, 1);
- }
- if(disown)
- {
+ }
+ if (disown) {
kwsysProcess_SetOption(kp, kwsysProcess_Option_Detach, 1);
- }
- if(createNewGroup)
- {
+ }
+ if (createNewGroup) {
kwsysProcess_SetOption(kp, kwsysProcess_Option_CreateProcessGroup, 1);
- }
+ }
kwsysProcess_Execute(kp);
- if(poll)
- {
+ if (poll) {
pUserTimeout = &userTimeout;
- }
+ }
- if(interruptDelay)
- {
+ if (interruptDelay) {
testProcess_sleep(interruptDelay);
kwsysProcess_Interrupt(kp);
- }
+ }
- if(!share && !disown)
- {
+ if (!share && !disown) {
int p;
- while((p = kwsysProcess_WaitForData(kp, &data, &length, pUserTimeout)))
- {
- if(output)
- {
- if(poll && p == kwsysProcess_Pipe_Timeout)
- {
+ while ((p = kwsysProcess_WaitForData(kp, &data, &length, pUserTimeout))) {
+ if (output) {
+ if (poll && p == kwsysProcess_Pipe_Timeout) {
fprintf(stdout, "WaitForData timeout reached.\n");
fflush(stdout);
/* Count the number of times we polled without getting data.
If it is excessive then kill the child and fail. */
- if(++poll >= MAXPOLL)
- {
- fprintf(stdout, "Poll count reached limit %d.\n",
- MAXPOLL);
+ if (++poll >= MAXPOLL) {
+ fprintf(stdout, "Poll count reached limit %d.\n", MAXPOLL);
kwsysProcess_Kill(kp);
- }
}
- else
- {
- fwrite(data, 1, (size_t) length, stdout);
+ } else {
+ fwrite(data, 1, (size_t)length, stdout);
fflush(stdout);
- }
}
- if(poll)
- {
+ }
+ if (poll) {
/* Delay to avoid busy loop during polling. */
testProcess_usleep(100000);
- }
- if(delay)
- {
- /* Purposely sleeping only on Win32 to let pipe fill up. */
+ }
+ if (delay) {
+/* Purposely sleeping only on Win32 to let pipe fill up. */
#if defined(_WIN32)
testProcess_usleep(100000);
#endif
- }
}
}
+ }
- if(disown)
- {
+ if (disown) {
kwsysProcess_Disown(kp);
- }
- else
- {
+ } else {
kwsysProcess_WaitForExit(kp, 0);
- }
+ }
- switch (kwsysProcess_GetState(kp))
- {
+ switch (kwsysProcess_GetState(kp)) {
case kwsysProcess_State_Starting:
- printf("No process has been executed.\n"); break;
+ printf("No process has been executed.\n");
+ break;
case kwsysProcess_State_Executing:
- printf("The process is still executing.\n"); break;
+ printf("The process is still executing.\n");
+ break;
case kwsysProcess_State_Expired:
- printf("Child was killed when timeout expired.\n"); break;
+ printf("Child was killed when timeout expired.\n");
+ break;
case kwsysProcess_State_Exited:
- printf("Child exited with value = %d\n",
- kwsysProcess_GetExitValue(kp));
+ printf("Child exited with value = %d\n", kwsysProcess_GetExitValue(kp));
result = ((exception != kwsysProcess_GetExitException(kp)) ||
- (value != kwsysProcess_GetExitValue(kp))); break;
+ (value != kwsysProcess_GetExitValue(kp)));
+ break;
case kwsysProcess_State_Killed:
- printf("Child was killed by parent.\n"); break;
+ printf("Child was killed by parent.\n");
+ break;
case kwsysProcess_State_Exception:
printf("Child terminated abnormally: %s\n",
kwsysProcess_GetExceptionString(kp));
result = ((exception != kwsysProcess_GetExitException(kp)) ||
- (value != kwsysProcess_GetExitValue(kp))); break;
+ (value != kwsysProcess_GetExitValue(kp)));
+ break;
case kwsysProcess_State_Disowned:
- printf("Child was disowned.\n"); break;
+ printf("Child was disowned.\n");
+ break;
case kwsysProcess_State_Error:
printf("Error in administrating child process: [%s]\n",
- kwsysProcess_GetErrorString(kp)); break;
- };
+ kwsysProcess_GetErrorString(kp));
+ break;
+ };
- if(result)
- {
- if(exception != kwsysProcess_GetExitException(kp))
- {
+ if (result) {
+ if (exception != kwsysProcess_GetExitException(kp)) {
fprintf(stderr, "Mismatch in exit exception. "
- "Should have been %d, was %d.\n",
+ "Should have been %d, was %d.\n",
exception, kwsysProcess_GetExitException(kp));
- }
- if(value != kwsysProcess_GetExitValue(kp))
- {
+ }
+ if (value != kwsysProcess_GetExitValue(kp)) {
fprintf(stderr, "Mismatch in exit value. "
- "Should have been %d, was %d.\n",
+ "Should have been %d, was %d.\n",
value, kwsysProcess_GetExitValue(kp));
- }
}
+ }
- if(kwsysProcess_GetState(kp) != state)
- {
+ if (kwsysProcess_GetState(kp) != state) {
fprintf(stderr, "Mismatch in state. "
- "Should have been %d, was %d.\n",
+ "Should have been %d, was %d.\n",
state, kwsysProcess_GetState(kp));
result = 1;
- }
+ }
/* We should have polled more times than there were data if polling
was enabled. */
- if(poll && poll < MINPOLL)
- {
- fprintf(stderr, "Poll count is %d, which is less than %d.\n",
- poll, MINPOLL);
+ if (poll && poll < MINPOLL) {
+ fprintf(stderr, "Poll count is %d, which is less than %d.\n", poll,
+ MINPOLL);
result = 1;
- }
+ }
return result;
}
@@ -551,28 +526,23 @@ static int runChild2(kwsysProcess* kp,
* BEFORE any reading/polling of pipes occurs and before any
* detachment occurs.
*/
-int runChild(const char* cmd[], int state, int exception, int value,
- int share, int output, int delay, double timeout,
- int poll, int repeat, int disown, int createNewGroup,
- unsigned int interruptDelay)
+int runChild(const char* cmd[], int state, int exception, int value, int share,
+ int output, int delay, double timeout, int poll, int repeat,
+ int disown, int createNewGroup, unsigned int interruptDelay)
{
int result = 1;
kwsysProcess* kp = kwsysProcess_New();
- if(!kp)
- {
+ if (!kp) {
fprintf(stderr, "kwsysProcess_New returned NULL!\n");
return 1;
- }
- while(repeat-- > 0)
- {
- result = runChild2(kp, cmd, state, exception, value, share,
- output, delay, timeout, poll, disown, createNewGroup,
- interruptDelay);
- if(result)
- {
+ }
+ while (repeat-- > 0) {
+ result = runChild2(kp, cmd, state, exception, value, share, output, delay,
+ timeout, poll, disown, createNewGroup, interruptDelay);
+ if (result) {
break;
- }
}
+ }
kwsysProcess_Delete(kp);
return result;
}
@@ -585,8 +555,7 @@ int main(int argc, const char* argv[])
int i;
char new_args[10][_MAX_PATH];
LPWSTR* w_av = CommandLineToArgvW(GetCommandLineW(), &argc);
- for(i=0; i<argc; i++)
- {
+ for (i = 0; i < argc; i++) {
kwsysEncoding_wcstombs(new_args[i], w_av[i], _MAX_PATH);
argv[i] = new_args[i];
}
@@ -609,107 +578,96 @@ int main(int argc, const char* argv[])
SetStdHandle(STD_ERROR_HANDLE, out);
}
#endif
- if(argc == 2)
- {
+ if (argc == 2) {
n = atoi(argv[1]);
- }
- else if(argc == 3 && strcmp(argv[1], "run") == 0)
- {
+ } else if (argc == 3 && strcmp(argv[1], "run") == 0) {
n = atoi(argv[2]);
- }
+ }
/* Check arguments. */
- if(((n >= 1 && n <= 10) || n == 108 || n == 109 || n == 110) && argc == 3)
- {
+ if (((n >= 1 && n <= 10) || n == 108 || n == 109 || n == 110) && argc == 3) {
/* This is the child process for a requested test number. */
- switch (n)
- {
- case 1: return test1(argc, argv);
- case 2: return test2(argc, argv);
- case 3: return test3(argc, argv);
- case 4: return test4(argc, argv);
- case 5: return test5(argc, argv);
- case 6: test6(argc, argv); return 0;
- case 7: return test7(argc, argv);
- case 8: return test8(argc, argv);
- case 9: return test9(argc, argv);
- case 10: return test10(argc, argv);
- case 108: return test8_grandchild(argc, argv);
- case 109: return test9_grandchild(argc, argv);
- case 110: return test10_grandchild(argc, argv);
- }
+ switch (n) {
+ case 1:
+ return test1(argc, argv);
+ case 2:
+ return test2(argc, argv);
+ case 3:
+ return test3(argc, argv);
+ case 4:
+ return test4(argc, argv);
+ case 5:
+ return test5(argc, argv);
+ case 6:
+ test6(argc, argv);
+ return 0;
+ case 7:
+ return test7(argc, argv);
+ case 8:
+ return test8(argc, argv);
+ case 9:
+ return test9(argc, argv);
+ case 10:
+ return test10(argc, argv);
+ case 108:
+ return test8_grandchild(argc, argv);
+ case 109:
+ return test9_grandchild(argc, argv);
+ case 110:
+ return test10_grandchild(argc, argv);
+ }
fprintf(stderr, "Invalid test number %d.\n", n);
return 1;
- }
- else if(n >= 1 && n <= 10)
- {
+ } else if (n >= 1 && n <= 10) {
/* This is the parent process for a requested test number. */
- int states[10] =
- {
- kwsysProcess_State_Exited,
- kwsysProcess_State_Exited,
- kwsysProcess_State_Expired,
- kwsysProcess_State_Exception,
- kwsysProcess_State_Exited,
- kwsysProcess_State_Expired,
- kwsysProcess_State_Exited,
- kwsysProcess_State_Exited,
- kwsysProcess_State_Expired, /* Ctrl+C handler test */
+ int states[10] = {
+ kwsysProcess_State_Exited, kwsysProcess_State_Exited,
+ kwsysProcess_State_Expired, kwsysProcess_State_Exception,
+ kwsysProcess_State_Exited, kwsysProcess_State_Expired,
+ kwsysProcess_State_Exited, kwsysProcess_State_Exited,
+ kwsysProcess_State_Expired, /* Ctrl+C handler test */
kwsysProcess_State_Exception /* Process group test */
};
- int exceptions[10] =
- {
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_Fault,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_None,
- kwsysProcess_Exception_Interrupt
+ int exceptions[10] = {
+ kwsysProcess_Exception_None, kwsysProcess_Exception_None,
+ kwsysProcess_Exception_None, kwsysProcess_Exception_Fault,
+ kwsysProcess_Exception_None, kwsysProcess_Exception_None,
+ kwsysProcess_Exception_None, kwsysProcess_Exception_None,
+ kwsysProcess_Exception_None, kwsysProcess_Exception_Interrupt
};
- int values[10] = {0, 123, 1, 1, 0, 0, 0, 0, 1, 1};
- int shares[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1};
- int outputs[10] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 1};
- int delays[10] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
- double timeouts[10] = {10, 10, 10, 30, 30, 10, -1, 10, 6, 4};
- int polls[10] = {0, 0, 0, 0, 0, 0, 1, 0, 0, 0};
- int repeat[10] = {257, 1, 1, 1, 1, 1, 1, 1, 1, 1};
- int createNewGroups[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1};
- unsigned int interruptDelays[10] = {0, 0, 0, 0, 0, 0, 0, 0, 3, 2};
+ int values[10] = { 0, 123, 1, 1, 0, 0, 0, 0, 1, 1 };
+ int shares[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 };
+ int outputs[10] = { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 };
+ int delays[10] = { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 };
+ double timeouts[10] = { 10, 10, 10, 30, 30, 10, -1, 10, 6, 4 };
+ int polls[10] = { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 };
+ int repeat[10] = { 257, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
+ int createNewGroups[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 };
+ unsigned int interruptDelays[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 2 };
int r;
const char* cmd[4];
#ifdef _WIN32
char* argv0 = 0;
#endif
char* test1IterationsStr = getenv("KWSYS_TEST_PROCESS_1_COUNT");
- if(test1IterationsStr)
- {
+ if (test1IterationsStr) {
long int test1Iterations = strtol(test1IterationsStr, 0, 10);
- if(test1Iterations > 10 && test1Iterations != LONG_MAX)
- {
+ if (test1Iterations > 10 && test1Iterations != LONG_MAX) {
repeat[0] = (int)test1Iterations;
- }
}
+ }
#ifdef _WIN32
- if(n == 0 && (argv0 = strdup(argv[0])))
- {
+ if (n == 0 && (argv0 = strdup(argv[0]))) {
/* Try converting to forward slashes to see if it works. */
char* c;
- for(c=argv0; *c; ++c)
- {
- if(*c == '\\')
- {
+ for (c = argv0; *c; ++c) {
+ if (*c == '\\') {
*c = '/';
- }
}
- cmd[0] = argv0;
}
- else
- {
+ cmd[0] = argv0;
+ } else {
cmd[0] = argv[0];
- }
+ }
#else
cmd[0] = argv[0];
#endif
@@ -720,36 +678,34 @@ int main(int argc, const char* argv[])
fprintf(stderr, "Output on stderr before test %d.\n", n);
fflush(stdout);
fflush(stderr);
- r = runChild(cmd, states[n-1], exceptions[n-1], values[n-1], shares[n-1],
- outputs[n-1], delays[n-1], timeouts[n-1],
- polls[n-1], repeat[n-1], 0, createNewGroups[n-1],
- interruptDelays[n-1]);
+ r = runChild(cmd, states[n - 1], exceptions[n - 1], values[n - 1],
+ shares[n - 1], outputs[n - 1], delays[n - 1], timeouts[n - 1],
+ polls[n - 1], repeat[n - 1], 0, createNewGroups[n - 1],
+ interruptDelays[n - 1]);
fprintf(stdout, "Output on stdout after test %d.\n", n);
fprintf(stderr, "Output on stderr after test %d.\n", n);
fflush(stdout);
fflush(stderr);
#if defined(_WIN32)
- if(argv0) { free(argv0); }
+ if (argv0) {
+ free(argv0);
+ }
#endif
return r;
- }
- else if(argc > 2 && strcmp(argv[1], "0") == 0)
- {
+ } else if (argc > 2 && strcmp(argv[1], "0") == 0) {
/* This is the special debugging test to run a given command
line. */
- const char** cmd = argv+2;
+ const char** cmd = argv + 2;
int state = kwsysProcess_State_Exited;
int exception = kwsysProcess_Exception_None;
int value = 0;
double timeout = 0;
- int r = runChild(cmd, state, exception, value, 0, 1, 0, timeout,
- 0, 1, 0, 0, 0);
+ int r =
+ runChild(cmd, state, exception, value, 0, 1, 0, timeout, 0, 1, 0, 0, 0);
return r;
- }
- else
- {
+ } else {
/* Improper usage. */
fprintf(stdout, "Usage: %s <test number>\n", argv[0]);
return 1;
- }
+ }
}
diff --git a/Source/kwsys/testSharedForward.c.in b/Source/kwsys/testSharedForward.c.in
index ee753ef..9a0c0c0 100644
--- a/Source/kwsys/testSharedForward.c.in
+++ b/Source/kwsys/testSharedForward.c.in
@@ -1,33 +1,24 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#if defined(CMAKE_INTDIR)
-# define CONFIG_DIR_PRE CMAKE_INTDIR "/"
-# define CONFIG_DIR_POST "/" CMAKE_INTDIR
+#define CONFIG_DIR_PRE CMAKE_INTDIR "/"
+#define CONFIG_DIR_POST "/" CMAKE_INTDIR
#else
-# define CONFIG_DIR_PRE ""
-# define CONFIG_DIR_POST ""
+#define CONFIG_DIR_PRE ""
+#define CONFIG_DIR_POST ""
#endif
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD "@EXEC_DIR@"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL 0
-#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD \
+#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD \
CONFIG_DIR_PRE "@KWSYS_NAMESPACE@TestProcess"
-#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL \
+#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL \
"@KWSYS_NAMESPACE@TestProcess"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND "--command"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT "--print"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD "--ldd"
#if defined(CMAKE_INTDIR)
-# define @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
+#define @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
#endif
#include <@KWSYS_NAMESPACE@/SharedForward.h>
int main(int argc, char** argv)
diff --git a/Source/kwsys/testSystemInformation.cxx b/Source/kwsys/testSystemInformation.cxx
index c96751a..86a1e1e 100644
--- a/Source/kwsys/testSystemInformation.cxx
+++ b/Source/kwsys/testSystemInformation.cxx
@@ -1,51 +1,41 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(SystemInformation.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "SystemInformation.hxx.in"
+#include "SystemInformation.hxx.in"
#endif
#include <iostream>
#if defined(KWSYS_USE_LONG_LONG)
-# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)x)
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)x)
+#endif
#elif defined(KWSYS_USE___INT64)
-# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)x)
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)x)
+#endif
#else
-# error "No Long Long"
+#error "No Long Long"
#endif
-#define printMethod(info, m) std::cout << #m << ": " \
-<< info.m() << "\n"
+#define printMethod(info, m) std::cout << #m << ": " << info.m() << "\n"
-#define printMethod2(info, m, unit) std::cout << #m << ": " \
-<< info.m() << " " << unit << "\n"
+#define printMethod2(info, m, unit) \
+ std::cout << #m << ": " << info.m() << " " << unit << "\n"
-#define printMethod3(info, m, unit) std::cout << #m << ": " \
-<< iostreamLongLong(info.m) << " " << unit << "\n"
+#define printMethod3(info, m, unit) \
+ std::cout << #m << ": " << iostreamLongLong(info.m) << " " << unit << "\n"
-int testSystemInformation(int, char*[])
+int testSystemInformation(int, char* [])
{
std::cout << "CTEST_FULL_OUTPUT\n"; // avoid truncation
@@ -84,25 +74,22 @@ int testSystemInformation(int, char*[])
printMethod2(info, GetAvailablePhysicalMemory, "MB");
printMethod3(info, GetHostMemoryTotal(), "KiB");
printMethod3(info, GetHostMemoryAvailable("KWSHL"), "KiB");
- printMethod3(info, GetProcMemoryAvailable("KWSHL","KWSPL"), "KiB");
+ printMethod3(info, GetProcMemoryAvailable("KWSHL", "KWSPL"), "KiB");
printMethod3(info, GetHostMemoryUsed(), "KiB");
printMethod3(info, GetProcMemoryUsed(), "KiB");
printMethod(info, GetLoadAverage);
- for (long int i = 0; i <= 31; i++)
- {
- if (info.DoesCPUSupportFeature(static_cast<long int>(1) << i))
- {
+ for (long int i = 0; i <= 31; i++) {
+ if (info.DoesCPUSupportFeature(static_cast<long int>(1) << i)) {
std::cout << "CPU feature " << i << "\n";
- }
}
+ }
/* test stack trace
*/
- std::cout
- << "Program Stack:" << std::endl
- << kwsys::SystemInformation::GetProgramStack(0,0) << std::endl
- << std::endl;
+ std::cout << "Program Stack:" << std::endl
+ << kwsys::SystemInformation::GetProgramStack(0, 0) << std::endl
+ << std::endl;
/* test segv handler
info.SetStackTraceOnError(1);
diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx
index 880b46e..b04f2cb 100644
--- a/Source/kwsys/testSystemTools.cxx
+++ b/Source/kwsys/testSystemTools.cxx
@@ -1,18 +1,9 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
#endif
#include KWSYS_HEADER(SystemTools.hxx)
@@ -20,7 +11,7 @@
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
-# include "SystemTools.hxx.in"
+#include "SystemTools.hxx.in"
#endif
// Include with <> instead of "" to avoid getting any in-source copy
@@ -31,77 +22,65 @@
#include <sstream>
#include <string.h> /* strcmp */
#if defined(_WIN32) && !defined(__CYGWIN__)
-# include <io.h> /* _umask (MSVC) / umask (Borland) */
-# ifdef _MSC_VER
-# define umask _umask // Note this is still umask on Borland
-# endif
+#include <io.h> /* _umask (MSVC) / umask (Borland) */
+#ifdef _MSC_VER
+#define umask _umask // Note this is still umask on Borland
+#endif
#endif
#include <sys/stat.h> /* umask (POSIX), _S_I* constants (Windows) */
// Visual C++ does not define mode_t (note that Borland does, however).
-#if defined( _MSC_VER )
+#if defined(_MSC_VER)
typedef unsigned short mode_t;
#endif
//----------------------------------------------------------------------------
-static const char* toUnixPaths[][2] =
-{
- { "/usr/local/bin/passwd", "/usr/local/bin/passwd" },
- { "/usr/lo cal/bin/pa sswd", "/usr/lo cal/bin/pa sswd" },
- { "/usr/lo\\ cal/bin/pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
- { "c:/usr/local/bin/passwd", "c:/usr/local/bin/passwd" },
- { "c:/usr/lo cal/bin/pa sswd", "c:/usr/lo cal/bin/pa sswd" },
- { "c:/usr/lo\\ cal/bin/pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
- { "\\usr\\local\\bin\\passwd", "/usr/local/bin/passwd" },
- { "\\usr\\lo cal\\bin\\pa sswd", "/usr/lo cal/bin/pa sswd" },
- { "\\usr\\lo\\ cal\\bin\\pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
- { "c:\\usr\\local\\bin\\passwd", "c:/usr/local/bin/passwd" },
- { "c:\\usr\\lo cal\\bin\\pa sswd", "c:/usr/lo cal/bin/pa sswd" },
- { "c:\\usr\\lo\\ cal\\bin\\pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
- { "\\\\usr\\local\\bin\\passwd", "//usr/local/bin/passwd" },
- { "\\\\usr\\lo cal\\bin\\pa sswd", "//usr/lo cal/bin/pa sswd" },
- { "\\\\usr\\lo\\ cal\\bin\\pa\\ sswd", "//usr/lo\\ cal/bin/pa\\ sswd" },
- {0, 0}
+static const char* toUnixPaths[][2] = {
+ { "/usr/local/bin/passwd", "/usr/local/bin/passwd" },
+ { "/usr/lo cal/bin/pa sswd", "/usr/lo cal/bin/pa sswd" },
+ { "/usr/lo\\ cal/bin/pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
+ { "c:/usr/local/bin/passwd", "c:/usr/local/bin/passwd" },
+ { "c:/usr/lo cal/bin/pa sswd", "c:/usr/lo cal/bin/pa sswd" },
+ { "c:/usr/lo\\ cal/bin/pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
+ { "\\usr\\local\\bin\\passwd", "/usr/local/bin/passwd" },
+ { "\\usr\\lo cal\\bin\\pa sswd", "/usr/lo cal/bin/pa sswd" },
+ { "\\usr\\lo\\ cal\\bin\\pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
+ { "c:\\usr\\local\\bin\\passwd", "c:/usr/local/bin/passwd" },
+ { "c:\\usr\\lo cal\\bin\\pa sswd", "c:/usr/lo cal/bin/pa sswd" },
+ { "c:\\usr\\lo\\ cal\\bin\\pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
+ { "\\\\usr\\local\\bin\\passwd", "//usr/local/bin/passwd" },
+ { "\\\\usr\\lo cal\\bin\\pa sswd", "//usr/lo cal/bin/pa sswd" },
+ { "\\\\usr\\lo\\ cal\\bin\\pa\\ sswd", "//usr/lo\\ cal/bin/pa\\ sswd" },
+ { 0, 0 }
};
-static bool CheckConvertToUnixSlashes(std::string input,
- std::string output)
+static bool CheckConvertToUnixSlashes(std::string input, std::string output)
{
std::string result = input;
kwsys::SystemTools::ConvertToUnixSlashes(result);
- if ( result != output )
- {
- std::cerr
- << "Problem with ConvertToUnixSlashes - input: " << input
- << " output: " << result << " expected: " << output
- << std::endl;
+ if (result != output) {
+ std::cerr << "Problem with ConvertToUnixSlashes - input: " << input
+ << " output: " << result << " expected: " << output << std::endl;
return false;
- }
+ }
return true;
}
//----------------------------------------------------------------------------
-static const char* checkEscapeChars[][4] =
-{
- { "1 foo 2 bar 2", "12", "\\", "\\1 foo \\2 bar \\2"},
- { " {} ", "{}", "#", " #{#} "},
- {0, 0, 0, 0}
-};
+static const char* checkEscapeChars[][4] = { { "1 foo 2 bar 2", "12", "\\",
+ "\\1 foo \\2 bar \\2" },
+ { " {} ", "{}", "#", " #{#} " },
+ { 0, 0, 0, 0 } };
-static bool CheckEscapeChars(std::string input,
- const char *chars_to_escape,
- char escape_char,
- std::string output)
+static bool CheckEscapeChars(std::string input, const char* chars_to_escape,
+ char escape_char, std::string output)
{
std::string result = kwsys::SystemTools::EscapeChars(
input.c_str(), chars_to_escape, escape_char);
- if (result != output)
- {
- std::cerr
- << "Problem with CheckEscapeChars - input: " << input
- << " output: " << result << " expected: " << output
- << std::endl;
+ if (result != output) {
+ std::cerr << "Problem with CheckEscapeChars - input: " << input
+ << " output: " << result << " expected: " << output << std::endl;
return false;
- }
+ }
return true;
}
@@ -110,268 +89,192 @@ static bool CheckFileOperations()
{
bool res = true;
const std::string testNonExistingFile(TEST_SYSTEMTOOLS_SOURCE_DIR
- "/testSystemToolsNonExistingFile");
- const std::string testDotFile(TEST_SYSTEMTOOLS_SOURCE_DIR
- "/.");
+ "/testSystemToolsNonExistingFile");
+ const std::string testDotFile(TEST_SYSTEMTOOLS_SOURCE_DIR "/.");
const std::string testBinFile(TEST_SYSTEMTOOLS_SOURCE_DIR
- "/testSystemTools.bin");
+ "/testSystemTools.bin");
const std::string testTxtFile(TEST_SYSTEMTOOLS_SOURCE_DIR
- "/testSystemTools.cxx");
+ "/testSystemTools.cxx");
const std::string testNewDir(TEST_SYSTEMTOOLS_BINARY_DIR
- "/testSystemToolsNewDir");
+ "/testSystemToolsNewDir");
const std::string testNewFile(testNewDir + "/testNewFile.txt");
if (kwsys::SystemTools::DetectFileType(testNonExistingFile.c_str()) !=
- kwsys::SystemTools::FileTypeUnknown)
- {
- std::cerr
- << "Problem with DetectFileType - failed to detect type of: "
- << testNonExistingFile << std::endl;
+ kwsys::SystemTools::FileTypeUnknown) {
+ std::cerr << "Problem with DetectFileType - failed to detect type of: "
+ << testNonExistingFile << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::DetectFileType(testDotFile.c_str()) !=
- kwsys::SystemTools::FileTypeUnknown)
- {
- std::cerr
- << "Problem with DetectFileType - failed to detect type of: "
- << testDotFile << std::endl;
+ kwsys::SystemTools::FileTypeUnknown) {
+ std::cerr << "Problem with DetectFileType - failed to detect type of: "
+ << testDotFile << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::DetectFileType(testBinFile.c_str()) !=
- kwsys::SystemTools::FileTypeBinary)
- {
- std::cerr
- << "Problem with DetectFileType - failed to detect type of: "
- << testBinFile << std::endl;
+ kwsys::SystemTools::FileTypeBinary) {
+ std::cerr << "Problem with DetectFileType - failed to detect type of: "
+ << testBinFile << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::DetectFileType(testTxtFile.c_str()) !=
- kwsys::SystemTools::FileTypeText)
- {
- std::cerr
- << "Problem with DetectFileType - failed to detect type of: "
- << testTxtFile << std::endl;
+ kwsys::SystemTools::FileTypeText) {
+ std::cerr << "Problem with DetectFileType - failed to detect type of: "
+ << testTxtFile << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::FileLength(testBinFile) != 766)
- {
- std::cerr
- << "Problem with FileLength - incorrect length for: "
- << testBinFile << std::endl;
+ if (kwsys::SystemTools::FileLength(testBinFile) != 766) {
+ std::cerr << "Problem with FileLength - incorrect length for: "
+ << testBinFile << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::MakeDirectory(testNewDir))
- {
- std::cerr
- << "Problem with MakeDirectory for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::MakeDirectory(testNewDir)) {
+ std::cerr << "Problem with MakeDirectory for: " << testNewDir << std::endl;
res = false;
- }
+ }
// calling it again should just return true
- if (!kwsys::SystemTools::MakeDirectory(testNewDir))
- {
- std::cerr
- << "Problem with second call to MakeDirectory for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::MakeDirectory(testNewDir)) {
+ std::cerr << "Problem with second call to MakeDirectory for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
// calling with 0 pointer should return false
- if (kwsys::SystemTools::MakeDirectory(0))
- {
- std::cerr
- << "Problem with MakeDirectory(0)"
- << std::endl;
+ if (kwsys::SystemTools::MakeDirectory(0)) {
+ std::cerr << "Problem with MakeDirectory(0)" << std::endl;
res = false;
- }
+ }
// calling with an empty string should return false
- if (kwsys::SystemTools::MakeDirectory(std::string()))
- {
- std::cerr
- << "Problem with MakeDirectory(std::string())"
- << std::endl;
+ if (kwsys::SystemTools::MakeDirectory(std::string())) {
+ std::cerr << "Problem with MakeDirectory(std::string())" << std::endl;
res = false;
- }
+ }
// check existence
- if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false))
- {
- std::cerr
- << "Problem with FileExists as C string and not file for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false)) {
+ std::cerr << "Problem with FileExists as C string and not file for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
// check existence
- if (!kwsys::SystemTools::PathExists(testNewDir))
- {
- std::cerr
- << "Problem with PathExists for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::PathExists(testNewDir)) {
+ std::cerr << "Problem with PathExists for: " << testNewDir << std::endl;
res = false;
- }
+ }
// remove it
- if (!kwsys::SystemTools::RemoveADirectory(testNewDir))
- {
- std::cerr
- << "Problem with RemoveADirectory for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::RemoveADirectory(testNewDir)) {
+ std::cerr << "Problem with RemoveADirectory for: " << testNewDir
+ << std::endl;
res = false;
- }
+ }
// check existence
- if (kwsys::SystemTools::FileExists(testNewDir.c_str(), false))
- {
- std::cerr
- << "After RemoveADirectory: "
- << "Problem with FileExists as C string and not file for: "
- << testNewDir << std::endl;
+ if (kwsys::SystemTools::FileExists(testNewDir.c_str(), false)) {
+ std::cerr << "After RemoveADirectory: "
+ << "Problem with FileExists as C string and not file for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
// check existence
- if (kwsys::SystemTools::PathExists(testNewDir))
- {
- std::cerr
- << "After RemoveADirectory: "
- << "Problem with PathExists for: "
- << testNewDir << std::endl;
+ if (kwsys::SystemTools::PathExists(testNewDir)) {
+ std::cerr << "After RemoveADirectory: "
+ << "Problem with PathExists for: " << testNewDir << std::endl;
res = false;
- }
+ }
// create it using the char* version
- if (!kwsys::SystemTools::MakeDirectory(testNewDir.c_str()))
- {
- std::cerr
- << "Problem with second call to MakeDirectory as C string for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::MakeDirectory(testNewDir.c_str())) {
+ std::cerr << "Problem with second call to MakeDirectory as C string for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::Touch(testNewFile.c_str(), true))
- {
- std::cerr
- << "Problem with Touch for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::Touch(testNewFile.c_str(), true)) {
+ std::cerr << "Problem with Touch for: " << testNewFile << std::endl;
res = false;
- }
+ }
// calling MakeDirectory with something that is no file should fail
- if (kwsys::SystemTools::MakeDirectory(testNewFile))
- {
- std::cerr
- << "Problem with to MakeDirectory for: "
- << testNewFile << std::endl;
+ if (kwsys::SystemTools::MakeDirectory(testNewFile)) {
+ std::cerr << "Problem with to MakeDirectory for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
// calling with 0 pointer should return false
- if (kwsys::SystemTools::FileExists(0))
- {
- std::cerr
- << "Problem with FileExists(0)"
- << std::endl;
+ if (kwsys::SystemTools::FileExists(0)) {
+ std::cerr << "Problem with FileExists(0)" << std::endl;
res = false;
- }
- if (kwsys::SystemTools::FileExists(0, true))
- {
- std::cerr
- << "Problem with FileExists(0) as file"
- << std::endl;
+ }
+ if (kwsys::SystemTools::FileExists(0, true)) {
+ std::cerr << "Problem with FileExists(0) as file" << std::endl;
res = false;
- }
+ }
// calling with an empty string should return false
- if (kwsys::SystemTools::FileExists(std::string()))
- {
- std::cerr
- << "Problem with FileExists(std::string())"
- << std::endl;
+ if (kwsys::SystemTools::FileExists(std::string())) {
+ std::cerr << "Problem with FileExists(std::string())" << std::endl;
res = false;
- }
+ }
// FileExists(x, true) should return false on a directory
- if (kwsys::SystemTools::FileExists(testNewDir, true))
- {
- std::cerr
- << "Problem with FileExists as file for: "
- << testNewDir << std::endl;
+ if (kwsys::SystemTools::FileExists(testNewDir, true)) {
+ std::cerr << "Problem with FileExists as file for: " << testNewDir
+ << std::endl;
res = false;
- }
- if (kwsys::SystemTools::FileExists(testNewDir.c_str(), true))
- {
- std::cerr
- << "Problem with FileExists as C string and file for: "
- << testNewDir << std::endl;
+ }
+ if (kwsys::SystemTools::FileExists(testNewDir.c_str(), true)) {
+ std::cerr << "Problem with FileExists as C string and file for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
// FileExists(x, false) should return true even on a directory
- if (!kwsys::SystemTools::FileExists(testNewDir, false))
- {
- std::cerr
- << "Problem with FileExists as not file for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::FileExists(testNewDir, false)) {
+ std::cerr << "Problem with FileExists as not file for: " << testNewDir
+ << std::endl;
res = false;
- }
- if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false))
- {
- std::cerr
- << "Problem with FileExists as C string and not file for: "
- << testNewDir << std::endl;
+ }
+ if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false)) {
+ std::cerr << "Problem with FileExists as C string and not file for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
// should work, was created as new file before
- if (!kwsys::SystemTools::FileExists(testNewFile))
- {
- std::cerr
- << "Problem with FileExists for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::FileExists(testNewFile)) {
+ std::cerr << "Problem with FileExists for: " << testNewDir << std::endl;
res = false;
- }
- if (!kwsys::SystemTools::FileExists(testNewFile.c_str()))
- {
- std::cerr
- << "Problem with FileExists as C string for: "
- << testNewDir << std::endl;
+ }
+ if (!kwsys::SystemTools::FileExists(testNewFile.c_str())) {
+ std::cerr << "Problem with FileExists as C string for: " << testNewDir
+ << std::endl;
res = false;
- }
- if (!kwsys::SystemTools::FileExists(testNewFile, true))
- {
- std::cerr
- << "Problem with FileExists as file for: "
- << testNewDir << std::endl;
+ }
+ if (!kwsys::SystemTools::FileExists(testNewFile, true)) {
+ std::cerr << "Problem with FileExists as file for: " << testNewDir
+ << std::endl;
res = false;
- }
- if (!kwsys::SystemTools::FileExists(testNewFile.c_str(), true))
- {
- std::cerr
- << "Problem with FileExists as C string and file for: "
- << testNewDir << std::endl;
+ }
+ if (!kwsys::SystemTools::FileExists(testNewFile.c_str(), true)) {
+ std::cerr << "Problem with FileExists as C string and file for: "
+ << testNewDir << std::endl;
res = false;
- }
+ }
// calling with an empty string should return false
- if (kwsys::SystemTools::PathExists(std::string()))
- {
- std::cerr
- << "Problem with PathExists(std::string())"
- << std::endl;
+ if (kwsys::SystemTools::PathExists(std::string())) {
+ std::cerr << "Problem with PathExists(std::string())" << std::endl;
res = false;
- }
+ }
// PathExists(x) should return true on a directory
- if (!kwsys::SystemTools::PathExists(testNewDir))
- {
- std::cerr
- << "Problem with PathExists for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::PathExists(testNewDir)) {
+ std::cerr << "Problem with PathExists for: " << testNewDir << std::endl;
res = false;
- }
+ }
// should work, was created as new file before
- if (!kwsys::SystemTools::PathExists(testNewFile))
- {
- std::cerr
- << "Problem with PathExists for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::PathExists(testNewFile)) {
+ std::cerr << "Problem with PathExists for: " << testNewDir << std::endl;
res = false;
- }
+ }
- // Reset umask
+// Reset umask
#if defined(_WIN32) && !defined(__CYGWIN__)
// NOTE: Windows doesn't support toggling _S_IREAD.
mode_t fullMask = _S_IWRITE;
@@ -383,208 +286,169 @@ static bool CheckFileOperations()
// Test file permissions without umask
mode_t origPerm, thisPerm;
- if (!kwsys::SystemTools::GetPermissions(testNewFile, origPerm))
- {
- std::cerr
- << "Problem with GetPermissions (1) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::GetPermissions(testNewFile, origPerm)) {
+ std::cerr << "Problem with GetPermissions (1) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::SetPermissions(testNewFile, 0))
- {
- std::cerr
- << "Problem with SetPermissions (1) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::SetPermissions(testNewFile, 0)) {
+ std::cerr << "Problem with SetPermissions (1) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm))
- {
- std::cerr
- << "Problem with GetPermissions (2) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm)) {
+ std::cerr << "Problem with GetPermissions (2) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if ((thisPerm & fullMask) != 0)
- {
- std::cerr
- << "SetPermissions failed to set permissions (1) for: "
- << testNewFile << ": actual = " << thisPerm << "; expected = "
- << 0 << std::endl;
+ if ((thisPerm & fullMask) != 0) {
+ std::cerr << "SetPermissions failed to set permissions (1) for: "
+ << testNewFile << ": actual = " << thisPerm
+ << "; expected = " << 0 << std::endl;
res = false;
- }
+ }
// While we're at it, check proper TestFileAccess functionality.
if (kwsys::SystemTools::TestFileAccess(testNewFile,
- kwsys::TEST_FILE_WRITE))
- {
+ kwsys::TEST_FILE_WRITE)) {
std::cerr
<< "TestFileAccess incorrectly indicated that this is a writable file:"
<< testNewFile << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::TestFileAccess(testNewFile,
- kwsys::TEST_FILE_OK))
- {
+ if (!kwsys::SystemTools::TestFileAccess(testNewFile, kwsys::TEST_FILE_OK)) {
std::cerr
<< "TestFileAccess incorrectly indicated that this file does not exist:"
<< testNewFile << std::endl;
res = false;
- }
+ }
// Test restoring/setting full permissions.
- if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask))
- {
- std::cerr
- << "Problem with SetPermissions (2) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask)) {
+ std::cerr << "Problem with SetPermissions (2) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm))
- {
- std::cerr
- << "Problem with GetPermissions (3) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm)) {
+ std::cerr << "Problem with GetPermissions (3) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if ((thisPerm & fullMask) != fullMask)
- {
- std::cerr
- << "SetPermissions failed to set permissions (2) for: "
- << testNewFile << ": actual = " << thisPerm << "; expected = "
- << fullMask << std::endl;
+ if ((thisPerm & fullMask) != fullMask) {
+ std::cerr << "SetPermissions failed to set permissions (2) for: "
+ << testNewFile << ": actual = " << thisPerm
+ << "; expected = " << fullMask << std::endl;
res = false;
- }
+ }
// Test setting file permissions while honoring umask
- if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask, true))
- {
- std::cerr
- << "Problem with SetPermissions (3) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask, true)) {
+ std::cerr << "Problem with SetPermissions (3) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm))
- {
- std::cerr
- << "Problem with GetPermissions (4) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm)) {
+ std::cerr << "Problem with GetPermissions (4) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
- if ((thisPerm & fullMask) != 0)
- {
- std::cerr
- << "SetPermissions failed to honor umask for: "
- << testNewFile << ": actual = " << thisPerm << "; expected = "
- << 0 << std::endl;
+ if ((thisPerm & fullMask) != 0) {
+ std::cerr << "SetPermissions failed to honor umask for: " << testNewFile
+ << ": actual = " << thisPerm << "; expected = " << 0
+ << std::endl;
res = false;
- }
+ }
// Restore umask
umask(orig_umask);
// Restore file permissions
- if (!kwsys::SystemTools::SetPermissions(testNewFile, origPerm))
- {
- std::cerr
- << "Problem with SetPermissions (4) for: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::SetPermissions(testNewFile, origPerm)) {
+ std::cerr << "Problem with SetPermissions (4) for: " << testNewFile
+ << std::endl;
res = false;
- }
+ }
// Remove the test file
- if (!kwsys::SystemTools::RemoveFile(testNewFile))
- {
- std::cerr
- << "Problem with RemoveFile: "
- << testNewFile << std::endl;
+ if (!kwsys::SystemTools::RemoveFile(testNewFile)) {
+ std::cerr << "Problem with RemoveFile: " << testNewFile << std::endl;
res = false;
- }
+ }
std::string const testFileMissing(testNewDir + "/testMissingFile.txt");
- if (!kwsys::SystemTools::RemoveFile(testFileMissing))
- {
+ if (!kwsys::SystemTools::RemoveFile(testFileMissing)) {
std::string const& msg = kwsys::SystemTools::GetLastSystemError();
- std::cerr <<
- "RemoveFile(\"" << testFileMissing << "\") failed: " << msg << "\n";
+ std::cerr << "RemoveFile(\"" << testFileMissing << "\") failed: " << msg
+ << "\n";
res = false;
- }
+ }
std::string const testFileMissingDir(testNewDir + "/missing/file.txt");
- if (!kwsys::SystemTools::RemoveFile(testFileMissingDir))
- {
+ if (!kwsys::SystemTools::RemoveFile(testFileMissingDir)) {
std::string const& msg = kwsys::SystemTools::GetLastSystemError();
- std::cerr <<
- "RemoveFile(\"" << testFileMissingDir << "\") failed: " << msg << "\n";
+ std::cerr << "RemoveFile(\"" << testFileMissingDir << "\") failed: " << msg
+ << "\n";
res = false;
- }
+ }
kwsys::SystemTools::Touch(testNewFile.c_str(), true);
- if (!kwsys::SystemTools::RemoveADirectory(testNewDir))
- {
- std::cerr
- << "Problem with RemoveADirectory for: "
- << testNewDir << std::endl;
+ if (!kwsys::SystemTools::RemoveADirectory(testNewDir)) {
+ std::cerr << "Problem with RemoveADirectory for: " << testNewDir
+ << std::endl;
res = false;
- }
+ }
#ifdef KWSYS_TEST_SYSTEMTOOLS_LONG_PATHS
// Perform the same file and directory creation and deletion tests but
// with paths > 256 characters in length.
const std::string testNewLongDir(
- TEST_SYSTEMTOOLS_BINARY_DIR "/"
+ TEST_SYSTEMTOOLS_BINARY_DIR
+ "/"
"012345678901234567890123456789012345678901234567890123456789"
"012345678901234567890123456789012345678901234567890123456789"
"012345678901234567890123456789012345678901234567890123456789"
"012345678901234567890123456789012345678901234567890123456789"
"01234567890123");
- const std::string testNewLongFile(testNewLongDir + "/"
+ const std::string testNewLongFile(
+ testNewLongDir +
+ "/"
"012345678901234567890123456789012345678901234567890123456789"
"012345678901234567890123456789012345678901234567890123456789"
"012345678901234567890123456789012345678901234567890123456789"
"012345678901234567890123456789012345678901234567890123456789"
"0123456789.txt");
- if (!kwsys::SystemTools::MakeDirectory(testNewLongDir))
- {
- std::cerr
- << "Problem with MakeDirectory for: "
- << testNewLongDir << std::endl;
+ if (!kwsys::SystemTools::MakeDirectory(testNewLongDir)) {
+ std::cerr << "Problem with MakeDirectory for: " << testNewLongDir
+ << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::Touch(testNewLongFile.c_str(), true))
- {
- std::cerr
- << "Problem with Touch for: "
- << testNewLongFile << std::endl;
+ if (!kwsys::SystemTools::Touch(testNewLongFile.c_str(), true)) {
+ std::cerr << "Problem with Touch for: " << testNewLongFile << std::endl;
res = false;
- }
+ }
- if (!kwsys::SystemTools::RemoveFile(testNewLongFile))
- {
- std::cerr
- << "Problem with RemoveFile: "
- << testNewLongFile << std::endl;
+ if (!kwsys::SystemTools::RemoveFile(testNewLongFile)) {
+ std::cerr << "Problem with RemoveFile: " << testNewLongFile << std::endl;
res = false;
- }
+ }
kwsys::SystemTools::Touch(testNewLongFile.c_str(), true);
- if (!kwsys::SystemTools::RemoveADirectory(testNewLongDir))
- {
- std::cerr
- << "Problem with RemoveADirectory for: "
- << testNewLongDir << std::endl;
+ if (!kwsys::SystemTools::RemoveADirectory(testNewLongDir)) {
+ std::cerr << "Problem with RemoveADirectory for: " << testNewLongDir
+ << std::endl;
res = false;
- }
+ }
#endif
return res;
@@ -596,326 +460,254 @@ static bool CheckStringOperations()
bool res = true;
std::string test = "mary had a little lamb.";
- if (kwsys::SystemTools::CapitalizedWords(test) != "Mary Had A Little Lamb.")
- {
- std::cerr
- << "Problem with CapitalizedWords "
- << '"' << test << '"' << std::endl;
+ if (kwsys::SystemTools::CapitalizedWords(test) !=
+ "Mary Had A Little Lamb.") {
+ std::cerr << "Problem with CapitalizedWords " << '"' << test << '"'
+ << std::endl;
res = false;
- }
+ }
test = "Mary Had A Little Lamb.";
if (kwsys::SystemTools::UnCapitalizedWords(test) !=
- "mary had a little lamb.")
- {
- std::cerr
- << "Problem with UnCapitalizedWords "
- << '"' << test << '"' << std::endl;
+ "mary had a little lamb.") {
+ std::cerr << "Problem with UnCapitalizedWords " << '"' << test << '"'
+ << std::endl;
res = false;
- }
+ }
test = "MaryHadTheLittleLamb.";
if (kwsys::SystemTools::AddSpaceBetweenCapitalizedWords(test) !=
- "Mary Had The Little Lamb.")
- {
- std::cerr
- << "Problem with AddSpaceBetweenCapitalizedWords "
- << '"' << test << '"' << std::endl;
+ "Mary Had The Little Lamb.") {
+ std::cerr << "Problem with AddSpaceBetweenCapitalizedWords " << '"' << test
+ << '"' << std::endl;
res = false;
- }
+ }
- char * cres =
- kwsys::SystemTools::AppendStrings("Mary Had A"," Little Lamb.");
- if (strcmp(cres,"Mary Had A Little Lamb."))
- {
- std::cerr
- << "Problem with AppendStrings "
- << "\"Mary Had A\" \" Little Lamb.\"" << std::endl;
+ char* cres =
+ kwsys::SystemTools::AppendStrings("Mary Had A", " Little Lamb.");
+ if (strcmp(cres, "Mary Had A Little Lamb.")) {
+ std::cerr << "Problem with AppendStrings "
+ << "\"Mary Had A\" \" Little Lamb.\"" << std::endl;
res = false;
- }
- delete [] cres;
+ }
+ delete[] cres;
- cres =
- kwsys::SystemTools::AppendStrings("Mary Had"," A ","Little Lamb.");
- if (strcmp(cres,"Mary Had A Little Lamb."))
- {
- std::cerr
- << "Problem with AppendStrings "
- << "\"Mary Had\" \" A \" \"Little Lamb.\"" << std::endl;
+ cres = kwsys::SystemTools::AppendStrings("Mary Had", " A ", "Little Lamb.");
+ if (strcmp(cres, "Mary Had A Little Lamb.")) {
+ std::cerr << "Problem with AppendStrings "
+ << "\"Mary Had\" \" A \" \"Little Lamb.\"" << std::endl;
res = false;
- }
- delete [] cres;
+ }
+ delete[] cres;
- if (kwsys::SystemTools::CountChar("Mary Had A Little Lamb.",'a') != 3)
- {
- std::cerr
- << "Problem with CountChar "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ if (kwsys::SystemTools::CountChar("Mary Had A Little Lamb.", 'a') != 3) {
+ std::cerr << "Problem with CountChar "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
+ }
- cres =
- kwsys::SystemTools::RemoveChars("Mary Had A Little Lamb.","aeiou");
- if (strcmp(cres,"Mry Hd A Lttl Lmb."))
- {
- std::cerr
- << "Problem with RemoveChars "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ cres = kwsys::SystemTools::RemoveChars("Mary Had A Little Lamb.", "aeiou");
+ if (strcmp(cres, "Mry Hd A Lttl Lmb.")) {
+ std::cerr << "Problem with RemoveChars "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
- delete [] cres;
+ }
+ delete[] cres;
- cres =
- kwsys::SystemTools::RemoveCharsButUpperHex("Mary Had A Little Lamb.");
- if (strcmp(cres,"A"))
- {
- std::cerr
- << "Problem with RemoveCharsButUpperHex "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ cres = kwsys::SystemTools::RemoveCharsButUpperHex("Mary Had A Little Lamb.");
+ if (strcmp(cres, "A")) {
+ std::cerr << "Problem with RemoveCharsButUpperHex "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
- delete [] cres;
+ }
+ delete[] cres;
- char *cres2 = new char [strlen("Mary Had A Little Lamb.")+1];
- strcpy(cres2,"Mary Had A Little Lamb.");
- kwsys::SystemTools::ReplaceChars(cres2,"aeiou",'X');
- if (strcmp(cres2,"MXry HXd A LXttlX LXmb."))
- {
- std::cerr
- << "Problem with ReplaceChars "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ char* cres2 = new char[strlen("Mary Had A Little Lamb.") + 1];
+ strcpy(cres2, "Mary Had A Little Lamb.");
+ kwsys::SystemTools::ReplaceChars(cres2, "aeiou", 'X');
+ if (strcmp(cres2, "MXry HXd A LXttlX LXmb.")) {
+ std::cerr << "Problem with ReplaceChars "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
- delete [] cres2;
+ }
+ delete[] cres2;
if (!kwsys::SystemTools::StringStartsWith("Mary Had A Little Lamb.",
- "Mary "))
- {
- std::cerr
- << "Problem with StringStartsWith "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ "Mary ")) {
+ std::cerr << "Problem with StringStartsWith "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
+ }
if (!kwsys::SystemTools::StringEndsWith("Mary Had A Little Lamb.",
- " Lamb."))
- {
- std::cerr
- << "Problem with StringEndsWith "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ " Lamb.")) {
+ std::cerr << "Problem with StringEndsWith "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
+ }
cres = kwsys::SystemTools::DuplicateString("Mary Had A Little Lamb.");
- if (strcmp(cres,"Mary Had A Little Lamb."))
- {
- std::cerr
- << "Problem with DuplicateString "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ if (strcmp(cres, "Mary Had A Little Lamb.")) {
+ std::cerr << "Problem with DuplicateString "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
- delete [] cres;
+ }
+ delete[] cres;
test = "Mary Had A Little Lamb.";
- if (kwsys::SystemTools::CropString(test,13) !=
- "Mary ...Lamb.")
- {
- std::cerr
- << "Problem with CropString "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ if (kwsys::SystemTools::CropString(test, 13) != "Mary ...Lamb.") {
+ std::cerr << "Problem with CropString "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
+ }
std::vector<std::string> lines;
- kwsys::SystemTools::Split("Mary Had A Little Lamb.",lines,' ');
- if (lines[0] != "Mary" || lines[1] != "Had" ||
- lines[2] != "A" || lines[3] != "Little" || lines[4] != "Lamb.")
- {
- std::cerr
- << "Problem with Split "
- << "\"Mary Had A Little Lamb.\"" << std::endl;
+ kwsys::SystemTools::Split("Mary Had A Little Lamb.", lines, ' ');
+ if (lines[0] != "Mary" || lines[1] != "Had" || lines[2] != "A" ||
+ lines[3] != "Little" || lines[4] != "Lamb.") {
+ std::cerr << "Problem with Split "
+ << "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
- }
+ }
#ifdef _WIN32
- if (kwsys::SystemTools::ConvertToWindowsExtendedPath
- ("L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
- L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+ "L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
+ L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
+ << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::ConvertToWindowsExtendedPath
- ("L:/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
- L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"L:/Local Mojo/Hex Power Pack/Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+ "L:/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+ L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"L:/Local Mojo/Hex Power Pack/Iffy Voodoo\"" << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::ConvertToWindowsExtendedPath
- ("\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
- L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+ "\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
+ L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
+ << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::ConvertToWindowsExtendedPath
- ("//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
- L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+ "//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+ L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo\""
+ << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::ConvertToWindowsExtendedPath("//") !=
- L"//")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"//\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsExtendedPath("//") != L"//") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"//\"" << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\") !=
- L"\\\\.\\")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"\\\\.\\\""
- << std::endl;
+ L"\\\\.\\") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"\\\\.\\\"" << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X") !=
- L"\\\\.\\X")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"\\\\.\\X\""
- << std::endl;
+ L"\\\\.\\X") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"\\\\.\\X\"" << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X:") !=
- L"\\\\?\\X:")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"\\\\.\\X:\""
- << std::endl;
+ L"\\\\?\\X:") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"\\\\.\\X:\"" << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X:\\") !=
- L"\\\\?\\X:\\")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"\\\\.\\X:\\\""
- << std::endl;
+ L"\\\\?\\X:\\") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"\\\\.\\X:\\\"" << std::endl;
res = false;
- }
+ }
if (kwsys::SystemTools::ConvertToWindowsExtendedPath("NUL") !=
- L"\\\\.\\NUL")
- {
- std::cerr
- << "Problem with ConvertToWindowsExtendedPath "
- << "\"NUL\""
- << std::endl;
+ L"\\\\.\\NUL") {
+ std::cerr << "Problem with ConvertToWindowsExtendedPath "
+ << "\"NUL\"" << std::endl;
res = false;
- }
+ }
#endif
- if (kwsys::SystemTools::ConvertToWindowsOutputPath
- ("L://Local Mojo/Hex Power Pack/Iffy Voodoo") !=
- "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
- {
- std::cerr
- << "Problem with ConvertToWindowsOutputPath "
- << "\"L://Local Mojo/Hex Power Pack/Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsOutputPath(
+ "L://Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+ "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"") {
+ std::cerr << "Problem with ConvertToWindowsOutputPath "
+ << "\"L://Local Mojo/Hex Power Pack/Iffy Voodoo\"" << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::ConvertToWindowsOutputPath
- ("//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
- "\"\\\\grayson\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
- {
- std::cerr
- << "Problem with ConvertToWindowsOutputPath "
- << "\"//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToWindowsOutputPath(
+ "//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+ "\"\\\\grayson\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"") {
+ std::cerr << "Problem with ConvertToWindowsOutputPath "
+ << "\"//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo\""
+ << std::endl;
res = false;
- }
+ }
- if (kwsys::SystemTools::ConvertToUnixOutputPath
- ("//Local Mojo/Hex Power Pack/Iffy Voodoo") !=
- "//Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo")
- {
- std::cerr
- << "Problem with ConvertToUnixOutputPath "
- << "\"//Local Mojo/Hex Power Pack/Iffy Voodoo\""
- << std::endl;
+ if (kwsys::SystemTools::ConvertToUnixOutputPath(
+ "//Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+ "//Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo") {
+ std::cerr << "Problem with ConvertToUnixOutputPath "
+ << "\"//Local Mojo/Hex Power Pack/Iffy Voodoo\"" << std::endl;
res = false;
- }
+ }
return res;
}
//----------------------------------------------------------------------------
-static bool CheckPutEnv(const std::string& env, const char* name, const char* value)
+static bool CheckPutEnv(const std::string& env, const char* name,
+ const char* value)
{
- if(!kwsys::SystemTools::PutEnv(env))
- {
- std::cerr << "PutEnv(\"" << env
- << "\") failed!" << std::endl;
+ if (!kwsys::SystemTools::PutEnv(env)) {
+ std::cerr << "PutEnv(\"" << env << "\") failed!" << std::endl;
return false;
- }
+ }
std::string v = "(null)";
kwsys::SystemTools::GetEnv(name, v);
- if(v != value)
- {
- std::cerr << "GetEnv(\"" << name << "\") returned \""
- << v << "\", not \"" << value << "\"!" << std::endl;
+ if (v != value) {
+ std::cerr << "GetEnv(\"" << name << "\") returned \"" << v << "\", not \""
+ << value << "\"!" << std::endl;
return false;
- }
+ }
return true;
}
static bool CheckUnPutEnv(const char* env, const char* name)
{
- if(!kwsys::SystemTools::UnPutEnv(env))
- {
- std::cerr << "UnPutEnv(\"" << env << "\") failed!"
- << std::endl;
+ if (!kwsys::SystemTools::UnPutEnv(env)) {
+ std::cerr << "UnPutEnv(\"" << env << "\") failed!" << std::endl;
return false;
- }
+ }
std::string v;
- if(kwsys::SystemTools::GetEnv(name, v))
- {
- std::cerr << "GetEnv(\"" << name << "\") returned \""
- << v << "\", not (null)!" << std::endl;
+ if (kwsys::SystemTools::GetEnv(name, v)) {
+ std::cerr << "GetEnv(\"" << name << "\") returned \"" << v
+ << "\", not (null)!" << std::endl;
return false;
- }
+ }
return true;
}
@@ -933,19 +725,16 @@ static bool CheckEnvironmentOperations()
return res;
}
-
-static bool CheckRelativePath(
- const std::string& local,
- const std::string& remote,
- const std::string& expected)
+static bool CheckRelativePath(const std::string& local,
+ const std::string& remote,
+ const std::string& expected)
{
std::string result = kwsys::SystemTools::RelativePath(local, remote);
- if (!kwsys::SystemTools::ComparePath(expected, result))
- {
- std::cerr << "RelativePath(" << local << ", " << remote
- << ") yielded " << result << " instead of " << expected << std::endl;
+ if (!kwsys::SystemTools::ComparePath(expected, result)) {
+ std::cerr << "RelativePath(" << local << ", " << remote << ") yielded "
+ << result << " instead of " << expected << std::endl;
return false;
- }
+ }
return true;
}
@@ -955,22 +744,21 @@ static bool CheckRelativePaths()
res &= CheckRelativePath("/usr/share", "/bin/bash", "../../bin/bash");
res &= CheckRelativePath("/usr/./share/", "/bin/bash", "../../bin/bash");
res &= CheckRelativePath("/usr//share/", "/bin/bash", "../../bin/bash");
- res &= CheckRelativePath("/usr/share/../bin/", "/bin/bash", "../../bin/bash");
+ res &=
+ CheckRelativePath("/usr/share/../bin/", "/bin/bash", "../../bin/bash");
res &= CheckRelativePath("/usr/share", "/usr/share//bin", "bin");
return res;
}
-static bool CheckCollapsePath(
- const std::string& path,
- const std::string& expected)
+static bool CheckCollapsePath(const std::string& path,
+ const std::string& expected)
{
std::string result = kwsys::SystemTools::CollapseFullPath(path);
- if (!kwsys::SystemTools::ComparePath(expected, result))
- {
- std::cerr << "CollapseFullPath(" << path
- << ") yielded " << result << " instead of " << expected << std::endl;
+ if (!kwsys::SystemTools::ComparePath(expected, result)) {
+ std::cerr << "CollapseFullPath(" << path << ") yielded " << result
+ << " instead of " << expected << std::endl;
return false;
- }
+ }
return true;
}
@@ -987,14 +775,12 @@ 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)
- {
- if (i != vec.begin())
- {
+ i != vec.end(); ++i) {
+ if (i != vec.begin()) {
ss << ", ";
- }
- ss << *i;
}
+ ss << *i;
+ }
ss << ")";
return ss.str();
}
@@ -1028,15 +814,13 @@ static bool CheckGetPath()
std::vector<std::string> pathes = originalPathes;
kwsys::SystemTools::GetPath(pathes, envName);
- if (pathes != expectedPathes)
- {
- std::cerr <<
- "GetPath(" << StringVectorToString(originalPathes) <<
- ", " << envName << ") yielded " << StringVectorToString(pathes) <<
- " instead of " << StringVectorToString(expectedPathes) <<
- std::endl;
+ if (pathes != expectedPathes) {
+ std::cerr << "GetPath(" << StringVectorToString(originalPathes) << ", "
+ << envName << ") yielded " << StringVectorToString(pathes)
+ << " instead of " << StringVectorToString(expectedPathes)
+ << std::endl;
res = false;
- }
+ }
res &= CheckUnPutEnv(envName, envName);
return res;
@@ -1046,64 +830,54 @@ static bool CheckFind()
{
bool res = true;
const std::string testFindFileName("testFindFile.txt");
- const std::string testFindFile(TEST_SYSTEMTOOLS_BINARY_DIR "/"
- + testFindFileName);
+ const std::string testFindFile(TEST_SYSTEMTOOLS_BINARY_DIR "/" +
+ testFindFileName);
- if (!kwsys::SystemTools::Touch(testFindFile.c_str(), true))
- {
- std::cerr
- << "Problem with Touch for: "
- << testFindFile << std::endl;
+ if (!kwsys::SystemTools::Touch(testFindFile.c_str(), true)) {
+ std::cerr << "Problem with Touch for: " << testFindFile << std::endl;
// abort here as the existence of the file only makes the test meaningful
return false;
- }
+ }
std::vector<std::string> searchPaths;
searchPaths.push_back(TEST_SYSTEMTOOLS_BINARY_DIR);
- if (kwsys::SystemTools::FindFile(testFindFileName,
- searchPaths, true).empty())
- {
- std::cerr
- << "Problem with FindFile without system paths for: "
- << testFindFileName << std::endl;
+ if (kwsys::SystemTools::FindFile(testFindFileName, searchPaths, true)
+ .empty()) {
+ std::cerr << "Problem with FindFile without system paths for: "
+ << testFindFileName << std::endl;
res = false;
- }
- if (kwsys::SystemTools::FindFile(testFindFileName,
- searchPaths, false).empty())
- {
- std::cerr
- << "Problem with FindFile with system paths for: "
- << testFindFileName << std::endl;
+ }
+ if (kwsys::SystemTools::FindFile(testFindFileName, searchPaths, false)
+ .empty()) {
+ std::cerr << "Problem with FindFile with system paths for: "
+ << testFindFileName << std::endl;
res = false;
- }
+ }
return res;
}
//----------------------------------------------------------------------------
-int testSystemTools(int, char*[])
+int testSystemTools(int, char* [])
{
bool res = true;
int cc;
- for ( cc = 0; toUnixPaths[cc][0]; cc ++ )
- {
+ for (cc = 0; toUnixPaths[cc][0]; cc++) {
res &= CheckConvertToUnixSlashes(toUnixPaths[cc][0], toUnixPaths[cc][1]);
- }
+ }
// Special check for ~
std::string output;
- if(kwsys::SystemTools::GetEnv("HOME", output))
- {
+ if (kwsys::SystemTools::GetEnv("HOME", output)) {
output += "/foo bar/lala";
res &= CheckConvertToUnixSlashes("~/foo bar/lala", output);
- }
+ }
- for (cc = 0; checkEscapeChars[cc][0]; cc ++ )
- {
+ for (cc = 0; checkEscapeChars[cc][0]; cc++) {
res &= CheckEscapeChars(checkEscapeChars[cc][0], checkEscapeChars[cc][1],
*checkEscapeChars[cc][2], checkEscapeChars[cc][3]);
- }
+ }
res &= CheckFileOperations();
diff --git a/Source/kwsys/testSystemTools.h.in b/Source/kwsys/testSystemTools.h.in
index 66f0f72..022e36e 100644
--- a/Source/kwsys/testSystemTools.h.in
+++ b/Source/kwsys/testSystemTools.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifndef @KWSYS_NAMESPACE@_testSystemtools_h
#define @KWSYS_NAMESPACE@_testSystemtools_h
diff --git a/Source/kwsys/testTerminal.c b/Source/kwsys/testTerminal.c
index 0d2d7a7..f6c1edd 100644
--- a/Source/kwsys/testTerminal.c
+++ b/Source/kwsys/testTerminal.c
@@ -1,21 +1,12 @@
-/*============================================================================
- KWSys - Kitware System Library
- Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
-
- Distributed under the OSI-approved BSD License (the "License");
- see accompanying file Copyright.txt for details.
-
- This software is distributed WITHOUT ANY WARRANTY; without even the
- implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- See the License for more information.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Terminal.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
-# include "Terminal.h.in"
+#include "Terminal.h.in"
#endif
int testTerminal(int argc, char* argv[])
@@ -23,8 +14,8 @@ int testTerminal(int argc, char* argv[])
(void)argc;
(void)argv;
kwsysTerminal_cfprintf(kwsysTerminal_Color_ForegroundYellow |
- kwsysTerminal_Color_BackgroundBlue |
- kwsysTerminal_Color_AssumeTTY,
+ kwsysTerminal_Color_BackgroundBlue |
+ kwsysTerminal_Color_AssumeTTY,
stdout, "Hello %s!", "World");
fprintf(stdout, "\n");
return 0;
diff --git a/Tests/CMakeLib/CMakeLists.txt b/Tests/CMakeLib/CMakeLists.txt
index 405917a..d680205 100644
--- a/Tests/CMakeLib/CMakeLists.txt
+++ b/Tests/CMakeLib/CMakeLists.txt
@@ -31,6 +31,9 @@ create_test_sourcelist(CMakeLib_TEST_SRCS CMakeLibTests.cxx ${CMakeLib_TESTS})
add_executable(CMakeLibTests ${CMakeLib_TEST_SRCS})
target_link_libraries(CMakeLibTests CMakeLib)
+add_executable(testEncoding testEncoding.cxx)
+target_link_libraries(testEncoding cmsys)
+
# Xcode 2.x forgets to create the output directory before linking
# the individual architectures.
if(CMAKE_OSX_ARCHITECTURES AND XCODE
diff --git a/Tests/CMakeLib/run_compile_commands.cxx b/Tests/CMakeLib/run_compile_commands.cxx
index 0bf0a7c..5d4ca70 100644
--- a/Tests/CMakeLib/run_compile_commands.cxx
+++ b/Tests/CMakeLib/run_compile_commands.cxx
@@ -1,4 +1,4 @@
-#include "cmSystemTools.h"
+#include <cmConfigure.h>
#include <cmsys/FStream.hxx>
#include <iostream>
@@ -8,6 +8,8 @@
#include <utility>
#include <vector>
+#include "cmSystemTools.h"
+
class CompileCommandParser
{
public:
diff --git a/Tests/CMakeLib/testEncoding.cxx b/Tests/CMakeLib/testEncoding.cxx
new file mode 100644
index 0000000..88743b0
--- /dev/null
+++ b/Tests/CMakeLib/testEncoding.cxx
@@ -0,0 +1,49 @@
+#include <fstream>
+#include <iostream>
+#include <string>
+
+#include <cmsys/ConsoleBuf.hxx>
+
+#ifdef _WIN32
+void setEncoding(cmsys::ConsoleBuf::Manager& buf, UINT codepage)
+{
+ cmsys::ConsoleBuf* cb = buf.GetConsoleBuf();
+ if (cb) {
+ cb->input_pipe_codepage = codepage;
+ cb->output_pipe_codepage = codepage;
+ cb->input_file_codepage = codepage;
+ cb->output_file_codepage = codepage;
+ cb->activateCodepageChange();
+ }
+}
+#endif
+
+int main(int argc, char* argv[])
+{
+#ifdef _WIN32
+ cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+#endif
+ if (argc <= 2) {
+ std::cout << "Usage: testEncoding <encoding> <file>" << std::endl;
+ return 1;
+ }
+ const std::string encoding(argv[1]);
+#ifdef _WIN32
+ if (encoding == "UTF8") {
+ setEncoding(consoleOut, CP_UTF8);
+ } else if (encoding == "ANSI") {
+ setEncoding(consoleOut, CP_ACP);
+ } else if (encoding == "OEM") {
+ setEncoding(consoleOut, CP_OEMCP);
+ } // else AUTO
+#endif
+ std::ifstream file(argv[2]);
+ if (!file.is_open()) {
+ std::cout << "Failed to open file: " << argv[2] << std::endl;
+ return 2;
+ }
+ std::string text((std::istreambuf_iterator<char>(file)),
+ std::istreambuf_iterator<char>());
+ std::cout << text;
+ return 0;
+}
diff --git a/Tests/CMakeLib/testFindPackageCommand.cxx b/Tests/CMakeLib/testFindPackageCommand.cxx
index 7622756..bfd429f 100644
--- a/Tests/CMakeLib/testFindPackageCommand.cxx
+++ b/Tests/CMakeLib/testFindPackageCommand.cxx
@@ -1,9 +1,13 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmFindPackageCommand.h"
+
+#include <cmConfigure.h> // IWYU pragma: keep
#include <iostream>
#include <string>
+#include <vector>
+
+#include "cmFindPackageCommand.h"
#define cmPassed(m) std::cout << "Passed: " << (m) << "\n"
#define cmFailed(m) \
diff --git a/Tests/CMakeLib/testSystemTools.cxx b/Tests/CMakeLib/testSystemTools.cxx
index b16b088..0dfa326 100644
--- a/Tests/CMakeLib/testSystemTools.cxx
+++ b/Tests/CMakeLib/testSystemTools.cxx
@@ -1,9 +1,14 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmSystemTools.h"
+
+#include <cmConfigure.h> // IWYU pragma: keep
#include <iostream>
+#include <stddef.h>
#include <string>
+#include <vector>
+
+#include "cmSystemTools.h"
#define cmPassed(m) std::cout << "Passed: " << (m) << "\n"
#define cmFailed(m) \
diff --git a/Tests/CMakeLib/testXMLSafe.cxx b/Tests/CMakeLib/testXMLSafe.cxx
index 6c59128..fe776c5 100644
--- a/Tests/CMakeLib/testXMLSafe.cxx
+++ b/Tests/CMakeLib/testXMLSafe.cxx
@@ -1,11 +1,14 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmXMLSafe.h"
+
+#include <cmConfigure.h>
#include <sstream>
#include <stdio.h>
#include <string>
+#include "cmXMLSafe.h"
+
struct test_pair
{
const char* in;
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index 5d72e5c..fa5f3e8 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -324,6 +324,8 @@ if(BUILD_TESTING)
ADD_TEST_MACRO(VSGNUFortran ${CMAKE_COMMAND} -P runtest.cmake)
endif()
endif()
+
+
ADD_TEST_MACRO(COnly COnly)
ADD_TEST_MACRO(CxxOnly CxxOnly)
ADD_TEST_MACRO(CxxSubdirC CxxSubdirC)
@@ -1243,7 +1245,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
set(run_autogen_test ${CMAKE_CTEST_COMMAND} -V)
set(run_autouic_test ${CMAKE_CTEST_COMMAND} -V)
else()
- set(run_autogen_test QtAutogen)
+ set(run_autogen_test complex/QtAutogen)
set(run_autouic_test QtAutoUicInterface)
endif()
if(NOT CMAKE_CONFIGURATION_TYPES)
@@ -1353,6 +1355,11 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
endif()
endif()
+ if(CMake_TEST_CUDA)
+ add_subdirectory(Cuda)
+ add_subdirectory(CudaOnly)
+ endif()
+
if(CMake_TEST_FindBoost)
add_subdirectory(FindBoost)
endif()
@@ -1377,6 +1384,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
add_subdirectory(FindJsonCpp)
endif()
+ if(CMake_TEST_FindLibRHash)
+ add_subdirectory(FindLibRHash)
+ endif()
+
if(CMake_TEST_FindLibUV)
add_subdirectory(FindLibUV)
endif()
@@ -3346,20 +3357,6 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
--test-command InterfaceLinkLibraries)
list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/InterfaceLinkLibraries")
- if(CMAKE_USE_KWSTYLE AND KWSTYLE_EXECUTABLE)
- # The "make StyleCheck" command line as a test. If the test fails, look
- # for lines like "Error #0 (624) Line length exceed 88 (max=79)" in the
- # output to find where the style errors are...
- add_test(KWStyle ${KWSTYLE_EXECUTABLE}
- -xml ${CMake_BINARY_DIR}/CMake.kws.xml
- -o ${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeOverwrite.txt
- -v
- -D ${CMake_BINARY_DIR}/CMakeKWSFiles.txt
- )
- set_tests_properties(KWStyle PROPERTIES
- WORKING_DIRECTORY ${CMake_BINARY_DIR}/Utilities/KWStyle)
- endif()
-
if(NOT CMake_TEST_EXTERNAL_CMAKE)
add_subdirectory(CMakeTests)
endif()
diff --git a/Tests/CMakeTests/File-SHA3_224-Works.cmake b/Tests/CMakeTests/File-SHA3_224-Works.cmake
new file mode 100644
index 0000000..e4f4e85
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_224-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_224 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_224)
+message("${sha3_224}")
diff --git a/Tests/CMakeTests/File-SHA3_256-Works.cmake b/Tests/CMakeTests/File-SHA3_256-Works.cmake
new file mode 100644
index 0000000..189c8a2
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_256-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_256 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_256)
+message("${sha3_256}")
diff --git a/Tests/CMakeTests/File-SHA3_384-Works.cmake b/Tests/CMakeTests/File-SHA3_384-Works.cmake
new file mode 100644
index 0000000..08f9f5b
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_384-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_384 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_384)
+message("${sha3_384}")
diff --git a/Tests/CMakeTests/File-SHA3_512-Works.cmake b/Tests/CMakeTests/File-SHA3_512-Works.cmake
new file mode 100644
index 0000000..4182196
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_512-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_512 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_512)
+message("${sha3_512}")
diff --git a/Tests/CMakeTests/FileTest.cmake.in b/Tests/CMakeTests/FileTest.cmake.in
index 61523e6..71cb3db 100644
--- a/Tests/CMakeTests/FileTest.cmake.in
+++ b/Tests/CMakeTests/FileTest.cmake.in
@@ -36,6 +36,14 @@ set(SHA384-Works-RESULT 0)
set(SHA384-Works-STDERR "1de9560b4e030e02051ea408200ffc55d70c97ac64ebf822461a5c786f495c36df43259b14483bc8d364f0106f4971ee")
set(SHA512-Works-RESULT 0)
set(SHA512-Works-STDERR "3982a1b4e651768bec70ab1fb97045cb7a659f4ba7203d501c52ab2e803071f9d5fd272022df15f27727fc67f8cd022e710e29010b2a9c0b467c111e2f6abf51")
+set(SHA3_224-Works-RESULT 0)
+set(SHA3_224-Works-STDERR "4272868085f4f25080681a7712509fd12e16dcda79bd356836dd2100")
+set(SHA3_256-Works-RESULT 0)
+set(SHA3_256-Works-STDERR "be0df472b6bd474417a166d12f2774f2ef5095e86f0a88ef4c78c703800cfc8a")
+set(SHA3_384-Works-RESULT 0)
+set(SHA3_384-Works-STDERR "935a17cc708443c1369549483656a4521af03a52e4f3b314566272017ccae03a2c5db838f6d4c156b1dc5c366182481b")
+set(SHA3_512-Works-RESULT 0)
+set(SHA3_512-Works-STDERR "471a85ed537e8f77f31412a089f22d836054ffa179599f87a5d7568927d8fa236b6793ded8a387d1de92398c967177bcc6361672a722bf736cb0f63a0956d5cf")
set(TIMESTAMP-NoFile-RESULT 0)
set(TIMESTAMP-NoFile-STDERR "~~")
set(TIMESTAMP-BadArg1-RESULT 1)
@@ -66,6 +74,10 @@ check_cmake_test(File
SHA256-Works
SHA384-Works
SHA512-Works
+ SHA3_224-Works
+ SHA3_256-Works
+ SHA3_384-Works
+ SHA3_512-Works
TIMESTAMP-NoFile
TIMESTAMP-BadArg1
TIMESTAMP-NotBogus
diff --git a/Tests/CMakeTests/String-SHA3_224-Works.cmake b/Tests/CMakeTests/String-SHA3_224-Works.cmake
new file mode 100644
index 0000000..6aeb91d
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_224-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_224 sha3_224 "sample input string\n")
+message("${sha3_224}")
diff --git a/Tests/CMakeTests/String-SHA3_256-Works.cmake b/Tests/CMakeTests/String-SHA3_256-Works.cmake
new file mode 100644
index 0000000..cc7ea1a
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_256-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_256 sha3_256 "sample input string\n")
+message("${sha3_256}")
diff --git a/Tests/CMakeTests/String-SHA3_384-Works.cmake b/Tests/CMakeTests/String-SHA3_384-Works.cmake
new file mode 100644
index 0000000..9341c3f
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_384-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_384 sha3_384 "sample input string\n")
+message("${sha3_384}")
diff --git a/Tests/CMakeTests/String-SHA3_512-Works.cmake b/Tests/CMakeTests/String-SHA3_512-Works.cmake
new file mode 100644
index 0000000..cf4eddd
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_512-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_512 sha3_512 "sample input string\n")
+message("${sha3_512}")
diff --git a/Tests/CMakeTests/StringTest.cmake.in b/Tests/CMakeTests/StringTest.cmake.in
index a45b205..83655da 100644
--- a/Tests/CMakeTests/StringTest.cmake.in
+++ b/Tests/CMakeTests/StringTest.cmake.in
@@ -16,6 +16,14 @@ set(SHA384-Works-RESULT 0)
set(SHA384-Works-STDERR "1de9560b4e030e02051ea408200ffc55d70c97ac64ebf822461a5c786f495c36df43259b14483bc8d364f0106f4971ee")
set(SHA512-Works-RESULT 0)
set(SHA512-Works-STDERR "3982a1b4e651768bec70ab1fb97045cb7a659f4ba7203d501c52ab2e803071f9d5fd272022df15f27727fc67f8cd022e710e29010b2a9c0b467c111e2f6abf51")
+set(SHA3_224-Works-RESULT 0)
+set(SHA3_224-Works-STDERR "4272868085f4f25080681a7712509fd12e16dcda79bd356836dd2100")
+set(SHA3_256-Works-RESULT 0)
+set(SHA3_256-Works-STDERR "be0df472b6bd474417a166d12f2774f2ef5095e86f0a88ef4c78c703800cfc8a")
+set(SHA3_384-Works-RESULT 0)
+set(SHA3_384-Works-STDERR "935a17cc708443c1369549483656a4521af03a52e4f3b314566272017ccae03a2c5db838f6d4c156b1dc5c366182481b")
+set(SHA3_512-Works-RESULT 0)
+set(SHA3_512-Works-STDERR "471a85ed537e8f77f31412a089f22d836054ffa179599f87a5d7568927d8fa236b6793ded8a387d1de92398c967177bcc6361672a722bf736cb0f63a0956d5cf")
set(TIMESTAMP-BadArg1-RESULT 1)
set(TIMESTAMP-BadArg1-STDERR "string sub-command TIMESTAMP requires at least one argument")
set(TIMESTAMP-BadArg2-RESULT 1)
@@ -52,6 +60,10 @@ check_cmake_test(String
SHA256-Works
SHA384-Works
SHA512-Works
+ SHA3_224-Works
+ SHA3_256-Works
+ SHA3_384-Works
+ SHA3_512-Works
TIMESTAMP-BadArg1
TIMESTAMP-BadArg2
TIMESTAMP-BadArg3
diff --git a/Tests/CompileFeatures/CMakeLists.txt b/Tests/CompileFeatures/CMakeLists.txt
index 9f08523..8acdd93 100644
--- a/Tests/CompileFeatures/CMakeLists.txt
+++ b/Tests/CompileFeatures/CMakeLists.txt
@@ -23,10 +23,12 @@ macro(run_test feature lang)
endmacro()
get_property(c_features GLOBAL PROPERTY CMAKE_C_KNOWN_FEATURES)
+list(REMOVE_ITEM c_features c_std_90 c_std_99 c_std_11)
foreach(feature ${c_features})
run_test(${feature} C)
endforeach()
get_property(cxx_features GLOBAL PROPERTY CMAKE_CXX_KNOWN_FEATURES)
+list(REMOVE_ITEM cxx_features cxx_std_98 cxx_std_11 cxx_std_14)
foreach(feature ${cxx_features})
run_test(${feature} CXX)
endforeach()
@@ -168,6 +170,15 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
endif()
endif()
+if (CMAKE_C_COMPILER_ID STREQUAL "Intel")
+ if (CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.2)
+ # This works on some pre-15.0.2 versions and not others.
+ list(REMOVE_ITEM C_non_features
+ c_static_assert
+ )
+ endif()
+endif()
+
set(C_ext c)
set(C_standard_flag 11)
set(CXX_ext cpp)
@@ -396,7 +407,7 @@ if (CMAKE_CXX_COMPILE_FEATURES)
)
add_executable(CompileFeaturesGenex2 genex_test.cpp)
- target_compile_features(CompileFeaturesGenex2 PRIVATE cxx_static_assert)
+ target_compile_features(CompileFeaturesGenex2 PRIVATE cxx_std_11)
target_compile_definitions(CompileFeaturesGenex2 PRIVATE
HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override>
HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type>
@@ -405,10 +416,10 @@ if (CMAKE_CXX_COMPILE_FEATURES)
HAVE_INHERITING_CONSTRUCTORS_AND_FINAL=$<COMPILE_FEATURES:cxx_inheriting_constructors,cxx_final>
)
- add_library(static_assert_iface INTERFACE)
- target_compile_features(static_assert_iface INTERFACE cxx_static_assert)
+ add_library(std_11_iface INTERFACE)
+ target_compile_features(std_11_iface INTERFACE cxx_std_11)
add_executable(CompileFeaturesGenex3 genex_test.cpp)
- target_link_libraries(CompileFeaturesGenex3 PRIVATE static_assert_iface)
+ target_link_libraries(CompileFeaturesGenex3 PRIVATE std_11_iface)
target_compile_definitions(CompileFeaturesGenex3 PRIVATE
HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override>
HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type>
diff --git a/Tests/Cuda/CMakeLists.txt b/Tests/Cuda/CMakeLists.txt
new file mode 100644
index 0000000..5772fcf
--- /dev/null
+++ b/Tests/Cuda/CMakeLists.txt
@@ -0,0 +1,4 @@
+
+ADD_TEST_MACRO(Cuda.Complex CudaComplex)
+ADD_TEST_MACRO(Cuda.ConsumeCompileFeatures CudaConsumeCompileFeatures)
+ADD_TEST_MACRO(Cuda.ObjectLibrary CudaObjectLibrary)
diff --git a/Tests/Cuda/Complex/CMakeLists.txt b/Tests/Cuda/Complex/CMakeLists.txt
new file mode 100644
index 0000000..9a3703a
--- /dev/null
+++ b/Tests/Cuda/Complex/CMakeLists.txt
@@ -0,0 +1,40 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaComplex CXX CUDA)
+#Goal for this example:
+
+#build a cpp dynamic library base
+#build a cuda static library base that uses separable compilation
+
+#build a cuda dynamic library that uses the first dynamic library
+#build a mixed cpp & cuda dynamic library uses all 3 previous libraries
+
+#lastly build a cpp executable that uses this last cuda dynamic library
+
+#this tests that we can properly handle linking cuda and cpp together
+#and also bulding cpp targets that need cuda implicit libraries
+
+#verify that we can pass explicit cuda arch flags
+set(CMAKE_CUDA_FLAGS "-gencode arch=compute_30,code=compute_30")
+set(CMAKE_CUDA_STANDARD 11)
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD_REQUIRED TRUE)
+set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
+
+add_library(CudaComplexCppBase SHARED dynamic.cpp)
+add_library(CudaComplexSeperableLib STATIC file1.cu file2.cu file3.cu)
+set_target_properties(CudaComplexSeperableLib
+ PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
+set_target_properties( CudaComplexSeperableLib
+ PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+add_library(CudaComplexSharedLib SHARED dynamic.cu)
+target_link_libraries(CudaComplexSharedLib PUBLIC CudaComplexCppBase)
+
+add_library(CudaComplexMixedLib SHARED mixed.cpp mixed.cu)
+target_link_libraries(CudaComplexMixedLib
+ PUBLIC CudaComplexSharedLib
+ PRIVATE CudaComplexSeperableLib)
+
+add_executable(CudaComplex main.cpp)
+target_link_libraries(CudaComplex PUBLIC CudaComplexMixedLib)
diff --git a/Tests/Cuda/Complex/dynamic.cpp b/Tests/Cuda/Complex/dynamic.cpp
new file mode 100644
index 0000000..d579f1e
--- /dev/null
+++ b/Tests/Cuda/Complex/dynamic.cpp
@@ -0,0 +1,5 @@
+
+int dynamic_base_func(int x)
+{
+ return x * x;
+}
diff --git a/Tests/Cuda/Complex/dynamic.cu b/Tests/Cuda/Complex/dynamic.cu
new file mode 100644
index 0000000..9540e86
--- /dev/null
+++ b/Tests/Cuda/Complex/dynamic.cu
@@ -0,0 +1,29 @@
+
+#include <string>
+#include <cuda.h>
+
+int dynamic_base_func(int);
+
+int __host__ cuda_dynamic_host_func(int x)
+{
+ return dynamic_base_func(x);
+}
+
+static
+__global__
+void DetermineIfValidCudaDevice()
+{
+}
+
+void cuda_dynamic_lib_func(std::string& contents )
+{
+ DetermineIfValidCudaDevice <<<1,1>>> ();
+ if(cudaSuccess == cudaGetLastError())
+ {
+ contents = "ran a cuda kernel";
+ }
+ else
+ {
+ contents = "cant run a cuda kernel";
+ }
+}
diff --git a/Tests/Cuda/Complex/file1.cu b/Tests/Cuda/Complex/file1.cu
new file mode 100644
index 0000000..a2e8bf3
--- /dev/null
+++ b/Tests/Cuda/Complex/file1.cu
@@ -0,0 +1,10 @@
+
+#include "file1.h"
+
+result_type __device__ file1_func(int x)
+{
+ result_type r;
+ r.input = x;
+ r.sum = x*x;
+ return r;
+}
diff --git a/Tests/Cuda/Complex/file1.h b/Tests/Cuda/Complex/file1.h
new file mode 100644
index 0000000..ff1945c
--- /dev/null
+++ b/Tests/Cuda/Complex/file1.h
@@ -0,0 +1,7 @@
+
+#pragma once
+struct result_type
+{
+ int input;
+ int sum;
+};
diff --git a/Tests/Cuda/Complex/file2.cu b/Tests/Cuda/Complex/file2.cu
new file mode 100644
index 0000000..6b8b06b
--- /dev/null
+++ b/Tests/Cuda/Complex/file2.cu
@@ -0,0 +1,20 @@
+
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+
+result_type_dynamic __device__ file2_func(int x)
+{
+ if(x!=42)
+ {
+ const result_type r = file1_func(x);
+ const result_type_dynamic rd { r.input, r.sum, true };
+ return rd;
+ }
+ else
+ {
+ const result_type_dynamic rd { x, x*x*x, false };
+ return rd;
+ }
+
+}
diff --git a/Tests/Cuda/Complex/file2.h b/Tests/Cuda/Complex/file2.h
new file mode 100644
index 0000000..d2dbaa4
--- /dev/null
+++ b/Tests/Cuda/Complex/file2.h
@@ -0,0 +1,10 @@
+
+#pragma once
+#include "file1.h"
+
+struct result_type_dynamic
+{
+ int input;
+ int sum;
+ bool from_static;
+};
diff --git a/Tests/Cuda/Complex/file3.cu b/Tests/Cuda/Complex/file3.cu
new file mode 100644
index 0000000..3c5e952
--- /dev/null
+++ b/Tests/Cuda/Complex/file3.cu
@@ -0,0 +1,25 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static
+__global__
+void file3_kernel(result_type& r, int x)
+{
+ //call static_func which is a method that is defined in the
+ //static library that is always out of date
+ r = file1_func(x);
+ result_type_dynamic rd = file2_func(x);
+}
+
+int file3_launch_kernel(int x)
+{
+ result_type r;
+ file3_kernel <<<1,1>>> (r,x);
+ return r.sum;
+}
diff --git a/Tests/Cuda/Complex/main.cpp b/Tests/Cuda/Complex/main.cpp
new file mode 100644
index 0000000..a72ffd7
--- /dev/null
+++ b/Tests/Cuda/Complex/main.cpp
@@ -0,0 +1,14 @@
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type call_cuda_seperable_code(int x);
+result_type mixed_launch_kernel(int x);
+
+int main(int argc, char** argv)
+{
+ call_cuda_seperable_code(42);
+ mixed_launch_kernel(42);
+ return 0;
+}
diff --git a/Tests/Cuda/Complex/mixed.cpp b/Tests/Cuda/Complex/mixed.cpp
new file mode 100644
index 0000000..205f091
--- /dev/null
+++ b/Tests/Cuda/Complex/mixed.cpp
@@ -0,0 +1,14 @@
+
+int dynamic_base_func(int);
+int cuda_dynamic_host_func(int);
+int file3_launch_kernel(int);
+
+int dynamic_final_func(int x)
+{
+ return cuda_dynamic_host_func(dynamic_base_func(x));
+}
+
+int call_cuda_seperable_code(int x)
+{
+ return file3_launch_kernel(x);
+}
diff --git a/Tests/Cuda/Complex/mixed.cu b/Tests/Cuda/Complex/mixed.cu
new file mode 100644
index 0000000..d2e8275
--- /dev/null
+++ b/Tests/Cuda/Complex/mixed.cu
@@ -0,0 +1,25 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static
+__global__
+void mixed_kernel(result_type& r, int x)
+{
+ //call static_func which is a method that is defined in the
+ //static library that is always out of date
+ r = file1_func(x);
+ result_type_dynamic rd = file2_func(x);
+}
+
+int mixed_launch_kernel(int x)
+{
+ result_type r;
+ mixed_kernel <<<1,1>>> (r,x);
+ return r.sum;
+}
diff --git a/Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt b/Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt
new file mode 100644
index 0000000..8361b9e
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt
@@ -0,0 +1,17 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaConsumeCompileFeatures CXX CUDA)
+#Goal for this example:
+
+#build a c++11 library that express a c++11 public compile feature
+#link a cuda library and verify it builds with c++11 enabled
+
+#build a standalone c++/cuda mixed executable where we express a c++11
+#compile feature.
+
+
+add_library(CudaConsumeLib STATIC static.cpp static.cu)
+target_compile_features(CudaConsumeLib PUBLIC cxx_constexpr)
+
+add_executable(CudaConsumeCompileFeatures main.cu)
+target_link_libraries(CudaConsumeCompileFeatures PRIVATE CudaConsumeLib)
diff --git a/Tests/Cuda/ConsumeCompileFeatures/main.cu b/Tests/Cuda/ConsumeCompileFeatures/main.cu
new file mode 100644
index 0000000..712871c
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/main.cu
@@ -0,0 +1,18 @@
+
+#include <iostream>
+
+int static_cxx11_func(int);
+
+void test_functions()
+{
+ auto x = static_cxx11_func( int(42) );
+ std::cout << x << std::endl;
+}
+
+int main(int argc, char **argv)
+{
+ test_functions();
+ std::cout << "this executable doesn't use cuda code, just call methods defined" << std::endl;
+ std::cout << "in libraries that have cuda code" << std::endl;
+ return 0;
+}
diff --git a/Tests/Cuda/ConsumeCompileFeatures/static.cpp b/Tests/Cuda/ConsumeCompileFeatures/static.cpp
new file mode 100644
index 0000000..565d52e
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/static.cpp
@@ -0,0 +1,10 @@
+
+
+#include <type_traits>
+
+int static_cuda11_func(int);
+
+int static_cxx11_func(int x)
+{
+ return static_cuda11_func(x) + std::integral_constant<int, 32>::value;
+}
diff --git a/Tests/Cuda/ConsumeCompileFeatures/static.cu b/Tests/Cuda/ConsumeCompileFeatures/static.cu
new file mode 100644
index 0000000..73e43a8
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/static.cu
@@ -0,0 +1,9 @@
+
+#include <type_traits>
+
+using tt = std::true_type;
+using ft = std::false_type;
+int __host__ static_cuda11_func(int x)
+{
+ return x * x + std::integral_constant<int, 17>::value;
+}
diff --git a/Tests/Cuda/ObjectLibrary/CMakeLists.txt b/Tests/Cuda/ObjectLibrary/CMakeLists.txt
new file mode 100644
index 0000000..cbe1e67
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/CMakeLists.txt
@@ -0,0 +1,12 @@
+cmake_minimum_required(VERSION 3.7)
+project (CudaObjectLibrary CUDA CXX)
+#Goal for this example:
+
+#build a object files some with cuda and some without than
+#embed these into an executable
+
+add_library(CudaMixedObjectLib OBJECT static.cu static.cpp)
+
+add_executable(CudaObjectLibrary
+ main.cpp
+ $<TARGET_OBJECTS:CudaMixedObjectLib>)
diff --git a/Tests/Cuda/ObjectLibrary/main.cpp b/Tests/Cuda/ObjectLibrary/main.cpp
new file mode 100644
index 0000000..1a70a99
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/main.cpp
@@ -0,0 +1,20 @@
+
+#include <iostream>
+
+int static_func(int);
+int file1_sq_func(int);
+
+void test_functions()
+{
+ file1_sq_func(static_func(42));
+}
+
+int main(int argc, char** argv)
+{
+ test_functions();
+ std::cout
+ << "this executable doesn't use cuda code, just call methods defined"
+ << std::endl;
+ std::cout << "in object files that have cuda code" << std::endl;
+ return 0;
+}
diff --git a/Tests/Cuda/ObjectLibrary/static.cpp b/Tests/Cuda/ObjectLibrary/static.cpp
new file mode 100644
index 0000000..6db1f91
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/static.cpp
@@ -0,0 +1,6 @@
+int file1_sq_func(int);
+
+int static_func(int x)
+{
+ return file1_sq_func(x);
+}
diff --git a/Tests/Cuda/ObjectLibrary/static.cu b/Tests/Cuda/ObjectLibrary/static.cu
new file mode 100644
index 0000000..2374c23
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/static.cu
@@ -0,0 +1,21 @@
+
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+int __host__ file1_sq_func(int x)
+{
+ cudaError_t err;
+ int nDevices = 0;
+ err = cudaGetDeviceCount(&nDevices);
+ if(err != cudaSuccess)
+ {
+ std::cout << "nDevices: " << nDevices << std::endl;
+ std::cout << "err: " << err << std::endl;
+ return 1;
+ }
+ std::cout << "this library uses cuda code" << std::endl;
+ std::cout << "you have " << nDevices << " devices that support cuda" << std::endl;
+
+ return x * x;
+}
diff --git a/Tests/CudaOnly/CMakeLists.txt b/Tests/CudaOnly/CMakeLists.txt
new file mode 100644
index 0000000..85a2051
--- /dev/null
+++ b/Tests/CudaOnly/CMakeLists.txt
@@ -0,0 +1,4 @@
+
+ADD_TEST_MACRO(CudaOnly.EnableStandard CudaOnlyEnableStandard)
+ADD_TEST_MACRO(CudaOnly.SeparateCompilation CudaOnlySeparateCompilation)
+ADD_TEST_MACRO(CudaOnly.WithDefs CudaOnlyWithDefs)
diff --git a/Tests/CudaOnly/EnableStandard/CMakeLists.txt b/Tests/CudaOnly/EnableStandard/CMakeLists.txt
new file mode 100644
index 0000000..53b9132
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/CMakeLists.txt
@@ -0,0 +1,15 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaOnlyEnableStandard CUDA)
+
+#Goal for this example:
+#build cuda sources that require C++11 to be enabled.
+
+add_library(CUDAStatic11 STATIC static.cu)
+add_library(CUDADynamic11 SHARED shared.cu)
+
+add_executable(CudaOnlyEnableStandard main.cu)
+target_link_libraries(CudaOnlyEnableStandard PRIVATE CUDAStatic11 CUDADynamic11)
+
+set_target_properties(CUDAStatic11 CUDADynamic11 PROPERTIES CUDA_STANDARD 11)
+set_target_properties(CUDAStatic11 CUDADynamic11 PROPERTIES CUDA_STANDARD_REQUIRED TRUE)
diff --git a/Tests/CudaOnly/EnableStandard/main.cu b/Tests/CudaOnly/EnableStandard/main.cu
new file mode 100644
index 0000000..83e9dfd
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/main.cu
@@ -0,0 +1,17 @@
+
+#include <iostream>
+
+int static_cuda11_func(int);
+int shared_cuda11_func(int);
+
+void test_functions()
+{
+ static_cuda11_func( int(42) );
+ shared_cuda11_func( int(42) );
+}
+
+int main(int argc, char **argv)
+{
+ test_functions();
+ return 0;
+}
diff --git a/Tests/CudaOnly/EnableStandard/shared.cu b/Tests/CudaOnly/EnableStandard/shared.cu
new file mode 100644
index 0000000..28555b3
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/shared.cu
@@ -0,0 +1,9 @@
+
+#include <type_traits>
+
+using tt = std::true_type;
+using ft = std::false_type;
+int __host__ shared_cuda11_func(int x)
+{
+ return x * x + std::integral_constant<int, 17>::value;
+}
diff --git a/Tests/CudaOnly/EnableStandard/static.cu b/Tests/CudaOnly/EnableStandard/static.cu
new file mode 100644
index 0000000..73e43a8
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/static.cu
@@ -0,0 +1,9 @@
+
+#include <type_traits>
+
+using tt = std::true_type;
+using ft = std::false_type;
+int __host__ static_cuda11_func(int x)
+{
+ return x * x + std::integral_constant<int, 17>::value;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt b/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
new file mode 100644
index 0000000..7055eef
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
@@ -0,0 +1,33 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaOnlySeparateCompilation CUDA)
+
+#Goal for this example:
+#Build a static library that defines multiple methods and kernels that
+#use each other.
+#After that confirm that we can call those methods from dynamic libraries
+#and executables.
+#We complicate the matter by also testing that multiple static libraries
+#all containing cuda separable compilation code links properly
+set(CMAKE_CUDA_FLAGS "-gencode arch=compute_30,code=compute_30")
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD 11)
+add_library(CUDASerarateLibA STATIC file1.cu file2.cu file3.cu)
+
+#Having file4/file5 in a shared library causes serious problems
+#with the nvcc linker and it will generate bad entries that will
+#cause a segv when trying to run the executable
+#
+add_library(CUDASerarateLibB STATIC file4.cu file5.cu)
+target_link_libraries(CUDASerarateLibB PRIVATE CUDASerarateLibA)
+
+add_executable(CudaOnlySeparateCompilation main.cu)
+target_link_libraries(CudaOnlySeparateCompilation PRIVATE CUDASerarateLibB)
+
+set_target_properties( CUDASerarateLibA
+ CUDASerarateLibB
+ PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
+
+set_target_properties( CUDASerarateLibA
+ CUDASerarateLibB
+ PROPERTIES POSITION_INDEPENDENT_CODE ON)
diff --git a/Tests/CudaOnly/SeparateCompilation/file1.cu b/Tests/CudaOnly/SeparateCompilation/file1.cu
new file mode 100644
index 0000000..a2e8bf3
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file1.cu
@@ -0,0 +1,10 @@
+
+#include "file1.h"
+
+result_type __device__ file1_func(int x)
+{
+ result_type r;
+ r.input = x;
+ r.sum = x*x;
+ return r;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file1.h b/Tests/CudaOnly/SeparateCompilation/file1.h
new file mode 100644
index 0000000..ff1945c
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file1.h
@@ -0,0 +1,7 @@
+
+#pragma once
+struct result_type
+{
+ int input;
+ int sum;
+};
diff --git a/Tests/CudaOnly/SeparateCompilation/file2.cu b/Tests/CudaOnly/SeparateCompilation/file2.cu
new file mode 100644
index 0000000..6b8b06b
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file2.cu
@@ -0,0 +1,20 @@
+
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+
+result_type_dynamic __device__ file2_func(int x)
+{
+ if(x!=42)
+ {
+ const result_type r = file1_func(x);
+ const result_type_dynamic rd { r.input, r.sum, true };
+ return rd;
+ }
+ else
+ {
+ const result_type_dynamic rd { x, x*x*x, false };
+ return rd;
+ }
+
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file2.h b/Tests/CudaOnly/SeparateCompilation/file2.h
new file mode 100644
index 0000000..d2dbaa4
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file2.h
@@ -0,0 +1,10 @@
+
+#pragma once
+#include "file1.h"
+
+struct result_type_dynamic
+{
+ int input;
+ int sum;
+ bool from_static;
+};
diff --git a/Tests/CudaOnly/SeparateCompilation/file3.cu b/Tests/CudaOnly/SeparateCompilation/file3.cu
new file mode 100644
index 0000000..670a18b
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file3.cu
@@ -0,0 +1,25 @@
+
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+
+static
+__global__
+void file3_kernel(result_type& r, int x)
+{
+ //call static_func which is a method that is defined in the
+ //static library that is always out of date
+ r = file1_func(x);
+ result_type_dynamic rd = file2_func(x);
+}
+
+result_type file3_launch_kernel(int x)
+{
+ result_type r;
+ file3_kernel <<<1,1>>> (r,x);
+ return r;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file4.cu b/Tests/CudaOnly/SeparateCompilation/file4.cu
new file mode 100644
index 0000000..86ef623
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file4.cu
@@ -0,0 +1,25 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static
+__global__
+void file4_kernel(result_type& r, int x)
+{
+ //call static_func which is a method that is defined in the
+ //static library that is always out of date
+ r = file1_func(x);
+ result_type_dynamic rd = file2_func(x);
+}
+
+int file4_launch_kernel(int x)
+{
+ result_type r;
+ file4_kernel <<<1,1>>> (r,x);
+ return r.sum;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file5.cu b/Tests/CudaOnly/SeparateCompilation/file5.cu
new file mode 100644
index 0000000..6fdb32a
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file5.cu
@@ -0,0 +1,25 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static
+__global__
+void file5_kernel(result_type& r, int x)
+{
+ //call static_func which is a method that is defined in the
+ //static library that is always out of date
+ r = file1_func(x);
+ result_type_dynamic rd = file2_func(x);
+}
+
+int file5_launch_kernel(int x)
+{
+ result_type r;
+ file5_kernel <<<1,1>>> (r,x);
+ return r.sum;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/main.cu b/Tests/CudaOnly/SeparateCompilation/main.cu
new file mode 100644
index 0000000..d4520ae
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/main.cu
@@ -0,0 +1,15 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+// result_type file4_launch_kernel(int x);
+// result_type file5_launch_kernel(int x);
+
+int main(int argc, char **argv)
+{
+ // file4_launch_kernel(42);
+ // file5_launch_kernel(42);
+ return 0;
+}
diff --git a/Tests/CudaOnly/WithDefs/CMakeLists.txt b/Tests/CudaOnly/WithDefs/CMakeLists.txt
new file mode 100644
index 0000000..c4ca8b9
--- /dev/null
+++ b/Tests/CudaOnly/WithDefs/CMakeLists.txt
@@ -0,0 +1,31 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaOnlyWithDefs CUDA)
+
+#verify that we can pass explicit cuda arch flags
+set(CMAKE_CUDA_FLAGS "-gencode arch=compute_30,code=compute_30")
+set(debug_compile_flags --generate-code arch=compute_20,code=sm_20 -Xcompiler=-Werror)
+set(release_compile_defs DEFREL)
+
+#Goal for this example:
+#build a executable that needs to be passed a complex define through add_defintions
+#this verifies we can pass things such as '_','(' to nvcc
+add_definitions("-DPACKED_DEFINE=__attribute__((packed))")
+set_source_files_properties(main.notcu PROPERTIES LANGUAGE CUDA)
+add_executable(CudaOnlyWithDefs main.notcu)
+
+target_compile_options(CudaOnlyWithDefs
+ PRIVATE
+ $<$<CONFIG:DEBUG>:$<BUILD_INTERFACE:${debug_compile_flags}>>
+ )
+
+target_compile_definitions(CudaOnlyWithDefs
+ PRIVATE
+ $<$<CONFIG:RELEASE>:$<BUILD_INTERFACE:${release_compile_defs}>>
+ )
+
+#we need to add an rpath for the cuda library so that everything
+#loads properly on the mac
+if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
+ set_target_properties(CudaOnlyWithDefs PROPERTIES LINK_FLAGS "-Wl,-rpath,${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}")
+endif()
diff --git a/Tests/CudaOnly/WithDefs/main.notcu b/Tests/CudaOnly/WithDefs/main.notcu
new file mode 100644
index 0000000..6b02bbc
--- /dev/null
+++ b/Tests/CudaOnly/WithDefs/main.notcu
@@ -0,0 +1,46 @@
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+static
+__global__
+void DetermineIfValidCudaDevice()
+{
+}
+
+struct PACKED_DEFINE result_type
+{
+ bool valid;
+ int value;
+#if defined(NDEBUG) && !defined(DEFREL)
+#error missing DEFREL flag
+#endif
+};
+
+result_type can_launch_kernel()
+{
+ result_type r;
+ DetermineIfValidCudaDevice <<<1,1>>> ();
+ r.valid = (cudaSuccess == cudaGetLastError());
+ if(r.valid)
+ {
+ r.value = 1;
+ }
+ else
+ {
+ r.value = -1;
+ }
+ return r;
+}
+
+int main(int argc, char **argv)
+{
+ cudaError_t err;
+ int nDevices = 0;
+ err = cudaGetDeviceCount(&nDevices);
+ if(err != cudaSuccess)
+ {
+ return 1;
+ }
+ return 0;
+}
diff --git a/Tests/ExternalProject/CMakeLists.txt b/Tests/ExternalProject/CMakeLists.txt
index ca6462d..72c20eb 100644
--- a/Tests/ExternalProject/CMakeLists.txt
+++ b/Tests/ExternalProject/CMakeLists.txt
@@ -363,6 +363,23 @@ if(do_git_tests)
)
set_property(TARGET ${proj} PROPERTY FOLDER "GIT")
+ # Live git / master (no GIT_TAG), but git config flags
+ #
+ # The `git clone --config` parameter has been introduced in Git 1.7.7
+ if(NOT git_version VERSION_LESS 1.7.7)
+ set(proj TutorialStep1-GIT-config)
+ ExternalProject_Add(${proj}
+ GIT_REPOSITORY "${local_git_repo}"
+ GIT_CONFIG core.eol=lf core.autocrlf=input
+ CMAKE_GENERATOR "${CMAKE_GENERATOR}"
+ CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
+ INSTALL_COMMAND ""
+ DEPENDS "SetupLocalGITRepository"
+ LOG_UPDATE 1
+ )
+ set_property(TARGET ${proj} PROPERTY FOLDER "GIT")
+ endif()
+
# git by explicit branch/tag with empty submodule list
#
set(proj TutorialStep1-GIT-bytag-withsubmodules)
diff --git a/Tests/ExternalProjectLocal/CMakeLists.txt b/Tests/ExternalProjectLocal/CMakeLists.txt
index 17f1630..5b94163 100644
--- a/Tests/ExternalProjectLocal/CMakeLists.txt
+++ b/Tests/ExternalProjectLocal/CMakeLists.txt
@@ -131,6 +131,7 @@ ExternalProject_Add(${proj}
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
INSTALL_COMMAND ""
LOG_BUILD 1
+ UPDATE_DISCONNECTED 1
)
set_property(TARGET ${proj} PROPERTY FOLDER "Local/TGZ")
diff --git a/Tests/FindLibRHash/CMakeLists.txt b/Tests/FindLibRHash/CMakeLists.txt
new file mode 100644
index 0000000..4d3954d
--- /dev/null
+++ b/Tests/FindLibRHash/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindLibRHash.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindLibRHash/Test"
+ "${CMake_BINARY_DIR}/Tests/FindLibRHash/Test"
+ ${build_generator_args}
+ --build-project TestFindLibRHash
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindLibRHash/Test/CMakeLists.txt b/Tests/FindLibRHash/Test/CMakeLists.txt
new file mode 100644
index 0000000..37e062a
--- /dev/null
+++ b/Tests/FindLibRHash/Test/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.7)
+project(TestFindLibRHash C)
+include(CTest)
+
+# CMake does not actually provide FindLibRHash publicly.
+set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../Source/Modules)
+
+find_package(LibRHash REQUIRED)
+
+add_executable(test_librhash_tgt main.c)
+target_link_libraries(test_librhash_tgt LibRHash::LibRHash)
+add_test(NAME test_librhash_tgt COMMAND test_librhash_tgt)
+
+add_executable(test_librhash_var main.c)
+target_include_directories(test_librhash_var PRIVATE ${LibRHash_INCLUDE_DIRS})
+target_link_libraries(test_librhash_var PRIVATE ${LibRHash_LIBRARIES})
+add_test(NAME test_librhash_var COMMAND test_librhash_var)
diff --git a/Tests/FindLibRHash/Test/main.c b/Tests/FindLibRHash/Test/main.c
new file mode 100644
index 0000000..201dced
--- /dev/null
+++ b/Tests/FindLibRHash/Test/main.c
@@ -0,0 +1,7 @@
+#include <rhash.h>
+
+int main()
+{
+ rhash_library_init();
+ return 0;
+}
diff --git a/Tests/IncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/CMakeLists.txt
index db18462..4920582 100644
--- a/Tests/IncludeDirectories/CMakeLists.txt
+++ b/Tests/IncludeDirectories/CMakeLists.txt
@@ -3,9 +3,7 @@ project(IncludeDirectories)
if (((CMAKE_C_COMPILER_ID STREQUAL GNU AND CMAKE_C_COMPILER_VERSION VERSION_GREATER 4.4)
OR CMAKE_C_COMPILER_ID STREQUAL Clang OR CMAKE_C_COMPILER_ID STREQUAL AppleClang)
- AND (CMAKE_GENERATOR STREQUAL "Unix Makefiles"
- OR CMAKE_GENERATOR STREQUAL "Ninja"
- OR (CMAKE_GENERATOR STREQUAL "Xcode" AND NOT XCODE_VERSION VERSION_LESS 6.0)))
+ AND (CMAKE_GENERATOR STREQUAL "Unix Makefiles" OR CMAKE_GENERATOR STREQUAL "Ninja"))
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-Wunused-variable run_sys_includes_test)
if(run_sys_includes_test)
diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
index 5078f30..dcee85e 100644
--- a/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
+++ b/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
@@ -15,17 +15,10 @@ target_include_directories(upstream SYSTEM PUBLIC
)
add_library(config_specific INTERFACE)
-if(CMAKE_GENERATOR STREQUAL "Xcode")
- # CMAKE_BUILD_TYPE does not work here for multi-config generators
- target_include_directories(config_specific SYSTEM INTERFACE
- "${CMAKE_CURRENT_SOURCE_DIR}/config_specific"
- )
-else()
- set(testConfig ${CMAKE_BUILD_TYPE})
- target_include_directories(config_specific SYSTEM INTERFACE
- "$<$<CONFIG:${testConfig}>:${CMAKE_CURRENT_SOURCE_DIR}/config_specific>"
- )
-endif()
+set(testConfig ${CMAKE_BUILD_TYPE})
+target_include_directories(config_specific SYSTEM INTERFACE
+ "$<$<CONFIG:${testConfig}>:${CMAKE_CURRENT_SOURCE_DIR}/config_specific>"
+)
add_library(consumer consumer.cpp)
target_link_libraries(consumer upstream config_specific)
diff --git a/Tests/InterfaceLibrary/CMakeLists.txt b/Tests/InterfaceLibrary/CMakeLists.txt
index ee81419..33c4b90 100644
--- a/Tests/InterfaceLibrary/CMakeLists.txt
+++ b/Tests/InterfaceLibrary/CMakeLists.txt
@@ -25,8 +25,25 @@ target_sources(iface_objlib INTERFACE $<TARGET_OBJECTS:objlib>)
add_library(intermediate INTERFACE)
target_link_libraries(intermediate INTERFACE iface_objlib)
+add_library(item_fake_tgt STATIC item_fake.cpp)
+set_property(TARGET item_fake_tgt PROPERTY OUTPUT_NAME item_fake)
+add_library(item_real STATIC item.cpp)
+add_library(item_iface INTERFACE IMPORTED)
+set_property(TARGET item_iface PROPERTY IMPORTED_LIBNAME item_real)
+add_dependencies(item_iface item_real)
+link_directories(${CMAKE_CURRENT_BINARY_DIR})
+
add_executable(InterfaceLibrary definetestexe.cpp)
-target_link_libraries(InterfaceLibrary iface_nodepends headeriface subiface intermediate)
+target_link_libraries(InterfaceLibrary
+ iface_nodepends
+ headeriface
+ subiface
+ intermediate
+
+ item_iface
+ item_fake # ensure that 'item_real' is ordered in place of item_iface
+ )
+add_dependencies(InterfaceLibrary item_fake_tgt)
add_subdirectory(libsdir)
@@ -47,6 +64,7 @@ target_link_libraries(iface_whitelist INTERFACE $<$<BOOL:$<TARGET_PROPERTY:CUSTO
add_executable(exec_whitelist dummy.cpp)
target_link_libraries(exec_whitelist iface_whitelist)
+set(CMAKE_NO_SYSTEM_FROM_IMPORTED 1)
add_library(iface_imported INTERFACE IMPORTED)
set_property(TARGET iface_imported PROPERTY
INTERFACE_COMPILE_DEFINITIONS
diff --git a/Tests/InterfaceLibrary/definetestexe.cpp b/Tests/InterfaceLibrary/definetestexe.cpp
index a6b5592..098502c 100644
--- a/Tests/InterfaceLibrary/definetestexe.cpp
+++ b/Tests/InterfaceLibrary/definetestexe.cpp
@@ -17,8 +17,9 @@
extern int obj();
extern int sub();
+extern int item();
int main(int, char**)
{
- return obj() + sub();
+ return obj() + sub() + item();
}
diff --git a/Tests/InterfaceLibrary/item.cpp b/Tests/InterfaceLibrary/item.cpp
new file mode 100644
index 0000000..85cda1b
--- /dev/null
+++ b/Tests/InterfaceLibrary/item.cpp
@@ -0,0 +1,4 @@
+int item()
+{
+ return 0;
+}
diff --git a/Tests/InterfaceLibrary/item_fake.cpp b/Tests/InterfaceLibrary/item_fake.cpp
new file mode 100644
index 0000000..b4bd829
--- /dev/null
+++ b/Tests/InterfaceLibrary/item_fake.cpp
@@ -0,0 +1,5 @@
+extern int item_undefined();
+int item()
+{
+ return item_undefined();
+}
diff --git a/Tests/Module/ExternalData/SHA3_256/.gitattributes b/Tests/Module/ExternalData/SHA3_256/.gitattributes
new file mode 100644
index 0000000..3e51d39
--- /dev/null
+++ b/Tests/Module/ExternalData/SHA3_256/.gitattributes
@@ -0,0 +1 @@
+* -crlf
diff --git a/Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231 b/Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231
new file mode 100644
index 0000000..0377f5d
--- /dev/null
+++ b/Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231
@@ -0,0 +1 @@
+SeriesMixed.5
diff --git a/Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-256 b/Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-256
new file mode 100644
index 0000000..1a5db39
--- /dev/null
+++ b/Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-256
@@ -0,0 +1 @@
+c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231
diff --git a/Tests/QtAutogen/CMakeLists.txt b/Tests/QtAutogen/CMakeLists.txt
index c713d1c..c4d0567 100644
--- a/Tests/QtAutogen/CMakeLists.txt
+++ b/Tests/QtAutogen/CMakeLists.txt
@@ -44,114 +44,45 @@ else()
endif()
-# -- RCC only
-add_executable(rcconly rcconly.cpp second_resource.qrc)
-set_property(TARGET rcconly PROPERTY AUTORCC ON)
-target_link_libraries(rcconly ${QT_QTCORE_TARGET})
-
-# -- RCC empty
-add_executable(rcc_empty rcc_empty.cpp rcc_empty_resource.qrc)
-set_property(TARGET rcc_empty PROPERTY AUTORCC ON)
-target_link_libraries(rcc_empty ${QT_QTCORE_TARGET})
-
+get_property(QT_COMPILE_FEATURES TARGET ${QT_QTCORE_TARGET} PROPERTY INTERFACE_COMPILE_FEATURES)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
-add_definitions(-DFOO -DSomeDefine="Barx")
-
-# enable relaxed mode so automoc can handle all the special cases:
-set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
-
-set(CMAKE_AUTOUIC ON)
-set(CMAKE_AUTORCC ON)
-
-# create an executable and two library targets, each requiring automoc:
-add_library(codeeditorLib STATIC codeeditor.cpp)
-
-add_library(privateSlot OBJECT private_slot.cpp)
-
-configure_file(generated_resource.qrc.in generated_resource.qrc @ONLY)
-add_custom_command(
- OUTPUT generated.txt
- COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in" "${CMAKE_CURRENT_BINARY_DIR}/generated.txt"
- DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in"
- )
-
-add_custom_target(generate_moc_input
- DEPENDS generated.txt
- COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}"
- COMMAND ${CMAKE_COMMAND} -E rename "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h"
-)
-
-add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
- COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
- DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in"
-)
-
-if (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_GENERATOR STREQUAL Ninja)
- set(debug_srcs "$<$<CONFIG:Debug>:debug_class.cpp>" $<$<CONFIG:Debug>:debug_resource.qrc>)
- set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:TEST_DEBUG_CLASS>)
-endif()
-
-# The -no-protection option disables the generation of include guards. Verify
-# that setting the source file property has an effect by using this and
-# issue an error in the preprocessor in calwidget.cpp if the include guard
-# is defined.
-set_source_files_properties(calwidget.ui PROPERTIES AUTOUIC_OPTIONS "-no-protection")
-
-add_executable(QtAutogen main.cpp calwidget.cpp second_widget.cpp foo.cpp blub.cpp bar.cpp abc.cpp
- multiplewidgets.cpp
- xyz.cpp yaf.cpp gadget.cpp $<TARGET_OBJECTS:privateSlot>
- test.qrc second_resource.qrc resourcetester.cpp generated.cpp ${debug_srcs}
- ${CMAKE_CURRENT_BINARY_DIR}/generated_resource.qrc
-)
-set_property(TARGET QtAutogen APPEND PROPERTY AUTOGEN_TARGET_DEPENDS generate_moc_input "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h")
-
-add_executable(targetObjectsTest targetObjectsTest.cpp $<TARGET_OBJECTS:privateSlot>)
-target_link_libraries(targetObjectsTest ${QT_LIBRARIES})
-
-set_target_properties(
- QtAutogen codeeditorLib privateSlot targetObjectsTest
- PROPERTIES
- AUTOMOC TRUE
-)
-
-# Test AUTOMOC and AUTORCC on source files with the same name
-# but in different subdirectories
-add_subdirectory(sameName)
-
-include(GenerateExportHeader)
-# The order is relevant here. B depends on A, and B headers depend on A
-# headers both subdirectories use CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE and we
-# test that CMAKE_AUTOMOC successfully reads the include directories
-# for the build interface from those targets. There has previously been
-# a bug where caching of the include directories happened before
-# extracting the includes to pass to moc.
-add_subdirectory(Bdir)
-add_subdirectory(Adir)
-add_library(libC SHARED libC.cpp)
-set_target_properties(libC PROPERTIES AUTOMOC TRUE)
-generate_export_header(libC)
-target_link_libraries(libC LINK_PUBLIC libB)
-
-target_link_libraries(QtAutogen codeeditorLib ${QT_LIBRARIES} libC)
-
+# -- Test: AUTORCC
+# RCC only
+add_executable(rccOnly rccOnly.cpp rccOnlyRes.qrc)
+set_property(TARGET rccOnly PROPERTY AUTORCC ON)
+target_link_libraries(rccOnly ${QT_QTCORE_TARGET})
+
+# -- Test: AUTORCC
+# RCC empty
+add_executable(rccEmpty rccEmpty.cpp rccEmptyRes.qrc)
+set_property(TARGET rccEmpty PROPERTY AUTORCC ON)
+target_link_libraries(rccEmpty ${QT_QTCORE_TARGET})
+
+# -- Test: AUTOUIC
+# UIC only
+qtx_wrap_cpp(uicOnlyMoc uicOnlySource/uiconly.h)
+add_executable(uicOnly uicOnlySource/uiconly.cpp ${uicOnlyMoc})
+set_property(TARGET uicOnly PROPERTY AUTOUIC ON)
+target_link_libraries(uicOnly ${QT_LIBRARIES})
+
+# -- Test: AUTOMOC, AUTORCC
# Add not_generated_file.qrc to the source list to get the file-level
# dependency, but don't generate a c++ file from it. Disable the AUTORCC
# feature for this target. This tests that qrc files in the sources don't
# have an effect on generation if AUTORCC is off.
add_library(empty STATIC empty.cpp not_generated_file.qrc)
set_target_properties(empty PROPERTIES AUTORCC OFF)
-
set_target_properties(empty PROPERTIES AUTOMOC TRUE)
target_link_libraries(empty no_link_language)
add_library(no_link_language STATIC empty.h)
set_target_properties(no_link_language PROPERTIES AUTOMOC TRUE)
+# Pass Qt compiler features to targets that don't link against Qt
+target_compile_features(no_link_language PRIVATE ${QT_COMPILE_FEATURES})
+target_compile_features(empty PRIVATE ${QT_COMPILE_FEATURES})
-qtx_wrap_cpp(uicOnlyMoc sub/uiconly.h)
-add_executable(uiconly sub/uiconly.cpp ${uicOnlyMoc})
-target_link_libraries(uiconly ${QT_LIBRARIES})
-
+# -- Test: AUTORCC
+# When a file listed in a .qrc file changes the target must be rebuilt
try_compile(RCC_DEPENDS
"${CMAKE_CURRENT_BINARY_DIR}/autorcc_depends"
"${CMAKE_CURRENT_SOURCE_DIR}/autorcc_depends"
@@ -185,7 +116,8 @@ if (NOT file1_step1 GREATER file1_before)
message(SEND_ERROR "file1 (${qrc_file1}) should have changed in the first step!")
endif()
-#-----------------------------------------------------------------------------
+# -- Test: AUTOMOC
+# Ensure a repeated build succeeds when a header containing a QObject changes
try_compile(MOC_RERUN
"${CMAKE_CURRENT_BINARY_DIR}/automoc_rerun"
"${CMAKE_CURRENT_SOURCE_DIR}/automoc_rerun"
@@ -207,3 +139,11 @@ execute_process(COMMAND "${CMAKE_COMMAND}" --build .
if (automoc_rerun_result)
message(SEND_ERROR "Second build of automoc_rerun failed.")
endif()
+
+# -- Test: AUTOMOC AUTORCC
+# Source files with the same basename in different subdirectories
+add_subdirectory(sameName)
+
+# -- Test: AUTOMOC AUTORCC AUTOUIC
+# Complex test case
+add_subdirectory(complex)
diff --git a/Tests/QtAutogen/Adir/CMakeLists.txt b/Tests/QtAutogen/complex/Adir/CMakeLists.txt
index a1c36ff..a1c36ff 100644
--- a/Tests/QtAutogen/Adir/CMakeLists.txt
+++ b/Tests/QtAutogen/complex/Adir/CMakeLists.txt
diff --git a/Tests/QtAutogen/Adir/libA.cpp b/Tests/QtAutogen/complex/Adir/libA.cpp
index f79f24a..f79f24a 100644
--- a/Tests/QtAutogen/Adir/libA.cpp
+++ b/Tests/QtAutogen/complex/Adir/libA.cpp
diff --git a/Tests/QtAutogen/Adir/libA.h b/Tests/QtAutogen/complex/Adir/libA.h
index c4eb9f7..c4eb9f7 100644
--- a/Tests/QtAutogen/Adir/libA.h
+++ b/Tests/QtAutogen/complex/Adir/libA.h
diff --git a/Tests/QtAutogen/Bdir/CMakeLists.txt b/Tests/QtAutogen/complex/Bdir/CMakeLists.txt
index d9d4aa7..d9d4aa7 100644
--- a/Tests/QtAutogen/Bdir/CMakeLists.txt
+++ b/Tests/QtAutogen/complex/Bdir/CMakeLists.txt
diff --git a/Tests/QtAutogen/Bdir/libB.cpp b/Tests/QtAutogen/complex/Bdir/libB.cpp
index d3b6753..d3b6753 100644
--- a/Tests/QtAutogen/Bdir/libB.cpp
+++ b/Tests/QtAutogen/complex/Bdir/libB.cpp
diff --git a/Tests/QtAutogen/Bdir/libB.h b/Tests/QtAutogen/complex/Bdir/libB.h
index e4ab788..e4ab788 100644
--- a/Tests/QtAutogen/Bdir/libB.h
+++ b/Tests/QtAutogen/complex/Bdir/libB.h
diff --git a/Tests/QtAutogen/complex/CMakeLists.txt b/Tests/QtAutogen/complex/CMakeLists.txt
new file mode 100644
index 0000000..0d44f50
--- /dev/null
+++ b/Tests/QtAutogen/complex/CMakeLists.txt
@@ -0,0 +1,81 @@
+cmake_minimum_required(VERSION 3.1)
+
+# -- Test: AUTOMOC AUTORCC AUTOUIC
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+add_definitions(-DFOO -DSomeDefine="Barx")
+
+# enable relaxed mode so automoc can handle all the special cases:
+set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+
+# create an executable and two library targets, each requiring automoc:
+add_library(codeeditorLib STATIC codeeditor.cpp)
+add_library(privateSlot OBJECT private_slot.cpp)
+# Pass Qt compiler features to targets that don't link against Qt
+target_compile_features(codeeditorLib PRIVATE ${QT_COMPILE_FEATURES})
+target_compile_features(privateSlot PRIVATE ${QT_COMPILE_FEATURES})
+
+configure_file(generated_resource.qrc.in generated_resource.qrc @ONLY)
+add_custom_command(
+ OUTPUT generated.txt
+ COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in" "${CMAKE_CURRENT_BINARY_DIR}/generated.txt"
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in"
+ )
+
+add_custom_target(generate_moc_input
+ DEPENDS generated.txt
+ COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}"
+ COMMAND ${CMAKE_COMMAND} -E rename "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h"
+)
+
+add_custom_command(
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
+ COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in"
+)
+
+if (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_GENERATOR STREQUAL Ninja)
+ set(debug_srcs "$<$<CONFIG:Debug>:debug_class.cpp>" $<$<CONFIG:Debug>:debug_resource.qrc>)
+ set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:TEST_DEBUG_CLASS>)
+endif()
+
+# The -no-protection option disables the generation of include guards. Verify
+# that setting the source file property has an effect by using this and
+# issue an error in the preprocessor in calwidget.cpp if the include guard
+# is defined.
+set_source_files_properties(calwidget.ui PROPERTIES AUTOUIC_OPTIONS "-no-protection")
+
+add_executable(QtAutogen main.cpp calwidget.cpp second_widget.cpp foo.cpp blub.cpp bar.cpp abc.cpp
+ multiplewidgets.cpp
+ xyz.cpp yaf.cpp gadget.cpp $<TARGET_OBJECTS:privateSlot>
+ test.qrc second_resource.qrc resourcetester.cpp generated.cpp ${debug_srcs}
+ ${CMAKE_CURRENT_BINARY_DIR}/generated_resource.qrc
+)
+set_property(TARGET QtAutogen APPEND PROPERTY AUTOGEN_TARGET_DEPENDS generate_moc_input "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h")
+
+add_executable(targetObjectsTest targetObjectsTest.cpp $<TARGET_OBJECTS:privateSlot>)
+target_link_libraries(targetObjectsTest ${QT_LIBRARIES})
+
+set_target_properties(
+ QtAutogen codeeditorLib privateSlot targetObjectsTest
+ PROPERTIES
+ AUTOMOC TRUE
+)
+
+
+include(GenerateExportHeader)
+# The order is relevant here. B depends on A, and B headers depend on A
+# headers both subdirectories use CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE and we
+# test that CMAKE_AUTOMOC successfully reads the include directories
+# for the build interface from those targets. There has previously been
+# a bug where caching of the include directories happened before
+# extracting the includes to pass to moc.
+add_subdirectory(Bdir)
+add_subdirectory(Adir)
+add_library(libC SHARED libC.cpp)
+set_target_properties(libC PROPERTIES AUTOMOC TRUE)
+generate_export_header(libC)
+target_link_libraries(libC LINK_PUBLIC libB)
+
+target_link_libraries(QtAutogen codeeditorLib ${QT_LIBRARIES} libC)
diff --git a/Tests/QtAutogen/abc.cpp b/Tests/QtAutogen/complex/abc.cpp
index 2929b92..2929b92 100644
--- a/Tests/QtAutogen/abc.cpp
+++ b/Tests/QtAutogen/complex/abc.cpp
diff --git a/Tests/QtAutogen/abc.h b/Tests/QtAutogen/complex/abc.h
index ec5f411..ec5f411 100644
--- a/Tests/QtAutogen/abc.h
+++ b/Tests/QtAutogen/complex/abc.h
diff --git a/Tests/QtAutogen/abc_p.h b/Tests/QtAutogen/complex/abc_p.h
index be98487..be98487 100644
--- a/Tests/QtAutogen/abc_p.h
+++ b/Tests/QtAutogen/complex/abc_p.h
diff --git a/Tests/QtAutogen/bar.cpp b/Tests/QtAutogen/complex/bar.cpp
index 734bd7a..734bd7a 100644
--- a/Tests/QtAutogen/bar.cpp
+++ b/Tests/QtAutogen/complex/bar.cpp
diff --git a/Tests/QtAutogen/blub.cpp b/Tests/QtAutogen/complex/blub.cpp
index 1c497e0..1c497e0 100644
--- a/Tests/QtAutogen/blub.cpp
+++ b/Tests/QtAutogen/complex/blub.cpp
diff --git a/Tests/QtAutogen/blub.h b/Tests/QtAutogen/complex/blub.h
index ff79878..ff79878 100644
--- a/Tests/QtAutogen/blub.h
+++ b/Tests/QtAutogen/complex/blub.h
diff --git a/Tests/QtAutogen/calwidget.cpp b/Tests/QtAutogen/complex/calwidget.cpp
index 380e982..380e982 100644
--- a/Tests/QtAutogen/calwidget.cpp
+++ b/Tests/QtAutogen/complex/calwidget.cpp
diff --git a/Tests/QtAutogen/calwidget.h b/Tests/QtAutogen/complex/calwidget.h
index 084d959..084d959 100644
--- a/Tests/QtAutogen/calwidget.h
+++ b/Tests/QtAutogen/complex/calwidget.h
diff --git a/Tests/QtAutogen/calwidget.ui b/Tests/QtAutogen/complex/calwidget.ui
index 1c245ca..1c245ca 100644
--- a/Tests/QtAutogen/calwidget.ui
+++ b/Tests/QtAutogen/complex/calwidget.ui
diff --git a/Tests/QtAutogen/codeeditor.cpp b/Tests/QtAutogen/complex/codeeditor.cpp
index 0caf8a7..0caf8a7 100644
--- a/Tests/QtAutogen/codeeditor.cpp
+++ b/Tests/QtAutogen/complex/codeeditor.cpp
diff --git a/Tests/QtAutogen/codeeditor.h b/Tests/QtAutogen/complex/codeeditor.h
index b410bd4..b410bd4 100644
--- a/Tests/QtAutogen/codeeditor.h
+++ b/Tests/QtAutogen/complex/codeeditor.h
diff --git a/Tests/QtAutogen/debug_class.cpp b/Tests/QtAutogen/complex/debug_class.cpp
index 46b09e7..46b09e7 100644
--- a/Tests/QtAutogen/debug_class.cpp
+++ b/Tests/QtAutogen/complex/debug_class.cpp
diff --git a/Tests/QtAutogen/debug_class.h b/Tests/QtAutogen/complex/debug_class.h
index c02f0ed..c02f0ed 100644
--- a/Tests/QtAutogen/debug_class.h
+++ b/Tests/QtAutogen/complex/debug_class.h
diff --git a/Tests/QtAutogen/debug_class.ui b/Tests/QtAutogen/complex/debug_class.ui
index dc2e1ac..dc2e1ac 100644
--- a/Tests/QtAutogen/debug_class.ui
+++ b/Tests/QtAutogen/complex/debug_class.ui
diff --git a/Tests/QtAutogen/debug_resource.qrc b/Tests/QtAutogen/complex/debug_resource.qrc
index db98b9b..db98b9b 100644
--- a/Tests/QtAutogen/debug_resource.qrc
+++ b/Tests/QtAutogen/complex/debug_resource.qrc
diff --git a/Tests/QtAutogen/foo.cpp b/Tests/QtAutogen/complex/foo.cpp
index f665eee..f665eee 100644
--- a/Tests/QtAutogen/foo.cpp
+++ b/Tests/QtAutogen/complex/foo.cpp
diff --git a/Tests/QtAutogen/foo.h b/Tests/QtAutogen/complex/foo.h
index 3e03fe6..3e03fe6 100644
--- a/Tests/QtAutogen/foo.h
+++ b/Tests/QtAutogen/complex/foo.h
diff --git a/Tests/QtAutogen/gadget.cpp b/Tests/QtAutogen/complex/gadget.cpp
index 23d95fa..23d95fa 100644
--- a/Tests/QtAutogen/gadget.cpp
+++ b/Tests/QtAutogen/complex/gadget.cpp
diff --git a/Tests/QtAutogen/gadget.h b/Tests/QtAutogen/complex/gadget.h
index 3253e31..3253e31 100644
--- a/Tests/QtAutogen/gadget.h
+++ b/Tests/QtAutogen/complex/gadget.h
diff --git a/Tests/QtAutogen/generated.cpp b/Tests/QtAutogen/complex/generated.cpp
index d514c61..d514c61 100644
--- a/Tests/QtAutogen/generated.cpp
+++ b/Tests/QtAutogen/complex/generated.cpp
diff --git a/Tests/QtAutogen/generated.h b/Tests/QtAutogen/complex/generated.h
index 62e1607..62e1607 100644
--- a/Tests/QtAutogen/generated.h
+++ b/Tests/QtAutogen/complex/generated.h
diff --git a/Tests/QtAutogen/generated.txt.in b/Tests/QtAutogen/complex/generated.txt.in
index 77507bb..77507bb 100644
--- a/Tests/QtAutogen/generated.txt.in
+++ b/Tests/QtAutogen/complex/generated.txt.in
diff --git a/Tests/QtAutogen/generated_resource.qrc.in b/Tests/QtAutogen/complex/generated_resource.qrc.in
index da5fa62..da5fa62 100644
--- a/Tests/QtAutogen/generated_resource.qrc.in
+++ b/Tests/QtAutogen/complex/generated_resource.qrc.in
diff --git a/Tests/QtAutogen/libC.cpp b/Tests/QtAutogen/complex/libC.cpp
index a3acff1..a3acff1 100644
--- a/Tests/QtAutogen/libC.cpp
+++ b/Tests/QtAutogen/complex/libC.cpp
diff --git a/Tests/QtAutogen/libC.h b/Tests/QtAutogen/complex/libC.h
index 3bc2bad..3bc2bad 100644
--- a/Tests/QtAutogen/libC.h
+++ b/Tests/QtAutogen/complex/libC.h
diff --git a/Tests/QtAutogen/main.cpp b/Tests/QtAutogen/complex/main.cpp
index d557c70..d557c70 100644
--- a/Tests/QtAutogen/main.cpp
+++ b/Tests/QtAutogen/complex/main.cpp
diff --git a/Tests/QtAutogen/multiplewidgets.cpp b/Tests/QtAutogen/complex/multiplewidgets.cpp
index fda36ea..fda36ea 100644
--- a/Tests/QtAutogen/multiplewidgets.cpp
+++ b/Tests/QtAutogen/complex/multiplewidgets.cpp
diff --git a/Tests/QtAutogen/multiplewidgets.h b/Tests/QtAutogen/complex/multiplewidgets.h
index a4d0a50..a4d0a50 100644
--- a/Tests/QtAutogen/multiplewidgets.h
+++ b/Tests/QtAutogen/complex/multiplewidgets.h
diff --git a/Tests/QtAutogen/myinterface.h.in b/Tests/QtAutogen/complex/myinterface.h.in
index c6c0ba1..c6c0ba1 100644
--- a/Tests/QtAutogen/myinterface.h.in
+++ b/Tests/QtAutogen/complex/myinterface.h.in
diff --git a/Tests/QtAutogen/myotherinterface.h.in b/Tests/QtAutogen/complex/myotherinterface.h.in
index d21e7af..d21e7af 100644
--- a/Tests/QtAutogen/myotherinterface.h.in
+++ b/Tests/QtAutogen/complex/myotherinterface.h.in
diff --git a/Tests/QtAutogen/private_slot.cpp b/Tests/QtAutogen/complex/private_slot.cpp
index ab1682a..ab1682a 100644
--- a/Tests/QtAutogen/private_slot.cpp
+++ b/Tests/QtAutogen/complex/private_slot.cpp
diff --git a/Tests/QtAutogen/private_slot.h b/Tests/QtAutogen/complex/private_slot.h
index 8041eb2..8041eb2 100644
--- a/Tests/QtAutogen/private_slot.h
+++ b/Tests/QtAutogen/complex/private_slot.h
diff --git a/Tests/QtAutogen/resourcetester.cpp b/Tests/QtAutogen/complex/resourcetester.cpp
index 4ecb6b4..4ecb6b4 100644
--- a/Tests/QtAutogen/resourcetester.cpp
+++ b/Tests/QtAutogen/complex/resourcetester.cpp
diff --git a/Tests/QtAutogen/resourcetester.h b/Tests/QtAutogen/complex/resourcetester.h
index dbdb3ad..dbdb3ad 100644
--- a/Tests/QtAutogen/resourcetester.h
+++ b/Tests/QtAutogen/complex/resourcetester.h
diff --git a/Tests/QtAutogen/second_resource.qrc b/Tests/QtAutogen/complex/second_resource.qrc
index 27bfb14..27bfb14 100644
--- a/Tests/QtAutogen/second_resource.qrc
+++ b/Tests/QtAutogen/complex/second_resource.qrc
diff --git a/Tests/QtAutogen/second_widget.cpp b/Tests/QtAutogen/complex/second_widget.cpp
index c575f10..c575f10 100644
--- a/Tests/QtAutogen/second_widget.cpp
+++ b/Tests/QtAutogen/complex/second_widget.cpp
diff --git a/Tests/QtAutogen/second_widget.h b/Tests/QtAutogen/complex/second_widget.h
index c7929c4..c7929c4 100644
--- a/Tests/QtAutogen/second_widget.h
+++ b/Tests/QtAutogen/complex/second_widget.h
diff --git a/Tests/QtAutogen/second_widget.ui b/Tests/QtAutogen/complex/second_widget.ui
index 4effa58..4effa58 100644
--- a/Tests/QtAutogen/second_widget.ui
+++ b/Tests/QtAutogen/complex/second_widget.ui
diff --git a/Tests/QtAutogen/sub/bar.h b/Tests/QtAutogen/complex/sub/bar.h
index e4093f6..e4093f6 100644
--- a/Tests/QtAutogen/sub/bar.h
+++ b/Tests/QtAutogen/complex/sub/bar.h
diff --git a/Tests/QtAutogen/targetObjectsTest.cpp b/Tests/QtAutogen/complex/targetObjectsTest.cpp
index 766b775..766b775 100644
--- a/Tests/QtAutogen/targetObjectsTest.cpp
+++ b/Tests/QtAutogen/complex/targetObjectsTest.cpp
diff --git a/Tests/QtAutogen/test.qrc b/Tests/QtAutogen/complex/test.qrc
index c3d4e3c..c3d4e3c 100644
--- a/Tests/QtAutogen/test.qrc
+++ b/Tests/QtAutogen/complex/test.qrc
diff --git a/Tests/QtAutogen/widget1.ui b/Tests/QtAutogen/complex/widget1.ui
index 8fce81a..8fce81a 100644
--- a/Tests/QtAutogen/widget1.ui
+++ b/Tests/QtAutogen/complex/widget1.ui
diff --git a/Tests/QtAutogen/widget2.ui b/Tests/QtAutogen/complex/widget2.ui
index 1f411b9..1f411b9 100644
--- a/Tests/QtAutogen/widget2.ui
+++ b/Tests/QtAutogen/complex/widget2.ui
diff --git a/Tests/QtAutogen/xyz.cpp b/Tests/QtAutogen/complex/xyz.cpp
index e46c9d3..e46c9d3 100644
--- a/Tests/QtAutogen/xyz.cpp
+++ b/Tests/QtAutogen/complex/xyz.cpp
diff --git a/Tests/QtAutogen/xyz.h b/Tests/QtAutogen/complex/xyz.h
index 8b813fd..8b813fd 100644
--- a/Tests/QtAutogen/xyz.h
+++ b/Tests/QtAutogen/complex/xyz.h
diff --git a/Tests/QtAutogen/yaf.cpp b/Tests/QtAutogen/complex/yaf.cpp
index 70e26aa..70e26aa 100644
--- a/Tests/QtAutogen/yaf.cpp
+++ b/Tests/QtAutogen/complex/yaf.cpp
diff --git a/Tests/QtAutogen/yaf.h b/Tests/QtAutogen/complex/yaf.h
index f271061..f271061 100644
--- a/Tests/QtAutogen/yaf.h
+++ b/Tests/QtAutogen/complex/yaf.h
diff --git a/Tests/QtAutogen/yaf_p.h b/Tests/QtAutogen/complex/yaf_p.h
index ea5eed6..ea5eed6 100644
--- a/Tests/QtAutogen/yaf_p.h
+++ b/Tests/QtAutogen/complex/yaf_p.h
diff --git a/Tests/QtAutogen/rcconly.cpp b/Tests/QtAutogen/rccEmpty.cpp
index 854c4c1..7f2c527 100644
--- a/Tests/QtAutogen/rcconly.cpp
+++ b/Tests/QtAutogen/rccEmpty.cpp
@@ -1,9 +1,9 @@
-extern int qInitResources_second_resource();
+extern int qInitResources_rccEmptyRes();
int main(int, char**)
{
// Fails to link if the symbol is not present.
- qInitResources_second_resource();
+ qInitResources_rccEmptyRes();
return 0;
}
diff --git a/Tests/QtAutogen/rcc_empty_resource.qrc b/Tests/QtAutogen/rccEmptyRes.qrc
index 4ca9cd5..4ca9cd5 100644
--- a/Tests/QtAutogen/rcc_empty_resource.qrc
+++ b/Tests/QtAutogen/rccEmptyRes.qrc
diff --git a/Tests/QtAutogen/rcc_empty.cpp b/Tests/QtAutogen/rccOnly.cpp
index 3f9f9a2..61c7bf4 100644
--- a/Tests/QtAutogen/rcc_empty.cpp
+++ b/Tests/QtAutogen/rccOnly.cpp
@@ -1,9 +1,9 @@
-extern int qInitResources_rcc_empty_resource();
+extern int qInitResources_rccOnlyRes();
int main(int, char**)
{
// Fails to link if the symbol is not present.
- qInitResources_rcc_empty_resource();
+ qInitResources_rccOnlyRes();
return 0;
}
diff --git a/Tests/QtAutogen/rccOnlyRes.qrc b/Tests/QtAutogen/rccOnlyRes.qrc
new file mode 100644
index 0000000..5551348
--- /dev/null
+++ b/Tests/QtAutogen/rccOnlyRes.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>rccOnly.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/sub/uiconly.cpp b/Tests/QtAutogen/uicOnlySource/uiconly.cpp
index ac22789..ac22789 100644
--- a/Tests/QtAutogen/sub/uiconly.cpp
+++ b/Tests/QtAutogen/uicOnlySource/uiconly.cpp
diff --git a/Tests/QtAutogen/sub/uiconly.h b/Tests/QtAutogen/uicOnlySource/uiconly.h
index 9b0b1b4..9b0b1b4 100644
--- a/Tests/QtAutogen/sub/uiconly.h
+++ b/Tests/QtAutogen/uicOnlySource/uiconly.h
diff --git a/Tests/QtAutogen/sub/uiconly.ui b/Tests/QtAutogen/uicOnlySource/uiconly.ui
index 13fb832..13fb832 100644
--- a/Tests/QtAutogen/sub/uiconly.ui
+++ b/Tests/QtAutogen/uicOnlySource/uiconly.ui
diff --git a/Tests/RunCMake/Android/common.cmake b/Tests/RunCMake/Android/common.cmake
index d803c98..bef2428 100644
--- a/Tests/RunCMake/Android/common.cmake
+++ b/Tests/RunCMake/Android/common.cmake
@@ -22,8 +22,23 @@ string(APPEND CMAKE_CXX_FLAGS " -Werror -Wno-attributes")
string(APPEND CMAKE_EXE_LINKER_FLAGS " -Wl,-no-undefined")
if(CMAKE_ANDROID_NDK)
- if(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION MATCHES "clang")
+ if(NOT CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION)
+ message(SEND_ERROR "CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION is not set!")
+ elseif(CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION MATCHES "^clang")
add_definitions(-DCOMPILER_IS_CLANG)
+ elseif(NOT "${CMAKE_C_COMPILER}" MATCHES "toolchains/[^/]+-${CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION}/prebuilt")
+ message(SEND_ERROR "CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION is\n"
+ " ${CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION}\n"
+ "which does not appear in CMAKE_C_COMPILER:\n"
+ " ${CMAKE_C_COMPILER}")
+ endif()
+ if(NOT CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG)
+ message(SEND_ERROR "CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG is not set!")
+ elseif(NOT "${CMAKE_C_COMPILER}" MATCHES "prebuilt/${CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG}/bin")
+ message(SEND_ERROR "CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG is\n"
+ " ${CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG}\n"
+ "which does not appear in CMAKE_C_COMPILER:\n"
+ " ${CMAKE_C_COMPILER}")
endif()
elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
execute_process(
@@ -37,6 +52,23 @@ elseif(CMAKE_ANDROID_STANDALONE_TOOLCHAIN)
endif()
endif()
+execute_process(
+ COMMAND "${CMAKE_C_ANDROID_TOOLCHAIN_PREFIX}gcc${CMAKE_C_ANDROID_TOOLCHAIN_SUFFIX}" -dumpmachine
+ OUTPUT_VARIABLE _out OUTPUT_STRIP_TRAILING_WHITESPACE
+ ERROR_VARIABLE _err
+ RESULT_VARIABLE _res
+ )
+if(NOT _res EQUAL 0)
+ message(SEND_ERROR "Failed to run 'gcc -dumpmachine':\n ${_res}")
+endif()
+if(NOT _out STREQUAL "${CMAKE_C_ANDROID_TOOLCHAIN_MACHINE}")
+ message(SEND_ERROR "'gcc -dumpmachine' produced:\n"
+ " ${_out}\n"
+ "which is not equal to CMAKE_C_ANDROID_TOOLCHAIN_MACHINE:\n"
+ " ${CMAKE_C_ANDROID_TOOLCHAIN_MACHINE}"
+ )
+endif()
+
if(CMAKE_ANDROID_STL_TYPE STREQUAL "none")
add_definitions(-DSTL_NONE)
elseif(CMAKE_ANDROID_STL_TYPE STREQUAL "system")
diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt
index 9dc540f..c02b917 100644
--- a/Tests/RunCMake/CMakeLists.txt
+++ b/Tests/RunCMake/CMakeLists.txt
@@ -179,6 +179,9 @@ add_RunCMake_test(add_custom_target)
add_RunCMake_test(add_dependencies)
add_RunCMake_test(add_subdirectory)
add_RunCMake_test(build_command)
+if(NOT CMake_TEST_EXTERNAL_CMAKE)
+ set(execute_process_ARGS -DTEST_ENCODING_EXE=$<TARGET_FILE:testEncoding>)
+endif()
add_RunCMake_test(execute_process)
add_RunCMake_test(export)
add_RunCMake_test(cmake_minimum_required)
diff --git a/Tests/RunCMake/CPack/CMakeLists.txt b/Tests/RunCMake/CPack/CMakeLists.txt
index e42e971..c361af0 100644
--- a/Tests/RunCMake/CPack/CMakeLists.txt
+++ b/Tests/RunCMake/CPack/CMakeLists.txt
@@ -1,12 +1,17 @@
cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
+set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "")
+
project(${RunCMake_TEST} CXX)
-include(${RunCMake_TEST_FILE_PREFIX}.cmake)
-# include test generator specifics
-if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-specifics.cmake")
- include("${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-specifics.cmake")
+if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${GENERATOR_TYPE}/packaging_${PACKAGING_TYPE}_default.cmake")
+ include(${GENERATOR_TYPE}/packaging_${PACKAGING_TYPE}_default.cmake)
endif()
+# set default test name (can be overwritten in test.cmake or specifics.cmake)
+string(TOLOWER "${RunCMake_TEST_FILE_PREFIX}" CPACK_PACKAGE_NAME)
+
+include(tests/${RunCMake_TEST_FILE_PREFIX}/test.cmake)
+
set(CPACK_GENERATOR "${GENERATOR_TYPE}")
include(CPack)
diff --git a/Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake b/Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake
deleted file mode 100644
index 7210e7d..0000000
--- a/Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(CPACK_COMPONENTS_ALL test)
-install(DIRECTORY DESTINATION empty
- COMPONENT test)
-
-set(CPACK_PACKAGE_NAME "components_empty_dir")
diff --git a/Tests/RunCMake/CPack/CPackTestHelpers.cmake b/Tests/RunCMake/CPack/CPackTestHelpers.cmake
index 7e6b4b1..89da610 100644
--- a/Tests/RunCMake/CPack/CPackTestHelpers.cmake
+++ b/Tests/RunCMake/CPack/CPackTestHelpers.cmake
@@ -1,6 +1,6 @@
cmake_policy(SET CMP0057 NEW)
-function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
+function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source PACKAGING_TYPE)
if(TEST_TYPE IN_LIST types)
set(RunCMake_TEST_NO_CLEAN TRUE)
set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${TEST_NAME}-build")
@@ -11,16 +11,17 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
set(full_test_name_ "${full_test_name_}-${SUBTEST_SUFFIX}-subtest")
endif()
+ string(APPEND full_test_name_ "-${PACKAGING_TYPE}-type")
+
# TODO this should be executed only once per ctest run (not per generator)
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
- if(EXISTS "${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-Prerequirements.cmake")
- include("${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-Prerequirements.cmake")
+ if(EXISTS "${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-Prerequirements.cmake")
+ include("${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-Prerequirements.cmake")
set(FOUND_PREREQUIREMENTS false)
- get_test_prerequirements("FOUND_PREREQUIREMENTS"
- "${TEST_CONFIG_DIR}/${type}_config.cmake")
+ get_test_prerequirements("FOUND_PREREQUIREMENTS" "${config_file}")
# skip the test if prerequirements are not met
if(NOT FOUND_PREREQUIREMENTS)
@@ -32,7 +33,8 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
# execute cmake
set(RunCMake_TEST_OPTIONS "-DGENERATOR_TYPE=${TEST_TYPE}"
"-DRunCMake_TEST_FILE_PREFIX=${TEST_NAME}"
- "-DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}")
+ "-DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}"
+ "-DPACKAGING_TYPE=${PACKAGING_TYPE}")
run_cmake(${full_test_name_})
# execute optional build step
@@ -43,7 +45,7 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
if(source)
set(pack_params_ -G ${TEST_TYPE} --config ./CPackSourceConfig.cmake)
FILE(APPEND ${RunCMake_TEST_BINARY_DIR}/CPackSourceConfig.cmake
- "\nset(CPACK_RPM_SOURCE_PKG_BUILD_PARAMS \"-DRunCMake_TEST:STRING=${full_test_name_}\ -DRunCMake_TEST_FILE_PREFIX:STRING=${TEST_NAME}\")")
+ "\nset(CPACK_RPM_SOURCE_PKG_BUILD_PARAMS \"-DRunCMake_TEST:STRING=${full_test_name_} -DRunCMake_TEST_FILE_PREFIX:STRING=${TEST_NAME} -DGENERATOR_TYPE:STRING=${TEST_TYPE}\")")
else()
unset(pack_params_)
endif()
@@ -58,10 +60,12 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
)
foreach(o out err)
- if(SUBTEST_SUFFIX AND EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-${SUBTEST_SUFFIX}-std${o}.txt)
- set(RunCMake-std${o}-file "${TEST_TYPE}/${TEST_NAME}-${SUBTEST_SUFFIX}-std${o}.txt")
- elseif(EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-std${o}.txt)
- set(RunCMake-std${o}-file "${TEST_TYPE}/${TEST_NAME}-std${o}.txt")
+ if(SUBTEST_SUFFIX AND EXISTS ${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-${SUBTEST_SUFFIX}-std${o}.txt)
+ set(RunCMake-std${o}-file "tests/${TEST_NAME}/${TEST_TYPE}-${SUBTEST_SUFFIX}-std${o}.txt")
+ elseif(EXISTS ${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-std${o}.txt)
+ set(RunCMake-std${o}-file "tests/${TEST_NAME}/${TEST_TYPE}-std${o}.txt")
+ elseif(EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/default_expected_std${o}.txt)
+ set(RunCMake-std${o}-file "${TEST_TYPE}/default_expected_std${o}.txt")
endif()
endforeach()
@@ -73,6 +77,7 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
-DRunCMake_TEST_FILE_PREFIX=${TEST_NAME}
-DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}
-DGENERATOR_TYPE=${TEST_TYPE}
+ -DPACKAGING_TYPE=${PACKAGING_TYPE}
"-Dsrc_dir=${RunCMake_SOURCE_DIR}"
"-Dbin_dir=${RunCMake_TEST_BINARY_DIR}"
"-Dconfig_file=${config_file}"
@@ -81,16 +86,20 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
endif()
endfunction()
-function(run_cpack_test TEST_NAME types build)
- run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" false)
-endfunction()
-
-function(run_cpack_source_test TEST_NAME types build)
- run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" true)
+function(run_cpack_test TEST_NAME types build PACKAGING_TYPES)
+ foreach(packaging_type_ IN LISTS PACKAGING_TYPES)
+ run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" false "${packaging_type_}")
+ endforeach()
endfunction()
-function(run_cpack_test_subtests TEST_NAME SUBTEST_SUFFIXES types build)
+function(run_cpack_test_subtests TEST_NAME SUBTEST_SUFFIXES types build PACKAGING_TYPES)
foreach(suffix_ IN LISTS SUBTEST_SUFFIXES)
- run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "${suffix_}" false)
+ foreach(packaging_type_ IN LISTS PACKAGING_TYPES)
+ run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "${suffix_}" false "${packaging_type_}")
+ endforeach()
endforeach()
endfunction()
+
+function(run_cpack_source_test TEST_NAME types)
+ run_cpack_test_common_("${TEST_NAME}" "${types}" false "" true "")
+endfunction()
diff --git a/Tests/RunCMake/CPack/CUSTOM_NAMES.cmake b/Tests/RunCMake/CPack/CUSTOM_NAMES.cmake
deleted file mode 100644
index c89df89..0000000
--- a/Tests/RunCMake/CPack/CUSTOM_NAMES.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
-
-set(CPACK_PACKAGE_NAME "custom_names")
diff --git a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 62f2f9c..0000000
--- a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "components_empty_dir-test_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/empty/$")
diff --git a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake
deleted file mode 100644
index 2acf45b..0000000
--- a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "custom_names-pkg_1_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "second*.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "pkg_3_abc.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake b/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake
deleted file mode 100644
index c64f161..0000000
--- a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake
+++ /dev/null
@@ -1,6 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-set(CPACK_DEBIAN_PKG_2_PACKAGE_NAME "second")
-set(CPACK_DEBIAN_PKG_3_FILE_NAME "pkg_3_abc.deb")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake
deleted file mode 100644
index 4531a34..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "deb_extra-foo_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "deb_extra-bar_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/${whitespaces_}.*/usr/bar/${whitespaces_}.*/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "deb_extra-bas_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/${whitespaces_}.*/usr/bas/${whitespaces_}.*/usr/bas/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake
deleted file mode 100644
index b98065a..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-function(get_test_prerequirements found_var)
- find_program(READELF_EXECUTABLE NAMES readelf)
-
- if(READELF_EXECUTABLE)
- set(${found_var} true PARENT_SCOPE)
- endif()
-endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake
deleted file mode 100644
index b98065a..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-function(get_test_prerequirements found_var)
- find_program(READELF_EXECUTABLE NAMES readelf)
-
- if(READELF_EXECUTABLE)
- set(${found_var} true PARENT_SCOPE)
- endif()
-endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake
deleted file mode 100644
index a6f08fe..0000000
--- a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,14 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "5")
-set(EXPECTED_FILE_1 "dependencies-0.1.1-*-applications.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/test_prog$")
-set(EXPECTED_FILE_2 "dependencies-0.1.1-*-applications_auto.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/foo_auto${whitespaces_}.*/usr/foo_auto/test_prog$")
-set(EXPECTED_FILE_3 "dependencies-0.1.1-*-headers.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/bar${whitespaces_}.*/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_4 "dependencies-0.1.1-*-libs.deb")
-# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
-set(EXPECTED_FILE_CONTENT_4 "^.*/usr/bas${whitespaces_}.*/usr/bas/libtest_lib\\..*$")
-set(EXPECTED_FILE_5 "dependencies-0.1.1-*-libs_auto.deb")
-set(EXPECTED_FILE_CONTENT_5 "^.*/usr/bas_auto${whitespaces_}.*/usr/bas_auto/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake b/Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake
deleted file mode 100644
index ba39f2e..0000000
--- a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake
+++ /dev/null
@@ -1,34 +0,0 @@
-function(checkDependencies_ FILE REGEX)
- set(whitespaces_ "[\t\n\r ]*")
-
- getPackageInfo("${FILE}" "FILE_INFO_")
- if(NOT FILE_INFO_ MATCHES "${REGEX}")
- message(FATAL_ERROR "Unexpected dependencies in '${FILE}'; file info: '${FILE_INFO_}'")
- endif()
-endfunction()
-
-foreach(dependency_type_ DEPENDS CONFLICTS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
- string(TOLOWER "${dependency_type_}" lower_dependency_type_)
- string(SUBSTRING ${lower_dependency_type_} 1 -1 lower_dependency_type_tail_)
- string(SUBSTRING ${dependency_type_} 0 1 dependency_type_head_)
- set(dependency_type_name_ "${dependency_type_head_}${lower_dependency_type_tail_}")
-
- checkDependencies_("${FOUND_FILE_1}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
- checkDependencies_("${FOUND_FILE_2}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}.*${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
- checkDependencies_("${FOUND_FILE_3}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-headers.*")
- checkDependencies_("${FOUND_FILE_4}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
- checkDependencies_("${FOUND_FILE_5}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
-endforeach()
-
-checkDependencies_("${FOUND_FILE_1}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
-checkDependencies_("${FOUND_FILE_2}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
-checkDependencies_("${FOUND_FILE_3}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
-checkDependencies_("${FOUND_FILE_4}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib.*")
-checkDependencies_("${FOUND_FILE_5}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib_auto.*, provided-lib_auto-b.*")
-
-# PREDEPENDS
-checkDependencies_("${FOUND_FILE_1}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-application, predepends-application-b.*")
-checkDependencies_("${FOUND_FILE_2}" ".*Pre-Depends${whitespaces_}:${whitespaces_}.*predepends-application, predepends-application-b.*")
-checkDependencies_("${FOUND_FILE_3}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-headers.*")
-checkDependencies_("${FOUND_FILE_4}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
-checkDependencies_("${FOUND_FILE_5}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
diff --git a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake b/Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake
deleted file mode 100644
index 5f82cc6..0000000
--- a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake
+++ /dev/null
@@ -1,23 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-#intentionaly commented out to test old file naming
-#set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-# false by default
-set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS FALSE)
-# FIXME can not be tested as libraries first have to be part of a package in order
-# to determine their dependencies and we can not be certain if there will be any
-set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_SHLIBDEPS TRUE)
-
-foreach(dependency_type_ DEPENDS CONFLICTS PREDEPENDS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
- string(TOLOWER "${dependency_type_}" lower_dependency_type_)
-
- set(CPACK_DEBIAN_PACKAGE_${dependency_type_} "${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b")
- set(CPACK_DEBIAN_APPLICATIONS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
- set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
- set(CPACK_DEBIAN_HEADERS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-headers")
-endforeach()
-
-set(CPACK_DEBIAN_PACKAGE_PROVIDES "provided-default, provided-default-b")
-set(CPACK_DEBIAN_LIBS_PACKAGE_PROVIDES "provided-lib")
-set(CPACK_DEBIAN_LIBS_AUTO_PACKAGE_PROVIDES "provided-lib_auto, provided-lib_auto-b")
diff --git a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 6dc5906..0000000
--- a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "empty_dir_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/empty/$")
diff --git a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake
deleted file mode 100644
index 4e9a2e7..0000000
--- a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake
+++ /dev/null
@@ -1,2 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
diff --git a/Tests/RunCMake/CPack/DEB/Helpers.cmake b/Tests/RunCMake/CPack/DEB/Helpers.cmake
index 9b1be22..ad1b47b 100644
--- a/Tests/RunCMake/CPack/DEB/Helpers.cmake
+++ b/Tests/RunCMake/CPack/DEB/Helpers.cmake
@@ -9,6 +9,47 @@ function(getPackageContent FILE RESULT_VAR)
set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
endfunction()
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+ if(COMPONENT)
+ set(COMPONENT "-${COMPONENT}")
+ endif()
+
+ if(DEFINED EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT)
+ set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT}")
+ elseif(DEFINED EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT)
+ set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT}")
+ else()
+ set(GENERATOR_SPECIFIC_FORMAT FALSE)
+ endif()
+
+ if(GENERATOR_SPECIFIC_FORMAT)
+ set(${RESULT_VAR} "${NAME}${COMPONENT}_${VERSION}-${REVISION}_*.deb" PARENT_SCOPE)
+ else()
+ set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.deb" PARENT_SCOPE)
+ endif()
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+ execute_process(COMMAND ${DPKG_EXECUTABLE} -c "${FILE}"
+ OUTPUT_VARIABLE package_content_
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ unset(items_)
+ string(REPLACE "\n" ";" package_content_ "${package_content_}")
+ foreach(i_ IN LISTS package_content_)
+ string(REGEX REPLACE "^.* \.(/[^$]*)$" "\\1" result_ "${i_}")
+ string(REGEX REPLACE "/$" "" result_ "${result_}")
+ list(APPEND items_ "${result_}")
+ endforeach()
+
+ set(${RESULT_VAR} "${items_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+ # no need to do anything
+endfunction()
+
function(getMissingShlibsErrorExtra FILE RESULT_VAR)
execute_process(COMMAND ${DPKG_EXECUTABLE} -x "${FILE}" data_${PREFIX}
ERROR_VARIABLE err_)
@@ -43,8 +84,6 @@ function(getMissingShlibsErrorExtra FILE RESULT_VAR)
string(APPEND error_extra "; errors \"${deb_install_files_errors}\"")
endif()
- find_program(READELF_EXECUTABLE NAMES readelf)
-
if(READELF_EXECUTABLE)
string(APPEND error_extra "; readelf \"\n")
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake
deleted file mode 100644
index dd72cf7..0000000
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "long_filenames_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake
deleted file mode 100644
index 0c1d77e..0000000
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-function(get_test_prerequirements found_var)
- find_program(FAKEROOT_EXECUTABLE NAMES fakeroot)
-
- if(FAKEROOT_EXECUTABLE)
- set(${found_var} true PARENT_SCOPE)
- endif()
-endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake
deleted file mode 100644
index 39a6be4..0000000
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
diff --git a/Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake
deleted file mode 100644
index 648c866..0000000
--- a/Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "minimal_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake b/Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake
deleted file mode 100644
index 4e9a2e7..0000000
--- a/Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake
+++ /dev/null
@@ -1,2 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
diff --git a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
deleted file mode 100644
index 40f6730..0000000
--- a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "per_component-pkg_1_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "second_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "per_component-pkg_3_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake b/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake
deleted file mode 100644
index 55293be..0000000
--- a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake
+++ /dev/null
@@ -1,18 +0,0 @@
-function(checkPackageInfo_ TYPE FILE REGEX)
- set(whitespaces_ "[\t\n\r ]*")
-
- getPackageInfo("${FILE}" "FILE_INFO_")
- if(NOT FILE_INFO_ MATCHES "${REGEX}")
- message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}'; file info: '${FILE_INFO_}'")
- endif()
-endfunction()
-
-# check package name
-checkPackageInfo_("name" "${FOUND_FILE_1}" ".*Package${whitespaces_}:${whitespaces_}per_component-pkg_1")
-checkPackageInfo_("name" "${FOUND_FILE_2}" ".*Package${whitespaces_}:${whitespaces_}second")
-checkPackageInfo_("name" "${FOUND_FILE_3}" ".*Package${whitespaces_}:${whitespaces_}per_component-pkg_3")
-
-# check package group
-checkPackageInfo_("group" "${FOUND_FILE_1}" ".*Section${whitespaces_}:${whitespaces_}default")
-checkPackageInfo_("group" "${FOUND_FILE_2}" ".*Section${whitespaces_}:${whitespaces_}second_group")
-checkPackageInfo_("group" "${FOUND_FILE_3}" ".*Section${whitespaces_}:${whitespaces_}default")
diff --git a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake b/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake
deleted file mode 100644
index 25bd2e7..0000000
--- a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-set(CPACK_DEBIAN_PACKAGE_SECTION "default")
-set(CPACK_DEBIAN_PKG_2_PACKAGE_NAME "second")
-set(CPACK_DEBIAN_PKG_2_PACKAGE_SECTION "second_group")
diff --git a/Tests/RunCMake/CPack/DEB/Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
index cb9a277..60d02e7 100644
--- a/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
+++ b/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
@@ -12,4 +12,11 @@ function(get_test_prerequirements found_var config_file)
file(APPEND "${config_file}"
"\nset(FAKEROOT_EXECUTABLE \"${FAKEROOT_EXECUTABLE}\")")
endif()
+
+ # optional tool for some tests
+ find_program(READELF_EXECUTABLE NAMES readelf)
+ if(READELF_EXECUTABLE)
+ file(APPEND "${config_file}"
+ "\nset(READELF_EXECUTABLE \"${READELF_EXECUTABLE}\")")
+ endif()
endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/DEB/packaging_COMPONENT_default.cmake
index 4b4ac8d..4219b0c 100644
--- a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake
+++ b/Tests/RunCMake/CPack/DEB/packaging_COMPONENT_default.cmake
@@ -1,3 +1,2 @@
-set(CPACK_PACKAGE_CONTACT "someone")
set(CPACK_DEB_COMPONENT_INSTALL "ON")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
+set(CPACK_PACKAGE_CONTACT "someone")
diff --git a/Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake b/Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake
new file mode 100644
index 0000000..8821ab9
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake
@@ -0,0 +1 @@
+set(CPACK_PACKAGE_CONTACT "someone")
diff --git a/Tests/RunCMake/CPack/DEPENDENCIES.cmake b/Tests/RunCMake/CPack/DEPENDENCIES.cmake
deleted file mode 100644
index 4f6d65f..0000000
--- a/Tests/RunCMake/CPack/DEPENDENCIES.cmake
+++ /dev/null
@@ -1,20 +0,0 @@
-set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
- "int test_lib();\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
- "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
-add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
- "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
-add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
-target_link_libraries(test_prog test_lib)
-
-install(TARGETS test_prog DESTINATION foo COMPONENT applications)
-install(TARGETS test_prog DESTINATION foo_auto COMPONENT applications_auto)
-install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
-install(TARGETS test_lib DESTINATION bas COMPONENT libs)
-install(TARGETS test_lib DESTINATION bas_auto COMPONENT libs_auto)
-
-set(CPACK_PACKAGE_NAME "dependencies")
diff --git a/Tests/RunCMake/CPack/EMPTY_DIR.cmake b/Tests/RunCMake/CPack/EMPTY_DIR.cmake
deleted file mode 100644
index 023ba17..0000000
--- a/Tests/RunCMake/CPack/EMPTY_DIR.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-install(DIRECTORY DESTINATION empty
- COMPONENT test)
-
-set(CPACK_PACKAGE_NAME "empty_dir")
diff --git a/Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake b/Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake
deleted file mode 100644
index bb42cf4..0000000
--- a/Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
-
-set(CPACK_PACKAGE_NAME "per_component")
diff --git a/Tests/RunCMake/CPack/README.txt b/Tests/RunCMake/CPack/README.txt
index 5c86880..f51d254 100644
--- a/Tests/RunCMake/CPack/README.txt
+++ b/Tests/RunCMake/CPack/README.txt
@@ -1,41 +1,75 @@
RunCMake.CPack is a test module that is intended for testing of package
generators that can be validated from command line.
-TODO: all tests should cover all packaging types (single package, grouped and
- component packaging)
-
-------------
Adding a test
-------------
-CPack test root directory: 'Tests/RunCMake/CPack'.
+CPack test root directory: 'Tests/RunCMake/CPack/tests'.
All phases are executed separately for each generator that is bound to a test.
Tests for each generator are subtests of test 'RunCMake.CPack_<generator_name>'.
Each test must also be added to 'RunCMakeTest.cmake' script located in CPack
test root directory.
+
Line that adds a test is:
-run_cpack_test(<test_name> "<generator_name>")
+run_cpack_test(<test_name> "<generator_name_list>" <compile_stage>
+ "<packaging_type_list>")
+
+<generator_name_list> may be one generator e.g. "RPM" or multiple e.g. "RPM;DEB"
+and will be run for all listed generators. In test and verification scripts
+current generator can be accessed through GENERATOR_TYPE variable.
+
+<compile_stage> is a boolean variable that enables or disables compile stage -
+most tests don't require compilation as a non binary file can be used for
+package content but sometimes an executable or a library has to be created
+before the packaging stage.
-<generator_name> may be one generator e.g. "RPM" or multiple e.g. "RPM;DEB" and
-will be run for all listed generators.
+<packaging_type_list> can be a list of one or more packaging types: MONOLITHIC,
+COMPONENT or GROUP - each type sets per generator default variables which can
+be overwritten in the test if needed
+(see <generator_type>/packaging_<packaging_type>_default.cmake for the variables
+that are set by default for each packaging type).
+Alternatively CUSTOM value can be set which means that default values will not
+be set and that values will be set manually in the test itself.
+
+Alternatively a test with subtests can be added:
+run_cpack_test_subtests(<test_name> "<subtests_list>" "<generator_name_list>"
+ <compile_stage> "<packaging_type_list>")
+
+<subtests_list> is the only new parameter and it is a list of names that will
+be used for subtests. In test and verification scripts subtest name can be
+accessed through RunCMake_SUBTEST_SUFFIX variable.
+
+Also source package tests can be added:
+run_cpack_source_test(<test_name> "<generator_name_list>" true)
Test consists of
- test prerequirements phase (optional)
- CMake execution phase
+- build phase (optional and not available for source package tests)
- CPack execution phase
- verification of generated files
+The phases are executed once per specified generator, packaging type and subtest
+combinatiion.
+
test prerequirements phase (optional):
--------------------------------------
In some cases individual tests for certain generator need additional
prerequirements met.
-In such cases '<generator_name>/<test_name>-Prerequirements.cmake' file
-containing 'function(get_test_prerequirements found_var)' should be created.
-Function should return true if all prerequirements are met.
+In such cases '<test_name>/<generator_name>-Prerequirements.cmake' file
+containing 'function(get_test_prerequirements found_var config_file)' should be
+created. Function should return true in found_var if all prerequirements are
+met. config_file variable contains the location of config file generated by the
+generator so that this function can check if prerequired variable is set in the
+file.
+NOTE: All required programs should be searched for in generator prerequirements
+function and only checked for the variable in configure file in per test
+function.
If prerequirements are not met test will be skipped outputting
'<test_name> - SKIPPED' string. Note that this doesn't fail the entire test
@@ -48,15 +82,21 @@ TODO: skipped tests should provide expected error string so test should fail
CMake execution phase:
----------------------
-To add a new CPack test we first create a <test_name>.cmake script that contains
-CMake commands that should be used as a preparation script for generation of
-different types of packages. This script is placed into CPack test root
-directory even if it will be used for only one of the generators.
+To add a new CPack test we first create a '<test_name>/test.cmake' script that
+contains CMake commands that should be used as a preparation script for
+generation of different types of packages. This script is placed into CPack
+test root directory.
If test will be used for multiple generators but some of them require some
-generator specific commands then those commands should be added to a separate
-file that should be located in '<generator_name>/<test_name>-specifics.cmake'
-in CPack test root directory.
+generator specific commands then those commands should be added to 'test.cmake'
+script wrapped with 'if(GENERATOR_TYPE STREQUAL <name_of_the_generator>)'.
+
+build phase (optional and not available for source package tests)
+-----------------------------------------------------------------
+
+This phase only runs make command.
+
+NOTE: By default all tests have CMAKE_BUILD_TYPE variable set to Debug.
CPack execution phase:
----------------------
@@ -64,6 +104,8 @@ CPack execution phase:
Only executes CPack for content that was generated during CMake execution
phase.
+NOTE: By default CPACK_PACKAGE_NAME variable is set to lower case test name.
+
Verification of generated files:
--------------------------------
@@ -76,24 +118,49 @@ contain expected files.
Mandatory verification phase also checks that no other unexpected package files
were generated (this is executed even if EXPECTED_FILES_COUNT contains 0 in
order to verify that no files were generated).
-CMake script '<generator_name>/<test_name>-ExpectedFiles.cmake' is required by
+CMake script '<test_name>/ExpectedFiles.cmake' is required by
this step and must contain
- EXPECTED_FILES_COUNT variable that contains the number of expected files that
will be generated (0 or more)
+
- EXPECTED_FILE_<file_number_starting_with_1> that contains globing expression
that uniquely defines expected file name (will be used to find expected file)
- and should be present once for each expected file
+ and should be present once for each expected file.
+ NOTE: This variable should be used only as last resort as it sets generator
+ specific globbing expression. Each generator can recreate file name from
+ parts that are already populated by default but can always be
+ overwritten if needed:
+ - EXPECTED_FILE_<file_number_starting_with_1>_NAME is the name component of
+ the file (by default it is set to package name that is same as test name
+ in lowercase)
+ - EXPECTED_FILE_<file_number_starting_with_1>_VERSION is the version of the
+ package (by default it is set to '0.1.1')
+ - EXPECTED_FILE_<file_number_starting_with_1>_REVISION is the revision of the
+ package (by default it is set to '1')
+
- EXPECTED_FILE_CONTENT_<file_number_starting_with_1> that contains regular
expression of files that should be present in generated file and should be
present once for each expected file
+ NOTE: This variable should be used only as last resort as it sets generator
+ specific regular expression.
+ EXPECTED_FILE_CONTENT_<file_number_starting_with_1>_LIST should be
+ prefered as it requires a list of expected files and directories that
+ is later changed automatically depending on the generator so expected
+ package content can be written only once per test for all generators.
Optional verification phase is generator specific and is optionaly executed.
-This phase is executed if '<generator_name>/<test_name>-VerifyResult.cmake'
-script exists.
-In case that the script doesn't exist VerifyResult.cmake script automatically
-prints out standard output and standard error from CPack execution phase that
-is compared with '<generator_name>/<test_name>-stdout.txt' regular expression
-and '<generator_name>/<test_name>-stderr.txt' regular expresson respectively.
+This phase is executed if '<test_name>/VerifyResult.cmake' script exists.
+
+VerifyResult.cmake script also automatically prints out standard output and
+standard error from CPack execution phase that is compared with
+'<test_name>/<generator_name>-stdout.txt' regular expression and
+and '<test_name>/<generator_name>-stderr.txt' regular expresson respectively.
+NOTE: For subtests generator name can also be suffixed with subtest name and in
+ such case subtest file is preferred.
+ File name format: '<generator_name>-<subtest_name>-std<type>.txt' where
+ <type> can either be 'out' or 'err'.
+NOTE: If none of the comparison files are present then the default generator
+ file is used if present.
----------------------
Adding a new generator
@@ -101,13 +168,44 @@ Adding a new generator
To add a new generator we must
- add new generator directory (e.g. RPM for RPM generator) to CPack test root
- directory that contains 'Helpers.cmake' script. In this script a function
- named 'getPackageContent' must exist. This function should list files that
- are contained in a package. Function should accept two parameters
- + FILE variable that will contain path to file for which the content should be
- listed
- + RESULT_VAR that will tell the function which variable in parent scope should
- contain the result (list of files inside package file)
+ directory that contains 'Helpers.cmake' script.
+ - In this script some functions must exist:
+ - getPackageContent: This function should list files that are contained in
+ a package.
+ Function parameters:
+ + FILE variable that will contain path to file for which the content
+ should be listed
+ + RESULT_VAR that will tell the function which variable in parent scope
+ should contain the result (list of files inside package file)
+ - getPackageNameGlobexpr: This function should generate package name
+ globbing expression.
+ Function parameters:
+ + NAME that will contain the expected package name
+ + COMPONENT that will contain the expected package component
+ + VERSION that will contain the expected package version
+ + REVISION that will contain the expected package revision number
+ + FILE_NO that will contain the file number for which the globbing
+ expression is generated
+ + RESULT_VAR that will tell the function which variable in parent scope
+ should contain the result (file name globbing expression)
+ - getPackageContentList: This function should return a list of files and
+ directories that are in the provided package.
+ Function parameters:
+ + FILE that will contain the package file for which the package content
+ should be returned.
+ + RESULT_VAR that will tell the function which variable in parent scope
+ should contain the result (list of pacakge content)
+ - toExpectedContentList: This function should convert an expected package
+ content list into one that is expected for the
+ generator (e.g. rpm packages have install/relocate
+ path prefixes which aren't part of the package so
+ those paths have to be removed from the expected
+ content list).
+ Function parameters:
+ + FILE_NO that will contain the file number for which the conversion
+ should be performed
+ + CONTENT_VAR that will contain the input list and is also the variable
+ in parent scope which should contain the result (converted content list)
- add 'Prerequirements.cmake' script to generator directory. In this script a
function named 'get_test_prerequirements' must exist. This function should
set a variable in parent scope (name of the variable is the first parameter)
@@ -119,3 +217,9 @@ To add a new generator we must
- add tests the same way as described above
- add generator to 'add_RunCMake_test_group' function call that is located in
RunCMake CMakeLists.txt file
+- if needed add 'packaging_<packaging_type>_default.cmake' scripts that define
+ default variables that will be set for each packaging type (MONOLITHIC,
+ COMPONENT and GROUP)
+- if needed add 'default_expected_std<type>.txt' files where <type> is either
+ 'out' or 'err' which will contain default expected output of package
+ generation regular expression.
diff --git a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index d396276..0000000
--- a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "components_empty_dir*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/empty$")
diff --git a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt b/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt
deleted file mode 100644
index 6ddca12..0000000
--- a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/COMPONENTS_EMPTY_DIR-build/_CPack_Packages/.*/RPM/SPECS/components_empty_dir.spec$
diff --git a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake
deleted file mode 100644
index 780e57e..0000000
--- a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "custom_names-pkg_1*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "second*.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "pkg_3_abc.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake b/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake
deleted file mode 100644
index 575aa01..0000000
--- a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CPACK_RPM_FILE_NAME "RPM-DEFAULT")
-set(CPACK_RPM_PKG_2_PACKAGE_NAME "second")
-set(CPACK_RPM_PKG_3_FILE_NAME "pkg_3_abc.rpm")
diff --git a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt b/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt
deleted file mode 100644
index 9bfba7e..0000000
--- a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/CUSTOM_NAMES-build/_CPack_Packages/.*/RPM/SPECS/custom_names-pkg_1.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/CUSTOM_NAMES-build/_CPack_Packages/.*/RPM/SPECS/second.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/CUSTOM_NAMES-build/_CPack_Packages/.*/RPM/SPECS/custom_names-pkg_3.spec$
diff --git a/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake
deleted file mode 100644
index a583e32..0000000
--- a/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake
+++ /dev/null
@@ -1,14 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "5")
-set(EXPECTED_FILE_1 "debuginfo-applications-0*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
-set(EXPECTED_FILE_2 "debuginfo*-headers.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "debuginfo*-libs.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/bas${whitespaces_}/usr/bas/libtest_lib.so$")
-
-set(EXPECTED_FILE_4 "debuginfo-applications-debuginfo*.rpm")
-set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
-set(EXPECTED_FILE_5 "debuginfo-libs-debuginfo*.rpm")
-set(EXPECTED_FILE_CONTENT_5 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/test_lib.cpp.*")
diff --git a/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt b/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt
deleted file mode 100644
index 557ef3d..0000000
--- a/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-applications.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-headers.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-libs.spec$
diff --git a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake
deleted file mode 100644
index cf85dab..0000000
--- a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "5")
-set(EXPECTED_FILE_1 "dependencies*-applications.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
-set(EXPECTED_FILE_2 "dependencies*-applications_auto.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/foo_auto${whitespaces_}/usr/foo_auto/test_prog$")
-set(EXPECTED_FILE_3 "dependencies*-headers.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_4 "dependencies*-libs.rpm")
-set(EXPECTED_FILE_CONTENT_4 "^/usr/bas${whitespaces_}/usr/bas/libtest_lib.so$")
-set(EXPECTED_FILE_5 "dependencies*-libs_auto.rpm")
-set(EXPECTED_FILE_CONTENT_5 "^/usr/bas_auto${whitespaces_}/usr/bas_auto/libtest_lib.so$")
diff --git a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake b/Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake
deleted file mode 100644
index fec8889..0000000
--- a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake
+++ /dev/null
@@ -1,45 +0,0 @@
-function(checkDependencies_ FILE TYPE COMPARE_LIST)
- set(whitespaces_ "[\t\n\r ]*")
-
- execute_process(COMMAND ${RPM_EXECUTABLE} -qp --${TYPE} ${FILE}
- WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
- OUTPUT_VARIABLE FILE_DEPENDENCIES_
- ERROR_QUIET
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-
- string(REPLACE "\n" ";" FILE_DEPENDENCIES_LIST_ "${FILE_DEPENDENCIES_}")
-
- foreach(COMPARE_REGEX_ IN LISTS COMPARE_LIST)
- unset(FOUND_)
-
- foreach(COMPARE_ IN LISTS FILE_DEPENDENCIES_LIST_)
- if(COMPARE_ MATCHES "${COMPARE_REGEX_}")
- set(FOUND_ true)
- break()
- endif()
- endforeach()
-
- if(NOT FOUND_)
- message(FATAL_ERROR "Missing dependencies in '${FILE}'; check type: '${TYPE}'; file info: '${FILE_DEPENDENCIES_}'; missing: '${COMPARE_REGEX_}'")
- endif()
- endforeach()
-endfunction()
-
-# TODO add tests for what should not be present in lists
-checkDependencies_("${FOUND_FILE_1}" "requires" "depend-application;depend-application-b")
-checkDependencies_("${FOUND_FILE_2}" "requires" "depend-application;depend-application-b;libtest_lib\\.so.*")
-checkDependencies_("${FOUND_FILE_3}" "requires" "depend-headers")
-checkDependencies_("${FOUND_FILE_4}" "requires" "depend-default;depend-default-b")
-checkDependencies_("${FOUND_FILE_5}" "requires" "depend-default;depend-default-b")
-
-checkDependencies_("${FOUND_FILE_1}" "conflicts" "conflict-application;conflict-application-b")
-checkDependencies_("${FOUND_FILE_2}" "conflicts" "conflict-application;conflict-application-b")
-checkDependencies_("${FOUND_FILE_3}" "conflicts" "conflict-headers")
-checkDependencies_("${FOUND_FILE_4}" "conflicts" "conflict-default;conflict-default-b")
-checkDependencies_("${FOUND_FILE_5}" "conflicts" "conflict-default;conflict-default-b")
-
-checkDependencies_("${FOUND_FILE_1}" "provides" "provided-default;provided-default-b")
-checkDependencies_("${FOUND_FILE_2}" "provides" "provided-default;provided-default-b")
-checkDependencies_("${FOUND_FILE_3}" "provides" "provided-default;provided-default-b")
-checkDependencies_("${FOUND_FILE_4}" "provides" "provided-lib")
-checkDependencies_("${FOUND_FILE_5}" "provides" "provided-lib_auto;provided-lib_auto-b")
diff --git a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake b/Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake
deleted file mode 100644
index 8b7fb1e..0000000
--- a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake
+++ /dev/null
@@ -1,22 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-# FIXME auto autoprov is not tested at the moment as Ubuntu 15.04 rpmbuild
-# does not use them correctly: https://bugs.launchpad.net/rpm/+bug/1475755
-set(CPACK_RPM_PACKAGE_AUTOREQ "no")
-set(CPACK_RPM_PACKAGE_AUTOPROV "no")
-set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_AUTOREQPROV "yes")
-set(CPACK_RPM_LIBS_AUTO_PACKAGE_AUTOREQPROV "yes")
-
-set(CPACK_RPM_PACKAGE_REQUIRES "depend-default, depend-default-b")
-set(CPACK_RPM_APPLICATIONS_PACKAGE_REQUIRES "depend-application, depend-application-b")
-set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_REQUIRES "depend-application, depend-application-b")
-set(CPACK_RPM_HEADERS_PACKAGE_REQUIRES "depend-headers")
-
-set(CPACK_RPM_PACKAGE_CONFLICTS "conflict-default, conflict-default-b")
-set(CPACK_RPM_APPLICATIONS_PACKAGE_CONFLICTS "conflict-application, conflict-application-b")
-set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_CONFLICTS "conflict-application, conflict-application-b")
-set(CPACK_RPM_HEADERS_PACKAGE_CONFLICTS "conflict-headers")
-
-set(CPACK_RPM_PACKAGE_PROVIDES "provided-default, provided-default-b")
-set(CPACK_RPM_LIBS_PACKAGE_PROVIDES "provided-lib")
-set(CPACK_RPM_LIBS_AUTO_PACKAGE_PROVIDES "provided-lib_auto, provided-lib_auto-b")
diff --git a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 0c2977f..0000000
--- a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "empty_dir*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/empty$")
diff --git a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt b/Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt
deleted file mode 100644
index 1777aa0..0000000
--- a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/EMPTY_DIR-build/_CPack_Packages/.*/RPM/SPECS/empty_dir.spec$
diff --git a/Tests/RunCMake/CPack/RPM/Helpers.cmake b/Tests/RunCMake/CPack/RPM/Helpers.cmake
index ba77a4a..bbc358c8 100644
--- a/Tests/RunCMake/CPack/RPM/Helpers.cmake
+++ b/Tests/RunCMake/CPack/RPM/Helpers.cmake
@@ -9,6 +9,59 @@ function(getPackageContent FILE RESULT_VAR)
set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
endfunction()
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+ if(COMPONENT)
+ set(COMPONENT "-${COMPONENT}")
+ endif()
+
+ if(DEFINED EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT)
+ set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT}")
+ elseif(DEFINED EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT)
+ set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT}")
+ else()
+ set(GENERATOR_SPECIFIC_FORMAT FALSE)
+ endif()
+
+ if(GENERATOR_SPECIFIC_FORMAT)
+ set(${RESULT_VAR} "${NAME}${COMPONENT}-${VERSION}-${REVISION}.*.rpm" PARENT_SCOPE)
+ else()
+ set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.rpm" PARENT_SCOPE)
+ endif()
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+ execute_process(COMMAND ${RPM_EXECUTABLE} -pql ${FILE}
+ OUTPUT_VARIABLE package_content_
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REGEX REPLACE "\n" ";" package_content_ "${package_content_}")
+
+ set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+ if(NOT DEFINED TEST_INSTALL_PREFIX_PATHS)
+ set(TEST_INSTALL_PREFIX_PATHS "/usr")
+ endif()
+
+ unset(filtered_)
+ foreach(part_ IN LISTS ${CONTENT_VAR})
+ unset(dont_add_)
+ foreach(for_removal_ IN LISTS TEST_INSTALL_PREFIX_PATHS)
+ if(part_ STREQUAL for_removal_)
+ set(dont_add_ TRUE)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT dont_add_)
+ list(APPEND filtered_ "${part_}")
+ endif()
+ endforeach()
+
+ set(${CONTENT_VAR} "${filtered_}" PARENT_SCOPE)
+endfunction()
+
function(getPackageInfo FILE RESULT_VAR)
execute_process(COMMAND ${RPM_EXECUTABLE} -pqi ${FILE}
OUTPUT_VARIABLE info_content
diff --git a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake
deleted file mode 100644
index 033a45d..0000000
--- a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "2")
-set(EXPECTED_FILE_1 "install_scripts*-foo.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "install_scripts*-bar.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake b/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake
deleted file mode 100644
index 4eb53c3..0000000
--- a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake
+++ /dev/null
@@ -1,19 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CPACK_RPM_PRE_INSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/pre_install.sh")
-set(CPACK_RPM_POST_INSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/post_install.sh")
-set(CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall.sh")
-set(CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall.sh")
-
-set(CPACK_RPM_foo_PRE_INSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/pre_install_foo.sh")
-set(CPACK_RPM_foo_POST_INSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/post_install_foo.sh")
-set(CPACK_RPM_foo_PRE_UNINSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall_foo.sh")
-set(CPACK_RPM_foo_POST_UNINSTALL_SCRIPT_FILE
- "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh")
diff --git a/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-ExpectedFiles.cmake
deleted file mode 100644
index 69603dd..0000000
--- a/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-ExpectedFiles.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "0")
-
-if(NOT RunCMake_SUBTEST_SUFFIX STREQUAL "invalid")
- set(EXPECTED_FILES_COUNT "3")
- set(EXPECTED_FILE_1 "main_component-0.1.1-1.*.rpm")
- set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
- set(EXPECTED_FILE_2 "main_component*-headers.rpm")
- set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
- set(EXPECTED_FILE_3 "main_component*-libs.rpm")
- set(EXPECTED_FILE_CONTENT_3 "^/usr/bas${whitespaces_}/usr/bas/CMakeLists.txt$")
-endif()
diff --git a/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-found-stderr.txt b/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-found-stderr.txt
deleted file mode 100644
index dff163d..0000000
--- a/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-found-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/MAIN_COMPONENT-build-found-subtest/_CPack_Packages/.*/RPM/SPECS/main_component-headers.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/MAIN_COMPONENT-build-found-subtest/_CPack_Packages/.*/RPM/SPECS/main_component-libs.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/MAIN_COMPONENT-build-found-subtest/_CPack_Packages/.*/RPM/SPECS/main_component.spec$
diff --git a/Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake
deleted file mode 100644
index 800b78e..0000000
--- a/Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "minimal*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt b/Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt
deleted file mode 100644
index 7c5fb46..0000000
--- a/Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/MINIMAL-build/_CPack_Packages/.*/RPM/SPECS/minimal.spec$
diff --git a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake
deleted file mode 100644
index 4e01f7b..0000000
--- a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "PARTIALLY_RELOCATABLE_WARNING-0.1.1-*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/not_relocatable${whitespaces_}/not_relocatable/CMakeLists.txt${whitespaces_}/opt$")
diff --git a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
deleted file mode 100644
index 3d28d41..0000000
--- a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "per_component*-pkg_1.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "per_component*-pkg_2.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "per_component*-pkg_3.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake b/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake
deleted file mode 100644
index d7d4f9d..0000000
--- a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake
+++ /dev/null
@@ -1,18 +0,0 @@
-function(checkPackageInfo_ TYPE FILE REGEX)
- set(whitespaces_ "[\t\n\r ]*")
-
- getPackageInfo("${FILE}" "FILE_INFO_")
- if(NOT FILE_INFO_ MATCHES "${REGEX}")
- message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}'; file info: '${FILE_INFO_}'")
- endif()
-endfunction()
-
-# check package name
-checkPackageInfo_("name" "${FOUND_FILE_1}" ".*Name${whitespaces_}:${whitespaces_}per_component-pkg_1")
-checkPackageInfo_("name" "${FOUND_FILE_2}" ".*Name${whitespaces_}:${whitespaces_}second")
-checkPackageInfo_("name" "${FOUND_FILE_3}" ".*Name${whitespaces_}:${whitespaces_}per_component-pkg_3")
-
-# check package group
-checkPackageInfo_("group" "${FOUND_FILE_1}" ".*Group${whitespaces_}:${whitespaces_}default")
-checkPackageInfo_("group" "${FOUND_FILE_2}" ".*Group${whitespaces_}:${whitespaces_}second_group")
-checkPackageInfo_("group" "${FOUND_FILE_3}" ".*Group${whitespaces_}:${whitespaces_}default")
diff --git a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake b/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake
deleted file mode 100644
index 524ef0c..0000000
--- a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CPACK_RPM_PACKAGE_GROUP "default")
-set(CPACK_RPM_PKG_2_PACKAGE_NAME "second")
-set(CPACK_RPM_PKG_2_PACKAGE_GROUP "second_group")
diff --git a/Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake
deleted file mode 100644
index 3b5a347..0000000
--- a/Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "rpm_dist*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_components-stderr.txt b/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_components-stderr.txt
deleted file mode 100644
index d80939f..0000000
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_components-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-no_components-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_debuginfo-stderr.txt b/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_debuginfo-stderr.txt
deleted file mode 100644
index 86396db..0000000
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_debuginfo-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-no_debuginfo-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo-headers.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-no_debuginfo-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo-libs.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-no_debuginfo-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component-stderr.txt b/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component-stderr.txt
deleted file mode 100644
index 080c4ff..0000000
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-one_component-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo-applications.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_main-stderr.txt b/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_main-stderr.txt
deleted file mode 100644
index 665597c..0000000
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_main-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-one_component_main-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_no_debuginfo-stderr.txt b/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_no_debuginfo-stderr.txt
deleted file mode 100644
index b64b1f5..0000000
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-one_component_no_debuginfo-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-one_component_no_debuginfo-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo-applications.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-valid-stderr.txt b/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-valid-stderr.txt
deleted file mode 100644
index f4c1bef..0000000
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-valid-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-valid-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo-headers.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-valid-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo-libs.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/SINGLE_DEBUGINFO-build-valid-subtest/_CPack_Packages/.*/RPM/SPECS/single_debuginfo.spec$
diff --git a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake
deleted file mode 100644
index d6811eb..0000000
--- a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "source_package*.src.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^source_package-0.1.1.tar.gz${whitespaces_}source_package.spec$")
diff --git a/Tests/RunCMake/CPack/RPM/default_expected_stderr.txt b/Tests/RunCMake/CPack/RPM/default_expected_stderr.txt
new file mode 100644
index 0000000..4a0e4e6
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/default_expected_stderr.txt
@@ -0,0 +1 @@
+^(CPackRPM: Will use GENERATED spec file: (/[^/]*)*/Tests/RunCMake/RPM/CPack/[^-]*-build((-[^-]*-subtest/)|/)_CPack_Packages/.*/RPM/SPECS/[^\.]*\.spec(\n|$))*$
diff --git a/Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake b/Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake
new file mode 100644
index 0000000..c8b93e9
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake
@@ -0,0 +1 @@
+set(CPACK_RPM_COMPONENT_INSTALL "ON")
diff --git a/Tests/RunCMake/CPack/RunCMakeTest.cmake b/Tests/RunCMake/CPack/RunCMakeTest.cmake
index 474ee33..092fb47 100644
--- a/Tests/RunCMake/CPack/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CPack/RunCMakeTest.cmake
@@ -3,22 +3,22 @@ cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
include(RunCMake)
include("${RunCMake_SOURCE_DIR}/CPackTestHelpers.cmake")
-# args: TEST_NAME "GENERATORS" RUN_CMAKE_BUILD_STEP
-run_cpack_test(MINIMAL "RPM;DEB;TGZ" false)
-run_cpack_source_test(SOURCE_PACKAGE "RPM" true)
-run_cpack_test(PARTIALLY_RELOCATABLE_WARNING "RPM" false)
-run_cpack_test(DEB_EXTRA "DEB" false)
-run_cpack_test(DEPENDENCIES "RPM;DEB" true)
-run_cpack_test(EMPTY_DIR "RPM;DEB;TGZ" true)
-run_cpack_test(COMPONENTS_EMPTY_DIR "RPM;DEB;TGZ" true)
-run_cpack_test(CUSTOM_NAMES "RPM;DEB" true)
-run_cpack_test_subtests(MAIN_COMPONENT "invalid;found" "RPM" false)
-run_cpack_test(PER_COMPONENT_FIELDS "RPM;DEB" false)
-run_cpack_test(RPM_DIST "RPM" false)
-run_cpack_test(INSTALL_SCRIPTS "RPM" false)
-run_cpack_test(DEB_GENERATE_SHLIBS "DEB" true)
-run_cpack_test(DEB_GENERATE_SHLIBS_LDCONFIG "DEB" true)
-run_cpack_test(DEBUGINFO "RPM" true)
-run_cpack_test_subtests(SINGLE_DEBUGINFO "no_main_component;one_component;one_component_main;no_debuginfo;one_component_no_debuginfo;no_components;valid" "RPM" true)
-run_cpack_test(LONG_FILENAMES "DEB" false)
-run_cpack_test_subtests(PACKAGE_CHECKSUM "invalid;MD5;SHA1;SHA224;SHA256;SHA384;SHA512" "TGZ" false)
+# run_cpack_test args: TEST_NAME "GENERATORS" RUN_CMAKE_BUILD_STEP "PACKAGING_TYPES"
+run_cpack_test(CUSTOM_NAMES "RPM;DEB" true "COMPONENT")
+run_cpack_test(DEBUGINFO "RPM" true "COMPONENT")
+run_cpack_test(DEPENDENCIES "RPM;DEB" true "COMPONENT")
+run_cpack_test(DIST "RPM" false "MONOLITHIC")
+run_cpack_test(EMPTY_DIR "RPM;DEB;TGZ" true "MONOLITHIC;COMPONENT")
+run_cpack_test(EXTRA "DEB" false "COMPONENT")
+run_cpack_test(GENERATE_SHLIBS "DEB" true "COMPONENT")
+run_cpack_test(GENERATE_SHLIBS_LDCONFIG "DEB" true "COMPONENT")
+run_cpack_test(INSTALL_SCRIPTS "RPM" false "COMPONENT")
+run_cpack_test(LONG_FILENAMES "DEB" false "MONOLITHIC")
+run_cpack_test_subtests(MAIN_COMPONENT "invalid;found" "RPM" false "COMPONENT")
+run_cpack_test(MINIMAL "RPM;DEB;TGZ" false "MONOLITHIC")
+run_cpack_test_subtests(PACKAGE_CHECKSUM "invalid;MD5;SHA1;SHA224;SHA256;SHA384;SHA512" "TGZ" false "MONOLITHIC")
+run_cpack_test(PARTIALLY_RELOCATABLE_WARNING "RPM" false "COMPONENT")
+run_cpack_test(PER_COMPONENT_FIELDS "RPM;DEB" false "COMPONENT")
+run_cpack_test_subtests(SINGLE_DEBUGINFO "no_main_component;one_component;one_component_main;no_debuginfo;one_component_no_debuginfo;no_components;valid" "RPM" true "CUSTOM")
+run_cpack_source_test(SOURCE_PACKAGE "RPM")
+run_cpack_test(SUGGESTS "RPM" false "MONOLITHIC")
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 26e2ab0..0000000
--- a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "components_empty_dir*.tar.gz")
-set(EXPECTED_FILE_CONTENT_1 "^[^\n]*empty/$")
diff --git a/Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index a75514a..0000000
--- a/Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "empty_dir*.tar.gz")
-set(EXPECTED_FILE_CONTENT_1 "^[^\n]*empty_dir-0.1.1-[^\n]*/empty/$")
diff --git a/Tests/RunCMake/CPack/TGZ/Helpers.cmake b/Tests/RunCMake/CPack/TGZ/Helpers.cmake
index f14d532..4a194c6 100644
--- a/Tests/RunCMake/CPack/TGZ/Helpers.cmake
+++ b/Tests/RunCMake/CPack/TGZ/Helpers.cmake
@@ -8,3 +8,55 @@ function(getPackageContent FILE RESULT_VAR)
set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
endfunction()
+
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+ if(COMPONENT)
+ set(COMPONENT "-${COMPONENT}")
+ endif()
+
+ set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.tar.gz" PARENT_SCOPE)
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+ execute_process(COMMAND ${CMAKE_COMMAND} -E tar -ztf ${FILE}
+ OUTPUT_VARIABLE package_content_
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ string(REPLACE "\n" ";" package_content_ "${package_content_}")
+ foreach(i_ IN LISTS package_content_)
+ string(REGEX REPLACE "/$" "" result_ "${i_}")
+ list(APPEND items_ "${result_}")
+ endforeach()
+
+ set(${RESULT_VAR} "${items_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+ findExpectedFile("${FILE_NO}" "file_")
+
+ # component and monolithic packages differ for some reason by either having
+ # package filename prefix in path or not
+ if(PACKAGING_TYPE STREQUAL "MONOLITHIC")
+ get_filename_component(prefix_ "${file_}" NAME)
+ # NAME_WE removes everything after the dot and dot is in version so replace instead
+ string(REPLACE ".tar.gz" "/" prefix_ "${prefix_}")
+ else()
+ unset(prefix_)
+ endif()
+
+ if(NOT DEFINED TEST_MAIN_INSTALL_PREFIX_PATH)
+ set(TEST_MAIN_INSTALL_PREFIX_PATH "/usr")
+ endif()
+
+ unset(filtered_)
+ foreach(part_ IN LISTS ${CONTENT_VAR})
+ string(REGEX REPLACE "^${TEST_MAIN_INSTALL_PREFIX_PATH}(/|$)" "" part_ "${part_}")
+
+ if(part_)
+ list(APPEND filtered_ "${prefix_}${part_}")
+ endif()
+ endforeach()
+
+ set(${CONTENT_VAR} "${filtered_}" PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake
deleted file mode 100644
index 5c31f27..0000000
--- a/Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "minimal*.tar.gz")
-set(EXPECTED_FILE_CONTENT_1 "^[^\n]*minimal-0.1.1-[^\n]*/foo/\n[^\n]*minimal-0.1.1-[^\n]*/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake
deleted file mode 100644
index 205dcd8..0000000
--- a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "0")
-
-if (NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
- set(EXPECTED_FILES_COUNT "1")
- set(EXPECTED_FILE_1 "package_checksum*.tar.gz")
- set(EXPECTED_FILE_CONTENT_1 "^[^\n]*package_checksum*-[^\n]*/foo/\n[^\n]*package_checksum-[^\n]*/foo/CMakeLists.txt$")
-endif()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/TGZ/packaging_COMPONENT_default.cmake
index 81a5035..81a5035 100644
--- a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
+++ b/Tests/RunCMake/CPack/TGZ/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/VerifyResult.cmake b/Tests/RunCMake/CPack/VerifyResult.cmake
index ad2a651..59751a7 100644
--- a/Tests/RunCMake/CPack/VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/VerifyResult.cmake
@@ -1,5 +1,28 @@
cmake_minimum_required(VERSION ${CMAKE_VERSION} FATAL_ERROR)
+function(findExpectedFile FILE_NO RESULT_VAR)
+ if(NOT DEFINED EXPECTED_FILE_${FILE_NO}) # explicit file name regex was not provided - construct one from other data
+ # set defaults if parameters are not provided
+ if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_NAME)
+ string(TOLOWER "${RunCMake_TEST_FILE_PREFIX}" EXPECTED_FILE_${FILE_NO}_NAME)
+ endif()
+ if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_VERSION)
+ set(EXPECTED_FILE_${FILE_NO}_VERSION "0.1.1")
+ endif()
+ if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_REVISION)
+ set(EXPECTED_FILE_${FILE_NO}_REVISION "1")
+ endif()
+
+ getPackageNameGlobexpr("${EXPECTED_FILE_${FILE_NO}_NAME}"
+ "${EXPECTED_FILE_${FILE_NO}_COMPONENT}" "${EXPECTED_FILE_${FILE_NO}_VERSION}"
+ "${EXPECTED_FILE_${FILE_NO}_REVISION}" "${FILE_NO}" "EXPECTED_FILE_${FILE_NO}")
+ endif()
+
+ file(GLOB found_file_ RELATIVE "${bin_dir}" "${EXPECTED_FILE_${FILE_NO}}")
+
+ set(${RESULT_VAR} "${found_file_}" PARENT_SCOPE)
+endfunction()
+
include("${config_file}")
include("${src_dir}/${GENERATOR_TYPE}/Helpers.cmake")
@@ -10,21 +33,38 @@ file(READ "${config_file}" config_file_content)
set(output_error_message
"\nCPack output: '${output}'\nCPack error: '${error}';\nCPack result: '${PACKAGING_RESULT}';\nconfig file: '${config_file_content}'")
-# check that expected generated files exist and contain expected content
-include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-ExpectedFiles.cmake")
+# generate default expected files data
+include("${src_dir}/tests/${RunCMake_TEST_FILE_PREFIX}/ExpectedFiles.cmake")
+# check that expected generated files exist and contain expected content
if(NOT EXPECTED_FILES_COUNT EQUAL 0)
foreach(file_no_ RANGE 1 ${EXPECTED_FILES_COUNT})
- file(GLOB FOUND_FILE_${file_no_} RELATIVE "${bin_dir}" "${EXPECTED_FILE_${file_no_}}")
+ findExpectedFile("${file_no_}" "FOUND_FILE_${file_no_}")
list(APPEND foundFiles_ "${FOUND_FILE_${file_no_}}")
list(LENGTH FOUND_FILE_${file_no_} foundFilesCount_)
if(foundFilesCount_ EQUAL 1)
unset(PACKAGE_CONTENT)
- getPackageContent("${bin_dir}/${FOUND_FILE_${file_no_}}" "PACKAGE_CONTENT")
- string(REGEX MATCH "${EXPECTED_FILE_CONTENT_${file_no_}}"
- expected_content_list "${PACKAGE_CONTENT}")
+ if(DEFINED EXPECTED_FILE_CONTENT_${file_no_})
+ getPackageContent("${bin_dir}/${FOUND_FILE_${file_no_}}" "PACKAGE_CONTENT")
+
+ string(REGEX MATCH "${EXPECTED_FILE_CONTENT_${file_no_}}"
+ expected_content_list "${PACKAGE_CONTENT}")
+ else() # use content list
+ getPackageContentList("${bin_dir}/${FOUND_FILE_${file_no_}}" "PACKAGE_CONTENT")
+ set(EXPECTED_FILE_CONTENT_${file_no_} "${EXPECTED_FILE_CONTENT_${file_no_}_LIST}")
+ toExpectedContentList("${file_no_}" "EXPECTED_FILE_CONTENT_${file_no_}")
+
+ list(SORT PACKAGE_CONTENT)
+ list(SORT EXPECTED_FILE_CONTENT_${file_no_})
+
+ if(PACKAGE_CONTENT STREQUAL EXPECTED_FILE_CONTENT_${file_no_})
+ set(expected_content_list TRUE)
+ else()
+ set(expected_content_list FALSE)
+ endif()
+ endif()
if(NOT expected_content_list)
string(REPLACE "\n" "\n actual> " msg_actual "\n${PACKAGE_CONTENT}")
@@ -40,6 +80,7 @@ if(NOT EXPECTED_FILES_COUNT EQUAL 0)
"Found more than one file for file No. '${file_no_}'!"
" Found files count '${foundFilesCount_}'."
" Files: '${FOUND_FILE_${file_no_}}'"
+ " Globbing expression: '${EXPECTED_FILE_${file_no_}}'"
"${output_error_message}")
endif()
endforeach()
@@ -84,11 +125,9 @@ else()
endif()
# handle additional result verifications
-if(EXISTS "${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-VerifyResult.cmake")
- include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-VerifyResult.cmake")
-else()
- # by default only print out output and error so that they can be compared by
- # regex
- message(STATUS "${output}")
- message("${error}")
+if(EXISTS "${src_dir}/tests/${RunCMake_TEST_FILE_PREFIX}/VerifyResult.cmake")
+ include("${src_dir}/tests/${RunCMake_TEST_FILE_PREFIX}/VerifyResult.cmake")
endif()
+
+message(STATUS "${output}")
+message("${error}")
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake
new file mode 100644
index 0000000..ae5f0af
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake
@@ -0,0 +1,12 @@
+set(EXPECTED_FILES_COUNT "3")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_1_COMPONENT "pkg_1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_NAME "second")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+ string(TOLOWER "${GENERATOR_TYPE}" file_extension_)
+ set(EXPECTED_FILE_3 "pkg_3_abc.${file_extension_}")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake
new file mode 100644
index 0000000..0c2b37b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake
@@ -0,0 +1,14 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+ if(GENERATOR_TYPE STREQUAL "DEB")
+ set(generator_type_suffix_ "IAN") # not entirely compatible...
+ endif()
+
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_FILE_NAME "${GENERATOR_TYPE}-DEFAULT")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_2_PACKAGE_NAME "second")
+ string(TOLOWER "${GENERATOR_TYPE}" file_extension_)
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_3_FILE_NAME "pkg_3_abc.${file_extension_}")
+endif()
+
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
diff --git a/Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake
new file mode 100644
index 0000000..06e56d3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake
@@ -0,0 +1,16 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "5")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+
+set(EXPECTED_FILE_1_COMPONENT "applications")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+set(EXPECTED_FILE_2 "debuginfo*-headers.rpm")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+set(EXPECTED_FILE_3 "debuginfo*-libs.rpm")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/libtest_lib.so")
+
+set(EXPECTED_FILE_4_COMPONENT "applications-debuginfo")
+set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
+set(EXPECTED_FILE_5_COMPONENT "libs-debuginfo")
+set(EXPECTED_FILE_CONTENT_5 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/test_lib.cpp.*")
diff --git a/Tests/RunCMake/CPack/DEBUGINFO.cmake b/Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake
index d98b682..0642d83 100644
--- a/Tests/RunCMake/CPack/DEBUGINFO.cmake
+++ b/Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake
@@ -6,8 +6,6 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "PGI")
string(APPEND CMAKE_SHARED_LINKER_FLAGS "-Wl,--build-id")
endif()
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
set(CMAKE_BUILD_TYPE Debug)
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
@@ -30,5 +28,3 @@ set(CPACK_RPM_APPLICATIONS_DEBUGINFO_PACKAGE ON)
set(CPACK_RPM_LIBS_DEBUGINFO_PACKAGE ON)
set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/src")
-
-set(CPACK_PACKAGE_NAME "debuginfo")
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt b/Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt
new file mode 100644
index 0000000..5df274a
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt
@@ -0,0 +1 @@
+^CPackDeb: ((- Generating dependency list)|(Using only user-provided dependencies because dpkg-shlibdeps is not found\.))$
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake
new file mode 100644
index 0000000..3b280ba
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake
@@ -0,0 +1,18 @@
+set(EXPECTED_FILES_COUNT "5")
+set(EXPECTED_FILE_1_COMPONENT "applications")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+set(EXPECTED_FILE_2_COMPONENT "applications_auto")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/foo_auto;/usr/foo_auto/test_prog")
+set(EXPECTED_FILE_3_COMPONENT "headers")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+set(EXPECTED_FILE_4_COMPONENT "libs")
+set(EXPECTED_FILE_CONTENT_4_LIST "/usr/bas;/usr/bas/libtest_lib.so")
+set(EXPECTED_FILE_5_COMPONENT "libs_auto")
+set(EXPECTED_FILE_CONTENT_5_LIST "/usr;/usr/bas_auto;/usr/bas_auto/libtest_lib.so")
+
+if(GENERATOR_TYPE STREQUAL "DEB")
+ set(whitespaces_ "[\t\n\r ]*")
+ # dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
+ set(EXPECTED_FILE_CONTENT_4 "^.*/usr/bas${whitespaces_}.*/usr/bas/libtest_lib\\..*$")
+ set(EXPECTED_FILE_CONTENT_5 "^.*/usr/bas_auto${whitespaces_}.*/usr/bas_auto/libtest_lib\\..*$")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake
new file mode 100644
index 0000000..7923148
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake
@@ -0,0 +1,82 @@
+if(GENERATOR_TYPE STREQUAL "DEB")
+ function(checkDependencies_ FILE REGEX)
+ set(whitespaces_ "[\t\n\r ]*")
+
+ getPackageInfo("${FILE}" "FILE_INFO_")
+ if(NOT FILE_INFO_ MATCHES "${REGEX}")
+ message(FATAL_ERROR "Unexpected dependencies in '${FILE}'; file info: '${FILE_INFO_}'")
+ endif()
+ endfunction()
+
+ foreach(dependency_type_ DEPENDS CONFLICTS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
+ string(TOLOWER "${dependency_type_}" lower_dependency_type_)
+ string(SUBSTRING ${lower_dependency_type_} 1 -1 lower_dependency_type_tail_)
+ string(SUBSTRING ${dependency_type_} 0 1 dependency_type_head_)
+ set(dependency_type_name_ "${dependency_type_head_}${lower_dependency_type_tail_}")
+
+ checkDependencies_("${FOUND_FILE_1}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
+ checkDependencies_("${FOUND_FILE_2}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}.*${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
+ checkDependencies_("${FOUND_FILE_3}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-headers.*")
+ checkDependencies_("${FOUND_FILE_4}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
+ checkDependencies_("${FOUND_FILE_5}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
+ endforeach()
+
+ checkDependencies_("${FOUND_FILE_1}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
+ checkDependencies_("${FOUND_FILE_2}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
+ checkDependencies_("${FOUND_FILE_3}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
+ checkDependencies_("${FOUND_FILE_4}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib.*")
+ checkDependencies_("${FOUND_FILE_5}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib_auto.*, provided-lib_auto-b.*")
+
+ # PREDEPENDS
+ checkDependencies_("${FOUND_FILE_1}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-application, predepends-application-b.*")
+ checkDependencies_("${FOUND_FILE_2}" ".*Pre-Depends${whitespaces_}:${whitespaces_}.*predepends-application, predepends-application-b.*")
+ checkDependencies_("${FOUND_FILE_3}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-headers.*")
+ checkDependencies_("${FOUND_FILE_4}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
+ checkDependencies_("${FOUND_FILE_5}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
+elseif(GENERATOR_TYPE STREQUAL "RPM")
+ function(checkDependencies_ FILE TYPE COMPARE_LIST)
+ set(whitespaces_ "[\t\n\r ]*")
+
+ execute_process(COMMAND ${RPM_EXECUTABLE} -qp --${TYPE} ${FILE}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE FILE_DEPENDENCIES_
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ string(REPLACE "\n" ";" FILE_DEPENDENCIES_LIST_ "${FILE_DEPENDENCIES_}")
+
+ foreach(COMPARE_REGEX_ IN LISTS COMPARE_LIST)
+ unset(FOUND_)
+
+ foreach(COMPARE_ IN LISTS FILE_DEPENDENCIES_LIST_)
+ if(COMPARE_ MATCHES "${COMPARE_REGEX_}")
+ set(FOUND_ true)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT FOUND_)
+ message(FATAL_ERROR "Missing dependencies in '${FILE}'; check type: '${TYPE}'; file info: '${FILE_DEPENDENCIES_}'; missing: '${COMPARE_REGEX_}'")
+ endif()
+ endforeach()
+ endfunction()
+
+ # TODO add tests for what should not be present in lists
+ checkDependencies_("${FOUND_FILE_1}" "requires" "depend-application;depend-application-b")
+ checkDependencies_("${FOUND_FILE_2}" "requires" "depend-application;depend-application-b;libtest_lib\\.so.*")
+ checkDependencies_("${FOUND_FILE_3}" "requires" "depend-headers")
+ checkDependencies_("${FOUND_FILE_4}" "requires" "depend-default;depend-default-b")
+ checkDependencies_("${FOUND_FILE_5}" "requires" "depend-default;depend-default-b")
+
+ checkDependencies_("${FOUND_FILE_1}" "conflicts" "conflicts-application;conflicts-application-b")
+ checkDependencies_("${FOUND_FILE_2}" "conflicts" "conflicts-application;conflicts-application-b")
+ checkDependencies_("${FOUND_FILE_3}" "conflicts" "conflicts-headers")
+ checkDependencies_("${FOUND_FILE_4}" "conflicts" "conflicts-default;conflicts-default-b")
+ checkDependencies_("${FOUND_FILE_5}" "conflicts" "conflicts-default;conflicts-default-b")
+
+ checkDependencies_("${FOUND_FILE_1}" "provides" "provided-default;provided-default-b")
+ checkDependencies_("${FOUND_FILE_2}" "provides" "provided-default;provided-default-b")
+ checkDependencies_("${FOUND_FILE_3}" "provides" "provided-default;provided-default-b")
+ checkDependencies_("${FOUND_FILE_4}" "provides" "provided-lib")
+ checkDependencies_("${FOUND_FILE_5}" "provides" "provided-lib_auto;provided-lib_auto-b")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake b/Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake
new file mode 100644
index 0000000..fbd786e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake
@@ -0,0 +1,60 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+ if(GENERATOR_TYPE STREQUAL "DEB")
+ # false by default
+ set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS FALSE)
+ # FIXME can not be tested as libraries first have to be part of a package in order
+ # to determine their dependencies and we can not be certain if there will be any
+ set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_SHLIBDEPS TRUE)
+
+ foreach(dependency_type_ DEPENDS PREDEPENDS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
+ string(TOLOWER "${dependency_type_}" lower_dependency_type_)
+
+ set(CPACK_DEBIAN_PACKAGE_${dependency_type_} "${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b")
+ set(CPACK_DEBIAN_APPLICATIONS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
+ set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
+ set(CPACK_DEBIAN_HEADERS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-headers")
+ endforeach()
+
+ set(generator_type_suffix_ "IAN") # not entirely compatible...
+ else() # RPM
+ # FIXME auto autoprov is not tested at the moment as Ubuntu 15.04 rpmbuild
+ # does not use them correctly: https://bugs.launchpad.net/rpm/+bug/1475755
+ set(CPACK_RPM_PACKAGE_AUTOREQ "no")
+ set(CPACK_RPM_PACKAGE_AUTOPROV "no")
+ set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_AUTOREQPROV "yes")
+ set(CPACK_RPM_LIBS_AUTO_PACKAGE_AUTOREQPROV "yes")
+
+ set(CPACK_RPM_PACKAGE_REQUIRES "depend-default, depend-default-b")
+ set(CPACK_RPM_APPLICATIONS_PACKAGE_REQUIRES "depend-application, depend-application-b")
+ set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_REQUIRES "depend-application, depend-application-b")
+ set(CPACK_RPM_HEADERS_PACKAGE_REQUIRES "depend-headers")
+ endif()
+
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PACKAGE_CONFLICTS "conflicts-default, conflicts-default-b")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_APPLICATIONS_PACKAGE_CONFLICTS "conflicts-application, conflicts-application-b")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_APPLICATIONS_AUTO_PACKAGE_CONFLICTS "conflicts-application, conflicts-application-b")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_HEADERS_PACKAGE_CONFLICTS "conflicts-headers")
+
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PACKAGE_PROVIDES "provided-default, provided-default-b")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_LIBS_PACKAGE_PROVIDES "provided-lib")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_LIBS_AUTO_PACKAGE_PROVIDES "provided-lib_auto, provided-lib_auto-b")
+endif()
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+ "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+ "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+ "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+target_link_libraries(test_prog test_lib)
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+install(TARGETS test_prog DESTINATION foo_auto COMPONENT applications_auto)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
+install(TARGETS test_lib DESTINATION bas COMPONENT libs)
+install(TARGETS test_lib DESTINATION bas_auto COMPONENT libs_auto)
diff --git a/Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/RPM/RPM_DIST-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
index 7375ecc..7375ecc 100644
--- a/Tests/RunCMake/CPack/RPM/RPM_DIST-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/RPM_DIST.cmake b/Tests/RunCMake/CPack/tests/DIST/test.cmake
index eb2a123..6bdd2c0 100644
--- a/Tests/RunCMake/CPack/RPM_DIST.cmake
+++ b/Tests/RunCMake/CPack/tests/DIST/test.cmake
@@ -1,4 +1,3 @@
install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
set(CPACK_RPM_PACKAGE_RELEASE_DIST ON)
-set(CPACK_PACKAGE_NAME "rpm_dist")
diff --git a/Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake
new file mode 100644
index 0000000..650687c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake
@@ -0,0 +1,7 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/empty")
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+ set(EXPECTED_FILE_1_COMPONENT "test")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake b/Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake
new file mode 100644
index 0000000..cd2c9fd
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake
@@ -0,0 +1,14 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+ if(GENERATOR_TYPE STREQUAL "DEB")
+ set(generator_type_suffix_ "IAN") # not entirely compatible...
+ endif()
+
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_FILE_NAME "${GENERATOR_TYPE}-DEFAULT")
+endif()
+
+install(DIRECTORY DESTINATION empty
+ COMPONENT test)
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+ set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake
new file mode 100644
index 0000000..ded2923
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake
@@ -0,0 +1,8 @@
+set(EXPECTED_FILES_COUNT "3")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_1_COMPONENT "foo")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_COMPONENT "bar")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+set(EXPECTED_FILE_3_COMPONENT "bas")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/EXTRA/VerifyResult.cmake
index 85e137f..85e137f 100644
--- a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/EXTRA/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/DEB_EXTRA.cmake b/Tests/RunCMake/CPack/tests/EXTRA/test.cmake
index 189d123..efa6dac 100644
--- a/Tests/RunCMake/CPack/DEB_EXTRA.cmake
+++ b/Tests/RunCMake/CPack/tests/EXTRA/test.cmake
@@ -32,8 +32,4 @@ endforeach()
set(CPACK_DEBIAN_BAR_PACKAGE_CONTROL_EXTRA
"${CMAKE_CURRENT_BINARY_DIR}/bar/preinst;${CMAKE_CURRENT_BINARY_DIR}/bar/prerm")
-set(CPACK_PACKAGE_NAME "deb_extra")
-set(CPACK_PACKAGE_CONTACT "someone")
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-set(CPACK_DEB_COMPONENT_INSTALL ON)
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake
new file mode 100644
index 0000000..be44b2e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var config_file)
+ include(${config_file})
+
+ if(READELF_EXECUTABLE)
+ set(${found_var} true PARENT_SCOPE)
+ endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/ExpectedFiles.cmake
index a8efb61..ccb5ef0 100644
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/ExpectedFiles.cmake
@@ -1,6 +1,6 @@
set(whitespaces_ "[\t\n\r ]*")
set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "generate_shlibs_0.1.1-1_*.deb")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/VerifyResult.cmake
index b1952ef..b1952ef 100644
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/test.cmake
index 1aeb06f..90351ba 100644
--- a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/test.cmake
@@ -1,5 +1,3 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS "ON")
@@ -14,5 +12,3 @@ add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
set_target_properties(test_lib PROPERTIES SOVERSION "0.8")
install(TARGETS test_lib DESTINATION foo COMPONENT libs)
-
-set(CPACK_PACKAGE_NAME "generate_shlibs")
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake
new file mode 100644
index 0000000..be44b2e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var config_file)
+ include(${config_file})
+
+ if(READELF_EXECUTABLE)
+ set(${found_var} true PARENT_SCOPE)
+ endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake
index 9a9dee3..d66c044 100644
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake
@@ -1,6 +1,6 @@
set(whitespaces_ "[\t\n\r ]*")
set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "generate_shlibs_ldconfig_0.1.1-1_*.deb")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
set(EXPECTED_FILE_CONTENT_1 "^.*/usr/lib${whitespaces_}.*/usr/lib/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/VerifyResult.cmake
index 422cfbe..422cfbe 100644
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/test.cmake
index f58c876..15c496b 100644
--- a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/test.cmake
@@ -1,5 +1,3 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS "ON")
@@ -15,5 +13,3 @@ add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
set_target_properties(test_lib PROPERTIES SOVERSION "0.8")
install(TARGETS test_lib LIBRARY DESTINATION lib COMPONENT libs NAMELINK_SKIP)
-
-set(CPACK_PACKAGE_NAME "generate_shlibs_ldconfig")
diff --git a/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake
new file mode 100644
index 0000000..44346ab
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake
@@ -0,0 +1,5 @@
+set(EXPECTED_FILES_COUNT "2")
+set(EXPECTED_FILE_1_COMPONENT "foo")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_COMPONENT "bar")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/VerifyResult.cmake
index d7d82f2..d7d82f2 100644
--- a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/test.cmake
index 13aa77b..fb1b8de 100644
--- a/Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake
+++ b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/test.cmake
@@ -1,3 +1,23 @@
+if(GENERATOR_TYPE STREQUAL "RPM")
+ set(CPACK_RPM_PRE_INSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/pre_install.sh")
+ set(CPACK_RPM_POST_INSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/post_install.sh")
+ set(CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall.sh")
+ set(CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall.sh")
+
+ set(CPACK_RPM_foo_PRE_INSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/pre_install_foo.sh")
+ set(CPACK_RPM_foo_POST_INSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/post_install_foo.sh")
+ set(CPACK_RPM_foo_PRE_UNINSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall_foo.sh")
+ set(CPACK_RPM_foo_POST_UNINSTALL_SCRIPT_FILE
+ "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh")
+endif()
+
set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
# default
@@ -22,5 +42,3 @@ file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh"
install(FILES CMakeLists.txt DESTINATION foo COMPONENT foo)
install(FILES CMakeLists.txt DESTINATION bar COMPONENT bar)
-
-set(CPACK_PACKAGE_NAME "install_scripts")
diff --git a/Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake
new file mode 100644
index 0000000..ddd16e5
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var config_file)
+ include(${config_file})
+
+ if(FAKEROOT_EXECUTABLE)
+ set(${found_var} true PARENT_SCOPE)
+ endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake
new file mode 100644
index 0000000..631d957
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake
@@ -0,0 +1,3 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt")
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/VerifyResult.cmake
index 0452343..0452343 100644
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/LONG_FILENAMES.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/test.cmake
index 3242aef..f235d47 100644
--- a/Tests/RunCMake/CPack/LONG_FILENAMES.cmake
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/test.cmake
@@ -1,3 +1,8 @@
+if(GENERATOR_TYPE STREQUAL "DEB")
+ set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
+ set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
+endif()
+
set(LONG_FILENAME
"${CMAKE_CURRENT_BINARY_DIR}/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt")
@@ -6,5 +11,3 @@ file(WRITE
"long_filename_test")
install(FILES ${LONG_FILENAME} DESTINATION foo)
-
-set(CPACK_PACKAGE_NAME "long_filenames")
diff --git a/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake
new file mode 100644
index 0000000..6bfb0c1
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake
@@ -0,0 +1,11 @@
+set(EXPECTED_FILES_COUNT "0")
+
+if(NOT RunCMake_SUBTEST_SUFFIX STREQUAL "invalid")
+ set(EXPECTED_FILES_COUNT "3")
+ set(EXPECTED_FILE_1 "main_component-0.1.1-1.*.rpm")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+ set(EXPECTED_FILE_2_COMPONENT "headers")
+ set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+ set(EXPECTED_FILE_3_COMPONENT "libs")
+ set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/CMakeLists.txt")
+endif()
diff --git a/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-invalid-stderr.txt b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/RPM-invalid-stderr.txt
index 4d8ac6e..4d8ac6e 100644
--- a/Tests/RunCMake/CPack/RPM/MAIN_COMPONENT-invalid-stderr.txt
+++ b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/RPM-invalid-stderr.txt
diff --git a/Tests/RunCMake/CPack/MAIN_COMPONENT.cmake b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake
index 99c6cae..791c586 100644
--- a/Tests/RunCMake/CPack/MAIN_COMPONENT.cmake
+++ b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake
@@ -1,5 +1,3 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
install(FILES CMakeLists.txt DESTINATION foo COMPONENT applications)
install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
install(FILES CMakeLists.txt DESTINATION bas COMPONENT libs)
@@ -10,5 +8,3 @@ else()
set(CPACK_RPM_MAIN_COMPONENT "applications")
set(CPACK_RPM_APPLICATIONS_FILE_NAME "RPM-DEFAULT")
endif()
-
-set(CPACK_PACKAGE_NAME "main_component")
diff --git a/Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/MINIMAL.cmake b/Tests/RunCMake/CPack/tests/MINIMAL/test.cmake
index f29ad2a..83ed0f2 100644
--- a/Tests/RunCMake/CPack/MINIMAL.cmake
+++ b/Tests/RunCMake/CPack/tests/MINIMAL/test.cmake
@@ -1,3 +1 @@
install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
-
-set(CPACK_PACKAGE_NAME "minimal")
diff --git a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake
new file mode 100644
index 0000000..eed5b92
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake
@@ -0,0 +1,6 @@
+set(EXPECTED_FILES_COUNT "0")
+
+if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
+ set(EXPECTED_FILES_COUNT "1")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+endif()
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/TGZ-invalid-stderr.txt
index abf6d8c..abf6d8c 100644
--- a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/TGZ-invalid-stderr.txt
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
index e9e65d6..e4f9618 100644
--- a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
@@ -9,6 +9,4 @@ if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
if(NOT expected_value STREQUAL CHSUM_VALUE)
message(FATAL_ERROR "Generated checksum is not valid! Expected [${expected_value}] Got [${CHSUM_VALUE}]")
endif()
-else()
- message(${error})
endif()
diff --git a/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/test.cmake
index 5ca288c..0838063 100644
--- a/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/test.cmake
@@ -1,4 +1,3 @@
install(FILES CMakeLists.txt DESTINATION foo)
-set(CPACK_PACKAGE_NAME "package_checksum")
set(CPACK_PACKAGE_CHECKSUM ${RunCMake_SUBTEST_SUFFIX})
diff --git a/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake
new file mode 100644
index 0000000..ae58c4b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/not_relocatable;/not_relocatable/CMakeLists.txt;/opt")
diff --git a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-stderr.txt b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/RPM-stderr.txt
index 3b63d5b..3b63d5b 100644
--- a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-stderr.txt
+++ b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/RPM-stderr.txt
diff --git a/Tests/RunCMake/CPack/PARTIALLY_RELOCATABLE_WARNING.cmake b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake
index 31e729b..4698fb3 100644
--- a/Tests/RunCMake/CPack/PARTIALLY_RELOCATABLE_WARNING.cmake
+++ b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake
@@ -2,5 +2,3 @@ install(FILES CMakeLists.txt DESTINATION /not_relocatable COMPONENT static)
set(CPACK_PACKAGE_RELOCATABLE TRUE)
set(CPACK_PACKAGING_INSTALL_PREFIX "/opt")
-
-set(CPACK_RPM_COMPONENT_INSTALL ON)
diff --git a/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake
new file mode 100644
index 0000000..9bdb176
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake
@@ -0,0 +1,8 @@
+set(EXPECTED_FILES_COUNT "3")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_1_COMPONENT "pkg_1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_NAME "second")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_3_COMPONENT "pkg_3")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake
new file mode 100644
index 0000000..18ef63c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake
@@ -0,0 +1,26 @@
+function(checkPackageInfo_ TYPE FILE REGEX)
+ getPackageInfo("${FILE}" "FILE_INFO_")
+ if(NOT FILE_INFO_ MATCHES "${REGEX}")
+ message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}'; file info: '${FILE_INFO_}'")
+ endif()
+endfunction()
+
+if(GENERATOR_TYPE STREQUAL "DEB")
+ set(name_ "Package")
+ set(group_ "Section")
+elseif(GENERATOR_TYPE STREQUAL "RPM")
+ set(name_ "Name")
+ set(group_ "Group")
+endif()
+
+set(whitespaces_ "[\t\n\r ]*")
+
+# check package name
+checkPackageInfo_("name" "${FOUND_FILE_1}" ".*${name_}${whitespaces_}:${whitespaces_}per_component_fields-pkg_1")
+checkPackageInfo_("name" "${FOUND_FILE_2}" ".*${name_}${whitespaces_}:${whitespaces_}second")
+checkPackageInfo_("name" "${FOUND_FILE_3}" ".*${name_}${whitespaces_}:${whitespaces_}per_component_fields-pkg_3")
+
+# check package group
+checkPackageInfo_("group" "${FOUND_FILE_1}" ".*${group_}${whitespaces_}:${whitespaces_}default")
+checkPackageInfo_("group" "${FOUND_FILE_2}" ".*${group_}${whitespaces_}:${whitespaces_}second_group")
+checkPackageInfo_("group" "${FOUND_FILE_3}" ".*${group_}${whitespaces_}:${whitespaces_}default")
diff --git a/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake
new file mode 100644
index 0000000..8719c0b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake
@@ -0,0 +1,18 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+ if(GENERATOR_TYPE STREQUAL "DEB")
+ set(generator_type_suffix_ "IAN") # not entirely compatible...
+ set(group_ "SECTION")
+ else()
+ set(group_ "GROUP")
+ endif()
+
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_FILE_NAME "${GENERATOR_TYPE}-DEFAULT")
+
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PACKAGE_${group_} "default")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_2_PACKAGE_NAME "second")
+ set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_2_PACKAGE_${group_} "second_group")
+endif()
+
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake
index dc49343..ca866ea 100644
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-ExpectedFiles.cmake
+++ b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake
@@ -1,29 +1,29 @@
set(whitespaces_ "[\t\n\r ]*")
-
set(EXPECTED_FILES_COUNT "0")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
if(RunCMake_SUBTEST_SUFFIX STREQUAL "valid" OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_debuginfo")
set(EXPECTED_FILES_COUNT "4")
set(EXPECTED_FILE_1 "single_debuginfo-0.1.1-1.*.rpm")
- set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
set(EXPECTED_FILE_2 "single_debuginfo*-headers.rpm")
- set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
+ set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
set(EXPECTED_FILE_3 "single_debuginfo*-libs.rpm")
- set(EXPECTED_FILE_CONTENT_3 "^/usr/bas${whitespaces_}/usr/bas/libtest_lib.so$")
+ set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/libtest_lib.so")
- set(EXPECTED_FILE_4 "single_debuginfo-debuginfo*.rpm")
+ set(EXPECTED_FILE_4_COMPONENT "debuginfo")
set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp${whitespaces_}/src/src_1/test_lib.cpp.*")
elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "one_component" OR RunCMake_SUBTEST_SUFFIX STREQUAL "one_component_no_debuginfo")
set(EXPECTED_FILES_COUNT "2")
set(EXPECTED_FILE_1 "single_debuginfo-0*-applications.rpm")
- set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
set(EXPECTED_FILE_2 "single_debuginfo-applications-debuginfo*.rpm")
set(EXPECTED_FILE_CONTENT_2 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "one_component_main" OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_components")
set(EXPECTED_FILES_COUNT "2")
set(EXPECTED_FILE_1 "single_debuginfo-0*.rpm")
- set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
set(EXPECTED_FILE_2 "single_debuginfo-debuginfo*.rpm")
set(EXPECTED_FILE_CONTENT_2 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
diff --git a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_main_component-stderr.txt b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/RPM-no_main_component-stderr.txt
index 454283c..454283c 100644
--- a/Tests/RunCMake/CPack/RPM/SINGLE_DEBUGINFO-no_main_component-stderr.txt
+++ b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/RPM-no_main_component-stderr.txt
diff --git a/Tests/RunCMake/CPack/SINGLE_DEBUGINFO.cmake b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/test.cmake
index ae4995e..60e9038 100644
--- a/Tests/RunCMake/CPack/SINGLE_DEBUGINFO.cmake
+++ b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/test.cmake
@@ -52,5 +52,3 @@ if(RunCMake_SUBTEST_SUFFIX STREQUAL "valid"
endif()
set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/src")
-
-set(CPACK_PACKAGE_NAME "single_debuginfo")
diff --git a/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake
new file mode 100644
index 0000000..0a3e426
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "source_package-0.1.1.tar.gz;source_package.spec")
diff --git a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake
index a84e296..bc54d79 100644
--- a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake
@@ -1,3 +1,5 @@
+set(whitespaces_ "[\t\n\r ]*")
+
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm")
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILD")
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILDROOT")
diff --git a/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake
index 946439d..359b98f 100644
--- a/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake
+++ b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake
@@ -5,5 +5,3 @@ add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
install(TARGETS test_prog DESTINATION foo COMPONENT applications)
set(CPACK_RPM_FILE_NAME "RPM-DEFAULT")
-
-set(CPACK_PACKAGE_NAME "source_package")
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt b/Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt
new file mode 100644
index 0000000..feb296c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt
@@ -0,0 +1 @@
+^(.*CPackRPM:Warning: SUGGESTS not supported in provided rpmbuild.*)?CPackRPM: Will use GENERATED spec file: (/[^/]*)*/Tests/RunCMake/RPM/CPack/[^-]*-build/_CPack_Packages/.*/RPM/SPECS/[^\.]*\.spec$
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake
new file mode 100644
index 0000000..32cc6d1
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake
@@ -0,0 +1,31 @@
+execute_process(COMMAND ${RPMBUILD_EXECUTABLE} --querytags
+ OUTPUT_VARIABLE RPMBUILD_CAPS
+ RESULT_VARIABLE RPMBUILD_CAPS_RESULT)
+
+if(NOT RPMBUILD_CAPS_RESULT)
+ string(REPLACE "\n" ";" RPMBUILD_CAPS "${RPMBUILD_CAPS}")
+ cmake_policy(PUSH)
+ cmake_policy(SET CMP0057 NEW)
+ if(SUGGESTS IN_LIST RPMBUILD_CAPS)
+ set(should_contain_suggests_tag_ true)
+ endif()
+ cmake_policy(POP)
+endif()
+
+# Only verify that suggests tag is present only if that tag is supported.
+# If it is not supported the rpm package was corretly generated by ignoring
+# that tag and that was already checked by expected files test.
+if(should_contain_suggests_tag_)
+ execute_process(COMMAND ${RPM_EXECUTABLE} -q --suggests -p "${FOUND_FILE_1}"
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ RESULT_VARIABLE rpm_result_
+ OUTPUT_VARIABLE rpm_output_
+ ERROR_VARIABLE error_variable_
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ if(rpm_result_ OR NOT rpm_output_ STREQUAL "libsuggested")
+ message(FATAL_ERROR "RPM_SUGGESTED package error: no suggested packages"
+ " (result: '${rpm_result_}'; output: '${rpm_output_}';"
+ " error: '${error_variable_}')")
+ endif()
+endif()
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake b/Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake
new file mode 100644
index 0000000..dc90ae8
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake
@@ -0,0 +1,3 @@
+install(FILES CMakeLists.txt DESTINATION foo)
+
+set(CPACK_RPM_PACKAGE_SUGGESTS "libsuggested")
diff --git a/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake
index 2bc3693..e936dab 100644
--- a/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake
@@ -135,6 +135,7 @@ function(run_TestOutputSize)
")
run_cmake_command(TestOutputSize
${CMAKE_CTEST_COMMAND} -M Experimental -T Test
+ --no-compress-output
--test-output-size-passed 10
--test-output-size-failed 12
)
diff --git a/Tests/RunCMake/ClangTidy/C-bad-Build-result.txt b/Tests/RunCMake/ClangTidy/C-bad-Build-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/ClangTidy/C-bad-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt b/Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt
new file mode 100644
index 0000000..2370ce1
--- /dev/null
+++ b/Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt
@@ -0,0 +1,2 @@
+stdout from bad command line arg '-bad'
+stderr from bad command line arg '-bad'
diff --git a/Tests/RunCMake/ClangTidy/C-bad.cmake b/Tests/RunCMake/ClangTidy/C-bad.cmake
new file mode 100644
index 0000000..aa54c08
--- /dev/null
+++ b/Tests/RunCMake/ClangTidy/C-bad.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+set(CMAKE_C_CLANG_TIDY "${PSEUDO_TIDY}" -bad)
+add_executable(main main.c)
diff --git a/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake b/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake
index 27cd922..2f41e50 100644
--- a/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake
@@ -20,3 +20,4 @@ if (NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
run_tidy(C-launch)
run_tidy(CXX-launch)
endif()
+run_tidy(C-bad)
diff --git a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake
index 09594bd..2d14a9e 100644
--- a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake
+++ b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake
@@ -3,13 +3,13 @@ add_library(empty1 empty.cpp)
add_library(empty2 INTERFACE)
add_library(empty3 INTERFACE)
-target_compile_features(empty3 INTERFACE cxx_static_assert)
+target_compile_features(empty3 INTERFACE cxx_std_11)
target_link_libraries(empty1
# When starting, $<COMPILE_FEATURES:cxx_auto_type> is '0', so 'freeze' the
# CXX_STANDARD at 98 during computation.
$<$<COMPILE_FEATURES:cxx_auto_type>:empty2>
- # This would add cxx_static_assert, but that would require CXX_STANDARD = 11,
+ # This would add cxx_std_11, but that would require CXX_STANDARD = 11,
# which is not allowed after freeze. Report an error.
empty3
)
diff --git a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake
index bbcf4e0..a04dcec 100644
--- a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake
+++ b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake
@@ -3,7 +3,7 @@ add_library(empty1 empty.cpp)
add_library(empty2 INTERFACE)
add_library(empty3 INTERFACE)
-target_compile_features(empty3 INTERFACE cxx_static_assert)
+target_compile_features(empty3 INTERFACE cxx_std_11)
target_link_libraries(empty1
$<$<COMPILE_FEATURES:cxx_nullptr>:empty2>
diff --git a/Tests/RunCMake/Configure/RemoveCache-stdout.txt b/Tests/RunCMake/Configure/RemoveCache-stdout.txt
new file mode 100644
index 0000000..73e7e5d
--- /dev/null
+++ b/Tests/RunCMake/Configure/RemoveCache-stdout.txt
@@ -0,0 +1 @@
+-- The C compiler identification is
diff --git a/Tests/RunCMake/Configure/RemoveCache.cmake b/Tests/RunCMake/Configure/RemoveCache.cmake
new file mode 100644
index 0000000..304918f
--- /dev/null
+++ b/Tests/RunCMake/Configure/RemoveCache.cmake
@@ -0,0 +1,17 @@
+enable_language(C)
+
+set(vars
+ CMAKE_EXECUTABLE_FORMAT
+ )
+
+if(CMAKE_HOST_UNIX)
+ list(APPEND vars
+ CMAKE_UNAME
+ )
+endif()
+
+foreach(v IN LISTS vars)
+ if(NOT DEFINED ${v})
+ message(SEND_ERROR "Variable '${v}' is not set!")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/Configure/RunCMakeTest.cmake b/Tests/RunCMake/Configure/RunCMakeTest.cmake
index 91adb4e..4a135be 100644
--- a/Tests/RunCMake/Configure/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Configure/RunCMakeTest.cmake
@@ -24,3 +24,12 @@ file(WRITE "${depend}" "2")
run_cmake_command(RerunCMake-build2 ${CMAKE_COMMAND} --build .)
unset(RunCMake_TEST_BINARY_DIR)
unset(RunCMake_TEST_NO_CLEAN)
+
+# Use a single build tree for a few tests without cleaning.
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/RemoveCache-build)
+set(RunCMake_TEST_NO_CLEAN 1)
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+run_cmake(RemoveCache)
+file(REMOVE "${RunCMake_TEST_BINARY_DIR}/CMakeCache.txt")
+run_cmake(RemoveCache)
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake
index 67fa30f..c4db11b 100644
--- a/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake
@@ -4,7 +4,15 @@ set(CMAKE_CROSSCOMPILING 1)
add_executable(generated_exe_emulator_expected simple_src_exiterror.cxx)
# Executable: Return error code equal to 0
-add_executable(generated_exe_emulator_unexpected simple_src_exitsuccess.cxx)
+add_executable(generated_exe_emulator_unexpected generated_exe_emulator_unexpected.cxx)
+# Place the executable in a predictable location.
+set_property(TARGET generated_exe_emulator_unexpected PROPERTY RUNTIME_OUTPUT_DIRECTORY $<1:${CMAKE_CURRENT_BINARY_DIR}>)
+
+# Executable: Imported version of above. Fake the imported target to use the above.
+add_executable(generated_exe_emulator_unexpected_imported IMPORTED)
+set_property(TARGET generated_exe_emulator_unexpected_imported PROPERTY IMPORTED_LOCATION
+ "${CMAKE_CURRENT_BINARY_DIR}/generated_exe_emulator_unexpected${CMAKE_EXECUTABLE_SUFFIX}")
+add_dependencies(generated_exe_emulator_unexpected_imported generated_exe_emulator_unexpected)
# DoesNotUseEmulator
add_custom_command(OUTPUT output1
@@ -22,6 +30,12 @@ add_custom_command(OUTPUT output3
COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/output3
DEPENDS generated_exe_emulator_unexpected)
+# DoesNotUseEmulator: The command will fail if emulator is prepended
+add_custom_command(OUTPUT outputImp
+ COMMAND generated_exe_emulator_unexpected_imported
+ COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/outputImp
+ )
+
# UsesEmulator: The command only succeeds if the emulator is prepended
# to the command.
add_custom_command(OUTPUT output4
@@ -34,5 +48,6 @@ add_custom_target(ensure_build ALL
${CMAKE_CURRENT_BINARY_DIR}/output1
${CMAKE_CURRENT_BINARY_DIR}/output2
${CMAKE_CURRENT_BINARY_DIR}/output3
+ ${CMAKE_CURRENT_BINARY_DIR}/outputImp
${CMAKE_CURRENT_BINARY_DIR}/output4
)
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake
index ced569f..5b01abc 100644
--- a/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake
@@ -4,7 +4,15 @@ set(CMAKE_CROSSCOMPILING 1)
add_executable(generated_exe_emulator_expected simple_src_exiterror.cxx)
# Executable: Return error code equal to 0
-add_executable(generated_exe_emulator_unexpected simple_src_exitsuccess.cxx)
+add_executable(generated_exe_emulator_unexpected generated_exe_emulator_unexpected.cxx)
+# Place the executable in a predictable location.
+set_property(TARGET generated_exe_emulator_unexpected PROPERTY RUNTIME_OUTPUT_DIRECTORY $<1:${CMAKE_CURRENT_BINARY_DIR}>)
+
+# Executable: Imported version of above. Fake the imported target to use the above.
+add_executable(generated_exe_emulator_unexpected_imported IMPORTED)
+set_property(TARGET generated_exe_emulator_unexpected_imported PROPERTY IMPORTED_LOCATION
+ "${CMAKE_CURRENT_BINARY_DIR}/generated_exe_emulator_unexpected${CMAKE_EXECUTABLE_SUFFIX}")
+add_dependencies(generated_exe_emulator_unexpected_imported generated_exe_emulator_unexpected)
# DoesNotUseEmulator
add_custom_target(generate_output1 ALL
@@ -22,6 +30,12 @@ add_custom_target(generate_output3 ALL
COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/output3
DEPENDS generated_exe_emulator_unexpected)
+# DoesNotUseEmulator: The command will fail if emulator is prepended
+add_custom_target(generate_outputImp ALL
+ COMMAND generated_exe_emulator_unexpected_imported
+ COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/outputImp
+ )
+
# UsesEmulator: The command only succeeds if the emulator is prepended
# to the command.
add_custom_target(generate_output4 ALL
diff --git a/Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx b/Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx
new file mode 100644
index 0000000..233f432
--- /dev/null
+++ b/Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx
@@ -0,0 +1,9 @@
+#include <stdio.h>
+
+int main(int argc, const char* argv[])
+{
+ for (int i = 1; i < argc; ++i) {
+ fprintf(stderr, "unexpected argument: '%s'\n", argv[i]);
+ }
+ return argc == 1 ? 0 : 1;
+}
diff --git a/Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx b/Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx
deleted file mode 100644
index a3dd891..0000000
--- a/Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx
+++ /dev/null
@@ -1,4 +0,0 @@
-int main(int, char**)
-{
- return 0;
-}
diff --git a/Tests/RunCMake/RunCMake.cmake b/Tests/RunCMake/RunCMake.cmake
index 247855a..6cc3054 100644
--- a/Tests/RunCMake/RunCMake.cmake
+++ b/Tests/RunCMake/RunCMake.cmake
@@ -75,6 +75,7 @@ function(run_cmake test)
OUTPUT_VARIABLE actual_stdout
ERROR_VARIABLE ${actual_stderr_var}
RESULT_VARIABLE actual_result
+ ENCODING UTF8
${maybe_timeout}
)
else()
@@ -90,6 +91,7 @@ function(run_cmake test)
OUTPUT_VARIABLE actual_stdout
ERROR_VARIABLE ${actual_stderr_var}
RESULT_VARIABLE actual_result
+ ENCODING UTF8
${maybe_timeout}
)
endif()
diff --git a/Tests/RunCMake/RunCTest.cmake b/Tests/RunCMake/RunCTest.cmake
index e94432b..89e16ee 100644
--- a/Tests/RunCMake/RunCTest.cmake
+++ b/Tests/RunCMake/RunCTest.cmake
@@ -12,6 +12,7 @@ function(run_ctest CASE_NAME)
-S ${RunCMake_BINARY_DIR}/${CASE_NAME}/test.cmake
-V
--output-log ${RunCMake_BINARY_DIR}/${CASE_NAME}-build/testOutput.log
+ --no-compress-output
${ARGN}
)
endfunction()
diff --git a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
index cc2cc2e..bc1ec97 100644
--- a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
+++ b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
@@ -1,2 +1,5 @@
include(RunCMake)
run_cmake(VsConfigurationType)
+run_cmake(VsTargetsFileReferences)
+run_cmake(VsCustomProps)
+run_cmake(VsDebuggerWorkingDir)
diff --git a/Tests/RunCMake/VS10Project/VsCustomProps-check.cmake b/Tests/RunCMake/VS10Project/VsCustomProps-check.cmake
new file mode 100644
index 0000000..22a3df0
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCustomProps-check.cmake
@@ -0,0 +1,25 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(importFound FALSE)
+
+set(props_file "${RunCMake_SOURCE_DIR}/my.props")
+file(TO_NATIVE_PATH "${props_file}" check_file)
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<Import Project=\"([^\"]+)\".*Label=\"([^\"]+)\".*$")
+ if("${CMAKE_MATCH_1}" STREQUAL "${check_file}" AND
+ "${CMAKE_MATCH_2}" STREQUAL "LocalAppDataPlatform")
+ message(STATUS "foo.vcxproj is importing ${check_file}")
+ set(importFound TRUE)
+ endif()
+ endif()
+endforeach()
+
+if(NOT importFound)
+ set(RunCMake_TEST_FAILED "Import of custom .props file not found.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCustomProps.cmake b/Tests/RunCMake/VS10Project/VsCustomProps.cmake
new file mode 100644
index 0000000..af52a3e
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCustomProps.cmake
@@ -0,0 +1,7 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+
+set(props_file "${CMAKE_CURRENT_SOURCE_DIR}/my.props")
+
+set_target_properties(foo PROPERTIES
+ VS_USER_PROPS_CXX "${props_file}")
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake
new file mode 100644
index 0000000..637c68c
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake
@@ -0,0 +1,22 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(debuggerWorkDirSet FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<LocalDebuggerWorkingDirectory[^>]*>([^<>]+)</LocalDebuggerWorkingDirectory>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "my-debugger-directory")
+ message(STATUS "foo.vcxproj has debugger working dir set")
+ set(debuggerWorkDirSet TRUE)
+ endif()
+ endif()
+endforeach()
+
+if(NOT debuggerWorkDirSet)
+ set(RunCMake_TEST_FAILED "LocalDebuggerWorkingDirectory not found or not set correctly.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake
new file mode 100644
index 0000000..a277c65
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+
+set_target_properties(foo PROPERTIES
+ VS_DEBUGGER_WORKING_DIRECTORY "my-debugger-directory")
diff --git a/Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake b/Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake
new file mode 100644
index 0000000..3d01c2c
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake
@@ -0,0 +1,45 @@
+set(files foo.vcxproj bar.vcxproj baz.vcxproj)
+
+foreach(file ${files})
+ set(vsProjectFile ${RunCMake_TEST_BINARY_DIR}/${file})
+
+ if(NOT EXISTS "${vsProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vsProjectFile} does not exist.")
+ return()
+ endif()
+
+ set(waldoFound FALSE)
+ set(xyzzyFound FALSE)
+ file(STRINGS "${vsProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<Import Project=.*/>$")
+ if(line MATCHES "^.*waldo.targets.*$")
+ set(waldoFound TRUE)
+ message(STATUS "${file} is importing waldo.targets")
+ elseif(line MATCHES "^.*xyzzy.targets.*$")
+ set(xyzzyFound TRUE)
+ message(STATUS "${file} is importing xyzzy.targets")
+ endif()
+ endif()
+ endforeach()
+
+ if("${file}" STREQUAL "foo.vcxproj")
+ if(NOT xyzzyFound)
+ set(RunCMake_TEST_FAILED "xyzzy.targets not imported from ${file}")
+ return()
+ endif()
+ if(waldoFound)
+ set(RunCMake_TEST_FAILED "waldo.targets imported from ${file}")
+ return()
+ endif()
+ else()
+ if(NOT xyzzyFound)
+ set(RunCMake_TEST_FAILED "xyzzy.targets not imported from ${file}")
+ return()
+ endif()
+ if(NOT waldoFound)
+ set(RunCMake_TEST_FAILED "waldo.targets not imported from ${file}")
+ return()
+ endif()
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake b/Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake
new file mode 100644
index 0000000..5ca4f1f
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake
@@ -0,0 +1,9 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+target_link_libraries(foo ${CMAKE_BINARY_DIR}/xyzzy.targets)
+
+add_library(bar bar.cpp)
+target_link_libraries(bar foo ${CMAKE_BINARY_DIR}/waldo.targets)
+
+add_executable(baz baz.cpp)
+target_link_libraries(baz bar)
diff --git a/Tests/RunCMake/VS10Project/bar.cpp b/Tests/RunCMake/VS10Project/bar.cpp
new file mode 100644
index 0000000..b72a1a5
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/bar.cpp
@@ -0,0 +1,3 @@
+void bar()
+{
+}
diff --git a/Tests/RunCMake/VS10Project/baz.cpp b/Tests/RunCMake/VS10Project/baz.cpp
new file mode 100644
index 0000000..d5d334a
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/baz.cpp
@@ -0,0 +1,3 @@
+void baz()
+{
+}
diff --git a/Tests/RunCMake/VS10Project/my.props b/Tests/RunCMake/VS10Project/my.props
new file mode 100644
index 0000000..7c98cde
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/my.props
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ </PropertyGroup>
+</Project>
diff --git a/Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake b/Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake
new file mode 100644
index 0000000..7265900
--- /dev/null
+++ b/Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake
@@ -0,0 +1,29 @@
+set(vcSlnFile "${RunCMake_TEST_BINARY_DIR}/AddPackageToDefault.sln")
+if(NOT EXISTS "${vcSlnFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcSlnFile} does not exist.")
+ return()
+endif()
+
+set(packageGuidFound FALSE)
+set(packageGuid "")
+set(packageInBuild FALSE)
+file(STRINGS "${vcSlnFile}" lines)
+foreach(line IN LISTS lines)
+ if(NOT packageGuidFound)
+ if(line MATCHES "^Project.*\"PACKAGE.vcx?proj\".*\"{([A-F0-9-]+)}\"$")
+ set(packageGuidFound TRUE)
+ set(packageGuid ${CMAKE_MATCH_1})
+ endif()
+ else()
+ if(line MATCHES ".*{${packageGuid}}.*")
+ if(line MATCHES "^[ \t]*{${packageGuid}}\\..*\\.Build.0 = .*$")
+ set(packageInBuild TRUE)
+ endif()
+ endif()
+ endif()
+endforeach()
+
+if(NOT packageInBuild)
+ set(RunCMake_TEST_FAILED "PACKAGE is not in default build")
+ return()
+endif()
diff --git a/Tests/RunCMake/VSSolution/AddPackageToDefault.cmake b/Tests/RunCMake/VSSolution/AddPackageToDefault.cmake
new file mode 100644
index 0000000..5f69ec5
--- /dev/null
+++ b/Tests/RunCMake/VSSolution/AddPackageToDefault.cmake
@@ -0,0 +1,2 @@
+include(CPack)
+set(CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD TRUE)
diff --git a/Tests/RunCMake/VSSolution/RunCMakeTest.cmake b/Tests/RunCMake/VSSolution/RunCMakeTest.cmake
index afd74a1..4ec3e3b 100644
--- a/Tests/RunCMake/VSSolution/RunCMakeTest.cmake
+++ b/Tests/RunCMake/VSSolution/RunCMakeTest.cmake
@@ -10,6 +10,7 @@ run_cmake(Override1)
run_cmake(Override2)
run_cmake(StartupProject)
run_cmake(StartupProjectMissing)
+run_cmake(AddPackageToDefault)
if(RunCMake_GENERATOR MATCHES "Visual Studio ([^7]|[7][0-9])" AND NOT NO_USE_FOLDERS)
run_cmake(StartupProjectUseFolders)
diff --git a/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-result.txt b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-result.txt
new file mode 100644
index 0000000..b57e2de
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt
new file mode 100644
index 0000000..d4b71ae
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt
@@ -0,0 +1 @@
+Defect count: 3
diff --git a/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt
new file mode 100644
index 0000000..97a8a9b
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt
@@ -0,0 +1,3 @@
+Memory checking results:
+Direct leak - 2
+Indirect leak - 1
diff --git a/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt
@@ -2,5 +2,7 @@
100% tests passed, 0 tests failed out of 1
.*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt
@@ -2,5 +2,7 @@
100% tests passed, 0 tests failed out of 1
.*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt
@@ -2,5 +2,7 @@
100% tests passed, 0 tests failed out of 1
.*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt
@@ -2,5 +2,7 @@
100% tests passed, 0 tests failed out of 1
.*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt
index 5a5675c..88b4788 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt
@@ -3,5 +3,7 @@
100% tests passed, 0 tests failed out of 1
.*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt
new file mode 100644
index 0000000..573541a
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt
new file mode 100644
index 0000000..ad28645
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt
@@ -0,0 +1 @@
+Defect count: 0
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt
new file mode 100644
index 0000000..69ab584
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt
@@ -0,0 +1,8 @@
+1/1 MemCheck #1: RunCMake \.+ Passed +[0-9]+.[0-9]+ sec
+
+100% tests passed, 0 tests failed out of 1
+.*
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
+Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt
@@ -2,5 +2,7 @@
100% tests passed, 0 tests failed out of 1
.*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake b/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
index 5ad6511..212bfdb 100644
--- a/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
@@ -12,6 +12,8 @@ endfunction()
unset(CTEST_EXTRA_CONFIG)
unset(CTEST_EXTRA_CODE)
+unset(CTEST_SUFFIX_CODE)
+unset(CTEST_MEMCHECK_ARGS)
unset(CMAKELISTS_EXTRA_CODE)
#-----------------------------------------------------------------------------
@@ -132,4 +134,31 @@ run_mc_test(DummyValgrindNoLogFile "${PSEUDO_VALGRIND_NOLOG}")
run_mc_test(DummyBCNoLogFile "${PSEUDO_BC_NOLOG}")
run_mc_test(NotExist "\${CTEST_BINARY_DIRECTORY}/no-memcheck-exe")
run_mc_test(Unknown "\${CMAKE_COMMAND}")
-run_mc_test(DummyQuiet "${PSEUDO_VALGRIND}" -DMEMCHECK_ARGS=QUIET)
+
+#----------------------------------------------------------------------------
+set(CTEST_MEMCHECK_ARGS QUIET)
+run_mc_test(DummyQuiet "${PSEUDO_VALGRIND}")
+unset(CTEST_MEMCHECK_ARGS)
+
+#-----------------------------------------------------------------------------
+set(CTEST_SUFFIX_CODE "message(\"Defect count: \${defect_count}\")")
+set(CTEST_MEMCHECK_ARGS "DEFECT_COUNT defect_count")
+run_mc_test(DummyValgrindNoDefects "${PSEUDO_VALGRIND}")
+unset(CTEST_MEMCHECK_ARGS)
+unset(CTEST_SUFFIX_CODE)
+
+#-----------------------------------------------------------------------------
+set(CTEST_SUFFIX_CODE "message(\"Defect count: \${defect_count}\")")
+set(CTEST_MEMCHECK_ARGS "DEFECT_COUNT defect_count")
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+")
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"${CMAKE_COMMAND}\"
+-P \"${RunCMake_SOURCE_DIR}/testLeakSanitizer.cmake\")
+")
+run_mc_test(DummyLeakSanitizerPrintDefects "" -DMEMCHECK_TYPE=AddressSanitizer)
+unset(CMAKELISTS_EXTRA_CODE)
+unset(CTEST_EXTRA_CODE)
+unset(CTEST_MEMCHECK_ARGS)
+unset(CTEST_SUFFIX_CODE)
diff --git a/Tests/RunCMake/ctest_memcheck/test.cmake.in b/Tests/RunCMake/ctest_memcheck/test.cmake.in
index 8431fa6..50b4b6a 100644
--- a/Tests/RunCMake/ctest_memcheck/test.cmake.in
+++ b/Tests/RunCMake/ctest_memcheck/test.cmake.in
@@ -21,4 +21,6 @@ set(CTEST_MEMORYCHECK_TYPE "${MEMCHECK_TYPE}")
CTEST_START(Experimental)
CTEST_CONFIGURE(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res)
CTEST_TEST(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res)
-CTEST_MEMCHECK(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res ${MEMCHECK_ARGS})
+CTEST_MEMCHECK(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res @CTEST_MEMCHECK_ARGS@)
+
+@CTEST_SUFFIX_CODE@
diff --git a/Tests/RunCMake/execute_process/CMakeLists.txt b/Tests/RunCMake/execute_process/CMakeLists.txt
new file mode 100644
index 0000000..a640c56
--- /dev/null
+++ b/Tests/RunCMake/execute_process/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.7)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/execute_process/Encoding.cmake b/Tests/RunCMake/execute_process/Encoding.cmake
new file mode 100644
index 0000000..3dc7c39
--- /dev/null
+++ b/Tests/RunCMake/execute_process/Encoding.cmake
@@ -0,0 +1,6 @@
+execute_process(
+ COMMAND ${TEST_ENCODING_EXE} ${TEST_ENCODING} ${CMAKE_CURRENT_LIST_DIR}/EncodingUTF8-stderr.txt
+ OUTPUT_VARIABLE out
+ ENCODING ${TEST_ENCODING}
+ )
+message("${out}")
diff --git a/Tests/RunCMake/execute_process/EncodingMissing-result.txt b/Tests/RunCMake/execute_process/EncodingMissing-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingMissing-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/execute_process/EncodingMissing-stderr.txt b/Tests/RunCMake/execute_process/EncodingMissing-stderr.txt
new file mode 100644
index 0000000..1a69579
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingMissing-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at EncodingMissing.cmake:[0-9]+ \(execute_process\):
+ execute_process called with no value for ENCODING.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/execute_process/EncodingMissing.cmake b/Tests/RunCMake/execute_process/EncodingMissing.cmake
new file mode 100644
index 0000000..ae97480
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingMissing.cmake
@@ -0,0 +1 @@
+execute_process(ENCODING)
diff --git a/Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt b/Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt
new file mode 100644
index 0000000..0ac68de
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt
@@ -0,0 +1 @@
+ą¤Æą„‚ą¤Øą¤æą¤•ą„‹ą¤” είναι very зГорово!
diff --git a/Tests/RunCMake/execute_process/RunCMakeTest.cmake b/Tests/RunCMake/execute_process/RunCMakeTest.cmake
index 2080437..62e18c6 100644
--- a/Tests/RunCMake/execute_process/RunCMakeTest.cmake
+++ b/Tests/RunCMake/execute_process/RunCMakeTest.cmake
@@ -6,3 +6,8 @@ unset(RunCMake_TEST_OUTPUT_MERGE)
run_cmake_command(MergeOutputFile ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/MergeOutputFile.cmake)
run_cmake_command(MergeOutputVars ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/MergeOutputVars.cmake)
+
+run_cmake(EncodingMissing)
+if(TEST_ENCODING_EXE)
+ run_cmake_command(EncodingUTF8 ${CMAKE_COMMAND} -DTEST_ENCODING=UTF8 -DTEST_ENCODING_EXE=${TEST_ENCODING_EXE} -P ${RunCMake_SOURCE_DIR}/Encoding.cmake)
+endif()
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt
new file mode 100644
index 0000000..454c655
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt
@@ -0,0 +1,44 @@
+^CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property value
+
+ -flag
+
+ may not start with '-'.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property value
+
+ item1;item2
+
+ may not contain ';'.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property value
+
+ /path/to/item1
+
+ may not contain '/'.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property value
+
+ \\path\\to\\item1
+
+ may not contain '\\'.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property value
+
+ c:\\path\\to\\item1
+
+ may not contain ':'.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake
new file mode 100644
index 0000000..1af65b4
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake
@@ -0,0 +1,6 @@
+add_library(MyTarget INTERFACE IMPORTED)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME -flag)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME item1 item2)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME /path/to/item1)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME \\path\\to\\item1)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME c:\\path\\to\\item1)
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt
new file mode 100644
index 0000000..3a329d2
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt
@@ -0,0 +1,45 @@
+^CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+ targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may not be APPENDed.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME_DEBUG property may be set only on imported INTERFACE
+ library targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME_DEBUG property may not be APPENDed.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+ targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+ targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+ targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+ targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake
new file mode 100644
index 0000000..fe6841a
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake
@@ -0,0 +1,17 @@
+add_custom_target(MyCustom)
+set_property(TARGET MyCustom PROPERTY IMPORTED_LIBNAME item1)
+set_property(TARGET MyCustom APPEND PROPERTY IMPORTED_LIBNAME item2)
+set_property(TARGET MyCustom PROPERTY IMPORTED_LIBNAME_DEBUG item1)
+set_property(TARGET MyCustom APPEND PROPERTY IMPORTED_LIBNAME_DEBUG item2)
+
+add_library(MyStatic STATIC IMPORTED)
+set_property(TARGET MyStatic PROPERTY IMPORTED_LIBNAME item1)
+
+add_library(MyShared SHARED IMPORTED)
+set_property(TARGET MyShared PROPERTY IMPORTED_LIBNAME item1)
+
+add_library(MyModule MODULE IMPORTED)
+set_property(TARGET MyModule PROPERTY IMPORTED_LIBNAME item1)
+
+add_executable(MyExe IMPORTED)
+set_property(TARGET MyExe PROPERTY IMPORTED_LIBNAME item1)
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt
new file mode 100644
index 0000000..e9d94cf
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt
@@ -0,0 +1,21 @@
+^CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+ targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME property may not be APPENDed.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME_DEBUG property may be set only on imported INTERFACE
+ library targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+ IMPORTED_LIBNAME_DEBUG property may not be APPENDed.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake
new file mode 100644
index 0000000..07a67d7
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake
@@ -0,0 +1,5 @@
+add_library(MyTarget INTERFACE)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME item1)
+set_property(TARGET MyTarget APPEND PROPERTY IMPORTED_LIBNAME item2)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME_DEBUG item1)
+set_property(TARGET MyTarget APPEND PROPERTY IMPORTED_LIBNAME_DEBUG item2)
diff --git a/Tests/RunCMake/interface_library/RunCMakeTest.cmake b/Tests/RunCMake/interface_library/RunCMakeTest.cmake
index 201daa7..5a6af1d 100644
--- a/Tests/RunCMake/interface_library/RunCMakeTest.cmake
+++ b/Tests/RunCMake/interface_library/RunCMakeTest.cmake
@@ -8,3 +8,6 @@ run_cmake(invalid_signature)
run_cmake(global-interface)
run_cmake(genex_link)
run_cmake(add_custom_command-TARGET)
+run_cmake(IMPORTED_LIBNAME-bad-value)
+run_cmake(IMPORTED_LIBNAME-non-iface)
+run_cmake(IMPORTED_LIBNAME-non-imported)
diff --git a/Tests/RunCMake/pseudo_emulator_custom_command.c b/Tests/RunCMake/pseudo_emulator_custom_command.c
index 760e83c..3a94795 100644
--- a/Tests/RunCMake/pseudo_emulator_custom_command.c
+++ b/Tests/RunCMake/pseudo_emulator_custom_command.c
@@ -14,7 +14,8 @@
int main(int argc, const char* argv[])
{
const char* substring_failure = "generated_exe_emulator_unexpected";
- const char* substring_success = "generated_exe_emulator_expected";
+ // Require a slash to make sure it is a path and not a target name.
+ const char* substring_success = "/generated_exe_emulator_expected";
const char* str = argv[1];
if (argc < 2) {
return EXIT_FAILURE;
diff --git a/Tests/RunCMake/pseudo_iwyu.c b/Tests/RunCMake/pseudo_iwyu.c
index 1e25de7..c761741 100644
--- a/Tests/RunCMake/pseudo_iwyu.c
+++ b/Tests/RunCMake/pseudo_iwyu.c
@@ -3,5 +3,6 @@
int main(void)
{
fprintf(stderr, "should add these lines:\n#include <...>\n");
- return 0;
+ /* include-what-you-use always returns failure */
+ return 1;
}
diff --git a/Tests/RunCMake/pseudo_tidy.c b/Tests/RunCMake/pseudo_tidy.c
index c950d03..2feeb0f 100644
--- a/Tests/RunCMake/pseudo_tidy.c
+++ b/Tests/RunCMake/pseudo_tidy.c
@@ -1,9 +1,15 @@
#include <stdio.h>
+#include <string.h>
int main(int argc, char* argv[])
{
int i;
for (i = 1; i < argc; ++i) {
+ if (strcmp(argv[i], "-bad") == 0) {
+ fprintf(stdout, "stdout from bad command line arg '-bad'\n");
+ fprintf(stderr, "stderr from bad command line arg '-bad'\n");
+ return 1;
+ }
if (argv[i][0] != '-') {
fprintf(stdout, "%s:0:0: warning: message [checker]\n", argv[i]);
break;
diff --git a/Tests/RunCMake/try_compile/RunCMakeTest.cmake b/Tests/RunCMake/try_compile/RunCMakeTest.cmake
index 522433a..4934bcd 100644
--- a/Tests/RunCMake/try_compile/RunCMakeTest.cmake
+++ b/Tests/RunCMake/try_compile/RunCMakeTest.cmake
@@ -18,6 +18,7 @@ run_cmake(NonSourceCompileDefinitions)
set(RunCMake_TEST_OPTIONS --debug-trycompile)
run_cmake(PlatformVariables)
+run_cmake(WarnDeprecated)
unset(RunCMake_TEST_OPTIONS)
run_cmake(TargetTypeExe)
diff --git a/Tests/RunCMake/try_compile/WarnDeprecated.cmake b/Tests/RunCMake/try_compile/WarnDeprecated.cmake
new file mode 100644
index 0000000..dfcb5f9
--- /dev/null
+++ b/Tests/RunCMake/try_compile/WarnDeprecated.cmake
@@ -0,0 +1,19 @@
+enable_language(C)
+
+set(CMAKE_WARN_DEPRECATED SOME_VALUE)
+
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+ SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+ OUTPUT_VARIABLE out
+ )
+if(NOT result)
+ message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
+
+# Check that the cache was populated with our custom variable.
+file(STRINGS ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp/CMakeCache.txt entries
+ REGEX CMAKE_WARN_DEPRECATED:UNINITIALIZED=${CMAKE_WARN_DEPRECATED}
+ )
+if(NOT entries)
+ message(FATAL_ERROR "try_compile did not populate cache as expected")
+endif()
diff --git a/Tests/RunCMake/while/EndAlone-stderr.txt b/Tests/RunCMake/while/EndAlone-stderr.txt
index cd98687..5fe6655 100644
--- a/Tests/RunCMake/while/EndAlone-stderr.txt
+++ b/Tests/RunCMake/while/EndAlone-stderr.txt
@@ -1,5 +1,5 @@
^CMake Error at EndAlone.cmake:1 \(endwhile\):
endwhile An ENDWHILE command was found outside of a proper WHILE ENDWHILE
- structure.
+ structure. Or its arguments did not match the opening WHILE command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)$
diff --git a/Tests/SwigTest/CMakeLists.txt b/Tests/SwigTest/CMakeLists.txt
index 17a502d..65f5c93 100644
--- a/Tests/SwigTest/CMakeLists.txt
+++ b/Tests/SwigTest/CMakeLists.txt
@@ -7,6 +7,7 @@ project(example_${language}_class)
find_package(SWIG REQUIRED)
include(${SWIG_USE_FILE})
+unset(SWIG_LANG_TYPE)
if(${language} MATCHES python)
find_package(PythonLibs)
include_directories(${PYTHON_INCLUDE_PATH})
@@ -38,6 +39,12 @@ if(${language} MATCHES pike)
include_directories(${PIKE_INCLUDE_PATH})
set(SWIG_LANG_LIBRARIES ${PIKE_LIBRARY})
endif()
+if(${language} MATCHES lua)
+ find_package(Lua)
+ include_directories(${LUA_INCLUDE_DIR})
+ set(SWIG_LANG_TYPE TYPE SHARED)
+ set(SWIG_LANG_LIBRARIES ${LUA_LIBRARIES})
+endif()
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
@@ -45,6 +52,8 @@ set(CMAKE_SWIG_FLAGS "")
set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON)
set_source_files_properties(example.i PROPERTIES SWIG_FLAGS "-includeall")
-SWIG_ADD_MODULE(example "${language}"
- example.i example.cxx)
+SWIG_ADD_LIBRARY(example
+ LANGUAGE "${language}"
+ ${SWIG_LANG_TYPE}
+ SOURCES example.i example.cxx)
SWIG_LINK_LIBRARIES(example ${SWIG_LANG_LIBRARIES})
diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt
index 1e51ea2..014204b 100644
--- a/Utilities/CMakeLists.txt
+++ b/Utilities/CMakeLists.txt
@@ -1,7 +1,7 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-subdirs(Doxygen KWStyle)
+subdirs(Doxygen)
if(CMAKE_DOC_TARBALL)
# Undocumented option to extract and install pre-built documentation.
diff --git a/Utilities/KWStyle/CMake.kws.xml.in b/Utilities/KWStyle/CMake.kws.xml.in
deleted file mode 100644
index c2b4429..0000000
--- a/Utilities/KWStyle/CMake.kws.xml.in
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Description>
-<LineLength>79</LineLength>
-<!--
-<Header>"@CMake_SOURCE_DIR@/Utilities/KWStyle/Headers",false,true</Header>
-<Functions>
-<regex>[A-Z]</regex>
-<length>100</length>
-</Functions>
--->
-</Description>
diff --git a/Utilities/KWStyle/CMakeFiles.txt.in b/Utilities/KWStyle/CMakeFiles.txt.in
deleted file mode 100644
index a95aac6..0000000
--- a/Utilities/KWStyle/CMakeFiles.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-"@CMake_SOURCE_DIR@/Source/*.txx"
-"@CMake_SOURCE_DIR@/Source/*.cxx"
-"@CMake_SOURCE_DIR@/Source/*.h*"
-"@CMake_SOURCE_DIR@/Source/CPack/*.txx"
-"@CMake_SOURCE_DIR@/Source/CPack/*.cxx"
-"@CMake_SOURCE_DIR@/Source/CPack/*.h*"
-"@CMake_SOURCE_DIR@/Source/CTest/*.txx"
-"@CMake_SOURCE_DIR@/Source/CTest/*.cxx"
-"@CMake_SOURCE_DIR@/Source/CTest/*.h*"
-"@CMake_SOURCE_DIR@/Source/CurseDialog/*.h*"
-"@CMake_SOURCE_DIR@/Source/CurseDialog/*.cxx"
-"@CMake_SOURCE_DIR@/Source/CurseDialog/*.txx"
--f (Lexer\.h)
--f (Lexer\.cxx)
--f (Parser\.cxx)
diff --git a/Utilities/KWStyle/CMakeLists.txt b/Utilities/KWStyle/CMakeLists.txt
deleted file mode 100644
index 3e96c33..0000000
--- a/Utilities/KWStyle/CMakeLists.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
-# file Copyright.txt or https://cmake.org/licensing for details.
-
-#-----------------------------------------------------------------------------
-# CMake uses KWStyle for checking the coding style
-
-# Search for a built-from-source KWStyle under Dashboards/Support on a typical
-# dashboard machines:
-#
-set(home "$ENV{HOME}")
-if(NOT home)
- string(REPLACE "\\" "/" home "$ENV{USERPROFILE}")
-endif()
-
-find_program(KWSTYLE_EXECUTABLE
- NAMES KWStyle
- PATHS
- "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Kitware Inc.\\KWStyle 1.0.0]/bin"
- "${home}/Dashboards/Support/KWStyle/bin"
- )
-mark_as_advanced(KWSTYLE_EXECUTABLE)
-
-set(CMAKE_USE_KWSTYLE_DEFAULT OFF)
-if(KWSTYLE_EXECUTABLE)
- set(CMAKE_USE_KWSTYLE_DEFAULT ON)
-endif()
-
-option(CMAKE_USE_KWSTYLE
- "Add StyleCheck target and KWStyle test: run KWStyle to check for coding standard violations."
- ${CMAKE_USE_KWSTYLE_DEFAULT})
-mark_as_advanced(CMAKE_USE_KWSTYLE)
-
-if(CMAKE_USE_KWSTYLE)
- option(KWSTYLE_USE_VIM_FORMAT "Set KWStyle to generate errors with a VIM-compatible format." OFF)
- option(KWSTYLE_USE_MSVC_FORMAT "Set KWStyle to generate errors with a VisualStudio-compatible format." OFF)
- mark_as_advanced(KWSTYLE_USE_VIM_FORMAT)
- mark_as_advanced(KWSTYLE_USE_MSVC_FORMAT)
-
- if(KWSTYLE_USE_VIM_FORMAT)
- set(KWSTYLE_ARGUMENTS -vim ${KWSTYLE_ARGUMENTS})
- endif()
-
- if(KWSTYLE_USE_MSVC_FORMAT)
- set(KWSTYLE_ARGUMENTS -msvc ${KWSTYLE_ARGUMENTS})
- endif()
-
- configure_file(${CMake_SOURCE_DIR}/Utilities/KWStyle/CMake.kws.xml.in
- ${CMake_BINARY_DIR}/CMake.kws.xml)
- configure_file(${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in
- ${CMake_BINARY_DIR}/CMakeMoreChecks.kws.xml)
-
- configure_file(${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeFiles.txt.in
- ${CMake_BINARY_DIR}/CMakeKWSFiles.txt)
-
- add_custom_command(
- OUTPUT ${CMake_BINARY_DIR}/KWStyleReport.txt
- COMMAND ${KWSTYLE_EXECUTABLE}
- ARGS -xml ${CMake_BINARY_DIR}/CMake.kws.xml -o ${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeOverwrite.txt -v ${KWSTYLE_ARGUMENTS} -D ${CMake_BINARY_DIR}/CMakeKWSFiles.txt
- COMMENT "Coding Style Checker"
- )
-
- add_custom_target(MoreStyleChecks
- COMMAND ${KWSTYLE_EXECUTABLE}
- -xml ${CMake_BINARY_DIR}/CMakeMoreChecks.kws.xml -html ${CMake_BINARY_DIR}/html -o ${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeOverwrite.txt -v ${KWSTYLE_ARGUMENTS} -D ${CMake_BINARY_DIR}/CMakeKWSFiles.txt
- COMMENT "Coding Style Checker, more checks enabled"
- )
-
- add_custom_target(StyleCheck DEPENDS ${CMake_BINARY_DIR}/KWStyleReport.txt)
-endif()
diff --git a/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in b/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in
deleted file mode 100644
index c48e92f..0000000
--- a/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Description>
- <ErrorThreshold>10</ErrorThreshold>
- <LineLength>79</LineLength>
- <Header>"@CMake_SOURCE_DIR@/Utilities/KWStyle/Headers",false,true</Header>
- <Functions>
- <regex>^(cm)?[A-Z]</regex>
- <length>200</length>
- </Functions>
- <InternalVariables>
- <regex>^[A-Z]</regex>
- <alignment>0</alignment>
- </InternalVariables>
- <SemicolonSpace>0</SemicolonSpace>
- <DeclarationOrder>
- <public>0</public>
- <protected>1</protected>
- <private>2</private>
- </DeclarationOrder>
- <Tabs>1</Tabs>
- <EmptyLines>4</EmptyLines>
- <StatementPerLine>
- <maxNumber>1</maxNumber>
- <checkInline>0</checkInline>
- </StatementPerLine>
- <VariablePerLine>
- <maxNumber>1</maxNumber>
- </VariablePerLine>
- <BadCharacters>true</BadCharacters>
-</Description>
diff --git a/Utilities/KWStyle/CMakeOverwrite.txt b/Utilities/KWStyle/CMakeOverwrite.txt
deleted file mode 100644
index e69de29..0000000
--- a/Utilities/KWStyle/CMakeOverwrite.txt
+++ /dev/null
diff --git a/Utilities/Release/linux64_release.cmake b/Utilities/Release/linux64_release.cmake
index b9447ca..feba2a5 100644
--- a/Utilities/Release/linux64_release.cmake
+++ b/Utilities/Release/linux64_release.cmake
@@ -29,9 +29,9 @@ CURSES_LIBRARY:FILEPATH=/home/kitware/ncurses-5.9/lib/libncurses.a
CURSES_INCLUDE_PATH:PATH=/home/kitware/ncurses-5.9/include
FORM_LIBRARY:FILEPATH=/home/kitware/ncurses-5.9/lib/libform.a
CMAKE_USE_OPENSSL:BOOL=ON
-OPENSSL_CRYPTO_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libcrypto.a
-OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.0.2h/include
-OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libssl.a
+OPENSSL_CRYPTO_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2j/lib/libcrypto.a
+OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.0.2j/include
+OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2j/lib/libssl.a
PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3
CPACK_SYSTEM_NAME:STRING=Linux-x86_64
BUILD_QtDialog:BOOL:=TRUE
diff --git a/Utilities/Scripts/clang-format.bash b/Utilities/Scripts/clang-format.bash
index ad3b3a1..8e07c99 100755
--- a/Utilities/Scripts/clang-format.bash
+++ b/Utilities/Scripts/clang-format.bash
@@ -121,7 +121,7 @@ $git_ls -z -- '*.c' '*.cc' '*.cpp' '*.cxx' '*.h' '*.hh' '*.hpp' '*.hxx' |
egrep -z -v '^Source/cmListFileLexer(\.in\.l|\.c)' |
# Exclude third-party sources.
- egrep -z -v '^Source/(cm_sha2|bindexplib)' |
+ egrep -z -v '^Source/bindexplib' |
egrep -z -v '^Source/(kwsys|CursesDialog/form)/' |
egrep -z -v '^Utilities/(KW|cm).*/' |
diff --git a/Utilities/Scripts/update-librhash.bash b/Utilities/Scripts/update-librhash.bash
new file mode 100755
index 0000000..009ce32
--- /dev/null
+++ b/Utilities/Scripts/update-librhash.bash
@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="librhash"
+readonly ownership="librhash upstream <kwrobot@kitware.com>"
+readonly subtree="Utilities/cmlibrhash"
+readonly repo="https://github.com/rhash/rhash.git"
+readonly tag="master"
+readonly shortlog=false
+readonly paths="
+ COPYING
+ README
+ librhash/algorithms.c
+ librhash/algorithms.h
+ librhash/byte_order.c
+ librhash/byte_order.h
+ librhash/hex.c
+ librhash/hex.h
+ librhash/md5.c
+ librhash/md5.h
+ librhash/rhash.c
+ librhash/rhash.h
+ librhash/sha1.c
+ librhash/sha1.h
+ librhash/sha256.c
+ librhash/sha256.h
+ librhash/sha3.c
+ librhash/sha3.h
+ librhash/sha512.c
+ librhash/sha512.h
+ librhash/ustd.h
+ librhash/util.h
+"
+
+extract_source () {
+ git_archive
+ pushd "${extractdir}/${name}-reduced"
+ echo "* -whitespace" > .gitattributes
+ popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/cmThirdParty.h.in b/Utilities/cmThirdParty.h.in
index 210e727..a547f0d 100644
--- a/Utilities/cmThirdParty.h.in
+++ b/Utilities/cmThirdParty.h.in
@@ -13,6 +13,7 @@
#cmakedefine CMAKE_USE_SYSTEM_LIBLZMA
#cmakedefine CMAKE_USE_SYSTEM_FORM
#cmakedefine CMAKE_USE_SYSTEM_JSONCPP
+#cmakedefine CMAKE_USE_SYSTEM_LIBRHASH
#cmakedefine CMAKE_USE_SYSTEM_LIBUV
#cmakedefine CTEST_USE_XMLRPC
diff --git a/Utilities/cm_rhash.h b/Utilities/cm_rhash.h
new file mode 100644
index 0000000..c793627
--- /dev/null
+++ b/Utilities/cm_rhash.h
@@ -0,0 +1,14 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cm_rhash_h
+#define cm_rhash_h
+
+/* Use the LibRHash library configured for CMake. */
+#include "cmThirdParty.h"
+#ifdef CMAKE_USE_SYSTEM_LIBRHASH
+#include <rhash.h>
+#else
+#include <cmlibrhash/librhash/rhash.h>
+#endif
+
+#endif
diff --git a/Utilities/cmlibarchive/libarchive/CMakeLists.txt b/Utilities/cmlibarchive/libarchive/CMakeLists.txt
index 4eeb5e3..eaa7b20 100644
--- a/Utilities/cmlibarchive/libarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/libarchive/CMakeLists.txt
@@ -38,6 +38,8 @@ SET(libarchive_SOURCES
archive_hmac.c
archive_hmac_private.h
archive_match.c
+ archive_openssl_evp_private.h
+ archive_openssl_hmac_private.h
archive_options.c
archive_options_private.h
archive_pack_dev.h
diff --git a/Utilities/cmlibarchive/libarchive/archive_cryptor.c b/Utilities/cmlibarchive/libarchive/archive_cryptor.c
index 0be30c6..2a51dfe 100644
--- a/Utilities/cmlibarchive/libarchive/archive_cryptor.c
+++ b/Utilities/cmlibarchive/libarchive/archive_cryptor.c
@@ -302,6 +302,7 @@ aes_ctr_release(archive_crypto_ctx *ctx)
static int
aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
{
+ ctx->ctx = EVP_CIPHER_CTX_new();
switch (key_len) {
case 16: ctx->type = EVP_aes_128_ecb(); break;
@@ -314,7 +315,7 @@ aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
memcpy(ctx->key, key, key_len);
memset(ctx->nonce, 0, sizeof(ctx->nonce));
ctx->encr_pos = AES_BLOCK_SIZE;
- EVP_CIPHER_CTX_init(&ctx->ctx);
+ EVP_CIPHER_CTX_init(ctx->ctx);
return 0;
}
@@ -324,10 +325,10 @@ aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
int outl = 0;
int r;
- r = EVP_EncryptInit_ex(&ctx->ctx, ctx->type, NULL, ctx->key, NULL);
+ r = EVP_EncryptInit_ex(ctx->ctx, ctx->type, NULL, ctx->key, NULL);
if (r == 0)
return -1;
- r = EVP_EncryptUpdate(&ctx->ctx, ctx->encr_buf, &outl, ctx->nonce,
+ r = EVP_EncryptUpdate(ctx->ctx, ctx->encr_buf, &outl, ctx->nonce,
AES_BLOCK_SIZE);
if (r == 0 || outl != AES_BLOCK_SIZE)
return -1;
@@ -337,7 +338,7 @@ aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
static int
aes_ctr_release(archive_crypto_ctx *ctx)
{
- EVP_CIPHER_CTX_cleanup(&ctx->ctx);
+ EVP_CIPHER_CTX_free(ctx->ctx);
memset(ctx->key, 0, ctx->key_len);
memset(ctx->nonce, 0, sizeof(ctx->nonce));
return 0;
diff --git a/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h b/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h
index 37eaad3..0ca544b 100644
--- a/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h
@@ -99,12 +99,12 @@ typedef struct {
} archive_crypto_ctx;
#elif defined(HAVE_LIBCRYPTO)
-#include <openssl/evp.h>
+#include "archive_openssl_evp_private.h"
#define AES_BLOCK_SIZE 16
#define AES_MAX_KEY_SIZE 32
typedef struct {
- EVP_CIPHER_CTX ctx;
+ EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *type;
uint8_t key[AES_MAX_KEY_SIZE];
unsigned key_len;
diff --git a/Utilities/cmlibarchive/libarchive/archive_digest.c b/Utilities/cmlibarchive/libarchive/archive_digest.c
index f009d31..4153923 100644
--- a/Utilities/cmlibarchive/libarchive/archive_digest.c
+++ b/Utilities/cmlibarchive/libarchive/archive_digest.c
@@ -207,7 +207,9 @@ __archive_nettle_md5final(archive_md5_ctx *ctx, void *md)
static int
__archive_openssl_md5init(archive_md5_ctx *ctx)
{
- EVP_DigestInit(ctx, EVP_md5());
+ if ((*ctx = EVP_MD_CTX_new()) == NULL)
+ return (ARCHIVE_FAILED);
+ EVP_DigestInit(*ctx, EVP_md5());
return (ARCHIVE_OK);
}
@@ -215,7 +217,7 @@ static int
__archive_openssl_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
- EVP_DigestUpdate(ctx, indata, insize);
+ EVP_DigestUpdate(*ctx, indata, insize);
return (ARCHIVE_OK);
}
@@ -226,8 +228,11 @@ __archive_openssl_md5final(archive_md5_ctx *ctx, void *md)
* this is meant to cope with that. Real fix is probably to fix
* archive_write_set_format_xar.c
*/
- if (ctx->digest)
- EVP_DigestFinal(ctx, md, NULL);
+ if (*ctx) {
+ EVP_DigestFinal(*ctx, md, NULL);
+ EVP_MD_CTX_free(*ctx);
+ *ctx = NULL;
+ }
return (ARCHIVE_OK);
}
@@ -359,7 +364,9 @@ __archive_nettle_ripemd160final(archive_rmd160_ctx *ctx, void *md)
static int
__archive_openssl_ripemd160init(archive_rmd160_ctx *ctx)
{
- EVP_DigestInit(ctx, EVP_ripemd160());
+ if ((*ctx = EVP_MD_CTX_new()) == NULL)
+ return (ARCHIVE_FAILED);
+ EVP_DigestInit(*ctx, EVP_ripemd160());
return (ARCHIVE_OK);
}
@@ -367,14 +374,18 @@ static int
__archive_openssl_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
- EVP_DigestUpdate(ctx, indata, insize);
+ EVP_DigestUpdate(*ctx, indata, insize);
return (ARCHIVE_OK);
}
static int
__archive_openssl_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
- EVP_DigestFinal(ctx, md, NULL);
+ if (*ctx) {
+ EVP_DigestFinal(*ctx, md, NULL);
+ EVP_MD_CTX_free(*ctx);
+ *ctx = NULL;
+ }
return (ARCHIVE_OK);
}
@@ -509,7 +520,9 @@ __archive_nettle_sha1final(archive_sha1_ctx *ctx, void *md)
static int
__archive_openssl_sha1init(archive_sha1_ctx *ctx)
{
- EVP_DigestInit(ctx, EVP_sha1());
+ if ((*ctx = EVP_MD_CTX_new()) == NULL)
+ return (ARCHIVE_FAILED);
+ EVP_DigestInit(*ctx, EVP_sha1());
return (ARCHIVE_OK);
}
@@ -517,7 +530,7 @@ static int
__archive_openssl_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
- EVP_DigestUpdate(ctx, indata, insize);
+ EVP_DigestUpdate(*ctx, indata, insize);
return (ARCHIVE_OK);
}
@@ -528,8 +541,11 @@ __archive_openssl_sha1final(archive_sha1_ctx *ctx, void *md)
* this is meant to cope with that. Real fix is probably to fix
* archive_write_set_format_xar.c
*/
- if (ctx->digest)
- EVP_DigestFinal(ctx, md, NULL);
+ if (*ctx) {
+ EVP_DigestFinal(*ctx, md, NULL);
+ EVP_MD_CTX_free(*ctx);
+ *ctx = NULL;
+ }
return (ARCHIVE_OK);
}
@@ -733,7 +749,9 @@ __archive_nettle_sha256final(archive_sha256_ctx *ctx, void *md)
static int
__archive_openssl_sha256init(archive_sha256_ctx *ctx)
{
- EVP_DigestInit(ctx, EVP_sha256());
+ if ((*ctx = EVP_MD_CTX_new()) == NULL)
+ return (ARCHIVE_FAILED);
+ EVP_DigestInit(*ctx, EVP_sha256());
return (ARCHIVE_OK);
}
@@ -741,14 +759,18 @@ static int
__archive_openssl_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
- EVP_DigestUpdate(ctx, indata, insize);
+ EVP_DigestUpdate(*ctx, indata, insize);
return (ARCHIVE_OK);
}
static int
__archive_openssl_sha256final(archive_sha256_ctx *ctx, void *md)
{
- EVP_DigestFinal(ctx, md, NULL);
+ if (*ctx) {
+ EVP_DigestFinal(*ctx, md, NULL);
+ EVP_MD_CTX_free(*ctx);
+ *ctx = NULL;
+ }
return (ARCHIVE_OK);
}
@@ -928,7 +950,9 @@ __archive_nettle_sha384final(archive_sha384_ctx *ctx, void *md)
static int
__archive_openssl_sha384init(archive_sha384_ctx *ctx)
{
- EVP_DigestInit(ctx, EVP_sha384());
+ if ((*ctx = EVP_MD_CTX_new()) == NULL)
+ return (ARCHIVE_FAILED);
+ EVP_DigestInit(*ctx, EVP_sha384());
return (ARCHIVE_OK);
}
@@ -936,14 +960,18 @@ static int
__archive_openssl_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
- EVP_DigestUpdate(ctx, indata, insize);
+ EVP_DigestUpdate(*ctx, indata, insize);
return (ARCHIVE_OK);
}
static int
__archive_openssl_sha384final(archive_sha384_ctx *ctx, void *md)
{
- EVP_DigestFinal(ctx, md, NULL);
+ if (*ctx) {
+ EVP_DigestFinal(*ctx, md, NULL);
+ EVP_MD_CTX_free(*ctx);
+ *ctx = NULL;
+ }
return (ARCHIVE_OK);
}
@@ -1147,7 +1175,9 @@ __archive_nettle_sha512final(archive_sha512_ctx *ctx, void *md)
static int
__archive_openssl_sha512init(archive_sha512_ctx *ctx)
{
- EVP_DigestInit(ctx, EVP_sha512());
+ if ((*ctx = EVP_MD_CTX_new()) == NULL)
+ return (ARCHIVE_FAILED);
+ EVP_DigestInit(*ctx, EVP_sha512());
return (ARCHIVE_OK);
}
@@ -1155,14 +1185,18 @@ static int
__archive_openssl_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
- EVP_DigestUpdate(ctx, indata, insize);
+ EVP_DigestUpdate(*ctx, indata, insize);
return (ARCHIVE_OK);
}
static int
__archive_openssl_sha512final(archive_sha512_ctx *ctx, void *md)
{
- EVP_DigestFinal(ctx, md, NULL);
+ if (*ctx) {
+ EVP_DigestFinal(*ctx, md, NULL);
+ EVP_MD_CTX_free(*ctx);
+ *ctx = NULL;
+ }
return (ARCHIVE_OK);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_digest_private.h b/Utilities/cmlibarchive/libarchive/archive_digest_private.h
index 77fad58..b58ffb3 100644
--- a/Utilities/cmlibarchive/libarchive/archive_digest_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_digest_private.h
@@ -134,7 +134,7 @@
defined(ARCHIVE_CRYPTO_SHA384_OPENSSL) ||\
defined(ARCHIVE_CRYPTO_SHA512_OPENSSL)
#define ARCHIVE_CRYPTO_OPENSSL 1
-#include <openssl/evp.h>
+#include "archive_openssl_evp_private.h"
#endif
/* Windows crypto headers */
@@ -161,7 +161,7 @@ typedef CC_MD5_CTX archive_md5_ctx;
#elif defined(ARCHIVE_CRYPTO_MD5_NETTLE)
typedef struct md5_ctx archive_md5_ctx;
#elif defined(ARCHIVE_CRYPTO_MD5_OPENSSL)
-typedef EVP_MD_CTX archive_md5_ctx;
+typedef EVP_MD_CTX *archive_md5_ctx;
#elif defined(ARCHIVE_CRYPTO_MD5_WIN)
typedef Digest_CTX archive_md5_ctx;
#else
@@ -175,7 +175,7 @@ typedef RIPEMD160_CTX archive_rmd160_ctx;
#elif defined(ARCHIVE_CRYPTO_RMD160_NETTLE)
typedef struct ripemd160_ctx archive_rmd160_ctx;
#elif defined(ARCHIVE_CRYPTO_RMD160_OPENSSL)
-typedef EVP_MD_CTX archive_rmd160_ctx;
+typedef EVP_MD_CTX *archive_rmd160_ctx;
#else
typedef unsigned char archive_rmd160_ctx;
#endif
@@ -189,7 +189,7 @@ typedef CC_SHA1_CTX archive_sha1_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA1_NETTLE)
typedef struct sha1_ctx archive_sha1_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA1_OPENSSL)
-typedef EVP_MD_CTX archive_sha1_ctx;
+typedef EVP_MD_CTX *archive_sha1_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA1_WIN)
typedef Digest_CTX archive_sha1_ctx;
#else
@@ -209,7 +209,7 @@ typedef CC_SHA256_CTX archive_sha256_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA256_NETTLE)
typedef struct sha256_ctx archive_sha256_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA256_OPENSSL)
-typedef EVP_MD_CTX archive_sha256_ctx;
+typedef EVP_MD_CTX *archive_sha256_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA256_WIN)
typedef Digest_CTX archive_sha256_ctx;
#else
@@ -227,7 +227,7 @@ typedef CC_SHA512_CTX archive_sha384_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA384_NETTLE)
typedef struct sha384_ctx archive_sha384_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA384_OPENSSL)
-typedef EVP_MD_CTX archive_sha384_ctx;
+typedef EVP_MD_CTX *archive_sha384_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA384_WIN)
typedef Digest_CTX archive_sha384_ctx;
#else
@@ -247,7 +247,7 @@ typedef CC_SHA512_CTX archive_sha512_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA512_NETTLE)
typedef struct sha512_ctx archive_sha512_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA512_OPENSSL)
-typedef EVP_MD_CTX archive_sha512_ctx;
+typedef EVP_MD_CTX *archive_sha512_ctx;
#elif defined(ARCHIVE_CRYPTO_SHA512_WIN)
typedef Digest_CTX archive_sha512_ctx;
#else
diff --git a/Utilities/cmlibarchive/libarchive/archive_hmac.c b/Utilities/cmlibarchive/libarchive/archive_hmac.c
index 7857c0f..1e0ae28 100644
--- a/Utilities/cmlibarchive/libarchive/archive_hmac.c
+++ b/Utilities/cmlibarchive/libarchive/archive_hmac.c
@@ -176,8 +176,10 @@ __hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx)
static int
__hmac_sha1_init(archive_hmac_sha1_ctx *ctx, const uint8_t *key, size_t key_len)
{
- HMAC_CTX_init(ctx);
- HMAC_Init(ctx, key, key_len, EVP_sha1());
+ *ctx = HMAC_CTX_new();
+ if (*ctx == NULL)
+ return -1;
+ HMAC_Init_ex(*ctx, key, key_len, EVP_sha1(), NULL);
return 0;
}
@@ -185,22 +187,22 @@ static void
__hmac_sha1_update(archive_hmac_sha1_ctx *ctx, const uint8_t *data,
size_t data_len)
{
- HMAC_Update(ctx, data, data_len);
+ HMAC_Update(*ctx, data, data_len);
}
static void
__hmac_sha1_final(archive_hmac_sha1_ctx *ctx, uint8_t *out, size_t *out_len)
{
unsigned int len = (unsigned int)*out_len;
- HMAC_Final(ctx, out, &len);
+ HMAC_Final(*ctx, out, &len);
*out_len = len;
}
static void
__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx)
{
- HMAC_CTX_cleanup(ctx);
- memset(ctx, 0, sizeof(*ctx));
+ HMAC_CTX_free(*ctx);
+ *ctx = NULL;
}
#else
diff --git a/Utilities/cmlibarchive/libarchive/archive_hmac_private.h b/Utilities/cmlibarchive/libarchive/archive_hmac_private.h
index 64de743..eb45c4e 100644
--- a/Utilities/cmlibarchive/libarchive/archive_hmac_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_hmac_private.h
@@ -70,9 +70,9 @@ typedef struct {
typedef struct hmac_sha1_ctx archive_hmac_sha1_ctx;
#elif defined(HAVE_LIBCRYPTO)
-#include <openssl/hmac.h>
+#include "archive_openssl_hmac_private.h"
-typedef HMAC_CTX archive_hmac_sha1_ctx;
+typedef HMAC_CTX* archive_hmac_sha1_ctx;
#else
diff --git a/Utilities/cmlibarchive/libarchive/archive_openssl_evp_private.h b/Utilities/cmlibarchive/libarchive/archive_openssl_evp_private.h
new file mode 100644
index 0000000..0e97e27
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_openssl_evp_private.h
@@ -0,0 +1,51 @@
+/*-
+ * Copyright (c) 2003-2007 Tim Kientzle
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef ARCHIVE_OPENSSL_EVP_PRIVATE_H_INCLUDED
+#define ARCHIVE_OPENSSL_EVP_PRIVATE_H_INCLUDED
+
+#include <openssl/evp.h>
+#include <openssl/opensslv.h>
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+#include <stdlib.h> /* malloc, free */
+#include <string.h> /* memset */
+static inline EVP_MD_CTX *EVP_MD_CTX_new(void)
+{
+ EVP_MD_CTX *ctx = (EVP_MD_CTX *)malloc(sizeof(EVP_MD_CTX));
+ if (ctx != NULL) {
+ memset(ctx, 0, sizeof(*ctx));
+ }
+ return ctx;
+}
+
+static inline void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
+{
+ EVP_MD_CTX_cleanup(ctx);
+ memset(ctx, 0, sizeof(*ctx));
+ free(ctx);
+}
+#endif
+
+#endif
diff --git a/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h b/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h
new file mode 100644
index 0000000..d4ae0d1
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h
@@ -0,0 +1,52 @@
+/*-
+ * Copyright (c) 2003-2007 Tim Kientzle
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef ARCHIVE_OPENSSL_HMAC_PRIVATE_H_INCLUDED
+#define ARCHIVE_OPENSSL_HMAC_PRIVATE_H_INCLUDED
+
+#include <openssl/hmac.h>
+#include <openssl/opensslv.h>
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+#include <stdlib.h> /* malloc, free */
+#include <string.h> /* memset */
+static inline HMAC_CTX *HMAC_CTX_new(void)
+{
+ HMAC_CTX *ctx = (HMAC_CTX *)malloc(sizeof(HMAC_CTX));
+ if (ctx != NULL) {
+ memset(ctx, 0, sizeof(*ctx));
+ HMAC_CTX_init(ctx);
+ }
+ return ctx;
+}
+
+static inline void HMAC_CTX_free(HMAC_CTX *ctx)
+{
+ HMAC_CTX_cleanup(ctx);
+ memset(ctx, 0, sizeof(*ctx));
+ free(ctx);
+}
+#endif
+
+#endif
diff --git a/Utilities/cmlibrhash/.gitattributes b/Utilities/cmlibrhash/.gitattributes
new file mode 100644
index 0000000..562b12e
--- /dev/null
+++ b/Utilities/cmlibrhash/.gitattributes
@@ -0,0 +1 @@
+* -whitespace
diff --git a/Utilities/cmlibrhash/CMakeLists.txt b/Utilities/cmlibrhash/CMakeLists.txt
new file mode 100644
index 0000000..aa28055
--- /dev/null
+++ b/Utilities/cmlibrhash/CMakeLists.txt
@@ -0,0 +1,40 @@
+project(librhash C)
+
+# Disable warnings to avoid changing 3rd party code.
+if(CMAKE_C_COMPILER_ID MATCHES
+ "^(GNU|Clang|AppleClang|XL|VisualAge|SunPro|MIPSpro|HP|Intel)$")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w")
+elseif(CMAKE_C_COMPILER_ID STREQUAL "PathScale")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
+endif()
+
+set(librhash_sources
+ librhash/algorithms.c
+ librhash/algorithms.h
+ librhash/byte_order.c
+ librhash/byte_order.h
+ librhash/hex.c
+ librhash/hex.h
+ librhash/md5.c
+ librhash/md5.h
+ librhash/rhash.c
+ librhash/rhash.h
+ librhash/sha1.c
+ librhash/sha1.h
+ librhash/sha256.c
+ librhash/sha256.h
+ librhash/sha3.c
+ librhash/sha3.h
+ librhash/sha512.c
+ librhash/sha512.h
+ librhash/ustd.h
+ librhash/util.h
+ )
+
+include_directories(
+ ${KWSYS_HEADER_ROOT}
+ )
+
+add_library(cmlibrhash ${librhash_sources})
+
+install(FILES COPYING README DESTINATION ${CMAKE_DOC_DIR}/cmlibrhash)
diff --git a/Utilities/cmlibrhash/COPYING b/Utilities/cmlibrhash/COPYING
new file mode 100644
index 0000000..bf65ee1
--- /dev/null
+++ b/Utilities/cmlibrhash/COPYING
@@ -0,0 +1,15 @@
+
+ RHash License
+
+Copyright (c) 2005-2014 Aleksey Kravchenko <rhash.admin@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so.
+
+The Software is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. Use this program at your own risk!
diff --git a/Utilities/cmlibrhash/README b/Utilities/cmlibrhash/README
new file mode 100644
index 0000000..4ea492f
--- /dev/null
+++ b/Utilities/cmlibrhash/README
@@ -0,0 +1,7 @@
+ === Notes on RHash License ===
+
+The RHash program and LibRHash library are distributed under RHash License,
+see the COPYING file for details. In particular, the program, the library
+and source code can be used free of charge under the MIT, BSD, GPL,
+commercial or freeware license without additional restrictions. In the case
+the OSI-approved license is required the MIT license should be used.
diff --git a/Utilities/cmlibrhash/librhash/algorithms.c b/Utilities/cmlibrhash/librhash/algorithms.c
new file mode 100644
index 0000000..fc01690
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/algorithms.c
@@ -0,0 +1,220 @@
+/* algorithms.c - the algorithms supported by the rhash library
+ *
+ * Copyright: 2011-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "byte_order.h"
+#include "rhash.h"
+#include "algorithms.h"
+
+/* header files of all supported hash sums */
+#if 0
+#include "aich.h"
+#include "crc32.h"
+#include "ed2k.h"
+#include "edonr.h"
+#include "gost.h"
+#include "has160.h"
+#include "md4.h"
+#endif
+#include "md5.h"
+#if 0
+#include "ripemd-160.h"
+#include "snefru.h"
+#endif
+#include "sha1.h"
+#include "sha256.h"
+#include "sha512.h"
+#include "sha3.h"
+#if 0
+#include "tiger.h"
+#include "tth.h"
+#include "whirlpool.h"
+#endif
+
+#ifdef USE_OPENSSL
+/* note: BTIH and AICH depends on the used SHA1 algorithm */
+# define NEED_OPENSSL_INIT (RHASH_MD4 | RHASH_MD5 | \
+ RHASH_SHA1 | RHASH_SHA224 | RHASH_SHA256 | RHASH_SHA384 | RHASH_SHA512 | \
+ RHASH_BTIH | RHASH_AICH | RHASH_RIPEMD160 | RHASH_WHIRLPOOL)
+#else
+# define NEED_OPENSSL_INIT 0
+#endif /* USE_OPENSSL */
+#ifdef GENERATE_GOST_LOOKUP_TABLE
+# define NEED_GOST_INIT (RHASH_GOST | RHASH_GOST_CRYPTOPRO)
+#else
+# define NEED_GOST_INIT 0
+#endif /* GENERATE_GOST_LOOKUP_TABLE */
+#ifdef GENERATE_CRC32_TABLE
+# define NEED_CRC32_INIT RHASH_CRC32
+#else
+# define NEED_CRC32_INIT 0
+#endif /* GENERATE_CRC32_TABLE */
+
+#define RHASH_NEED_INIT_ALG (NEED_CRC32_INIT | NEED_GOST_INIT | NEED_OPENSSL_INIT)
+unsigned rhash_uninitialized_algorithms = RHASH_NEED_INIT_ALG;
+
+rhash_hash_info* rhash_info_table = rhash_hash_info_default;
+int rhash_info_size = RHASH_HASH_COUNT;
+
+#if 0
+static void rhash_crc32_init(uint32_t* crc32);
+static void rhash_crc32_update(uint32_t* crc32, const unsigned char* msg, size_t size);
+static void rhash_crc32_final(uint32_t* crc32, unsigned char* result);
+#endif
+
+#if 0
+rhash_info info_crc32 = { RHASH_CRC32, F_BE32, 4, "CRC32", "crc32" };
+rhash_info info_md4 = { RHASH_MD4, F_LE32, 16, "MD4", "md4" };
+#endif
+rhash_info info_md5 = { RHASH_MD5, F_LE32, 16, "MD5", "md5" };
+rhash_info info_sha1 = { RHASH_SHA1, F_BE32, 20, "SHA1", "sha1" };
+#if 0
+rhash_info info_tiger = { RHASH_TIGER, F_LE64, 24, "TIGER", "tiger" };
+rhash_info info_tth = { RHASH_TTH, F_BS32, 24, "TTH", "tree:tiger" };
+rhash_info info_btih = { RHASH_BTIH, 0, 20, "BTIH", "btih" };
+rhash_info info_ed2k = { RHASH_ED2K, F_LE32, 16, "ED2K", "ed2k" };
+rhash_info info_aich = { RHASH_AICH, F_BS32, 20, "AICH", "aich" };
+rhash_info info_whirlpool = { RHASH_WHIRLPOOL, F_BE64, 64, "WHIRLPOOL", "whirlpool" };
+rhash_info info_rmd160 = { RHASH_RIPEMD160, F_LE32, 20, "RIPEMD-160", "ripemd160" };
+rhash_info info_gost = { RHASH_GOST, F_LE32, 32, "GOST", "gost" };
+rhash_info info_gostpro = { RHASH_GOST_CRYPTOPRO, F_LE32, 32, "GOST-CRYPTOPRO", "gost-cryptopro" };
+rhash_info info_has160 = { RHASH_HAS160, F_LE32, 20, "HAS-160", "has160" };
+rhash_info info_snf128 = { RHASH_SNEFRU128, F_BE32, 16, "SNEFRU-128", "snefru128" };
+rhash_info info_snf256 = { RHASH_SNEFRU256, F_BE32, 32, "SNEFRU-256", "snefru256" };
+#endif
+rhash_info info_sha224 = { RHASH_SHA224, F_BE32, 28, "SHA-224", "sha224" };
+rhash_info info_sha256 = { RHASH_SHA256, F_BE32, 32, "SHA-256", "sha256" };
+rhash_info info_sha384 = { RHASH_SHA384, F_BE64, 48, "SHA-384", "sha384" };
+rhash_info info_sha512 = { RHASH_SHA512, F_BE64, 64, "SHA-512", "sha512" };
+#if 0
+rhash_info info_edr256 = { RHASH_EDONR256, F_LE32, 32, "EDON-R256", "edon-r256" };
+rhash_info info_edr512 = { RHASH_EDONR512, F_LE64, 64, "EDON-R512", "edon-r512" };
+#endif
+rhash_info info_sha3_224 = { RHASH_SHA3_224, F_LE64, 28, "SHA3-224", "sha3-224" };
+rhash_info info_sha3_256 = { RHASH_SHA3_256, F_LE64, 32, "SHA3-256", "sha3-256" };
+rhash_info info_sha3_384 = { RHASH_SHA3_384, F_LE64, 48, "SHA3-384", "sha3-384" };
+rhash_info info_sha3_512 = { RHASH_SHA3_512, F_LE64, 64, "SHA3-512", "sha3-512" };
+
+/* some helper macros */
+#define dgshft(name) (((char*)&((name##_ctx*)0)->hash) - (char*)0)
+#define dgshft2(name, field) (((char*)&((name##_ctx*)0)->field) - (char*)0)
+#define ini(name) ((pinit_t)(name##_init))
+#define upd(name) ((pupdate_t)(name##_update))
+#define fin(name) ((pfinal_t)(name##_final))
+#define iuf(name) ini(name), upd(name), fin(name)
+#define diuf(name) dgshft(name), ini(name), upd(name), fin(name)
+
+/* information about all hashes */
+rhash_hash_info rhash_hash_info_default[RHASH_HASH_COUNT] =
+{
+#if 0
+ { &info_crc32, sizeof(uint32_t), 0, iuf(rhash_crc32), 0 }, /* 32 bit */
+ { &info_md4, sizeof(md4_ctx), dgshft(md4), iuf(rhash_md4), 0 }, /* 128 bit */
+#endif
+ { &info_md5, sizeof(md5_ctx), dgshft(md5), iuf(rhash_md5), 0 }, /* 128 bit */
+ { &info_sha1, sizeof(sha1_ctx), dgshft(sha1), iuf(rhash_sha1), 0 }, /* 160 bit */
+#if 0
+ { &info_tiger, sizeof(tiger_ctx), dgshft(tiger), iuf(rhash_tiger), 0 }, /* 192 bit */
+ { &info_tth, sizeof(tth_ctx), dgshft2(tth, tiger.hash), iuf(rhash_tth), 0 }, /* 192 bit */
+ { &info_ed2k, sizeof(ed2k_ctx), dgshft2(ed2k, md4_context_inner.hash), iuf(rhash_ed2k), 0 }, /* 128 bit */
+ { &info_aich, sizeof(aich_ctx), dgshft2(aich, sha1_context.hash), iuf(rhash_aich), (pcleanup_t)rhash_aich_cleanup }, /* 160 bit */
+ { &info_whirlpool, sizeof(whirlpool_ctx), dgshft(whirlpool), iuf(rhash_whirlpool), 0 }, /* 512 bit */
+ { &info_rmd160, sizeof(ripemd160_ctx), dgshft(ripemd160), iuf(rhash_ripemd160), 0 }, /* 160 bit */
+ { &info_gost, sizeof(gost_ctx), dgshft(gost), iuf(rhash_gost), 0 }, /* 256 bit */
+ { &info_gostpro, sizeof(gost_ctx), dgshft(gost), ini(rhash_gost_cryptopro), upd(rhash_gost), fin(rhash_gost), 0 }, /* 256 bit */
+ { &info_has160, sizeof(has160_ctx), dgshft(has160), iuf(rhash_has160), 0 }, /* 160 bit */
+ { &info_snf128, sizeof(snefru_ctx), dgshft(snefru), ini(rhash_snefru128), upd(rhash_snefru), fin(rhash_snefru), 0 }, /* 128 bit */
+ { &info_snf256, sizeof(snefru_ctx), dgshft(snefru), ini(rhash_snefru256), upd(rhash_snefru), fin(rhash_snefru), 0 }, /* 256 bit */
+#endif
+ { &info_sha224, sizeof(sha256_ctx), dgshft(sha256), ini(rhash_sha224), upd(rhash_sha256), fin(rhash_sha256), 0 }, /* 224 bit */
+ { &info_sha256, sizeof(sha256_ctx), dgshft(sha256), iuf(rhash_sha256), 0 }, /* 256 bit */
+ { &info_sha384, sizeof(sha512_ctx), dgshft(sha512), ini(rhash_sha384), upd(rhash_sha512), fin(rhash_sha512), 0 }, /* 384 bit */
+ { &info_sha512, sizeof(sha512_ctx), dgshft(sha512), iuf(rhash_sha512), 0 }, /* 512 bit */
+#if 0
+ { &info_edr256, sizeof(edonr_ctx), dgshft2(edonr, u.data256.hash) + 32, iuf(rhash_edonr256), 0 }, /* 256 bit */
+ { &info_edr512, sizeof(edonr_ctx), dgshft2(edonr, u.data512.hash) + 64, iuf(rhash_edonr512), 0 }, /* 512 bit */
+#endif
+ { &info_sha3_224, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_224), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 224 bit */
+ { &info_sha3_256, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_256), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 256 bit */
+ { &info_sha3_384, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_384), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 384 bit */
+ { &info_sha3_512, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_512), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 512 bit */
+};
+
+/**
+ * Initialize requested algorithms.
+ */
+void rhash_init_algorithms(unsigned mask)
+{
+ (void)mask; /* unused now */
+
+ /* verify that RHASH_HASH_COUNT is the index of the major bit of RHASH_ALL_HASHES */
+ assert(1 == (RHASH_ALL_HASHES >> (RHASH_HASH_COUNT - 1)));
+
+#ifdef GENERATE_CRC32_TABLE
+ rhash_crc32_init_table();
+#endif
+#ifdef GENERATE_GOST_LOOKUP_TABLE
+ rhash_gost_init_table();
+#endif
+ rhash_uninitialized_algorithms = 0;
+}
+
+#if 0
+/* CRC32 helper functions */
+
+/**
+ * Initialize crc32 hash.
+ *
+ * @param crc32 pointer to the hash to initialize
+ */
+static void rhash_crc32_init(uint32_t* crc32)
+{
+ *crc32 = 0; /* note: context size is sizeof(uint32_t) */
+}
+
+/**
+ * Calculate message CRC32 hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param crc32 pointer to the hash
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+static void rhash_crc32_update(uint32_t* crc32, const unsigned char* msg, size_t size)
+{
+ *crc32 = rhash_get_crc32(*crc32, msg, size);
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param crc32 pointer to the current hash value
+ * @param result calculated hash in binary form
+ */
+static void rhash_crc32_final(uint32_t* crc32, unsigned char* result)
+{
+#if defined(CPU_IA32) || defined(CPU_X64)
+ /* intel CPUs support assigment with non 32-bit aligned pointers */
+ *(unsigned*)result = be2me_32(*crc32);
+#else
+ /* correct saving BigEndian integer on all archs */
+ result[0] = (unsigned char)(*crc32 >> 24), result[1] = (unsigned char)(*crc32 >> 16);
+ result[2] = (unsigned char)(*crc32 >> 8), result[3] = (unsigned char)(*crc32);
+#endif
+}
+#endif
diff --git a/Utilities/cmlibrhash/librhash/algorithms.h b/Utilities/cmlibrhash/librhash/algorithms.h
new file mode 100644
index 0000000..4db2517
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/algorithms.h
@@ -0,0 +1,120 @@
+/* algorithms.h - rhash library algorithms */
+#ifndef RHASH_ALGORITHMS_H
+#define RHASH_ALGORITHMS_H
+
+#include <stddef.h> /* for ptrdiff_t */
+#include "rhash.h"
+#include "byte_order.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef RHASH_API
+/* modifier for RHash library functions */
+# define RHASH_API
+#endif
+
+typedef void (*pinit_t)(void*);
+typedef void (*pupdate_t)(void *ctx, const void* msg, size_t size);
+typedef void (*pfinal_t)(void*, unsigned char*);
+typedef void (*pcleanup_t)(void*);
+
+/**
+ * Information about a hash function
+ */
+typedef struct rhash_hash_info
+{
+ rhash_info *info;
+ size_t context_size;
+ ptrdiff_t digest_diff;
+ pinit_t init;
+ pupdate_t update;
+ pfinal_t final;
+ pcleanup_t cleanup;
+} rhash_hash_info;
+
+/**
+ * Information on a hash function and its context
+ */
+typedef struct rhash_vector_item
+{
+ struct rhash_hash_info* hash_info;
+ void *context;
+} rhash_vector_item;
+
+/**
+ * The rhash context containing contexts for several hash functions
+ */
+typedef struct rhash_context_ext
+{
+ struct rhash_context rc;
+ unsigned hash_vector_size; /* number of contained hash sums */
+ unsigned flags;
+ unsigned state;
+ void *callback, *callback_data;
+ void *bt_ctx;
+ rhash_vector_item vector[1]; /* contexts of contained hash sums */
+} rhash_context_ext;
+
+extern rhash_hash_info rhash_hash_info_default[RHASH_HASH_COUNT];
+extern rhash_hash_info* rhash_info_table;
+extern int rhash_info_size;
+extern unsigned rhash_uninitialized_algorithms;
+
+extern rhash_info info_crc32;
+extern rhash_info info_md4;
+extern rhash_info info_md5;
+extern rhash_info info_sha1;
+extern rhash_info info_tiger;
+extern rhash_info info_tth ;
+extern rhash_info info_btih;
+extern rhash_info info_ed2k;
+extern rhash_info info_aich;
+extern rhash_info info_whirlpool;
+extern rhash_info info_rmd160;
+extern rhash_info info_gost;
+extern rhash_info info_gostpro;
+extern rhash_info info_has160;
+extern rhash_info info_snf128;
+extern rhash_info info_snf256;
+extern rhash_info info_sha224;
+extern rhash_info info_sha256;
+extern rhash_info info_sha384;
+extern rhash_info info_sha512;
+extern rhash_info info_sha3_224;
+extern rhash_info info_sha3_256;
+extern rhash_info info_sha3_384;
+extern rhash_info info_sha3_512;
+extern rhash_info info_edr256;
+extern rhash_info info_edr512;
+
+/* rhash_info flags */
+#define F_BS32 1 /* default output in base32 */
+#define F_SWAP32 2 /* Big endian flag */
+#define F_SWAP64 4
+
+/* define endianness flags */
+#ifndef CPU_BIG_ENDIAN
+#define F_LE32 0
+#define F_LE64 0
+#define F_BE32 F_SWAP32
+#define F_BE64 F_SWAP64
+#else
+#define F_LE32 F_SWAP32
+#define F_LE64 F_SWAP64
+#define F_BE32 0
+#define F_BE64 0
+#endif
+
+void rhash_init_algorithms(unsigned mask);
+
+#if defined(OPENSSL_RUNTIME) && !defined(USE_OPENSSL)
+# define USE_OPENSSL
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* RHASH_ALGORITHMS_H */
diff --git a/Utilities/cmlibrhash/librhash/byte_order.c b/Utilities/cmlibrhash/librhash/byte_order.c
new file mode 100644
index 0000000..8ce6fc8
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/byte_order.c
@@ -0,0 +1,150 @@
+/* byte_order.c - byte order related platform dependent routines,
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+#include "byte_order.h"
+
+#if !(__GNUC__ >= 4 || (__GNUC__ ==3 && __GNUC_MINOR__ >= 4)) /* if !GCC or GCC < 4.3 */
+
+# if _MSC_VER >= 1300 && (_M_IX86 || _M_AMD64 || _M_IA64) /* if MSVC++ >= 2002 on x86/x64 */
+# include <intrin.h>
+# pragma intrinsic(_BitScanForward)
+
+/**
+ * Returns index of the trailing bit of x.
+ *
+ * @param x the number to process
+ * @return zero-based index of the trailing bit
+ */
+unsigned rhash_ctz(unsigned x)
+{
+ unsigned long index;
+ unsigned char isNonzero = _BitScanForward(&index, x); /* MSVC intrinsic */
+ return (isNonzero ? (unsigned)index : 0);
+}
+# else /* _MSC_VER >= 1300... */
+
+/**
+ * Returns index of the trailing bit of a 32-bit number.
+ * This is a plain C equivalent for GCC __builtin_ctz() bit scan.
+ *
+ * @param x the number to process
+ * @return zero-based index of the trailing bit
+ */
+unsigned rhash_ctz(unsigned x)
+{
+ /* array for conversion to bit position */
+ static unsigned char bit_pos[32] = {
+ 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
+ 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
+ };
+
+ /* The De Bruijn bit-scan was devised in 1997, according to Donald Knuth
+ * by Martin Lauter. The constant 0x077CB531UL is a De Bruijn sequence,
+ * which produces a unique pattern of bits into the high 5 bits for each
+ * possible bit position that it is multiplied against.
+ * See http://graphics.stanford.edu/~seander/bithacks.html
+ * and http://chessprogramming.wikispaces.com/BitScan */
+ return (unsigned)bit_pos[((uint32_t)((x & -x) * 0x077CB531U)) >> 27];
+}
+# endif /* _MSC_VER >= 1300... */
+#endif /* !(GCC >= 4.3) */
+
+/**
+ * Copy a memory block with simultaneous exchanging byte order.
+ * The byte order is changed from little-endian 32-bit integers
+ * to big-endian (or vice-versa).
+ *
+ * @param to the pointer where to copy memory block
+ * @param index the index to start writing from
+ * @param from the source block to copy
+ * @param length length of the memory block
+ */
+void rhash_swap_copy_str_to_u32(void* to, int index, const void* from, size_t length)
+{
+ /* if all pointers and length are 32-bits aligned */
+ if ( 0 == (( (int)((char*)to - (char*)0) | ((char*)from - (char*)0) | index | length ) & 3) ) {
+ /* copy memory as 32-bit words */
+ const uint32_t* src = (const uint32_t*)from;
+ const uint32_t* end = (const uint32_t*)((const char*)src + length);
+ uint32_t* dst = (uint32_t*)((char*)to + index);
+ while (src < end) *(dst++) = bswap_32( *(src++) );
+ } else {
+ const char* src = (const char*)from;
+ for (length += index; (size_t)index < length; index++) ((char*)to)[index ^ 3] = *(src++);
+ }
+}
+
+/**
+ * Copy a memory block with changed byte order.
+ * The byte order is changed from little-endian 64-bit integers
+ * to big-endian (or vice-versa).
+ *
+ * @param to the pointer where to copy memory block
+ * @param index the index to start writing from
+ * @param from the source block to copy
+ * @param length length of the memory block
+ */
+void rhash_swap_copy_str_to_u64(void* to, int index, const void* from, size_t length)
+{
+ /* if all pointers and length are 64-bits aligned */
+ if ( 0 == (( (int)((char*)to - (char*)0) | ((char*)from - (char*)0) | index | length ) & 7) ) {
+ /* copy aligned memory block as 64-bit integers */
+ const uint64_t* src = (const uint64_t*)from;
+ const uint64_t* end = (const uint64_t*)((const char*)src + length);
+ uint64_t* dst = (uint64_t*)((char*)to + index);
+ while (src < end) *(dst++) = bswap_64( *(src++) );
+ } else {
+ const char* src = (const char*)from;
+ for (length += index; (size_t)index < length; index++) ((char*)to)[index ^ 7] = *(src++);
+ }
+}
+
+/**
+ * Copy data from a sequence of 64-bit words to a binary string of given length,
+ * while changing byte order.
+ *
+ * @param to the binary string to receive data
+ * @param from the source sequence of 64-bit words
+ * @param length the size in bytes of the data being copied
+ */
+void rhash_swap_copy_u64_to_str(void* to, const void* from, size_t length)
+{
+ /* if all pointers and length are 64-bits aligned */
+ if ( 0 == (( (int)((char*)to - (char*)0) | ((char*)from - (char*)0) | length ) & 7) ) {
+ /* copy aligned memory block as 64-bit integers */
+ const uint64_t* src = (const uint64_t*)from;
+ const uint64_t* end = (const uint64_t*)((const char*)src + length);
+ uint64_t* dst = (uint64_t*)to;
+ while (src < end) *(dst++) = bswap_64( *(src++) );
+ } else {
+ size_t index;
+ char* dst = (char*)to;
+ for (index = 0; index < length; index++) *(dst++) = ((char*)from)[index ^ 7];
+ }
+}
+
+/**
+ * Exchange byte order in the given array of 32-bit integers.
+ *
+ * @param arr the array to process
+ * @param length array length
+ */
+void rhash_u32_mem_swap(unsigned *arr, int length)
+{
+ unsigned* end = arr + length;
+ for (; arr < end; arr++) {
+ *arr = bswap_32(*arr);
+ }
+}
diff --git a/Utilities/cmlibrhash/librhash/byte_order.h b/Utilities/cmlibrhash/librhash/byte_order.h
new file mode 100644
index 0000000..d34a020
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/byte_order.h
@@ -0,0 +1,156 @@
+/* byte_order.h */
+#ifndef BYTE_ORDER_H
+#define BYTE_ORDER_H
+#include "ustd.h"
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* if x86 compatible cpu */
+#if defined(i386) || defined(__i386__) || defined(__i486__) || \
+ defined(__i586__) || defined(__i686__) || defined(__pentium__) || \
+ defined(__pentiumpro__) || defined(__pentium4__) || \
+ defined(__nocona__) || defined(prescott) || defined(__core2__) || \
+ defined(__k6__) || defined(__k8__) || defined(__athlon__) || \
+ defined(__amd64) || defined(__amd64__) || \
+ defined(__x86_64) || defined(__x86_64__) || defined(_M_IX86) || \
+ defined(_M_AMD64) || defined(_M_IA64) || defined(_M_X64)
+/* detect if x86-64 instruction set is supported */
+# if defined(_LP64) || defined(__LP64__) || defined(__x86_64) || \
+ defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
+# define CPU_X64
+# else
+# define CPU_IA32
+# endif
+#endif
+
+
+/* detect CPU endianness */
+#include <cm_kwiml.h>
+#if KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_LITTLE
+# define CPU_LITTLE_ENDIAN
+# define IS_BIG_ENDIAN 0
+# define IS_LITTLE_ENDIAN 1
+#elif KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_BIG
+# define CPU_BIG_ENDIAN
+# define IS_BIG_ENDIAN 1
+# define IS_LITTLE_ENDIAN 0
+#else
+# error "Can't detect CPU architechture"
+#endif
+
+#define IS_ALIGNED_32(p) (0 == (3 & ((const char*)(p) - (const char*)0)))
+#define IS_ALIGNED_64(p) (0 == (7 & ((const char*)(p) - (const char*)0)))
+
+#if defined(_MSC_VER)
+#define ALIGN_ATTR(n) __declspec(align(n))
+#elif defined(__GNUC__)
+#define ALIGN_ATTR(n) __attribute__((aligned (n)))
+#else
+#define ALIGN_ATTR(n) /* nothing */
+#endif
+
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+#define I64(x) x##ui64
+#else
+#define I64(x) x##LL
+#endif
+
+/* convert a hash flag to index */
+#if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) /* GCC < 3.4 */
+# define rhash_ctz(x) __builtin_ctz(x)
+#else
+unsigned rhash_ctz(unsigned); /* define as function */
+#endif
+
+void rhash_swap_copy_str_to_u32(void* to, int index, const void* from, size_t length);
+void rhash_swap_copy_str_to_u64(void* to, int index, const void* from, size_t length);
+void rhash_swap_copy_u64_to_str(void* to, const void* from, size_t length);
+void rhash_u32_mem_swap(unsigned *p, int length_in_u32);
+
+#ifndef __has_builtin
+# define __has_builtin(x) 0
+#endif
+
+/* define bswap_32 */
+#if defined(__GNUC__) && defined(CPU_IA32) && !defined(__i386__)
+/* for intel x86 CPU */
+static inline uint32_t bswap_32(uint32_t x) {
+ __asm("bswap\t%0" : "=r" (x) : "0" (x));
+ return x;
+}
+#elif defined(__GNUC__) && (__GNUC__ >= 4) && (__GNUC__ > 4 || __GNUC_MINOR__ >= 3)
+/* for GCC >= 4.3 */
+# define bswap_32(x) __builtin_bswap32(x)
+#elif defined(__clang__) && __has_builtin(__builtin_bswap32)
+# define bswap_32(x) __builtin_bswap32(x)
+#elif (_MSC_VER > 1300) && (defined(CPU_IA32) || defined(CPU_X64)) /* MS VC */
+# define bswap_32(x) _byteswap_ulong((unsigned long)x)
+#else
+/* general bswap_32 definition */
+static uint32_t bswap_32(uint32_t x) {
+ x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0x00FF00FF);
+ return (x >> 16) | (x << 16);
+}
+#endif /* bswap_32 */
+
+#if defined(__GNUC__) && (__GNUC__ >= 4) && (__GNUC__ > 4 || __GNUC_MINOR__ >= 3)
+# define bswap_64(x) __builtin_bswap64(x)
+#elif defined(__clang__) && __has_builtin(__builtin_bswap64)
+# define bswap_64(x) __builtin_bswap64(x)
+#elif (_MSC_VER > 1300) && (defined(CPU_IA32) || defined(CPU_X64)) /* MS VC */
+# define bswap_64(x) _byteswap_uint64((__int64)x)
+#else
+static uint64_t bswap_64(uint64_t x) {
+ union {
+ uint64_t ll;
+ uint32_t l[2];
+ } w, r;
+ w.ll = x;
+ r.l[0] = bswap_32(w.l[1]);
+ r.l[1] = bswap_32(w.l[0]);
+ return r.ll;
+}
+#endif
+
+#ifdef CPU_BIG_ENDIAN
+# define be2me_32(x) (x)
+# define be2me_64(x) (x)
+# define le2me_32(x) bswap_32(x)
+# define le2me_64(x) bswap_64(x)
+
+# define be32_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define le32_copy(to, index, from, length) rhash_swap_copy_str_to_u32((to), (index), (from), (length))
+# define be64_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define le64_copy(to, index, from, length) rhash_swap_copy_str_to_u64((to), (index), (from), (length))
+# define me64_to_be_str(to, from, length) memcpy((to), (from), (length))
+# define me64_to_le_str(to, from, length) rhash_swap_copy_u64_to_str((to), (from), (length))
+
+#else /* CPU_BIG_ENDIAN */
+# define be2me_32(x) bswap_32(x)
+# define be2me_64(x) bswap_64(x)
+# define le2me_32(x) (x)
+# define le2me_64(x) (x)
+
+# define be32_copy(to, index, from, length) rhash_swap_copy_str_to_u32((to), (index), (from), (length))
+# define le32_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define be64_copy(to, index, from, length) rhash_swap_copy_str_to_u64((to), (index), (from), (length))
+# define le64_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define me64_to_be_str(to, from, length) rhash_swap_copy_u64_to_str((to), (from), (length))
+# define me64_to_le_str(to, from, length) memcpy((to), (from), (length))
+#endif /* CPU_BIG_ENDIAN */
+
+/* ROTL/ROTR macros rotate a 32/64-bit word left/right by n bits */
+#define ROTL32(dword, n) ((dword) << (n) ^ ((dword) >> (32 - (n))))
+#define ROTR32(dword, n) ((dword) >> (n) ^ ((dword) << (32 - (n))))
+#define ROTL64(qword, n) ((qword) << (n) ^ ((qword) >> (64 - (n))))
+#define ROTR64(qword, n) ((qword) >> (n) ^ ((qword) << (64 - (n))))
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* BYTE_ORDER_H */
diff --git a/Utilities/cmlibrhash/librhash/hex.c b/Utilities/cmlibrhash/librhash/hex.c
new file mode 100644
index 0000000..c941149
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/hex.c
@@ -0,0 +1,188 @@
+/* hex.c - conversion for hexadecimal and base32 strings.
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+#include <string.h>
+#include <ctype.h>
+#include "hex.h"
+
+/**
+* Convert a byte to a hexadecimal number. The result, consisting of two
+* hexadecimal digits is stored into a buffer.
+ *
+ * @param dest the buffer to receive two symbols of hex representation
+ * @param byte the byte to decode
+ * @param upper_case flag to print string in uppercase
+ * @return pointer to the chararcter just after the written number (dest + 2)
+ */
+char* rhash_print_hex_byte(char *dest, const unsigned char byte, int upper_case)
+{
+ const char add = (upper_case ? 'A' - 10 : 'a' - 10);
+ unsigned char c = (byte >> 4) & 15;
+ *dest++ = (c > 9 ? c + add : c + '0');
+ c = byte & 15;
+ *dest++ = (c > 9 ? c + add : c + '0');
+ return dest;
+}
+
+/**
+ * Store hexadecimal representation of a binary string to given buffer.
+ *
+ * @param dest the buffer to receive hexadecimal representation
+ * @param src binary string
+ * @param len string length
+ * @param upper_case flag to print string in uppercase
+ */
+void rhash_byte_to_hex(char *dest, const unsigned char *src, unsigned len, int upper_case)
+{
+ while (len-- > 0) {
+ dest = rhash_print_hex_byte(dest, *src++, upper_case);
+ }
+ *dest = '\0';
+}
+
+/**
+ * Encode a binary string to base32.
+ *
+ * @param dest the buffer to store result
+ * @param src binary string
+ * @param len string length
+ * @param upper_case flag to print string in uppercase
+ */
+void rhash_byte_to_base32(char* dest, const unsigned char* src, unsigned len, int upper_case)
+{
+ const char a = (upper_case ? 'A' : 'a');
+ unsigned shift = 0;
+ unsigned char word;
+ const unsigned char* e = src + len;
+ while (src < e) {
+ if (shift > 3) {
+ word = (*src & (0xFF >> shift));
+ shift = (shift + 5) % 8;
+ word <<= shift;
+ if (src + 1 < e)
+ word |= *(src + 1) >> (8 - shift);
+ ++src;
+ } else {
+ shift = (shift + 5) % 8;
+ word = ( *src >> ( (8 - shift) & 7 ) ) & 0x1F;
+ if (shift == 0) src++;
+ }
+ *dest++ = ( word < 26 ? word + a : word + '2' - 26 );
+ }
+ *dest = '\0';
+}
+
+/**
+ * Encode a binary string to base64.
+ * Encoded output length is always a multiple of 4 bytes.
+ *
+ * @param dest the buffer to store result
+ * @param src binary string
+ * @param len string length
+ */
+void rhash_byte_to_base64(char* dest, const unsigned char* src, unsigned len)
+{
+ static const char* tail = "0123456789+/";
+ unsigned shift = 0;
+ unsigned char word;
+ const unsigned char* e = src + len;
+ while (src < e) {
+ if (shift > 2) {
+ word = (*src & (0xFF >> shift));
+ shift = (shift + 6) % 8;
+ word <<= shift;
+ if (src + 1 < e)
+ word |= *(src + 1) >> (8 - shift);
+ ++src;
+ } else {
+ shift = (shift + 6) % 8;
+ word = ( *src >> ( (8 - shift) & 7 ) ) & 0x3F;
+ if (shift == 0) src++;
+ }
+ *dest++ = ( word < 52 ? (word < 26 ? word + 'A' : word - 26 + 'a') : tail[word - 52]);
+ }
+ if (shift > 0) {
+ *dest++ = '=';
+ if (shift == 4) *dest++ = '=';
+ }
+ *dest = '\0';
+}
+
+/* unsafe characters are "<>{}[]%#/|\^~`@:;?=&+ */
+#define IS_GOOD_URL_CHAR(c) (isalnum((unsigned char)c) || strchr("$-_.!'(),", c))
+
+/**
+ * URL-encode a string.
+ *
+ * @param dst buffer to receive result or NULL to calculate
+ * the lengths of encoded string
+ * @param filename the file name
+ * @return the length of the result string
+ */
+int rhash_urlencode(char *dst, const char *name)
+{
+ const char *start;
+ if (!dst) {
+ int len;
+ for (len = 0; *name; name++) len += (IS_GOOD_URL_CHAR(*name) ? 1 : 3);
+ return len;
+ }
+ /* encode URL as specified by RFC 1738 */
+ for (start = dst; *name; name++) {
+ if ( IS_GOOD_URL_CHAR(*name) ) {
+ *dst++ = *name;
+ } else {
+ *dst++ = '%';
+ dst = rhash_print_hex_byte(dst, *name, 'A');
+ }
+ }
+ *dst = 0;
+ return (int)(dst - start);
+}
+
+/**
+ * Print 64-bit number with trailing '\0' to a string buffer.
+ * if dst is NULL, then just return the length of the number.
+ *
+ * @param dst output buffer
+ * @param number the number to print
+ * @return length of the printed number (without trailing '\0')
+ */
+int rhash_sprintI64(char *dst, uint64_t number)
+{
+ /* The biggest number has 20 digits: 2^64 = 18 446 744 073 709 551 616 */
+ char buf[24], *p;
+ size_t length;
+
+ if (dst == NULL) {
+ /* just calculate the length of the number */
+ if (number == 0) return 1;
+ for (length = 0; number != 0; number /= 10) length++;
+ return (int)length;
+ }
+
+ p = buf + 23;
+ *p = '\0'; /* last symbol should be '\0' */
+ if (number == 0) {
+ *(--p) = '0';
+ } else {
+ for (; p >= buf && number != 0; number /= 10) {
+ *(--p) = '0' + (char)(number % 10);
+ }
+ }
+ length = buf + 23 - p;
+ memcpy(dst, p, length + 1);
+ return (int)length;
+}
diff --git a/Utilities/cmlibrhash/librhash/hex.h b/Utilities/cmlibrhash/librhash/hex.h
new file mode 100644
index 0000000..2b365e2
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/hex.h
@@ -0,0 +1,25 @@
+/* hex.h - conversion for hexadecimal and base32 strings. */
+#ifndef HEX_H
+#define HEX_H
+
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void rhash_byte_to_hex(char *dest, const unsigned char *src, unsigned len, int upper_case);
+void rhash_byte_to_base32(char* dest, const unsigned char* src, unsigned len, int upper_case);
+void rhash_byte_to_base64(char* dest, const unsigned char* src, unsigned len);
+char* rhash_print_hex_byte(char *dest, const unsigned char byte, int upper_case);
+int rhash_urlencode(char *dst, const char *name);
+int rhash_sprintI64(char *dst, uint64_t number);
+
+#define BASE32_LENGTH(bytes) (((bytes) * 8 + 4) / 5)
+#define BASE64_LENGTH(bytes) ((((bytes) + 2) / 3) * 4)
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* HEX_H */
diff --git a/Utilities/cmlibrhash/librhash/md5.c b/Utilities/cmlibrhash/librhash/md5.c
new file mode 100644
index 0000000..b20de45
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/md5.c
@@ -0,0 +1,236 @@
+/* md5.c - an implementation of the MD5 algorithm, based on RFC 1321.
+ *
+ * Copyright: 2007-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "md5.h"
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_md5_init(md5_ctx *ctx)
+{
+ ctx->length = 0;
+
+ /* initialize state */
+ ctx->hash[0] = 0x67452301;
+ ctx->hash[1] = 0xefcdab89;
+ ctx->hash[2] = 0x98badcfe;
+ ctx->hash[3] = 0x10325476;
+}
+
+/* First, define four auxiliary functions that each take as input
+ * three 32-bit words and returns a 32-bit word.*/
+
+/* F(x,y,z) = ((y XOR z) AND x) XOR z - is faster then original version */
+#define MD5_F(x, y, z) ((((y) ^ (z)) & (x)) ^ (z))
+#define MD5_G(x, y, z) (((x) & (z)) | ((y) & (~z)))
+#define MD5_H(x, y, z) ((x) ^ (y) ^ (z))
+#define MD5_I(x, y, z) ((y) ^ ((x) | (~z)))
+
+/* transformations for rounds 1, 2, 3, and 4. */
+#define MD5_ROUND1(a, b, c, d, x, s, ac) { \
+ (a) += MD5_F((b), (c), (d)) + (x) + (ac); \
+ (a) = ROTL32((a), (s)); \
+ (a) += (b); \
+}
+#define MD5_ROUND2(a, b, c, d, x, s, ac) { \
+ (a) += MD5_G((b), (c), (d)) + (x) + (ac); \
+ (a) = ROTL32((a), (s)); \
+ (a) += (b); \
+}
+#define MD5_ROUND3(a, b, c, d, x, s, ac) { \
+ (a) += MD5_H((b), (c), (d)) + (x) + (ac); \
+ (a) = ROTL32((a), (s)); \
+ (a) += (b); \
+}
+#define MD5_ROUND4(a, b, c, d, x, s, ac) { \
+ (a) += MD5_I((b), (c), (d)) + (x) + (ac); \
+ (a) = ROTL32((a), (s)); \
+ (a) += (b); \
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ * The function has been taken from RFC 1321 with little changes.
+ *
+ * @param state algorithm state
+ * @param x the message block to process
+ */
+static void rhash_md5_process_block(unsigned state[4], const unsigned* x)
+{
+ register unsigned a, b, c, d;
+ a = state[0];
+ b = state[1];
+ c = state[2];
+ d = state[3];
+
+ MD5_ROUND1(a, b, c, d, x[ 0], 7, 0xd76aa478);
+ MD5_ROUND1(d, a, b, c, x[ 1], 12, 0xe8c7b756);
+ MD5_ROUND1(c, d, a, b, x[ 2], 17, 0x242070db);
+ MD5_ROUND1(b, c, d, a, x[ 3], 22, 0xc1bdceee);
+ MD5_ROUND1(a, b, c, d, x[ 4], 7, 0xf57c0faf);
+ MD5_ROUND1(d, a, b, c, x[ 5], 12, 0x4787c62a);
+ MD5_ROUND1(c, d, a, b, x[ 6], 17, 0xa8304613);
+ MD5_ROUND1(b, c, d, a, x[ 7], 22, 0xfd469501);
+ MD5_ROUND1(a, b, c, d, x[ 8], 7, 0x698098d8);
+ MD5_ROUND1(d, a, b, c, x[ 9], 12, 0x8b44f7af);
+ MD5_ROUND1(c, d, a, b, x[10], 17, 0xffff5bb1);
+ MD5_ROUND1(b, c, d, a, x[11], 22, 0x895cd7be);
+ MD5_ROUND1(a, b, c, d, x[12], 7, 0x6b901122);
+ MD5_ROUND1(d, a, b, c, x[13], 12, 0xfd987193);
+ MD5_ROUND1(c, d, a, b, x[14], 17, 0xa679438e);
+ MD5_ROUND1(b, c, d, a, x[15], 22, 0x49b40821);
+
+ MD5_ROUND2(a, b, c, d, x[ 1], 5, 0xf61e2562);
+ MD5_ROUND2(d, a, b, c, x[ 6], 9, 0xc040b340);
+ MD5_ROUND2(c, d, a, b, x[11], 14, 0x265e5a51);
+ MD5_ROUND2(b, c, d, a, x[ 0], 20, 0xe9b6c7aa);
+ MD5_ROUND2(a, b, c, d, x[ 5], 5, 0xd62f105d);
+ MD5_ROUND2(d, a, b, c, x[10], 9, 0x2441453);
+ MD5_ROUND2(c, d, a, b, x[15], 14, 0xd8a1e681);
+ MD5_ROUND2(b, c, d, a, x[ 4], 20, 0xe7d3fbc8);
+ MD5_ROUND2(a, b, c, d, x[ 9], 5, 0x21e1cde6);
+ MD5_ROUND2(d, a, b, c, x[14], 9, 0xc33707d6);
+ MD5_ROUND2(c, d, a, b, x[ 3], 14, 0xf4d50d87);
+ MD5_ROUND2(b, c, d, a, x[ 8], 20, 0x455a14ed);
+ MD5_ROUND2(a, b, c, d, x[13], 5, 0xa9e3e905);
+ MD5_ROUND2(d, a, b, c, x[ 2], 9, 0xfcefa3f8);
+ MD5_ROUND2(c, d, a, b, x[ 7], 14, 0x676f02d9);
+ MD5_ROUND2(b, c, d, a, x[12], 20, 0x8d2a4c8a);
+
+ MD5_ROUND3(a, b, c, d, x[ 5], 4, 0xfffa3942);
+ MD5_ROUND3(d, a, b, c, x[ 8], 11, 0x8771f681);
+ MD5_ROUND3(c, d, a, b, x[11], 16, 0x6d9d6122);
+ MD5_ROUND3(b, c, d, a, x[14], 23, 0xfde5380c);
+ MD5_ROUND3(a, b, c, d, x[ 1], 4, 0xa4beea44);
+ MD5_ROUND3(d, a, b, c, x[ 4], 11, 0x4bdecfa9);
+ MD5_ROUND3(c, d, a, b, x[ 7], 16, 0xf6bb4b60);
+ MD5_ROUND3(b, c, d, a, x[10], 23, 0xbebfbc70);
+ MD5_ROUND3(a, b, c, d, x[13], 4, 0x289b7ec6);
+ MD5_ROUND3(d, a, b, c, x[ 0], 11, 0xeaa127fa);
+ MD5_ROUND3(c, d, a, b, x[ 3], 16, 0xd4ef3085);
+ MD5_ROUND3(b, c, d, a, x[ 6], 23, 0x4881d05);
+ MD5_ROUND3(a, b, c, d, x[ 9], 4, 0xd9d4d039);
+ MD5_ROUND3(d, a, b, c, x[12], 11, 0xe6db99e5);
+ MD5_ROUND3(c, d, a, b, x[15], 16, 0x1fa27cf8);
+ MD5_ROUND3(b, c, d, a, x[ 2], 23, 0xc4ac5665);
+
+ MD5_ROUND4(a, b, c, d, x[ 0], 6, 0xf4292244);
+ MD5_ROUND4(d, a, b, c, x[ 7], 10, 0x432aff97);
+ MD5_ROUND4(c, d, a, b, x[14], 15, 0xab9423a7);
+ MD5_ROUND4(b, c, d, a, x[ 5], 21, 0xfc93a039);
+ MD5_ROUND4(a, b, c, d, x[12], 6, 0x655b59c3);
+ MD5_ROUND4(d, a, b, c, x[ 3], 10, 0x8f0ccc92);
+ MD5_ROUND4(c, d, a, b, x[10], 15, 0xffeff47d);
+ MD5_ROUND4(b, c, d, a, x[ 1], 21, 0x85845dd1);
+ MD5_ROUND4(a, b, c, d, x[ 8], 6, 0x6fa87e4f);
+ MD5_ROUND4(d, a, b, c, x[15], 10, 0xfe2ce6e0);
+ MD5_ROUND4(c, d, a, b, x[ 6], 15, 0xa3014314);
+ MD5_ROUND4(b, c, d, a, x[13], 21, 0x4e0811a1);
+ MD5_ROUND4(a, b, c, d, x[ 4], 6, 0xf7537e82);
+ MD5_ROUND4(d, a, b, c, x[11], 10, 0xbd3af235);
+ MD5_ROUND4(c, d, a, b, x[ 2], 15, 0x2ad7d2bb);
+ MD5_ROUND4(b, c, d, a, x[ 9], 21, 0xeb86d391);
+
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_md5_update(md5_ctx *ctx, const unsigned char* msg, size_t size)
+{
+ unsigned index = (unsigned)ctx->length & 63;
+ ctx->length += size;
+
+ /* fill partial block */
+ if (index) {
+ unsigned left = md5_block_size - index;
+ le32_copy((char*)ctx->message, index, msg, (size < left ? size : left));
+ if (size < left) return;
+
+ /* process partial block */
+ rhash_md5_process_block(ctx->hash, ctx->message);
+ msg += left;
+ size -= left;
+ }
+ while (size >= md5_block_size) {
+ unsigned* aligned_message_block;
+ if (IS_LITTLE_ENDIAN && IS_ALIGNED_32(msg)) {
+ /* the most common case is processing a 32-bit aligned message
+ on a little-endian CPU without copying it */
+ aligned_message_block = (unsigned*)msg;
+ } else {
+ le32_copy(ctx->message, 0, msg, md5_block_size);
+ aligned_message_block = ctx->message;
+ }
+
+ rhash_md5_process_block(ctx->hash, aligned_message_block);
+ msg += md5_block_size;
+ size -= md5_block_size;
+ }
+ if (size) {
+ /* save leftovers */
+ le32_copy(ctx->message, 0, msg, size);
+ }
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_md5_final(md5_ctx *ctx, unsigned char* result)
+{
+ unsigned index = ((unsigned)ctx->length & 63) >> 2;
+ unsigned shift = ((unsigned)ctx->length & 3) * 8;
+
+ /* pad message and run for last block */
+
+ /* append the byte 0x80 to the message */
+ ctx->message[index] &= ~(0xFFFFFFFFu << shift);
+ ctx->message[index++] ^= 0x80u << shift;
+
+ /* if no room left in the message to store 64-bit message length */
+ if (index > 14) {
+ /* then fill the rest with zeros and process it */
+ while (index < 16) {
+ ctx->message[index++] = 0;
+ }
+ rhash_md5_process_block(ctx->hash, ctx->message);
+ index = 0;
+ }
+ while (index < 14) {
+ ctx->message[index++] = 0;
+ }
+ ctx->message[14] = (unsigned)(ctx->length << 3);
+ ctx->message[15] = (unsigned)(ctx->length >> 29);
+ rhash_md5_process_block(ctx->hash, ctx->message);
+
+ if (result) le32_copy(result, 0, &ctx->hash, 16);
+}
diff --git a/Utilities/cmlibrhash/librhash/md5.h b/Utilities/cmlibrhash/librhash/md5.h
new file mode 100644
index 0000000..1af6f13
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/md5.h
@@ -0,0 +1,31 @@
+/* md5.h */
+#ifndef MD5_HIDER
+#define MD5_HIDER
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define md5_block_size 64
+#define md5_hash_size 16
+
+/* algorithm context */
+typedef struct md5_ctx
+{
+ unsigned message[md5_block_size / 4]; /* 512-bit buffer for leftovers */
+ uint64_t length; /* number of processed bytes */
+ unsigned hash[4]; /* 128-bit algorithm internal hashing state */
+} md5_ctx;
+
+/* hash functions */
+
+void rhash_md5_init(md5_ctx *ctx);
+void rhash_md5_update(md5_ctx *ctx, const unsigned char* msg, size_t size);
+void rhash_md5_final(md5_ctx *ctx, unsigned char result[16]);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* MD5_HIDER */
diff --git a/Utilities/cmlibrhash/librhash/rhash.c b/Utilities/cmlibrhash/librhash/rhash.c
new file mode 100644
index 0000000..ad6249b
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/rhash.c
@@ -0,0 +1,872 @@
+/* rhash.c - implementation of LibRHash library calls
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+/* macros for large file support, must be defined before any include file */
+#define _LARGEFILE64_SOURCE
+#define _FILE_OFFSET_BITS 64
+
+#include <string.h> /* memset() */
+#include <stdlib.h> /* free() */
+#include <stddef.h> /* ptrdiff_t */
+#include <stdio.h>
+#include <assert.h>
+#include <errno.h>
+
+/* modifier for Windows DLL */
+#if defined(_WIN32) && defined(RHASH_EXPORTS)
+# define RHASH_API __declspec(dllexport)
+#endif
+
+#include "byte_order.h"
+#include "algorithms.h"
+#include "util.h"
+#include "hex.h"
+#include "rhash.h" /* RHash library interface */
+
+#define STATE_ACTIVE 0xb01dbabe
+#define STATE_STOPED 0xdeadbeef
+#define STATE_DELETED 0xdecea5ed
+#define RCTX_AUTO_FINAL 0x1
+#define RCTX_FINALIZED 0x2
+#define RCTX_FINALIZED_MASK (RCTX_AUTO_FINAL | RCTX_FINALIZED)
+#define RHPR_FORMAT (RHPR_RAW | RHPR_HEX | RHPR_BASE32 | RHPR_BASE64)
+#define RHPR_MODIFIER (RHPR_UPPERCASE | RHPR_REVERSE)
+
+/**
+ * Initialize static data of rhash algorithms
+ */
+void rhash_library_init(void)
+{
+ rhash_init_algorithms(RHASH_ALL_HASHES);
+#ifdef USE_OPENSSL
+ rhash_plug_openssl();
+#endif
+}
+
+/**
+ * Returns the number of supported hash algorithms.
+ *
+ * @return the number of supported hash functions
+ */
+int RHASH_API rhash_count(void)
+{
+ return rhash_info_size;
+}
+
+/* Lo-level rhash library functions */
+
+/**
+ * Allocate and initialize RHash context for calculating hash(es).
+ * After initializing rhash_update()/rhash_final() functions should be used.
+ * Then the context must be freed by calling rhash_free().
+ *
+ * @param hash_id union of bit flags, containing ids of hashes to calculate.
+ * @return initialized rhash context, NULL on error and errno is set
+ */
+RHASH_API rhash rhash_init(unsigned hash_id)
+{
+ unsigned tail_bit_index; /* index of hash_id trailing bit */
+ unsigned num = 0; /* number of hashes to compute */
+ rhash_context_ext *rctx = NULL; /* allocated rhash context */
+ size_t hash_size_sum = 0; /* size of hash contexts to store in rctx */
+
+ unsigned i, bit_index, id;
+ struct rhash_hash_info* info;
+ size_t aligned_size;
+ char* phash_ctx;
+
+ hash_id &= RHASH_ALL_HASHES;
+ if (hash_id == 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ tail_bit_index = rhash_ctz(hash_id); /* get trailing bit index */
+ assert(tail_bit_index < RHASH_HASH_COUNT);
+
+ id = 1 << tail_bit_index;
+
+ if (hash_id == id) {
+ /* handle the most common case of only one hash */
+ num = 1;
+ info = &rhash_info_table[tail_bit_index];
+ hash_size_sum = info->context_size;
+ } else {
+ /* another case: hash_id contains several hashes */
+ for (bit_index = tail_bit_index; id <= hash_id; bit_index++, id = id << 1) {
+ assert(id != 0);
+ assert(bit_index < RHASH_HASH_COUNT);
+ info = &rhash_info_table[bit_index];
+ if (hash_id & id) {
+ /* align sizes by 8 bytes */
+ aligned_size = (info->context_size + 7) & ~7;
+ hash_size_sum += aligned_size;
+ num++;
+ }
+ }
+ assert(num > 1);
+ }
+
+ /* align the size of the rhash context common part */
+ aligned_size = (offsetof(rhash_context_ext, vector[num]) + 7) & ~7;
+ assert(aligned_size >= sizeof(rhash_context_ext));
+
+ /* allocate rhash context with enough memory to store contexts of all used hashes */
+ rctx = (rhash_context_ext*)malloc(aligned_size + hash_size_sum);
+ if (rctx == NULL) return NULL;
+
+ /* initialize common fields of the rhash context */
+ memset(rctx, 0, sizeof(rhash_context_ext));
+ rctx->rc.hash_id = hash_id;
+ rctx->flags = RCTX_AUTO_FINAL; /* turn on auto-final by default */
+ rctx->state = STATE_ACTIVE;
+ rctx->hash_vector_size = num;
+
+ /* aligned hash contexts follows rctx->vector[num] in the same memory block */
+ phash_ctx = (char*)rctx + aligned_size;
+ assert(phash_ctx >= (char*)&rctx->vector[num]);
+
+ /* initialize context for every hash in a loop */
+ for (bit_index = tail_bit_index, id = 1 << tail_bit_index, i = 0;
+ id <= hash_id; bit_index++, id = id << 1)
+ {
+ /* check if a hash function with given id shall be included into rctx */
+ if ((hash_id & id) != 0) {
+ info = &rhash_info_table[bit_index];
+ assert(info->context_size > 0);
+ assert(((phash_ctx - (char*)0) & 7) == 0); /* hash context is aligned */
+ assert(info->init != NULL);
+
+ rctx->vector[i].hash_info = info;
+ rctx->vector[i].context = phash_ctx;
+
+#if 0
+ /* BTIH initialization is complex, save pointer for later */
+ if ((id & RHASH_BTIH) != 0) rctx->bt_ctx = phash_ctx;
+#endif
+ phash_ctx += (info->context_size + 7) & ~7;
+
+ /* initialize the i-th hash context */
+ info->init(rctx->vector[i].context);
+ i++;
+ }
+ }
+
+ return &rctx->rc; /* return allocated and initialized rhash context */
+}
+
+/**
+ * Free RHash context memory.
+ *
+ * @param ctx the context to free.
+ */
+void rhash_free(rhash ctx)
+{
+ rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+ unsigned i;
+
+ if (ctx == 0) return;
+ assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+ ectx->state = STATE_DELETED; /* mark memory block as being removed */
+
+ /* clean the hash functions, which require additional clean up */
+ for (i = 0; i < ectx->hash_vector_size; i++) {
+ struct rhash_hash_info* info = ectx->vector[i].hash_info;
+ if (info->cleanup != 0) {
+ info->cleanup(ectx->vector[i].context);
+ }
+ }
+
+ free(ectx);
+}
+
+/**
+ * Re-initialize RHash context to reuse it.
+ * Useful to speed up processing of many small messages.
+ *
+ * @param ctx context to reinitialize
+ */
+RHASH_API void rhash_reset(rhash ctx)
+{
+ rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+ unsigned i;
+
+ assert(ectx->hash_vector_size > 0);
+ assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+ ectx->state = STATE_ACTIVE; /* re-activate the structure */
+
+ /* re-initialize every hash in a loop */
+ for (i = 0; i < ectx->hash_vector_size; i++) {
+ struct rhash_hash_info* info = ectx->vector[i].hash_info;
+ if (info->cleanup != 0) {
+ info->cleanup(ectx->vector[i].context);
+ }
+
+ assert(info->init != NULL);
+ info->init(ectx->vector[i].context);
+ }
+ ectx->flags &= ~RCTX_FINALIZED; /* clear finalized state */
+}
+
+/**
+ * Calculate hashes of message.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the rhash context
+ * @param message message chunk
+ * @param length length of the message chunk
+ * @return 0 on success; On fail return -1 and set errno
+ */
+RHASH_API int rhash_update(rhash ctx, const void* message, size_t length)
+{
+ rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+ unsigned i;
+
+ assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+ if (ectx->state != STATE_ACTIVE) return 0; /* do nothing if canceled */
+
+ ctx->msg_size += length;
+
+ /* call update method for every algorithm */
+ for (i = 0; i < ectx->hash_vector_size; i++) {
+ struct rhash_hash_info* info = ectx->vector[i].hash_info;
+ assert(info->update != 0);
+ info->update(ectx->vector[i].context, message, length);
+ }
+ return 0; /* no error processing at the moment */
+}
+
+/**
+ * Finalize hash calculation and optionally store the first hash.
+ *
+ * @param ctx the rhash context
+ * @param first_result optional buffer to store a calculated hash with the lowest available id
+ * @return 0 on success; On fail return -1 and set errno
+ */
+RHASH_API int rhash_final(rhash ctx, unsigned char* first_result)
+{
+ unsigned i = 0;
+ unsigned char buffer[130];
+ unsigned char* out = (first_result ? first_result : buffer);
+ rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+ assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+
+ /* skip final call if already finalized and auto-final is on */
+ if ((ectx->flags & RCTX_FINALIZED_MASK) ==
+ (RCTX_AUTO_FINAL | RCTX_FINALIZED)) return 0;
+
+ /* call final method for every algorithm */
+ for (i = 0; i < ectx->hash_vector_size; i++) {
+ struct rhash_hash_info* info = ectx->vector[i].hash_info;
+ assert(info->final != 0);
+ assert(info->info->digest_size < sizeof(buffer));
+ info->final(ectx->vector[i].context, out);
+ out = buffer;
+ }
+ ectx->flags |= RCTX_FINALIZED;
+ return 0; /* no error processing at the moment */
+}
+
+/**
+ * Store digest for given hash_id.
+ * If hash_id is zero, function stores digest for a hash with the lowest id found in the context.
+ * For nonzero hash_id the context must contain it, otherwise function silently does nothing.
+ *
+ * @param ctx rhash context
+ * @param hash_id id of hash to retrieve or zero for hash with the lowest available id
+ * @param result buffer to put the hash into
+ */
+static void rhash_put_digest(rhash ctx, unsigned hash_id, unsigned char* result)
+{
+ rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+ unsigned i;
+ rhash_vector_item *item;
+ struct rhash_hash_info* info;
+ unsigned char* digest;
+
+ assert(ectx);
+ assert(ectx->hash_vector_size > 0 && ectx->hash_vector_size <= RHASH_HASH_COUNT);
+
+ /* finalize context if not yet finalized and auto-final is on */
+ if ((ectx->flags & RCTX_FINALIZED_MASK) == RCTX_AUTO_FINAL) {
+ rhash_final(ctx, NULL);
+ }
+
+ if (hash_id == 0) {
+ item = &ectx->vector[0]; /* get the first hash */
+ info = item->hash_info;
+ } else {
+ for (i = 0;; i++) {
+ if (i >= ectx->hash_vector_size) {
+ return; /* hash_id not found, do nothing */
+ }
+ item = &ectx->vector[i];
+ info = item->hash_info;
+ if (info->info->hash_id == hash_id) break;
+ }
+ }
+ digest = ((unsigned char*)item->context + info->digest_diff);
+ if (info->info->flags & F_SWAP32) {
+ assert((info->info->digest_size & 3) == 0);
+ /* NB: the next call is correct only for multiple of 4 byte size */
+ rhash_swap_copy_str_to_u32(result, 0, digest, info->info->digest_size);
+ } else if (info->info->flags & F_SWAP64) {
+ rhash_swap_copy_u64_to_str(result, digest, info->info->digest_size);
+ } else {
+ memcpy(result, digest, info->info->digest_size);
+ }
+}
+
+/**
+ * Set the callback function to be called from the
+ * rhash_file() and rhash_file_update() functions
+ * on processing every file block. The file block
+ * size is set internally by rhash and now is 8 KiB.
+ *
+ * @param ctx rhash context
+ * @param callback pointer to the callback function
+ * @param callback_data pointer to data passed to the callback
+ */
+RHASH_API void rhash_set_callback(rhash ctx, rhash_callback_t callback, void* callback_data)
+{
+ ((rhash_context_ext*)ctx)->callback = callback;
+ ((rhash_context_ext*)ctx)->callback_data = callback_data;
+}
+
+
+/* hi-level message hashing interface */
+
+/**
+ * Compute a hash of the given message.
+ *
+ * @param hash_id id of hash sum to compute
+ * @param message the message to process
+ * @param length message length
+ * @param result buffer to receive binary hash string
+ * @return 0 on success, -1 on error
+ */
+RHASH_API int rhash_msg(unsigned hash_id, const void* message, size_t length, unsigned char* result)
+{
+ rhash ctx;
+ hash_id &= RHASH_ALL_HASHES;
+ ctx = rhash_init(hash_id);
+ if (ctx == NULL) return -1;
+ rhash_update(ctx, message, length);
+ rhash_final(ctx, result);
+ rhash_free(ctx);
+ return 0;
+}
+
+/**
+ * Hash a file or stream. Multiple hashes can be computed.
+ * First, inintialize ctx parameter with rhash_init() before calling
+ * rhash_file_update(). Then use rhash_final() and rhash_print()
+ * to retrive hash values. Finaly call rhash_free() on ctx
+ * to free allocated memory or call rhash_reset() to reuse ctx.
+ *
+ * @param ctx rhash context
+ * @param fd descriptor of the file to hash
+ * @return 0 on success, -1 on error and errno is set
+ */
+RHASH_API int rhash_file_update(rhash ctx, FILE* fd)
+{
+ rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+ const size_t block_size = 8192;
+ unsigned char *buffer, *pmem;
+ size_t length = 0, align8;
+ int res = 0;
+ if (ectx->state != STATE_ACTIVE) return 0; /* do nothing if canceled */
+
+ if (ctx == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ pmem = (unsigned char*)malloc(block_size + 8);
+ if (!pmem) return -1; /* errno is set to ENOMEM according to UNIX 98 */
+
+ align8 = ((unsigned char*)0 - pmem) & 7;
+ buffer = pmem + align8;
+
+ while (!feof(fd)) {
+ /* stop if canceled */
+ if (ectx->state != STATE_ACTIVE) break;
+
+ length = fread(buffer, 1, block_size, fd);
+
+ if (ferror(fd)) {
+ res = -1; /* note: errno contains error code */
+ break;
+ } else if (length) {
+ rhash_update(ctx, buffer, length);
+
+ if (ectx->callback) {
+ ((rhash_callback_t)ectx->callback)(ectx->callback_data, ectx->rc.msg_size);
+ }
+ }
+ }
+
+ free(buffer);
+ return res;
+}
+
+/**
+ * Compute a single hash for given file.
+ *
+ * @param hash_id id of hash sum to compute
+ * @param filepath path to the file to hash
+ * @param result buffer to receive hash value with the lowest requested id
+ * @return 0 on success, -1 on error and errno is set
+ */
+RHASH_API int rhash_file(unsigned hash_id, const char* filepath, unsigned char* result)
+{
+ FILE* fd;
+ rhash ctx;
+ int res;
+
+ hash_id &= RHASH_ALL_HASHES;
+ if (hash_id == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if ((fd = fopen(filepath, "rb")) == NULL) return -1;
+
+ if ((ctx = rhash_init(hash_id)) == NULL) return -1;
+
+ res = rhash_file_update(ctx, fd); /* hash the file */
+ fclose(fd);
+
+ rhash_final(ctx, result);
+ rhash_free(ctx);
+ return res;
+}
+
+#ifdef _WIN32 /* windows only function */
+#include <share.h>
+
+/**
+ * Compute a single hash for given file.
+ *
+ * @param hash_id id of hash sum to compute
+ * @param filepath path to the file to hash
+ * @param result buffer to receive hash value with the lowest requested id
+ * @return 0 on success, -1 on error, -1 on error and errno is set
+ */
+RHASH_API int rhash_wfile(unsigned hash_id, const wchar_t* filepath, unsigned char* result)
+{
+ FILE* fd;
+ rhash ctx;
+ int res;
+
+ hash_id &= RHASH_ALL_HASHES;
+ if (hash_id == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if ((fd = _wfsopen(filepath, L"rb", _SH_DENYWR)) == NULL) return -1;
+
+ if ((ctx = rhash_init(hash_id)) == NULL) return -1;
+
+ res = rhash_file_update(ctx, fd); /* hash the file */
+ fclose(fd);
+
+ rhash_final(ctx, result);
+ rhash_free(ctx);
+ return res;
+}
+#endif
+
+/* RHash information functions */
+
+/**
+ * Returns information about a hash function by its hash_id.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return pointer to the rhash_info structure containing the information
+ */
+const rhash_info* rhash_info_by_id(unsigned hash_id)
+{
+ hash_id &= RHASH_ALL_HASHES;
+ /* check that only one bit is set */
+ if (hash_id != (hash_id & -(int)hash_id)) return NULL;
+ /* note: alternative condition is (hash_id == 0 || (hash_id & (hash_id - 1)) != 0) */
+ return rhash_info_table[rhash_ctz(hash_id)].info;
+}
+
+#if 0
+/**
+ * Detect default digest output format for given hash algorithm.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return 1 for base32 format, 0 for hexadecimal
+ */
+RHASH_API int rhash_is_base32(unsigned hash_id)
+{
+ /* fast method is just to test a bit-mask */
+ return ((hash_id & (RHASH_TTH | RHASH_AICH)) != 0);
+}
+#endif
+
+/**
+ * Returns size of binary digest for given hash algorithm.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return digest size in bytes
+ */
+RHASH_API int rhash_get_digest_size(unsigned hash_id)
+{
+ hash_id &= RHASH_ALL_HASHES;
+ if (hash_id == 0 || (hash_id & (hash_id - 1)) != 0) return -1;
+ return (int)rhash_info_table[rhash_ctz(hash_id)].info->digest_size;
+}
+
+/**
+ * Returns length of digest hash string in default output format.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return the length of hash string
+ */
+RHASH_API int rhash_get_hash_length(unsigned hash_id)
+{
+ const rhash_info* info = rhash_info_by_id(hash_id);
+ return (int)(info ? (info->flags & F_BS32 ?
+ BASE32_LENGTH(info->digest_size) : info->digest_size * 2) : 0);
+}
+
+/**
+ * Returns a name of given hash algorithm.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return algorithm name
+ */
+RHASH_API const char* rhash_get_name(unsigned hash_id)
+{
+ const rhash_info* info = rhash_info_by_id(hash_id);
+ return (info ? info->name : 0);
+}
+
+/**
+ * Returns a name part of magnet urn of the given hash algorithm.
+ * Such magnet_name is used to generate a magnet link of the form
+ * urn:&lt;magnet_name&gt;=&lt;hash_value&gt;.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return name
+ */
+RHASH_API const char* rhash_get_magnet_name(unsigned hash_id)
+{
+ const rhash_info* info = rhash_info_by_id(hash_id);
+ return (info ? info->magnet_name : 0);
+}
+
+#if 0
+static size_t rhash_get_magnet_url_size(const char* filepath,
+ rhash context, unsigned hash_mask, int flags)
+{
+ size_t size = 0; /* count terminating '\0' */
+ unsigned bit, hash = context->hash_id & hash_mask;
+
+ /* RHPR_NO_MAGNET, RHPR_FILESIZE */
+ if ((flags & RHPR_NO_MAGNET) == 0) {
+ size += 8;
+ }
+
+ if ((flags & RHPR_FILESIZE) != 0) {
+ uint64_t num = context->msg_size;
+
+ size += 4;
+ if (num == 0) size++;
+ else {
+ for (; num; num /= 10, size++);
+ }
+ }
+
+ if (filepath) {
+ size += 4 + rhash_urlencode(NULL, filepath);
+ }
+
+ /* loop through hash values */
+ for (bit = hash & -(int)hash; bit <= hash; bit <<= 1) {
+ const char* name;
+ if ((bit & hash) == 0) continue;
+ if ((name = rhash_get_magnet_name(bit)) == 0) continue;
+
+ size += (7 + 2) + strlen(name);
+ size += rhash_print(NULL, context, bit,
+ (bit & (RHASH_SHA1 | RHASH_BTIH) ? RHPR_BASE32 : 0));
+ }
+
+ return size;
+}
+
+/**
+ * Print magnet link with given filepath and calculated hash sums into the
+ * output buffer. The hash_mask can limit which hash values will be printed.
+ * The function returns the size of the required buffer.
+ * If output is NULL the .
+ *
+ * @param output a string buffer to receive the magnet link or NULL
+ * @param filepath the file path to be printed or NULL
+ * @param context algorithms state
+ * @param hash_mask bit mask of the hash sums to add to the link
+ * @param flags can be combination of bits RHPR_UPPERCASE, RHPR_NO_MAGNET,
+ * RHPR_FILESIZE
+ * @return number of written characters, including terminating '\0' on success, 0 on fail
+ */
+RHASH_API size_t rhash_print_magnet(char* output, const char* filepath,
+ rhash context, unsigned hash_mask, int flags)
+{
+ int i;
+ const char* begin = output;
+
+ if (output == NULL) return rhash_get_magnet_url_size(
+ filepath, context, hash_mask, flags);
+
+ /* RHPR_NO_MAGNET, RHPR_FILESIZE */
+ if ((flags & RHPR_NO_MAGNET) == 0) {
+ strcpy(output, "magnet:?");
+ output += 8;
+ }
+
+ if ((flags & RHPR_FILESIZE) != 0) {
+ strcpy(output, "xl=");
+ output += 3;
+ output += rhash_sprintI64(output, context->msg_size);
+ *(output++) = '&';
+ }
+
+ if (filepath) {
+ strcpy(output, "dn=");
+ output += 3;
+ output += rhash_urlencode(output, filepath);
+ *(output++) = '&';
+ }
+ flags &= RHPR_UPPERCASE;
+
+ for (i = 0; i < 2; i++) {
+ unsigned bit;
+ unsigned hash = context->hash_id & hash_mask;
+ hash = (i == 0 ? hash & (RHASH_ED2K | RHASH_AICH)
+ : hash & ~(RHASH_ED2K | RHASH_AICH));
+ if (!hash) continue;
+
+ /* loop through hash values */
+ for (bit = hash & -(int)hash; bit <= hash; bit <<= 1) {
+ const char* name;
+ if ((bit & hash) == 0) continue;
+ if (!(name = rhash_get_magnet_name(bit))) continue;
+
+ strcpy(output, "xt=urn:");
+ output += 7;
+ strcpy(output, name);
+ output += strlen(name);
+ *(output++) = ':';
+ output += rhash_print(output, context, bit,
+ (bit & (RHASH_SHA1 | RHASH_BTIH) ? flags | RHPR_BASE32 : flags));
+ *(output++) = '&';
+ }
+ }
+ output[-1] = '\0'; /* terminate the line */
+
+ return (output - begin);
+}
+
+/* hash sum output */
+
+/**
+ * Print a text presentation of a given hash sum to the specified buffer,
+ *
+ * @param output a buffer to print the hash to
+ * @param bytes a hash sum to print
+ * @param size a size of hash sum in bytes
+ * @param flags a bit-mask controlling how to format the hash sum,
+ * can be a mix of the flags: RHPR_RAW, RHPR_HEX, RHPR_BASE32,
+ * RHPR_BASE64, RHPR_UPPERCASE, RHPR_REVERSE
+ * @return the number of written characters
+ */
+size_t rhash_print_bytes(char* output, const unsigned char* bytes,
+ size_t size, int flags)
+{
+ size_t str_len;
+ int upper_case = (flags & RHPR_UPPERCASE);
+ int format = (flags & ~RHPR_MODIFIER);
+
+ switch (format) {
+ case RHPR_HEX:
+ str_len = size * 2;
+ rhash_byte_to_hex(output, bytes, (unsigned)size, upper_case);
+ break;
+ case RHPR_BASE32:
+ str_len = BASE32_LENGTH(size);
+ rhash_byte_to_base32(output, bytes, (unsigned)size, upper_case);
+ break;
+ case RHPR_BASE64:
+ str_len = BASE64_LENGTH(size);
+ rhash_byte_to_base64(output, bytes, (unsigned)size);
+ break;
+ default:
+ str_len = size;
+ memcpy(output, bytes, size);
+ break;
+ }
+ return str_len;
+}
+
+/**
+ * Print text presentation of a hash sum with given hash_id to the specified
+ * output buffer. If the hash_id is zero, then print the hash sum with
+ * the lowest id stored in the hash context.
+ * The function call fails if the context doesn't include a hash with the
+ * given hash_id.
+ *
+ * @param output a buffer to print the hash to
+ * @param context algorithms state
+ * @param hash_id id of the hash sum to print or 0 to print the first hash
+ * saved in the context.
+ * @param flags a bitmask controlling how to print the hash. Can contain flags
+ * RHPR_UPPERCASE, RHPR_HEX, RHPR_BASE32, RHPR_BASE64, etc.
+ * @return the number of written characters on success or 0 on fail
+ */
+size_t RHASH_API rhash_print(char* output, rhash context, unsigned hash_id, int flags)
+{
+ const rhash_info* info;
+ unsigned char digest[80];
+ size_t digest_size;
+
+ info = (hash_id != 0 ? rhash_info_by_id(hash_id) :
+ ((rhash_context_ext*)context)->vector[0].hash_info->info);
+
+ if (info == NULL) return 0;
+ digest_size = info->digest_size;
+ assert(digest_size <= 64);
+
+ flags &= (RHPR_FORMAT | RHPR_MODIFIER);
+ if ((flags & RHPR_FORMAT) == 0) {
+ /* use default format if not specified by flags */
+ flags |= (info->flags & RHASH_INFO_BASE32 ? RHPR_BASE32 : RHPR_HEX);
+ }
+
+ if (output == NULL) {
+ switch (flags & RHPR_FORMAT) {
+ case RHPR_HEX:
+ return (digest_size * 2);
+ case RHPR_BASE32:
+ return BASE32_LENGTH(digest_size);
+ case RHPR_BASE64:
+ return BASE64_LENGTH(digest_size);
+ default:
+ return digest_size;
+ }
+ }
+
+ /* note: use info->hash_id, cause hash_id can be 0 */
+ rhash_put_digest(context, info->hash_id, digest);
+
+ if ((flags & ~RHPR_UPPERCASE) == (RHPR_REVERSE | RHPR_HEX)) {
+ /* reverse the digest */
+ unsigned char *p = digest, *r = digest + digest_size - 1;
+ char tmp;
+ for (; p < r; p++, r--) {
+ tmp = *p;
+ *p = *r;
+ *r = tmp;
+ }
+ }
+
+ return rhash_print_bytes(output, digest, digest_size, flags);
+}
+
+#if defined(_WIN32) && defined(RHASH_EXPORTS)
+#include <windows.h>
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved);
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved)
+{
+ (void)hModule;
+ (void)reserved;
+ switch (reason) {
+ case DLL_PROCESS_ATTACH:
+ rhash_library_init();
+ break;
+ case DLL_PROCESS_DETACH:
+ /*rhash_library_free();*/
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ break;
+ }
+ return TRUE;
+}
+#endif
+
+#define PVOID2UPTR(p) ((rhash_uptr_t)((char*)p - 0))
+
+/**
+ * Process a rhash message.
+ *
+ * @param msg_id message identifier
+ * @param dst message destination (can be NULL for generic messages)
+ * @param ldata data depending on message
+ * @param rdata data depending on message
+ * @return message-specific data
+ */
+RHASH_API rhash_uptr_t rhash_transmit(unsigned msg_id, void* dst, rhash_uptr_t ldata, rhash_uptr_t rdata)
+{
+ /* for messages working with rhash context */
+ rhash_context_ext* const ctx = (rhash_context_ext*)dst;
+
+ switch (msg_id) {
+ case RMSG_GET_CONTEXT:
+ {
+ unsigned i;
+ for (i = 0; i < ctx->hash_vector_size; i++) {
+ struct rhash_hash_info* info = ctx->vector[i].hash_info;
+ if (info->info->hash_id == (unsigned)ldata)
+ return PVOID2UPTR(ctx->vector[i].context);
+ }
+ return (rhash_uptr_t)0;
+ }
+
+ case RMSG_CANCEL:
+ /* mark rhash context as canceled, in a multithreaded program */
+ atomic_compare_and_swap(&ctx->state, STATE_ACTIVE, STATE_STOPED);
+ return 0;
+
+ case RMSG_IS_CANCELED:
+ return (ctx->state == STATE_STOPED);
+
+ case RMSG_GET_FINALIZED:
+ return ((ctx->flags & RCTX_FINALIZED) != 0);
+ case RMSG_SET_AUTOFINAL:
+ ctx->flags &= ~RCTX_AUTO_FINAL;
+ if (ldata) ctx->flags |= RCTX_AUTO_FINAL;
+ break;
+
+ /* OpenSSL related messages */
+#ifdef USE_OPENSSL
+ case RMSG_SET_OPENSSL_MASK:
+ rhash_openssl_hash_mask = (unsigned)ldata;
+ break;
+ case RMSG_GET_OPENSSL_MASK:
+ return rhash_openssl_hash_mask;
+#endif
+
+ default:
+ return RHASH_ERROR; /* unknown message */
+ }
+ return 0;
+}
+#endif
diff --git a/Utilities/cmlibrhash/librhash/rhash.h b/Utilities/cmlibrhash/librhash/rhash.h
new file mode 100644
index 0000000..cee0e25
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/rhash.h
@@ -0,0 +1,288 @@
+/** @file rhash.h LibRHash interface */
+#ifndef RHASH_H
+#define RHASH_H
+
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef RHASH_API
+/* modifier for LibRHash functions */
+# define RHASH_API
+#endif
+
+/**
+ * Identifiers of supported hash functions.
+ * The rhash_init() function allows mixing several ids using
+ * binary OR, to calculate several hash functions for one message.
+ */
+enum rhash_ids
+{
+#if 0
+ RHASH_CRC32 = 0x01,
+ RHASH_MD4 = 0x02,
+ RHASH_MD5 = 0x04,
+ RHASH_SHA1 = 0x08,
+ RHASH_TIGER = 0x10,
+ RHASH_TTH = 0x20,
+ RHASH_BTIH = 0x40,
+ RHASH_ED2K = 0x80,
+ RHASH_AICH = 0x100,
+ RHASH_WHIRLPOOL = 0x200,
+ RHASH_RIPEMD160 = 0x400,
+ RHASH_GOST = 0x800,
+ RHASH_GOST_CRYPTOPRO = 0x1000,
+ RHASH_HAS160 = 0x2000,
+ RHASH_SNEFRU128 = 0x4000,
+ RHASH_SNEFRU256 = 0x8000,
+ RHASH_SHA224 = 0x10000,
+ RHASH_SHA256 = 0x20000,
+ RHASH_SHA384 = 0x40000,
+ RHASH_SHA512 = 0x80000,
+ RHASH_EDONR256 = 0x0100000,
+ RHASH_EDONR512 = 0x0200000,
+ RHASH_SHA3_224 = 0x0400000,
+ RHASH_SHA3_256 = 0x0800000,
+ RHASH_SHA3_384 = 0x1000000,
+ RHASH_SHA3_512 = 0x2000000,
+
+ /** The bit-mask containing all supported hashe functions */
+ RHASH_ALL_HASHES = RHASH_CRC32 | RHASH_MD4 | RHASH_MD5 | RHASH_ED2K | RHASH_SHA1 |
+ RHASH_TIGER | RHASH_TTH | RHASH_GOST | RHASH_GOST_CRYPTOPRO |
+ RHASH_BTIH | RHASH_AICH | RHASH_WHIRLPOOL | RHASH_RIPEMD160 |
+ RHASH_HAS160 | RHASH_SNEFRU128 | RHASH_SNEFRU256 |
+ RHASH_SHA224 | RHASH_SHA256 | RHASH_SHA384 | RHASH_SHA512 |
+ RHASH_SHA3_224 | RHASH_SHA3_256 | RHASH_SHA3_384 | RHASH_SHA3_512 |
+ RHASH_EDONR256 | RHASH_EDONR512,
+
+ /** The number of supported hash functions */
+ RHASH_HASH_COUNT = 26
+#else
+ RHASH_MD5 = 0x01,
+ RHASH_SHA1 = 0x02,
+ RHASH_SHA224 = 0x04,
+ RHASH_SHA256 = 0x08,
+ RHASH_SHA384 = 0x10,
+ RHASH_SHA512 = 0x20,
+ RHASH_SHA3_224 = 0x40,
+ RHASH_SHA3_256 = 0x80,
+ RHASH_SHA3_384 = 0x100,
+ RHASH_SHA3_512 = 0x200,
+ RHASH_ALL_HASHES =
+ RHASH_MD5 |
+ RHASH_SHA1 |
+ RHASH_SHA224 |
+ RHASH_SHA256 |
+ RHASH_SHA384 |
+ RHASH_SHA512 |
+ RHASH_SHA3_224 |
+ RHASH_SHA3_256 |
+ RHASH_SHA3_384 |
+ RHASH_SHA3_512,
+ RHASH_HASH_COUNT = 10
+#endif
+};
+
+/**
+ * The rhash context structure contains contexts for several hash functions
+ */
+typedef struct rhash_context
+{
+ /** The size of the hashed message */
+ unsigned long long msg_size;
+
+ /**
+ * The bit-mask containing identifiers of the hashes being calculated
+ */
+ unsigned hash_id;
+} rhash_context;
+
+#ifndef LIBRHASH_RHASH_CTX_DEFINED
+#define LIBRHASH_RHASH_CTX_DEFINED
+/**
+ * Hashing context.
+ */
+typedef struct rhash_context* rhash;
+#endif /* LIBRHASH_RHASH_CTX_DEFINED */
+
+/** type of a callback to be called periodically while hashing a file */
+typedef void (*rhash_callback_t)(void* data, unsigned long long offset);
+
+RHASH_API void rhash_library_init(void); /* initialize static data */
+
+/* hi-level hashing functions */
+RHASH_API int rhash_msg(unsigned hash_id, const void* message, size_t length, unsigned char* result);
+RHASH_API int rhash_file(unsigned hash_id, const char* filepath, unsigned char* result);
+RHASH_API int rhash_file_update(rhash ctx, FILE* fd);
+
+#ifdef _WIN32 /* windows only function */
+RHASH_API int rhash_wfile(unsigned hash_id, const wchar_t* filepath, unsigned char* result);
+#endif
+
+/* lo-level interface */
+RHASH_API rhash rhash_init(unsigned hash_id);
+/*RHASH_API rhash rhash_init_by_ids(unsigned hash_ids[], unsigned count);*/
+RHASH_API int rhash_update(rhash ctx, const void* message, size_t length);
+RHASH_API int rhash_final(rhash ctx, unsigned char* first_result);
+RHASH_API void rhash_reset(rhash ctx); /* reinitialize the context */
+RHASH_API void rhash_free(rhash ctx);
+
+/* additional lo-level functions */
+RHASH_API void rhash_set_callback(rhash ctx, rhash_callback_t callback, void* callback_data);
+
+/** bit-flag: default hash output format is base32 */
+#define RHASH_INFO_BASE32 1
+
+/**
+ * Information about a hash function.
+ */
+typedef struct rhash_info
+{
+ /** hash function indentifier */
+ unsigned hash_id;
+ /** flags bit-mask, including RHASH_INFO_BASE32 bit */
+ unsigned flags;
+ /** size of binary message digest in bytes */
+ size_t digest_size;
+ const char* name;
+ const char* magnet_name;
+} rhash_info;
+
+/* information functions */
+RHASH_API int rhash_count(void); /* number of supported hashes */
+RHASH_API int rhash_get_digest_size(unsigned hash_id); /* size of binary message digest */
+RHASH_API int rhash_get_hash_length(unsigned hash_id); /* length of formatted hash string */
+RHASH_API int rhash_is_base32(unsigned hash_id); /* default digest output format */
+RHASH_API const char* rhash_get_name(unsigned hash_id); /* get hash function name */
+RHASH_API const char* rhash_get_magnet_name(unsigned hash_id); /* get name part of magnet urn */
+
+/* note, that rhash_info_by_id() is not exported to a shared library or DLL */
+const rhash_info* rhash_info_by_id(unsigned hash_id); /* get hash sum info by hash id */
+
+#if 0
+/**
+ * Flags for printing a hash sum
+ */
+enum rhash_print_sum_flags
+{
+ /** print in a default format */
+ RHPR_DEFAULT = 0x0,
+ /** output as binary message digest */
+ RHPR_RAW = 0x1,
+ /** print as a hexadecimal string */
+ RHPR_HEX = 0x2,
+ /** print as a base32-encoded string */
+ RHPR_BASE32 = 0x3,
+ /** print as a base64-encoded string */
+ RHPR_BASE64 = 0x4,
+
+ /**
+ * Print as an uppercase string. Can be used
+ * for base32 or hexadecimal format only.
+ */
+ RHPR_UPPERCASE = 0x8,
+
+ /**
+ * Reverse hash bytes. Can be used for GOST hash.
+ */
+ RHPR_REVERSE = 0x10,
+
+ /** don't print 'magnet:?' prefix in rhash_print_magnet */
+ RHPR_NO_MAGNET = 0x20,
+ /** print file size in rhash_print_magnet */
+ RHPR_FILESIZE = 0x40,
+};
+#endif
+
+/* output hash into the given buffer */
+RHASH_API size_t rhash_print_bytes(char* output,
+ const unsigned char* bytes, size_t size, int flags);
+
+RHASH_API size_t rhash_print(char* output, rhash ctx, unsigned hash_id,
+ int flags);
+
+/* output magnet URL into the given buffer */
+RHASH_API size_t rhash_print_magnet(char* output, const char* filepath,
+ rhash context, unsigned hash_mask, int flags);
+
+/* macros for message API */
+
+/** The type of an unsigned integer large enough to hold a pointer */
+#if defined(UINTPTR_MAX)
+typedef uintptr_t rhash_uptr_t;
+#elif defined(_LP64) || defined(__LP64__) || defined(__x86_64) || \
+ defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
+typedef unsigned long long rhash_uptr_t;
+#else
+typedef unsigned long rhash_uptr_t;
+#endif
+
+/** The value returned by rhash_transmit on error */
+#define RHASH_ERROR ((rhash_uptr_t)-1)
+/** Convert a pointer to rhash_uptr_t */
+#define RHASH_STR2UPTR(str) ((rhash_uptr_t)(char*)(str))
+/** Convert a rhash_uptr_t to a void* pointer */
+#define RHASH_UPTR2PVOID(u) ((void*)((char*)0 + (u)))
+
+/* rhash API to set/get data via messages */
+RHASH_API rhash_uptr_t rhash_transmit(
+ unsigned msg_id, void* dst, rhash_uptr_t ldata, rhash_uptr_t rdata);
+
+/* rhash message constants */
+
+#define RMSG_GET_CONTEXT 1
+#define RMSG_CANCEL 2
+#define RMSG_IS_CANCELED 3
+#define RMSG_GET_FINALIZED 4
+#define RMSG_SET_AUTOFINAL 5
+#define RMSG_SET_OPENSSL_MASK 10
+#define RMSG_GET_OPENSSL_MASK 11
+
+/* helper macros */
+
+/** Get a pointer to context of the specified hash function */
+#define rhash_get_context_ptr(ctx, hash_id) RHASH_UPTR2PVOID(rhash_transmit(RMSG_GET_CONTEXT, ctx, hash_id, 0))
+/** Cancel hash calculation of a file */
+#define rhash_cancel(ctx) rhash_transmit(RMSG_CANCEL, ctx, 0, 0)
+/** Return non-zero if hash calculation was canceled, zero otherwise */
+#define rhash_is_canceled(ctx) rhash_transmit(RMSG_IS_CANCELED, ctx, 0, 0)
+/** Return non-zero if rhash_final was called for rhash_context */
+#define rhash_get_finalized(ctx) rhash_transmit(RMSG_GET_FINALIZED, ctx, 0, 0)
+
+/**
+ * Turn on/off the auto-final flag for the given rhash_context. By default
+ * auto-final is on, which means rhash_final is called automatically, if
+ * needed when a hash value is retrived by rhash_print call.
+ */
+#define rhash_set_autofinal(ctx, on) rhash_transmit(RMSG_SET_AUTOFINAL, ctx, on, 0)
+
+/**
+ * Set the bit-mask of hash algorithms to be calculated by OpenSSL library.
+ * The call rhash_set_openssl_mask(0) made before rhash_library_init(),
+ * turns off loading of the OpenSSL dynamic library.
+ * This call works if the LibRHash was compiled with OpenSSL support.
+ */
+#define rhash_set_openssl_mask(mask) rhash_transmit(RMSG_SET_OPENSSL_MASK, NULL, mask, 0)
+
+/**
+ * Return current bit-mask of hash algorithms selected to be calculated
+ * by OpenSSL library.
+ */
+#define rhash_get_openssl_mask() rhash_transmit(RMSG_GET_OPENSSL_MASK, NULL, 0, 0)
+
+/** The bit mask of hash algorithms implemented by OpenSSL */
+#if defined(USE_OPENSSL) || defined(OPENSSL_RUNTIME)
+# define RHASH_OPENSSL_SUPPORTED_HASHES (RHASH_MD4 | RHASH_MD5 | \
+ RHASH_SHA1 | RHASH_SHA224 | RHASH_SHA256 | RHASH_SHA384 | \
+ RHASH_SHA512 | RHASH_RIPEMD160 | RHASH_WHIRLPOOL)
+#else
+# define RHASH_OPENSSL_SUPPORTED_HASHES 0
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* RHASH_H */
diff --git a/Utilities/cmlibrhash/librhash/sha1.c b/Utilities/cmlibrhash/librhash/sha1.c
new file mode 100644
index 0000000..f5a053b
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha1.c
@@ -0,0 +1,196 @@
+/* sha1.c - an implementation of Secure Hash Algorithm 1 (SHA1)
+ * based on RFC 3174.
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "sha1.h"
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha1_init(sha1_ctx *ctx)
+{
+ ctx->length = 0;
+
+ /* initialize algorithm state */
+ ctx->hash[0] = 0x67452301;
+ ctx->hash[1] = 0xefcdab89;
+ ctx->hash[2] = 0x98badcfe;
+ ctx->hash[3] = 0x10325476;
+ ctx->hash[4] = 0xc3d2e1f0;
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ * The function has been taken from RFC 3174 with little changes.
+ *
+ * @param hash algorithm state
+ * @param block the message block to process
+ */
+static void rhash_sha1_process_block(unsigned* hash, const unsigned* block)
+{
+ int t; /* Loop counter */
+ uint32_t temp; /* Temporary word value */
+ uint32_t W[80]; /* Word sequence */
+ uint32_t A, B, C, D, E; /* Word buffers */
+
+ /* initialize the first 16 words in the array W */
+ for (t = 0; t < 16; t++) {
+ /* note: it is much faster to apply be2me here, then using be32_copy */
+ W[t] = be2me_32(block[t]);
+ }
+
+ /* initialize the rest */
+ for (t = 16; t < 80; t++) {
+ W[t] = ROTL32(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
+ }
+
+ A = hash[0];
+ B = hash[1];
+ C = hash[2];
+ D = hash[3];
+ E = hash[4];
+
+ for (t = 0; t < 20; t++) {
+ /* the following is faster than ((B & C) | ((~B) & D)) */
+ temp = ROTL32(A, 5) + (((C ^ D) & B) ^ D)
+ + E + W[t] + 0x5A827999;
+ E = D;
+ D = C;
+ C = ROTL32(B, 30);
+ B = A;
+ A = temp;
+ }
+
+ for (t = 20; t < 40; t++) {
+ temp = ROTL32(A, 5) + (B ^ C ^ D) + E + W[t] + 0x6ED9EBA1;
+ E = D;
+ D = C;
+ C = ROTL32(B, 30);
+ B = A;
+ A = temp;
+ }
+
+ for (t = 40; t < 60; t++) {
+ temp = ROTL32(A, 5) + ((B & C) | (B & D) | (C & D))
+ + E + W[t] + 0x8F1BBCDC;
+ E = D;
+ D = C;
+ C = ROTL32(B, 30);
+ B = A;
+ A = temp;
+ }
+
+ for (t = 60; t < 80; t++) {
+ temp = ROTL32(A, 5) + (B ^ C ^ D) + E + W[t] + 0xCA62C1D6;
+ E = D;
+ D = C;
+ C = ROTL32(B, 30);
+ B = A;
+ A = temp;
+ }
+
+ hash[0] += A;
+ hash[1] += B;
+ hash[2] += C;
+ hash[3] += D;
+ hash[4] += E;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha1_update(sha1_ctx *ctx, const unsigned char* msg, size_t size)
+{
+ unsigned index = (unsigned)ctx->length & 63;
+ ctx->length += size;
+
+ /* fill partial block */
+ if (index) {
+ unsigned left = sha1_block_size - index;
+ memcpy(ctx->message + index, msg, (size < left ? size : left));
+ if (size < left) return;
+
+ /* process partial block */
+ rhash_sha1_process_block(ctx->hash, (unsigned*)ctx->message);
+ msg += left;
+ size -= left;
+ }
+ while (size >= sha1_block_size) {
+ unsigned* aligned_message_block;
+ if (IS_ALIGNED_32(msg)) {
+ /* the most common case is processing of an already aligned message
+ without copying it */
+ aligned_message_block = (unsigned*)msg;
+ } else {
+ memcpy(ctx->message, msg, sha1_block_size);
+ aligned_message_block = (unsigned*)ctx->message;
+ }
+
+ rhash_sha1_process_block(ctx->hash, aligned_message_block);
+ msg += sha1_block_size;
+ size -= sha1_block_size;
+ }
+ if (size) {
+ /* save leftovers */
+ memcpy(ctx->message, msg, size);
+ }
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha1_final(sha1_ctx *ctx, unsigned char* result)
+{
+ unsigned index = (unsigned)ctx->length & 63;
+ unsigned* msg32 = (unsigned*)ctx->message;
+
+ /* pad message and run for last block */
+ ctx->message[index++] = 0x80;
+ while ((index & 3) != 0) {
+ ctx->message[index++] = 0;
+ }
+ index >>= 2;
+
+ /* if no room left in the message to store 64-bit message length */
+ if (index > 14) {
+ /* then fill the rest with zeros and process it */
+ while (index < 16) {
+ msg32[index++] = 0;
+ }
+ rhash_sha1_process_block(ctx->hash, msg32);
+ index = 0;
+ }
+ while (index < 14) {
+ msg32[index++] = 0;
+ }
+ msg32[14] = be2me_32( (unsigned)(ctx->length >> 29) );
+ msg32[15] = be2me_32( (unsigned)(ctx->length << 3) );
+ rhash_sha1_process_block(ctx->hash, msg32);
+
+ if (result) be32_copy(result, 0, &ctx->hash, sha1_hash_size);
+}
diff --git a/Utilities/cmlibrhash/librhash/sha1.h b/Utilities/cmlibrhash/librhash/sha1.h
new file mode 100644
index 0000000..74b2f94
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha1.h
@@ -0,0 +1,31 @@
+/* sha1.h */
+#ifndef SHA1_H
+#define SHA1_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha1_block_size 64
+#define sha1_hash_size 20
+
+/* algorithm context */
+typedef struct sha1_ctx
+{
+ unsigned char message[sha1_block_size]; /* 512-bit buffer for leftovers */
+ uint64_t length; /* number of processed bytes */
+ unsigned hash[5]; /* 160-bit algorithm internal hashing state */
+} sha1_ctx;
+
+/* hash functions */
+
+void rhash_sha1_init(sha1_ctx *ctx);
+void rhash_sha1_update(sha1_ctx *ctx, const unsigned char* msg, size_t size);
+void rhash_sha1_final(sha1_ctx *ctx, unsigned char* result);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* SHA1_H */
diff --git a/Utilities/cmlibrhash/librhash/sha256.c b/Utilities/cmlibrhash/librhash/sha256.c
new file mode 100644
index 0000000..af5b0fe
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha256.c
@@ -0,0 +1,241 @@
+/* sha256.c - an implementation of SHA-256/224 hash functions
+ * based on FIPS 180-3 (Federal Information Processing Standart).
+ *
+ * Copyright: 2010-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "sha256.h"
+
+/* SHA-224 and SHA-256 constants for 64 rounds. These words represent
+ * the first 32 bits of the fractional parts of the cube
+ * roots of the first 64 prime numbers. */
+static const unsigned rhash_k256[64] = {
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+};
+
+/* The SHA256/224 functions defined by FIPS 180-3, 4.1.2 */
+/* Optimized version of Ch(x,y,z)=((x & y) | (~x & z)) */
+#define Ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
+/* Optimized version of Maj(x,y,z)=((x & y) ^ (x & z) ^ (y & z)) */
+#define Maj(x,y,z) (((x) & (y)) ^ ((z) & ((x) ^ (y))))
+
+#define Sigma0(x) (ROTR32((x), 2) ^ ROTR32((x), 13) ^ ROTR32((x), 22))
+#define Sigma1(x) (ROTR32((x), 6) ^ ROTR32((x), 11) ^ ROTR32((x), 25))
+#define sigma0(x) (ROTR32((x), 7) ^ ROTR32((x), 18) ^ ((x) >> 3))
+#define sigma1(x) (ROTR32((x),17) ^ ROTR32((x), 19) ^ ((x) >> 10))
+
+/* Recalculate element n-th of circular buffer W using formula
+ * W[n] = sigma1(W[n - 2]) + W[n - 7] + sigma0(W[n - 15]) + W[n - 16]; */
+#define RECALCULATE_W(W,n) (W[n] += \
+ (sigma1(W[(n - 2) & 15]) + W[(n - 7) & 15] + sigma0(W[(n - 15) & 15])))
+
+#define ROUND(a,b,c,d,e,f,g,h,k,data) { \
+ unsigned T1 = h + Sigma1(e) + Ch(e,f,g) + k + (data); \
+ d += T1, h = T1 + Sigma0(a) + Maj(a,b,c); }
+#define ROUND_1_16(a,b,c,d,e,f,g,h,n) \
+ ROUND(a,b,c,d,e,f,g,h, rhash_k256[n], W[n] = be2me_32(block[n]))
+#define ROUND_17_64(a,b,c,d,e,f,g,h,n) \
+ ROUND(a,b,c,d,e,f,g,h, k[n], RECALCULATE_W(W, n))
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha256_init(sha256_ctx *ctx)
+{
+ /* Initial values. These words were obtained by taking the first 32
+ * bits of the fractional parts of the square roots of the first
+ * eight prime numbers. */
+ static const unsigned SHA256_H0[8] = {
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
+ };
+
+ ctx->length = 0;
+ ctx->digest_length = sha256_hash_size;
+
+ /* initialize algorithm state */
+ memcpy(ctx->hash, SHA256_H0, sizeof(ctx->hash));
+}
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha224_init(struct sha256_ctx *ctx)
+{
+ /* Initial values from FIPS 180-3. These words were obtained by taking
+ * bits from 33th to 64th of the fractional parts of the square
+ * roots of ninth through sixteenth prime numbers. */
+ static const unsigned SHA224_H0[8] = {
+ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
+ 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
+ };
+
+ ctx->length = 0;
+ ctx->digest_length = sha224_hash_size;
+
+ memcpy(ctx->hash, SHA224_H0, sizeof(ctx->hash));
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ *
+ * @param hash algorithm state
+ * @param block the message block to process
+ */
+static void rhash_sha256_process_block(unsigned hash[8], unsigned block[16])
+{
+ unsigned A, B, C, D, E, F, G, H;
+ unsigned W[16];
+ const unsigned *k;
+ int i;
+
+ A = hash[0], B = hash[1], C = hash[2], D = hash[3];
+ E = hash[4], F = hash[5], G = hash[6], H = hash[7];
+
+ /* Compute SHA using alternate Method: FIPS 180-3 6.1.3 */
+ ROUND_1_16(A, B, C, D, E, F, G, H, 0);
+ ROUND_1_16(H, A, B, C, D, E, F, G, 1);
+ ROUND_1_16(G, H, A, B, C, D, E, F, 2);
+ ROUND_1_16(F, G, H, A, B, C, D, E, 3);
+ ROUND_1_16(E, F, G, H, A, B, C, D, 4);
+ ROUND_1_16(D, E, F, G, H, A, B, C, 5);
+ ROUND_1_16(C, D, E, F, G, H, A, B, 6);
+ ROUND_1_16(B, C, D, E, F, G, H, A, 7);
+ ROUND_1_16(A, B, C, D, E, F, G, H, 8);
+ ROUND_1_16(H, A, B, C, D, E, F, G, 9);
+ ROUND_1_16(G, H, A, B, C, D, E, F, 10);
+ ROUND_1_16(F, G, H, A, B, C, D, E, 11);
+ ROUND_1_16(E, F, G, H, A, B, C, D, 12);
+ ROUND_1_16(D, E, F, G, H, A, B, C, 13);
+ ROUND_1_16(C, D, E, F, G, H, A, B, 14);
+ ROUND_1_16(B, C, D, E, F, G, H, A, 15);
+
+ for (i = 16, k = &rhash_k256[16]; i < 64; i += 16, k += 16) {
+ ROUND_17_64(A, B, C, D, E, F, G, H, 0);
+ ROUND_17_64(H, A, B, C, D, E, F, G, 1);
+ ROUND_17_64(G, H, A, B, C, D, E, F, 2);
+ ROUND_17_64(F, G, H, A, B, C, D, E, 3);
+ ROUND_17_64(E, F, G, H, A, B, C, D, 4);
+ ROUND_17_64(D, E, F, G, H, A, B, C, 5);
+ ROUND_17_64(C, D, E, F, G, H, A, B, 6);
+ ROUND_17_64(B, C, D, E, F, G, H, A, 7);
+ ROUND_17_64(A, B, C, D, E, F, G, H, 8);
+ ROUND_17_64(H, A, B, C, D, E, F, G, 9);
+ ROUND_17_64(G, H, A, B, C, D, E, F, 10);
+ ROUND_17_64(F, G, H, A, B, C, D, E, 11);
+ ROUND_17_64(E, F, G, H, A, B, C, D, 12);
+ ROUND_17_64(D, E, F, G, H, A, B, C, 13);
+ ROUND_17_64(C, D, E, F, G, H, A, B, 14);
+ ROUND_17_64(B, C, D, E, F, G, H, A, 15);
+ }
+
+ hash[0] += A, hash[1] += B, hash[2] += C, hash[3] += D;
+ hash[4] += E, hash[5] += F, hash[6] += G, hash[7] += H;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha256_update(sha256_ctx *ctx, const unsigned char *msg, size_t size)
+{
+ size_t index = (size_t)ctx->length & 63;
+ ctx->length += size;
+
+ /* fill partial block */
+ if (index) {
+ size_t left = sha256_block_size - index;
+ memcpy((char*)ctx->message + index, msg, (size < left ? size : left));
+ if (size < left) return;
+
+ /* process partial block */
+ rhash_sha256_process_block(ctx->hash, (unsigned*)ctx->message);
+ msg += left;
+ size -= left;
+ }
+ while (size >= sha256_block_size) {
+ unsigned* aligned_message_block;
+ if (IS_ALIGNED_32(msg)) {
+ /* the most common case is processing of an already aligned message
+ without copying it */
+ aligned_message_block = (unsigned*)msg;
+ } else {
+ memcpy(ctx->message, msg, sha256_block_size);
+ aligned_message_block = (unsigned*)ctx->message;
+ }
+
+ rhash_sha256_process_block(ctx->hash, aligned_message_block);
+ msg += sha256_block_size;
+ size -= sha256_block_size;
+ }
+ if (size) {
+ memcpy(ctx->message, msg, size); /* save leftovers */
+ }
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha256_final(sha256_ctx *ctx, unsigned char* result)
+{
+ size_t index = ((unsigned)ctx->length & 63) >> 2;
+ unsigned shift = ((unsigned)ctx->length & 3) * 8;
+
+ /* pad message and run for last block */
+
+ /* append the byte 0x80 to the message */
+ ctx->message[index] &= le2me_32(~(0xFFFFFFFFu << shift));
+ ctx->message[index++] ^= le2me_32(0x80u << shift);
+
+ /* if no room left in the message to store 64-bit message length */
+ if (index > 14) {
+ /* then fill the rest with zeros and process it */
+ while (index < 16) {
+ ctx->message[index++] = 0;
+ }
+ rhash_sha256_process_block(ctx->hash, ctx->message);
+ index = 0;
+ }
+ while (index < 14) {
+ ctx->message[index++] = 0;
+ }
+ ctx->message[14] = be2me_32( (unsigned)(ctx->length >> 29) );
+ ctx->message[15] = be2me_32( (unsigned)(ctx->length << 3) );
+ rhash_sha256_process_block(ctx->hash, ctx->message);
+
+ if (result) be32_copy(result, 0, ctx->hash, ctx->digest_length);
+}
diff --git a/Utilities/cmlibrhash/librhash/sha256.h b/Utilities/cmlibrhash/librhash/sha256.h
new file mode 100644
index 0000000..f87ebaa
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha256.h
@@ -0,0 +1,32 @@
+/* sha.h sha256 and sha224 hash functions */
+#ifndef SHA256_H
+#define SHA256_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha256_block_size 64
+#define sha256_hash_size 32
+#define sha224_hash_size 28
+
+/* algorithm context */
+typedef struct sha256_ctx
+{
+ unsigned message[16]; /* 512-bit buffer for leftovers */
+ uint64_t length; /* number of processed bytes */
+ unsigned hash[8]; /* 256-bit algorithm internal hashing state */
+ unsigned digest_length; /* length of the algorithm digest in bytes */
+} sha256_ctx;
+
+void rhash_sha224_init(sha256_ctx *ctx);
+void rhash_sha256_init(sha256_ctx *ctx);
+void rhash_sha256_update(sha256_ctx *ctx, const unsigned char* data, size_t length);
+void rhash_sha256_final(sha256_ctx *ctx, unsigned char result[32]);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* SHA256_H */
diff --git a/Utilities/cmlibrhash/librhash/sha3.c b/Utilities/cmlibrhash/librhash/sha3.c
new file mode 100644
index 0000000..e4a845f
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha3.c
@@ -0,0 +1,356 @@
+/* sha3.c - an implementation of Secure Hash Algorithm 3 (Keccak).
+ * based on the
+ * The Keccak SHA-3 submission. Submission to NIST (Round 3), 2011
+ * by Guido Bertoni, Joan Daemen, Michaƫl Peeters and Gilles Van Assche
+ *
+ * Copyright: 2013 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+#include <assert.h>
+#include <string.h>
+#include "byte_order.h"
+#include "sha3.h"
+
+/* constants */
+#define NumberOfRounds 24
+
+/* SHA3 (Keccak) constants for 24 rounds */
+static uint64_t keccak_round_constants[NumberOfRounds] = {
+ I64(0x0000000000000001), I64(0x0000000000008082), I64(0x800000000000808A), I64(0x8000000080008000),
+ I64(0x000000000000808B), I64(0x0000000080000001), I64(0x8000000080008081), I64(0x8000000000008009),
+ I64(0x000000000000008A), I64(0x0000000000000088), I64(0x0000000080008009), I64(0x000000008000000A),
+ I64(0x000000008000808B), I64(0x800000000000008B), I64(0x8000000000008089), I64(0x8000000000008003),
+ I64(0x8000000000008002), I64(0x8000000000000080), I64(0x000000000000800A), I64(0x800000008000000A),
+ I64(0x8000000080008081), I64(0x8000000000008080), I64(0x0000000080000001), I64(0x8000000080008008)
+};
+
+/* Initializing a sha3 context for given number of output bits */
+static void rhash_keccak_init(sha3_ctx *ctx, unsigned bits)
+{
+ /* NB: The Keccak capacity parameter = bits * 2 */
+ unsigned rate = 1600 - bits * 2;
+
+ memset(ctx, 0, sizeof(sha3_ctx));
+ ctx->block_size = rate / 8;
+ assert(rate <= 1600 && (rate % 64) == 0);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_224_init(sha3_ctx *ctx)
+{
+ rhash_keccak_init(ctx, 224);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_256_init(sha3_ctx *ctx)
+{
+ rhash_keccak_init(ctx, 256);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_384_init(sha3_ctx *ctx)
+{
+ rhash_keccak_init(ctx, 384);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_512_init(sha3_ctx *ctx)
+{
+ rhash_keccak_init(ctx, 512);
+}
+
+/* Keccak theta() transformation */
+static void keccak_theta(uint64_t *A)
+{
+ unsigned int x;
+ uint64_t C[5], D[5];
+
+ for (x = 0; x < 5; x++) {
+ C[x] = A[x] ^ A[x + 5] ^ A[x + 10] ^ A[x + 15] ^ A[x + 20];
+ }
+ D[0] = ROTL64(C[1], 1) ^ C[4];
+ D[1] = ROTL64(C[2], 1) ^ C[0];
+ D[2] = ROTL64(C[3], 1) ^ C[1];
+ D[3] = ROTL64(C[4], 1) ^ C[2];
+ D[4] = ROTL64(C[0], 1) ^ C[3];
+
+ for (x = 0; x < 5; x++) {
+ A[x] ^= D[x];
+ A[x + 5] ^= D[x];
+ A[x + 10] ^= D[x];
+ A[x + 15] ^= D[x];
+ A[x + 20] ^= D[x];
+ }
+}
+
+/* Keccak pi() transformation */
+static void keccak_pi(uint64_t *A)
+{
+ uint64_t A1;
+ A1 = A[1];
+ A[ 1] = A[ 6];
+ A[ 6] = A[ 9];
+ A[ 9] = A[22];
+ A[22] = A[14];
+ A[14] = A[20];
+ A[20] = A[ 2];
+ A[ 2] = A[12];
+ A[12] = A[13];
+ A[13] = A[19];
+ A[19] = A[23];
+ A[23] = A[15];
+ A[15] = A[ 4];
+ A[ 4] = A[24];
+ A[24] = A[21];
+ A[21] = A[ 8];
+ A[ 8] = A[16];
+ A[16] = A[ 5];
+ A[ 5] = A[ 3];
+ A[ 3] = A[18];
+ A[18] = A[17];
+ A[17] = A[11];
+ A[11] = A[ 7];
+ A[ 7] = A[10];
+ A[10] = A1;
+ /* note: A[ 0] is left as is */
+}
+
+/* Keccak chi() transformation */
+static void keccak_chi(uint64_t *A)
+{
+ int i;
+ for (i = 0; i < 25; i += 5) {
+ uint64_t A0 = A[0 + i], A1 = A[1 + i];
+ A[0 + i] ^= ~A1 & A[2 + i];
+ A[1 + i] ^= ~A[2 + i] & A[3 + i];
+ A[2 + i] ^= ~A[3 + i] & A[4 + i];
+ A[3 + i] ^= ~A[4 + i] & A0;
+ A[4 + i] ^= ~A0 & A1;
+ }
+}
+
+static void rhash_sha3_permutation(uint64_t *state)
+{
+ int round;
+ for (round = 0; round < NumberOfRounds; round++)
+ {
+ keccak_theta(state);
+
+ /* apply Keccak rho() transformation */
+ state[ 1] = ROTL64(state[ 1], 1);
+ state[ 2] = ROTL64(state[ 2], 62);
+ state[ 3] = ROTL64(state[ 3], 28);
+ state[ 4] = ROTL64(state[ 4], 27);
+ state[ 5] = ROTL64(state[ 5], 36);
+ state[ 6] = ROTL64(state[ 6], 44);
+ state[ 7] = ROTL64(state[ 7], 6);
+ state[ 8] = ROTL64(state[ 8], 55);
+ state[ 9] = ROTL64(state[ 9], 20);
+ state[10] = ROTL64(state[10], 3);
+ state[11] = ROTL64(state[11], 10);
+ state[12] = ROTL64(state[12], 43);
+ state[13] = ROTL64(state[13], 25);
+ state[14] = ROTL64(state[14], 39);
+ state[15] = ROTL64(state[15], 41);
+ state[16] = ROTL64(state[16], 45);
+ state[17] = ROTL64(state[17], 15);
+ state[18] = ROTL64(state[18], 21);
+ state[19] = ROTL64(state[19], 8);
+ state[20] = ROTL64(state[20], 18);
+ state[21] = ROTL64(state[21], 2);
+ state[22] = ROTL64(state[22], 61);
+ state[23] = ROTL64(state[23], 56);
+ state[24] = ROTL64(state[24], 14);
+
+ keccak_pi(state);
+ keccak_chi(state);
+
+ /* apply iota(state, round) */
+ *state ^= keccak_round_constants[round];
+ }
+}
+
+/**
+ * The core transformation. Process the specified block of data.
+ *
+ * @param hash the algorithm state
+ * @param block the message block to process
+ * @param block_size the size of the processed block in bytes
+ */
+static void rhash_sha3_process_block(uint64_t hash[25], const uint64_t *block, size_t block_size)
+{
+ /* expanded loop */
+ hash[ 0] ^= le2me_64(block[ 0]);
+ hash[ 1] ^= le2me_64(block[ 1]);
+ hash[ 2] ^= le2me_64(block[ 2]);
+ hash[ 3] ^= le2me_64(block[ 3]);
+ hash[ 4] ^= le2me_64(block[ 4]);
+ hash[ 5] ^= le2me_64(block[ 5]);
+ hash[ 6] ^= le2me_64(block[ 6]);
+ hash[ 7] ^= le2me_64(block[ 7]);
+ hash[ 8] ^= le2me_64(block[ 8]);
+ /* if not sha3-512 */
+ if (block_size > 72) {
+ hash[ 9] ^= le2me_64(block[ 9]);
+ hash[10] ^= le2me_64(block[10]);
+ hash[11] ^= le2me_64(block[11]);
+ hash[12] ^= le2me_64(block[12]);
+ /* if not sha3-384 */
+ if (block_size > 104) {
+ hash[13] ^= le2me_64(block[13]);
+ hash[14] ^= le2me_64(block[14]);
+ hash[15] ^= le2me_64(block[15]);
+ hash[16] ^= le2me_64(block[16]);
+ /* if not sha3-256 */
+ if (block_size > 136) {
+ hash[17] ^= le2me_64(block[17]);
+#ifdef FULL_SHA3_FAMILY_SUPPORT
+ /* if not sha3-224 */
+ if (block_size > 144) {
+ hash[18] ^= le2me_64(block[18]);
+ hash[19] ^= le2me_64(block[19]);
+ hash[20] ^= le2me_64(block[20]);
+ hash[21] ^= le2me_64(block[21]);
+ hash[22] ^= le2me_64(block[22]);
+ hash[23] ^= le2me_64(block[23]);
+ hash[24] ^= le2me_64(block[24]);
+ }
+#endif
+ }
+ }
+ }
+ /* make a permutation of the hash */
+ rhash_sha3_permutation(hash);
+}
+
+#define SHA3_FINALIZED 0x80000000
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha3_update(sha3_ctx *ctx, const unsigned char *msg, size_t size)
+{
+ size_t index = (size_t)ctx->rest;
+ size_t block_size = (size_t)ctx->block_size;
+
+ if (ctx->rest & SHA3_FINALIZED) return; /* too late for additional input */
+ ctx->rest = (unsigned)((ctx->rest + size) % block_size);
+
+ /* fill partial block */
+ if (index) {
+ size_t left = block_size - index;
+ memcpy((char*)ctx->message + index, msg, (size < left ? size : left));
+ if (size < left) return;
+
+ /* process partial block */
+ rhash_sha3_process_block(ctx->hash, ctx->message, block_size);
+ msg += left;
+ size -= left;
+ }
+ while (size >= block_size) {
+ uint64_t* aligned_message_block;
+ if (IS_ALIGNED_64(msg)) {
+ /* the most common case is processing of an already aligned message
+ without copying it */
+ aligned_message_block = (uint64_t*)msg;
+ } else {
+ memcpy(ctx->message, msg, block_size);
+ aligned_message_block = ctx->message;
+ }
+
+ rhash_sha3_process_block(ctx->hash, aligned_message_block, block_size);
+ msg += block_size;
+ size -= block_size;
+ }
+ if (size) {
+ memcpy(ctx->message, msg, size); /* save leftovers */
+ }
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha3_final(sha3_ctx *ctx, unsigned char* result)
+{
+ size_t digest_length = 100 - ctx->block_size / 2;
+ const size_t block_size = ctx->block_size;
+
+ if (!(ctx->rest & SHA3_FINALIZED))
+ {
+ /* clear the rest of the data queue */
+ memset((char*)ctx->message + ctx->rest, 0, block_size - ctx->rest);
+ ((char*)ctx->message)[ctx->rest] |= 0x06;
+ ((char*)ctx->message)[block_size - 1] |= 0x80;
+
+ /* process final block */
+ rhash_sha3_process_block(ctx->hash, ctx->message, block_size);
+ ctx->rest = SHA3_FINALIZED; /* mark context as finalized */
+ }
+
+ assert(block_size > digest_length);
+ if (result) me64_to_le_str(result, ctx->hash, digest_length);
+}
+
+#ifdef USE_KECCAK
+/**
+* Store calculated hash into the given array.
+*
+* @param ctx the algorithm context containing current hashing state
+* @param result calculated hash in binary form
+*/
+void rhash_keccak_final(sha3_ctx *ctx, unsigned char* result)
+{
+ size_t digest_length = 100 - ctx->block_size / 2;
+ const size_t block_size = ctx->block_size;
+
+ if (!(ctx->rest & SHA3_FINALIZED))
+ {
+ /* clear the rest of the data queue */
+ memset((char*)ctx->message + ctx->rest, 0, block_size - ctx->rest);
+ ((char*)ctx->message)[ctx->rest] |= 0x01;
+ ((char*)ctx->message)[block_size - 1] |= 0x80;
+
+ /* process final block */
+ rhash_sha3_process_block(ctx->hash, ctx->message, block_size);
+ ctx->rest = SHA3_FINALIZED; /* mark context as finalized */
+ }
+
+ assert(block_size > digest_length);
+ if (result) me64_to_le_str(result, ctx->hash, digest_length);
+}
+#endif /* USE_KECCAK */
diff --git a/Utilities/cmlibrhash/librhash/sha3.h b/Utilities/cmlibrhash/librhash/sha3.h
new file mode 100644
index 0000000..2831997
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha3.h
@@ -0,0 +1,54 @@
+/* sha3.h */
+#ifndef RHASH_SHA3_H
+#define RHASH_SHA3_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha3_224_hash_size 28
+#define sha3_256_hash_size 32
+#define sha3_384_hash_size 48
+#define sha3_512_hash_size 64
+#define sha3_max_permutation_size 25
+#define sha3_max_rate_in_qwords 24
+
+/**
+ * SHA3 Algorithm context.
+ */
+typedef struct sha3_ctx
+{
+ /* 1600 bits algorithm hashing state */
+ uint64_t hash[sha3_max_permutation_size];
+ /* 1536-bit buffer for leftovers */
+ uint64_t message[sha3_max_rate_in_qwords];
+ /* count of bytes in the message[] buffer */
+ unsigned rest;
+ /* size of a message block processed at once */
+ unsigned block_size;
+} sha3_ctx;
+
+/* methods for calculating the hash function */
+
+void rhash_sha3_224_init(sha3_ctx *ctx);
+void rhash_sha3_256_init(sha3_ctx *ctx);
+void rhash_sha3_384_init(sha3_ctx *ctx);
+void rhash_sha3_512_init(sha3_ctx *ctx);
+void rhash_sha3_update(sha3_ctx *ctx, const unsigned char* msg, size_t size);
+void rhash_sha3_final(sha3_ctx *ctx, unsigned char* result);
+
+#ifdef USE_KECCAK
+#define rhash_keccak_224_init rhash_sha3_224_init
+#define rhash_keccak_256_init rhash_sha3_256_init
+#define rhash_keccak_384_init rhash_sha3_384_init
+#define rhash_keccak_512_init rhash_sha3_512_init
+#define rhash_keccak_update rhash_sha3_update
+void rhash_keccak_final(sha3_ctx *ctx, unsigned char* result);
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* RHASH_SHA3_H */
diff --git a/Utilities/cmlibrhash/librhash/sha512.c b/Utilities/cmlibrhash/librhash/sha512.c
new file mode 100644
index 0000000..a3e681d
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha512.c
@@ -0,0 +1,255 @@
+/* sha512.c - an implementation of SHA-384/512 hash functions
+ * based on FIPS 180-3 (Federal Information Processing Standart).
+ *
+ * Copyright: 2010-2012 Aleksey Kravchenko <rhash.admin@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "sha512.h"
+
+/* SHA-384 and SHA-512 constants for 80 rounds. These qwords represent
+ * the first 64 bits of the fractional parts of the cube
+ * roots of the first 80 prime numbers. */
+static const uint64_t rhash_k512[80] = {
+ I64(0x428a2f98d728ae22), I64(0x7137449123ef65cd), I64(0xb5c0fbcfec4d3b2f),
+ I64(0xe9b5dba58189dbbc), I64(0x3956c25bf348b538), I64(0x59f111f1b605d019),
+ I64(0x923f82a4af194f9b), I64(0xab1c5ed5da6d8118), I64(0xd807aa98a3030242),
+ I64(0x12835b0145706fbe), I64(0x243185be4ee4b28c), I64(0x550c7dc3d5ffb4e2),
+ I64(0x72be5d74f27b896f), I64(0x80deb1fe3b1696b1), I64(0x9bdc06a725c71235),
+ I64(0xc19bf174cf692694), I64(0xe49b69c19ef14ad2), I64(0xefbe4786384f25e3),
+ I64(0x0fc19dc68b8cd5b5), I64(0x240ca1cc77ac9c65), I64(0x2de92c6f592b0275),
+ I64(0x4a7484aa6ea6e483), I64(0x5cb0a9dcbd41fbd4), I64(0x76f988da831153b5),
+ I64(0x983e5152ee66dfab), I64(0xa831c66d2db43210), I64(0xb00327c898fb213f),
+ I64(0xbf597fc7beef0ee4), I64(0xc6e00bf33da88fc2), I64(0xd5a79147930aa725),
+ I64(0x06ca6351e003826f), I64(0x142929670a0e6e70), I64(0x27b70a8546d22ffc),
+ I64(0x2e1b21385c26c926), I64(0x4d2c6dfc5ac42aed), I64(0x53380d139d95b3df),
+ I64(0x650a73548baf63de), I64(0x766a0abb3c77b2a8), I64(0x81c2c92e47edaee6),
+ I64(0x92722c851482353b), I64(0xa2bfe8a14cf10364), I64(0xa81a664bbc423001),
+ I64(0xc24b8b70d0f89791), I64(0xc76c51a30654be30), I64(0xd192e819d6ef5218),
+ I64(0xd69906245565a910), I64(0xf40e35855771202a), I64(0x106aa07032bbd1b8),
+ I64(0x19a4c116b8d2d0c8), I64(0x1e376c085141ab53), I64(0x2748774cdf8eeb99),
+ I64(0x34b0bcb5e19b48a8), I64(0x391c0cb3c5c95a63), I64(0x4ed8aa4ae3418acb),
+ I64(0x5b9cca4f7763e373), I64(0x682e6ff3d6b2b8a3), I64(0x748f82ee5defb2fc),
+ I64(0x78a5636f43172f60), I64(0x84c87814a1f0ab72), I64(0x8cc702081a6439ec),
+ I64(0x90befffa23631e28), I64(0xa4506cebde82bde9), I64(0xbef9a3f7b2c67915),
+ I64(0xc67178f2e372532b), I64(0xca273eceea26619c), I64(0xd186b8c721c0c207),
+ I64(0xeada7dd6cde0eb1e), I64(0xf57d4f7fee6ed178), I64(0x06f067aa72176fba),
+ I64(0x0a637dc5a2c898a6), I64(0x113f9804bef90dae), I64(0x1b710b35131c471b),
+ I64(0x28db77f523047d84), I64(0x32caab7b40c72493), I64(0x3c9ebe0a15c9bebc),
+ I64(0x431d67c49c100d4c), I64(0x4cc5d4becb3e42b6), I64(0x597f299cfc657e2a),
+ I64(0x5fcb6fab3ad6faec), I64(0x6c44198c4a475817)
+};
+
+/* The SHA512/384 functions defined by FIPS 180-3, 4.1.3 */
+/* Optimized version of Ch(x,y,z)=((x & y) | (~x & z)) */
+#define Ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
+/* Optimized version of Maj(x,y,z)=((x & y) ^ (x & z) ^ (y & z)) */
+#define Maj(x,y,z) (((x) & (y)) ^ ((z) & ((x) ^ (y))))
+
+#define Sigma0(x) (ROTR64((x), 28) ^ ROTR64((x), 34) ^ ROTR64((x), 39))
+#define Sigma1(x) (ROTR64((x), 14) ^ ROTR64((x), 18) ^ ROTR64((x), 41))
+#define sigma0(x) (ROTR64((x), 1) ^ ROTR64((x), 8) ^ ((x) >> 7))
+#define sigma1(x) (ROTR64((x), 19) ^ ROTR64((x), 61) ^ ((x) >> 6))
+
+/* Recalculate element n-th of circular buffer W using formula
+ * W[n] = sigma1(W[n - 2]) + W[n - 7] + sigma0(W[n - 15]) + W[n - 16]; */
+#define RECALCULATE_W(W,n) (W[n] += \
+ (sigma1(W[(n - 2) & 15]) + W[(n - 7) & 15] + sigma0(W[(n - 15) & 15])))
+
+#define ROUND(a,b,c,d,e,f,g,h,k,data) { \
+ uint64_t T1 = h + Sigma1(e) + Ch(e,f,g) + k + (data); \
+ d += T1, h = T1 + Sigma0(a) + Maj(a,b,c); }
+#define ROUND_1_16(a,b,c,d,e,f,g,h,n) \
+ ROUND(a,b,c,d,e,f,g,h, rhash_k512[n], W[n] = be2me_64(block[n]))
+#define ROUND_17_80(a,b,c,d,e,f,g,h,n) \
+ ROUND(a,b,c,d,e,f,g,h, k[n], RECALCULATE_W(W, n))
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha512_init(sha512_ctx *ctx)
+{
+ /* Initial values. These words were obtained by taking the first 32
+ * bits of the fractional parts of the square roots of the first
+ * eight prime numbers. */
+ static const uint64_t SHA512_H0[8] = {
+ I64(0x6a09e667f3bcc908), I64(0xbb67ae8584caa73b), I64(0x3c6ef372fe94f82b),
+ I64(0xa54ff53a5f1d36f1), I64(0x510e527fade682d1), I64(0x9b05688c2b3e6c1f),
+ I64(0x1f83d9abfb41bd6b), I64(0x5be0cd19137e2179)
+ };
+
+ ctx->length = 0;
+ ctx->digest_length = sha512_hash_size;
+
+ /* initialize algorithm state */
+ memcpy(ctx->hash, SHA512_H0, sizeof(ctx->hash));
+}
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha384_init(struct sha512_ctx *ctx)
+{
+ /* Initial values from FIPS 180-3. These words were obtained by taking
+ * the first sixty-four bits of the fractional parts of the square
+ * roots of ninth through sixteenth prime numbers. */
+ static const uint64_t SHA384_H0[8] = {
+ I64(0xcbbb9d5dc1059ed8), I64(0x629a292a367cd507), I64(0x9159015a3070dd17),
+ I64(0x152fecd8f70e5939), I64(0x67332667ffc00b31), I64(0x8eb44a8768581511),
+ I64(0xdb0c2e0d64f98fa7), I64(0x47b5481dbefa4fa4)
+ };
+
+ ctx->length = 0;
+ ctx->digest_length = sha384_hash_size;
+
+ memcpy(ctx->hash, SHA384_H0, sizeof(ctx->hash));
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ *
+ * @param hash algorithm state
+ * @param block the message block to process
+ */
+static void rhash_sha512_process_block(uint64_t hash[8], uint64_t block[16])
+{
+ uint64_t A, B, C, D, E, F, G, H;
+ uint64_t W[16];
+ const uint64_t *k;
+ int i;
+
+ A = hash[0], B = hash[1], C = hash[2], D = hash[3];
+ E = hash[4], F = hash[5], G = hash[6], H = hash[7];
+
+ /* Compute SHA using alternate Method: FIPS 180-3 6.1.3 */
+ ROUND_1_16(A, B, C, D, E, F, G, H, 0);
+ ROUND_1_16(H, A, B, C, D, E, F, G, 1);
+ ROUND_1_16(G, H, A, B, C, D, E, F, 2);
+ ROUND_1_16(F, G, H, A, B, C, D, E, 3);
+ ROUND_1_16(E, F, G, H, A, B, C, D, 4);
+ ROUND_1_16(D, E, F, G, H, A, B, C, 5);
+ ROUND_1_16(C, D, E, F, G, H, A, B, 6);
+ ROUND_1_16(B, C, D, E, F, G, H, A, 7);
+ ROUND_1_16(A, B, C, D, E, F, G, H, 8);
+ ROUND_1_16(H, A, B, C, D, E, F, G, 9);
+ ROUND_1_16(G, H, A, B, C, D, E, F, 10);
+ ROUND_1_16(F, G, H, A, B, C, D, E, 11);
+ ROUND_1_16(E, F, G, H, A, B, C, D, 12);
+ ROUND_1_16(D, E, F, G, H, A, B, C, 13);
+ ROUND_1_16(C, D, E, F, G, H, A, B, 14);
+ ROUND_1_16(B, C, D, E, F, G, H, A, 15);
+
+ for (i = 16, k = &rhash_k512[16]; i < 80; i += 16, k += 16) {
+ ROUND_17_80(A, B, C, D, E, F, G, H, 0);
+ ROUND_17_80(H, A, B, C, D, E, F, G, 1);
+ ROUND_17_80(G, H, A, B, C, D, E, F, 2);
+ ROUND_17_80(F, G, H, A, B, C, D, E, 3);
+ ROUND_17_80(E, F, G, H, A, B, C, D, 4);
+ ROUND_17_80(D, E, F, G, H, A, B, C, 5);
+ ROUND_17_80(C, D, E, F, G, H, A, B, 6);
+ ROUND_17_80(B, C, D, E, F, G, H, A, 7);
+ ROUND_17_80(A, B, C, D, E, F, G, H, 8);
+ ROUND_17_80(H, A, B, C, D, E, F, G, 9);
+ ROUND_17_80(G, H, A, B, C, D, E, F, 10);
+ ROUND_17_80(F, G, H, A, B, C, D, E, 11);
+ ROUND_17_80(E, F, G, H, A, B, C, D, 12);
+ ROUND_17_80(D, E, F, G, H, A, B, C, 13);
+ ROUND_17_80(C, D, E, F, G, H, A, B, 14);
+ ROUND_17_80(B, C, D, E, F, G, H, A, 15);
+ }
+
+ hash[0] += A, hash[1] += B, hash[2] += C, hash[3] += D;
+ hash[4] += E, hash[5] += F, hash[6] += G, hash[7] += H;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha512_update(sha512_ctx *ctx, const unsigned char *msg, size_t size)
+{
+ size_t index = (size_t)ctx->length & 127;
+ ctx->length += size;
+
+ /* fill partial block */
+ if (index) {
+ size_t left = sha512_block_size - index;
+ memcpy((char*)ctx->message + index, msg, (size < left ? size : left));
+ if (size < left) return;
+
+ /* process partial block */
+ rhash_sha512_process_block(ctx->hash, ctx->message);
+ msg += left;
+ size -= left;
+ }
+ while (size >= sha512_block_size) {
+ uint64_t* aligned_message_block;
+ if (IS_ALIGNED_64(msg)) {
+ /* the most common case is processing of an already aligned message
+ without copying it */
+ aligned_message_block = (uint64_t*)msg;
+ } else {
+ memcpy(ctx->message, msg, sha512_block_size);
+ aligned_message_block = ctx->message;
+ }
+
+ rhash_sha512_process_block(ctx->hash, aligned_message_block);
+ msg += sha512_block_size;
+ size -= sha512_block_size;
+ }
+ if (size) {
+ memcpy(ctx->message, msg, size); /* save leftovers */
+ }
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha512_final(sha512_ctx *ctx, unsigned char* result)
+{
+ size_t index = ((unsigned)ctx->length & 127) >> 3;
+ unsigned shift = ((unsigned)ctx->length & 7) * 8;
+
+ /* pad message and process the last block */
+
+ /* append the byte 0x80 to the message */
+ ctx->message[index] &= le2me_64( ~(I64(0xFFFFFFFFFFFFFFFF) << shift) );
+ ctx->message[index++] ^= le2me_64( I64(0x80) << shift );
+
+ /* if no room left in the message to store 128-bit message length */
+ if (index >= 15) {
+ if (index == 15) ctx->message[index] = 0;
+ rhash_sha512_process_block(ctx->hash, ctx->message);
+ index = 0;
+ }
+ while (index < 15) {
+ ctx->message[index++] = 0;
+ }
+ ctx->message[15] = be2me_64(ctx->length << 3);
+ rhash_sha512_process_block(ctx->hash, ctx->message);
+
+ if (result) be64_copy(result, 0, ctx->hash, ctx->digest_length);
+}
diff --git a/Utilities/cmlibrhash/librhash/sha512.h b/Utilities/cmlibrhash/librhash/sha512.h
new file mode 100644
index 0000000..7c689be
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha512.h
@@ -0,0 +1,32 @@
+/* sha.h sha512 and sha384 hash functions */
+#ifndef SHA512_H
+#define SHA512_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha512_block_size 128
+#define sha512_hash_size 64
+#define sha384_hash_size 48
+
+/* algorithm context */
+typedef struct sha512_ctx
+{
+ uint64_t message[16]; /* 1024-bit buffer for leftovers */
+ uint64_t length; /* number of processed bytes */
+ uint64_t hash[8]; /* 512-bit algorithm internal hashing state */
+ unsigned digest_length; /* length of the algorithm digest in bytes */
+} sha512_ctx;
+
+void rhash_sha384_init(sha512_ctx *ctx);
+void rhash_sha512_init(sha512_ctx *ctx);
+void rhash_sha512_update(sha512_ctx *ctx, const unsigned char* data, size_t length);
+void rhash_sha512_final(sha512_ctx *ctx, unsigned char* result);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* SHA512_H */
diff --git a/Utilities/cmlibrhash/librhash/ustd.h b/Utilities/cmlibrhash/librhash/ustd.h
new file mode 100644
index 0000000..019b931
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/ustd.h
@@ -0,0 +1,39 @@
+/* ustd.h common macros and includes */
+#ifndef LIBRHASH_USTD_H
+#define LIBRHASH_USTD_H
+
+/* Include KWSys Large File Support configuration. */
+#include <cmsys/Configure.h>
+
+#if defined(_MSC_VER)
+# pragma warning(push,1)
+#endif
+
+#include <cm_kwiml.h>
+
+#ifndef KWIML_INT_HAVE_INT64_T
+# define int64_t KWIML_INT_int64_t
+#endif
+#ifndef KWIML_INT_HAVE_INT32_T
+# define int32_t KWIML_INT_int32_t
+#endif
+#ifndef KWIML_INT_HAVE_INT16_T
+# define int16_t KWIML_INT_int16_t
+#endif
+#ifndef KWIML_INT_HAVE_INT8_T
+# define int8_t KWIML_INT_int8_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT64_T
+# define uint64_t KWIML_INT_uint64_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT32_T
+# define uint32_t KWIML_INT_uint32_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT16_T
+# define uint16_t KWIML_INT_uint16_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT8_T
+# define uint8_t KWIML_INT_uint8_t
+#endif
+
+#endif /* LIBRHASH_USTD_H */
diff --git a/Utilities/cmlibrhash/librhash/util.h b/Utilities/cmlibrhash/librhash/util.h
new file mode 100644
index 0000000..9f37157
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/util.h
@@ -0,0 +1,31 @@
+/* util.h */
+#ifndef UTIL_H
+#define UTIL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if (defined(__GNUC__) && __GNUC__ >= 4 && (__GNUC__ > 4 || __GNUC_MINOR__ >= 1) \
+ && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) \
+ || (defined(__INTEL_COMPILER) && !defined(_WIN32))
+/* atomic operations are defined by ICC and GCC >= 4.1, but by the later one supposedly not for ARM */
+/* note: ICC on ia64 platform possibly require ia64intrin.h, need testing */
+# define atomic_compare_and_swap(ptr, oldval, newval) __sync_val_compare_and_swap(ptr, oldval, newval)
+#elif defined(_MSC_VER)
+# include <windows.h>
+# define atomic_compare_and_swap(ptr, oldval, newval) InterlockedCompareExchange(ptr, newval, oldval)
+#elif defined(__sun)
+# include <atomic.h>
+# define atomic_compare_and_swap(ptr, oldval, newval) atomic_cas_32(ptr, oldval, newval)
+#else
+/* pray that it will work */
+# define atomic_compare_and_swap(ptr, oldval, newval) { if(*(ptr) == (oldval)) *(ptr) = (newval); }
+# define NO_ATOMIC_BUILTINS
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* UTIL_H */
diff --git a/bootstrap b/bootstrap
index 4ce0dee..8063edb 100755
--- a/bootstrap
+++ b/bootstrap
@@ -277,14 +277,8 @@ CMAKE_CXX_SOURCES="\
cmDepends \
cmDependsC \
cmDocumentationFormatter \
- cmElseCommand \
cmEnableLanguageCommand \
cmEnableTestingCommand \
- cmEndForEachCommand \
- cmEndFunctionCommand \
- cmEndIfCommand \
- cmEndMacroCommand \
- cmEndWhileCommand \
cmExecProgramCommand \
cmExecuteProcessCommand \
cmExpandedCommandArgument \
@@ -372,6 +366,7 @@ CMAKE_CXX_SOURCES="\
cmParseArgumentsCommand \
cmPathLabel \
cmPolicies \
+ cmProcessOutput \
cmProjectCommand \
cmProperty \
cmPropertyDefinition \
@@ -405,6 +400,7 @@ CMAKE_CXX_SOURCES="\
cmTimestamp \
cmTryCompileCommand \
cmTryRunCommand \
+ cmUnexpectedCommand \
cmUnsetCommand \
cmVersion \
cmWhileCommand \
@@ -493,6 +489,8 @@ Configuration:
--no-system-liblzma use cmake-provided liblzma library (default)
--system-libarchive use system-installed libarchive library
--no-system-libarchive use cmake-provided libarchive library (default)
+ --system-librhash use system-installed librhash library
+ --no-system-librhash use cmake-provided librhash library (default)
--qt-gui build the Qt-based GUI (requires Qt >= 4.2)
--no-qt-gui do not build the Qt-based GUI (default)
@@ -726,10 +724,10 @@ while test $# != 0; do
--init=*) cmake_init_file=`cmake_arg "$1"` ;;
--system-libs) cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARIES=1" ;;
--no-system-libs) cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARIES=0" ;;
- --system-bzip2|--system-curl|--system-expat|--system-jsoncpp|--system-libarchive|--system-zlib|--system-liblzma)
+ --system-bzip2|--system-curl|--system-expat|--system-jsoncpp|--system-libarchive|--system-librhash|--system-zlib|--system-liblzma)
lib=`cmake_arg "$1" "--system-"`
cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARY_`cmake_toupper $lib`=1" ;;
- --no-system-bzip2|--no-system-curl|--no-system-expat|--no-system-jsoncpp|--no-system-libarchive|--no-system-zlib|--no-system-liblzma)
+ --no-system-bzip2|--no-system-curl|--no-system-expat|--no-system-jsoncpp|--no-system-libarchive|--no-system-librhash|--no-system-zlib|--no-system-liblzma)
lib=`cmake_arg "$1" "--no-system-"`
cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARY_`cmake_toupper $lib`=0" ;;
--qt-gui) cmake_bootstrap_qt_gui="1" ;;
@@ -1421,6 +1419,7 @@ fi
cmake_c_flags_String="-DKWSYS_STRING_C"
if ${cmake_system_mingw}; then
cmake_c_flags_EncodingC="-DKWSYS_ENCODING_DEFAULT_CODEPAGE=CP_ACP"
+ cmake_cxx_flags_cmProcessOutput="${cmake_c_flags_EncodingC}"
fi
cmake_cxx_flags_SystemTools="
-DKWSYS_CXX_HAS_SETENV=${KWSYS_CXX_HAS_SETENV}
@@ -1437,8 +1436,9 @@ echo "cmake: ${objs}" > "${cmake_bootstrap_dir}/Makefile"
echo " ${cmake_cxx_compiler} ${cmake_ld_flags} ${cmake_cxx_flags} ${objs} -o cmake" >> "${cmake_bootstrap_dir}/Makefile"
for a in ${CMAKE_CXX_SOURCES}; do
src=`cmake_escape "${cmake_source_dir}/Source/${a}.cxx"`
+ src_flags=`eval echo \\${cmake_cxx_flags_\${a}}`
echo "${a}.o : ${src} ${dep}" >> "${cmake_bootstrap_dir}/Makefile"
- echo " ${cmake_cxx_compiler} ${cmake_cxx_flags} -c ${src} -o ${a}.o" >> "${cmake_bootstrap_dir}/Makefile"
+ echo " ${cmake_cxx_compiler} ${cmake_cxx_flags} ${src_flags} -c ${src} -o ${a}.o" >> "${cmake_bootstrap_dir}/Makefile"
done
echo "cmBootstrapCommands1.o : $cmBootstrapCommands1Deps" >> "${cmake_bootstrap_dir}/Makefile"
echo "cmBootstrapCommands2.o : $cmBootstrapCommands2Deps" >> "${cmake_bootstrap_dir}/Makefile"