summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitlab/os-windows.yml8
-rw-r--r--Help/command/cmake_host_system_information.rst268
-rw-r--r--Help/command/cmake_path.rst4
-rw-r--r--Help/command/ctest_submit.rst3
-rw-r--r--Help/command/file.rst5
-rw-r--r--Help/command/find_package.rst38
-rw-r--r--Help/command/get_property.rst2
-rw-r--r--Help/command/if.rst2
-rw-r--r--Help/command/install.rst4
-rw-r--r--Help/command/set_property.rst4
-rw-r--r--Help/envvar/CMAKE_INSTALL_MODE.rst37
-rw-r--r--Help/generator/Visual Studio 17 2022.rst4
-rw-r--r--Help/manual/cmake-env-variables.7.rst1
-rw-r--r--Help/manual/cmake-packages.7.rst2
-rw-r--r--Help/manual/cmake-policies.7.rst8
-rw-r--r--Help/policy/CMP0127.rst32
-rw-r--r--Help/prop_sf/VS_SETTINGS.rst7
-rw-r--r--Help/prop_tgt/AUTOMOC.rst15
-rw-r--r--Help/prop_tgt/AUTORCC.rst4
-rw-r--r--Help/prop_tgt/AUTOUIC.rst4
-rw-r--r--Help/release/3.21.rst5
-rw-r--r--Help/release/dev/GoogleTest-gtest-filter.rst6
-rw-r--r--Help/release/dev/cmake-install-mode-symlink.rst16
-rw-r--r--Help/release/dev/cmake_dependent_option_policy.rst6
-rw-r--r--Help/release/dev/ctest_memcheck-generate-test.xml.rst6
-rw-r--r--Help/release/dev/find-matlab-imported-targets.rst4
-rw-r--r--Help/release/dev/os-release.rst6
-rw-r--r--Help/release/dev/vs_settings.rst5
-rw-r--r--Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst18
-rw-r--r--Help/variable/CMAKE_LANG_IMPLICIT_LINK_LIBRARIES.rst20
-rw-r--r--Modules/CMakeASM_MASMInformation.cmake2
-rw-r--r--Modules/CMakeDependentOption.cmake61
-rw-r--r--Modules/CMakeDetermineASMCompiler.cmake19
-rw-r--r--Modules/CMakeFindBinUtils.cmake10
-rw-r--r--Modules/CMakeFindPackageMode.cmake2
-rw-r--r--Modules/CheckCXXSymbolExists.cmake2
-rw-r--r--Modules/CheckFortranFunctionExists.cmake6
-rw-r--r--Modules/CheckLanguage.cmake5
-rw-r--r--Modules/CheckSymbolExists.cmake2
-rw-r--r--Modules/Compiler/ARMClang-C.cmake8
-rw-r--r--Modules/Compiler/ARMClang-CXX.cmake8
-rw-r--r--Modules/Compiler/Clang-C.cmake1
-rw-r--r--Modules/Compiler/Clang-CXX.cmake1
-rw-r--r--Modules/Compiler/Clang-FindBinUtils.cmake2
-rw-r--r--Modules/Compiler/GNU-FindBinUtils.cmake2
-rw-r--r--Modules/Compiler/Intel-C.cmake1
-rw-r--r--Modules/Compiler/Intel-CXX.cmake1
-rw-r--r--Modules/Compiler/IntelLLVM-C.cmake1
-rw-r--r--Modules/Compiler/IntelLLVM-CXX.cmake1
-rw-r--r--Modules/Compiler/MSVC-C.cmake1
-rw-r--r--Modules/Compiler/MSVC-CXX.cmake1
-rw-r--r--Modules/Compiler/NVHPC-C.cmake5
-rw-r--r--Modules/Compiler/NVHPC-CXX.cmake5
-rw-r--r--Modules/FetchContent.cmake452
-rw-r--r--Modules/FindBoost.cmake21
-rw-r--r--Modules/FindICU.cmake4
-rw-r--r--Modules/FindMPI.cmake3
-rw-r--r--Modules/FindMatlab.cmake53
-rw-r--r--Modules/FindPkgConfig.cmake8
-rw-r--r--Modules/FindPython/Support.cmake1
-rw-r--r--Modules/FindThreads.cmake2
-rw-r--r--Modules/GNUInstallDirs.cmake39
-rw-r--r--Modules/GoogleTest.cmake11
-rw-r--r--Modules/GoogleTestAddTests.cmake11
-rw-r--r--Modules/InstallRequiredSystemLibraries.cmake8
-rw-r--r--Modules/Internal/OSRelease/010-TryOldCentOS.cmake41
-rw-r--r--Modules/Internal/OSRelease/020-TryDebianVersion.cmake38
-rw-r--r--Modules/Platform/Android-Determine.cmake2
-rw-r--r--Modules/Platform/Windows-MSVC.cmake5
-rw-r--r--Source/CMakeLists.txt5
-rw-r--r--Source/CMakeVersion.cmake2
-rw-r--r--Source/CPack/IFW/cmCPackIFWCommon.cxx2
-rw-r--r--Source/CPack/IFW/cmCPackIFWCommon.h4
-rw-r--r--Source/CPack/IFW/cmCPackIFWGenerator.cxx57
-rw-r--r--Source/CPack/IFW/cmCPackIFWInstaller.cxx112
-rw-r--r--Source/CPack/IFW/cmCPackIFWPackage.cxx96
-rw-r--r--Source/CPack/IFW/cmCPackIFWRepository.cxx25
-rw-r--r--Source/CPack/WiX/cmCPackWIXGenerator.cxx79
-rw-r--r--Source/CPack/cmCPackArchiveGenerator.cxx20
-rw-r--r--Source/CPack/cmCPackBundleGenerator.cxx45
-rw-r--r--Source/CPack/cmCPackCygwinBinaryGenerator.cxx8
-rw-r--r--Source/CPack/cmCPackCygwinSourceGenerator.cxx15
-rw-r--r--Source/CPack/cmCPackDebGenerator.cxx171
-rw-r--r--Source/CPack/cmCPackDragNDropGenerator.cxx52
-rw-r--r--Source/CPack/cmCPackExternalGenerator.cxx37
-rw-r--r--Source/CPack/cmCPackFreeBSDGenerator.cxx4
-rw-r--r--Source/CPack/cmCPackGenerator.cxx153
-rw-r--r--Source/CPack/cmCPackGenerator.h3
-rw-r--r--Source/CPack/cmCPackNSISGenerator.cxx26
-rw-r--r--Source/CPack/cmCPackNuGetGenerator.cxx5
-rw-r--r--Source/CPack/cmCPackOSXX11Generator.cxx11
-rw-r--r--Source/CPack/cmCPackPKGGenerator.cxx9
-rw-r--r--Source/CPack/cmCPackPackageMakerGenerator.cxx23
-rw-r--r--Source/CPack/cmCPackProductBuildGenerator.cxx15
-rw-r--r--Source/CPack/cmCPackProductBuildGenerator.h4
-rw-r--r--Source/CPack/cmCPackRPMGenerator.cxx3
-rw-r--r--Source/CPack/cmCPackSTGZGenerator.cxx1
-rw-r--r--Source/CTest/cmCTestGenericHandler.cxx4
-rw-r--r--Source/CTest/cmCTestGenericHandler.h3
-rw-r--r--Source/CTest/cmCTestStartCommand.cxx8
-rw-r--r--Source/CTest/cmCTestSubmitCommand.cxx4
-rw-r--r--Source/CTest/cmCTestSubmitHandler.cxx21
-rw-r--r--Source/CTest/cmCTestTestHandler.cxx39
-rw-r--r--Source/CTest/cmCTestTestHandler.h7
-rw-r--r--Source/CTest/cmCTestUpdateHandler.cxx5
-rw-r--r--Source/CTest/cmCTestUpdateHandler.h2
-rw-r--r--Source/QtDialog/QCMake.cxx6
-rw-r--r--Source/cmAddTestCommand.cxx2
-rw-r--r--Source/cmAlgorithms.h12
-rw-r--r--Source/cmArchiveWrite.cxx3
-rw-r--r--Source/cmCMakeHostSystemInformationCommand.cxx606
-rw-r--r--Source/cmCMakePolicyCommand.cxx1
-rw-r--r--Source/cmCPluginAPI.cxx2
-rw-r--r--Source/cmCacheManager.cxx20
-rw-r--r--Source/cmCacheManager.h18
-rw-r--r--Source/cmCommandArgumentParserHelper.cxx2
-rw-r--r--Source/cmCommonTargetGenerator.cxx6
-rw-r--r--Source/cmCommonTargetGenerator.h5
-rw-r--r--Source/cmComputeLinkDepends.cxx2
-rw-r--r--Source/cmComputeLinkInformation.cxx7
-rw-r--r--Source/cmComputeLinkInformation.h3
-rw-r--r--Source/cmComputeTargetDepends.cxx2
-rw-r--r--Source/cmConditionEvaluator.cxx16
-rw-r--r--Source/cmCoreTryCompile.cxx10
-rw-r--r--Source/cmDefinitions.cxx6
-rw-r--r--Source/cmDefinitions.h4
-rw-r--r--Source/cmExportBuildFileGenerator.cxx1
-rw-r--r--Source/cmExportFileGenerator.cxx2
-rw-r--r--Source/cmExportInstallFileGenerator.cxx1
-rw-r--r--Source/cmFileAPICodemodel.cxx3
-rw-r--r--Source/cmFileCommand.cxx4
-rw-r--r--Source/cmFileCopier.h5
-rw-r--r--Source/cmFileInstaller.cxx118
-rw-r--r--Source/cmFileInstaller.h5
-rw-r--r--Source/cmFindBase.cxx8
-rw-r--r--Source/cmForEachCommand.cxx1
-rw-r--r--Source/cmGeneratorExpressionNode.cxx2
-rw-r--r--Source/cmGeneratorTarget.cxx155
-rw-r--r--Source/cmGeneratorTarget.h11
-rw-r--r--Source/cmGetDirectoryPropertyCommand.cxx11
-rw-r--r--Source/cmGetPropertyCommand.cxx24
-rw-r--r--Source/cmGetTestPropertyCommand.cxx5
-rw-r--r--Source/cmGlobalCommonGenerator.cxx2
-rw-r--r--Source/cmGlobalGenerator.cxx27
-rw-r--r--Source/cmGlobalGenerator.h3
-rw-r--r--Source/cmGlobalGhsMultiGenerator.cxx3
-rw-r--r--Source/cmGlobalNinjaGenerator.cxx2
-rw-r--r--Source/cmGlobalVisualStudio71Generator.cxx6
-rw-r--r--Source/cmGlobalVisualStudio71Generator.h2
-rw-r--r--Source/cmGlobalVisualStudio7Generator.cxx7
-rw-r--r--Source/cmGlobalVisualStudio7Generator.h3
-rw-r--r--Source/cmGlobalVisualStudioVersionedGenerator.cxx9
-rw-r--r--Source/cmGlobalXCodeGenerator.cxx7
-rw-r--r--Source/cmIncludeExternalMSProjectCommand.cxx5
-rw-r--r--Source/cmIncludeGuardCommand.cxx1
-rw-r--r--Source/cmIncludeRegularExpressionCommand.cxx2
-rw-r--r--Source/cmInstallMode.h17
-rw-r--r--Source/cmLocalGenerator.cxx44
-rw-r--r--Source/cmLocalGenerator.h2
-rw-r--r--Source/cmLocalVisualStudio7Generator.cxx6
-rw-r--r--Source/cmLocalVisualStudioGenerator.cxx11
-rw-r--r--Source/cmLocalVisualStudioGenerator.h6
-rw-r--r--Source/cmMakefile.cxx86
-rw-r--r--Source/cmMakefile.h29
-rw-r--r--Source/cmMakefileTargetGenerator.cxx27
-rw-r--r--Source/cmMarkAsAdvancedCommand.cxx1
-rw-r--r--Source/cmNinjaTargetGenerator.cxx35
-rw-r--r--Source/cmOptionCommand.cxx4
-rw-r--r--Source/cmPolicies.cxx1
-rw-r--r--Source/cmPolicies.h5
-rw-r--r--Source/cmProperty.cxx113
-rw-r--r--Source/cmProperty.h210
-rw-r--r--Source/cmPropertyMap.cxx11
-rw-r--r--Source/cmPropertyMap.h5
-rw-r--r--Source/cmQTWrapCPPCommand.cxx3
-rw-r--r--Source/cmQtAutoGen.cxx36
-rw-r--r--Source/cmQtAutoGen.h3
-rw-r--r--Source/cmQtAutoGenGlobalInitializer.cxx2
-rw-r--r--Source/cmQtAutoGenInitializer.cxx56
-rw-r--r--Source/cmQtAutoGenInitializer.h2
-rw-r--r--Source/cmQtAutoGenerator.cxx37
-rw-r--r--Source/cmQtAutoGenerator.h2
-rw-r--r--Source/cmQtAutoMocUic.cxx20
-rw-r--r--Source/cmQtAutoUicHelpers.cxx25
-rw-r--r--Source/cmQtAutoUicHelpers.h20
-rw-r--r--Source/cmSetDirectoryPropertiesCommand.cxx2
-rw-r--r--Source/cmSetPropertyCommand.cxx10
-rw-r--r--Source/cmSetSourceFilesPropertiesCommand.cxx2
-rw-r--r--Source/cmSetTestsPropertiesCommand.cxx2
-rw-r--r--Source/cmSourceFile.cxx26
-rw-r--r--Source/cmSourceFile.h8
-rw-r--r--Source/cmStandardLevelResolver.cxx6
-rw-r--r--Source/cmStandardLevelResolver.h4
-rw-r--r--Source/cmState.cxx29
-rw-r--r--Source/cmState.h13
-rw-r--r--Source/cmStateDirectory.cxx232
-rw-r--r--Source/cmStateDirectory.h57
-rw-r--r--Source/cmStatePrivate.h15
-rw-r--r--Source/cmStateSnapshot.cxx32
-rw-r--r--Source/cmStateSnapshot.h3
-rw-r--r--Source/cmStringAlgorithms.cxx70
-rw-r--r--Source/cmStringAlgorithms.h85
-rw-r--r--Source/cmSystemTools.cxx5
-rw-r--r--Source/cmTarget.cxx384
-rw-r--r--Source/cmTarget.h51
-rw-r--r--Source/cmTargetCompileOptionsCommand.cxx3
-rw-r--r--Source/cmTargetIncludeDirectoriesCommand.cxx2
-rw-r--r--Source/cmTargetLinkDirectoriesCommand.cxx3
-rw-r--r--Source/cmTargetLinkOptionsCommand.cxx2
-rw-r--r--Source/cmTargetPropertyComputer.h6
-rw-r--r--Source/cmTest.cxx10
-rw-r--r--Source/cmTest.h8
-rw-r--r--Source/cmVisualStudio10TargetGenerator.cxx101
-rw-r--r--Source/cmVisualStudio10TargetGenerator.h14
-rw-r--r--Source/cmWhileCommand.cxx89
-rw-r--r--Source/cmake.cxx70
-rw-r--r--Source/cmake.h17
-rw-r--r--Source/kwsys/Status.hxx.in5
-rw-r--r--Source/kwsys/SystemInformation.cxx6
-rw-r--r--Source/kwsys/SystemTools.cxx28
-rw-r--r--Source/kwsys/testDirectory.cxx2
-rw-r--r--Source/kwsys/testStatus.cxx12
-rw-r--r--Source/kwsys/testSystemTools.cxx2
-rw-r--r--Templates/MSBuild/FlagTables/v142_CL.json4
-rw-r--r--Templates/MSBuild/FlagTables/v143_CL.json4
-rw-r--r--Tests/CMakeLists.txt49
-rw-r--r--Tests/CMakeTests/CMakeLists.txt1
-rw-r--r--Tests/FindMatlab/targets_checks/CMakeLists.txt44
-rw-r--r--Tests/InstallMode/CMakeLists.txt124
-rw-r--r--Tests/InstallMode/README.txt43
-rw-r--r--Tests/InstallMode/Subproject.cmake73
-rw-r--r--Tests/InstallMode/Test.cmake38
-rw-r--r--Tests/InstallMode/subpro_a_static_lib/CMakeLists.txt60
-rw-r--r--Tests/InstallMode/subpro_a_static_lib/cmake/PackageConfig.cmake.in8
-rw-r--r--Tests/InstallMode/subpro_a_static_lib/include/static_lib.h3
-rw-r--r--Tests/InstallMode/subpro_a_static_lib/src/static_lib.cpp10
-rw-r--r--Tests/InstallMode/subpro_b_shared_lib/CMakeLists.txt75
-rw-r--r--Tests/InstallMode/subpro_b_shared_lib/cmake/PackageConfig.cmake.in8
-rw-r--r--Tests/InstallMode/subpro_b_shared_lib/include/shared_lib.h5
-rw-r--r--Tests/InstallMode/subpro_b_shared_lib/src/shared_lib.cpp10
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/CMakeLists.txt10
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/CMakeLists.txt61
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/cmake/PackageConfig.cmake.in8
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/include/c1_lib.h3
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/src/c1_lib.cpp10
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/CMakeLists.txt71
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/cmake/PackageConfig.cmake.in11
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/include/c2_lib.h3
-rw-r--r--Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/src/c2_lib.cpp12
-rw-r--r--Tests/InstallMode/subpro_d_executable/CMakeLists.txt27
-rw-r--r--Tests/InstallMode/subpro_d_executable/src/main.cpp13
-rw-r--r--Tests/InstallMode/superpro/CMakeLists.txt29
-rw-r--r--Tests/InstallMode/superpro/file_copy.txt1
-rw-r--r--Tests/InstallMode/superpro/file_copy_file.txt1
-rw-r--r--Tests/InstallMode/superpro/file_create_link_symbolic.txt2
-rw-r--r--Tests/InstallMode/superpro/file_install.txt6
-rw-r--r--Tests/QtAutogen/RerunUicOnFileChange/CMakeLists.txt3
-rw-r--r--Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/CMakeLists.txt.in1
-rw-r--r--Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/main.cpp4
-rw-r--r--Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/mainwindowsubdir.ui.in7
-rw-r--r--Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/subdircheck.cpp9
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW-stdout.txt (renamed from Tests/RunCMake/CMakeDependentOption/Regex-stdout.txt)0
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW.cmake9
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stderr.txt9
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stdout.txt2
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN.cmake9
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW-stdout.txt1
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW.cmake7
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD-stdout.txt1
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD.cmake (renamed from Tests/RunCMake/CMakeDependentOption/Regex.cmake)2
-rw-r--r--Tests/RunCMake/CMakeDependentOption/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD-stdout.txt1
-rw-r--r--Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD.cmake6
-rw-r--r--Tests/RunCMake/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMP0126_NEW.cmake64
-rw-r--r--Tests/RunCMake/FindPkgConfig/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test3-stdout.txt16
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test4-stdout.txt9
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest.cmake18
-rw-r--r--Tests/RunCMake/GoogleTest/RunCMakeTest.cmake14
-rw-r--r--Tests/RunCMake/GoogleTest/fake_gtest.cpp55
-rw-r--r--Tests/RunCMake/VS10Project/VsSettings-check.cmake15
-rw-r--r--Tests/RunCMake/VS10Project/VsSettings.cmake2
-rw-r--r--Tests/RunCMake/cmake_host_system_information/000-FirstFallbackScript.cmake1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/999-LastFallbackScript.cmake21
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg1-result.txt1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg1-stderr.txt4
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg1.cmake (renamed from Tests/CMakeTests/CMakeHostSystemInformation-BadArg1.cmake)0
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg2-result.txt1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg2-stderr.txt4
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg2.cmake (renamed from Tests/CMakeTests/CMakeHostSystemInformation-BadArg2.cmake)0
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg3-result.txt1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg3-stderr.txt4
-rw-r--r--Tests/RunCMake/cmake_host_system_information/BadArg3.cmake (renamed from Tests/CMakeTests/CMakeHostSystemInformation-BadArg3.cmake)0
-rw-r--r--Tests/RunCMake/cmake_host_system_information/CMakeLists.txt7
-rw-r--r--Tests/RunCMake/cmake_host_system_information/CentOS6-stdout.txt7
-rw-r--r--Tests/RunCMake/cmake_host_system_information/CentOS6.cmake5
-rw-r--r--Tests/RunCMake/cmake_host_system_information/CentOS6/etc/centos-release1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Debian6-stdout.txt5
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Debian6.cmake5
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Debian6/etc/debian_version1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Exherbo-stdout.txt9
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Exherbo.cmake11
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Exherbo/etc/os-release7
-rw-r--r--Tests/RunCMake/cmake_host_system_information/QueryKeys-stdout.txt27
-rw-r--r--Tests/RunCMake/cmake_host_system_information/QueryKeys.cmake (renamed from Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in)24
-rw-r--r--Tests/RunCMake/cmake_host_system_information/QueryList-stdout.txt1
-rw-r--r--Tests/RunCMake/cmake_host_system_information/QueryList.cmake (renamed from Tests/CMakeTests/CMakeHostSystemInformation-QueryList.cmake)2
-rw-r--r--Tests/RunCMake/cmake_host_system_information/RunCMakeTest.cmake17
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Ubuntu-stdout.txt14
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Ubuntu.cmake11
-rw-r--r--Tests/RunCMake/cmake_host_system_information/Ubuntu/etc/os-release12
-rw-r--r--Tests/RunCMake/cmake_host_system_information/UnitTest-stdout.txt7
-rw-r--r--Tests/RunCMake/cmake_host_system_information/UnitTest.cmake5
-rw-r--r--Tests/RunCMake/cmake_host_system_information/UnitTest/etc/os-release9
-rw-r--r--Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stderr.txt5
-rw-r--r--Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stdout.txt7
-rw-r--r--Tests/RunCMake/cmake_host_system_information/UserFallbackScript.cmake12
-rw-r--r--Tests/RunCMake/ctest_memcheck/ExpectedOutputs-check.cmake10
-rw-r--r--Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stdout.txt2
-rw-r--r--Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake13
-rw-r--r--Tests/RunCMake/if/RunCMakeTest.cmake2
-rw-r--r--Tests/RunCMake/if/unbalanced-parenthesis-result.txt1
-rw-r--r--Tests/RunCMake/if/unbalanced-parenthesis-stderr.txt8
-rw-r--r--Tests/RunCMake/if/unbalanced-parenthesis.cmake8
-rw-r--r--Tests/RunCMake/while/RunCMakeTest.cmake2
-rw-r--r--Tests/RunCMake/while/unbalanced-parenthesis-result.txt1
-rw-r--r--Tests/RunCMake/while/unbalanced-parenthesis-stderr.txt8
-rw-r--r--Tests/RunCMake/while/unbalanced-parenthesis.cmake8
-rw-r--r--Utilities/IWYU/mapping.imp1
-rw-r--r--Utilities/KWIML/include/kwiml/int.h17
-rwxr-xr-xUtilities/Scripts/update-jsoncpp.bash2
-rwxr-xr-xUtilities/Scripts/update-libarchive.bash2
-rw-r--r--Utilities/cmThirdPartyChecks.cmake1
-rw-r--r--Utilities/cmjsoncpp/include/json/allocator.h141
-rw-r--r--Utilities/cmjsoncpp/include/json/assertions.h43
-rw-r--r--Utilities/cmjsoncpp/include/json/config.h214
-rw-r--r--Utilities/cmjsoncpp/include/json/forwards.h10
-rw-r--r--Utilities/cmjsoncpp/include/json/json.h5
-rw-r--r--Utilities/cmjsoncpp/include/json/json_features.h (renamed from Utilities/cmjsoncpp/include/json/features.h)14
-rw-r--r--Utilities/cmjsoncpp/include/json/reader.h390
-rw-r--r--Utilities/cmjsoncpp/include/json/value.h608
-rw-r--r--Utilities/cmjsoncpp/include/json/version.h26
-rw-r--r--Utilities/cmjsoncpp/include/json/writer.h251
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_reader.cpp949
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_tool.h55
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_value.cpp1060
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl39
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_writer.cpp822
-rw-r--r--Utilities/cmlibarchive/CMakeLists.txt30
-rw-r--r--Utilities/cmlibarchive/COPYING1
-rw-r--r--Utilities/cmlibarchive/build/cmake/CreatePkgConfigFile.cmake4
-rw-r--r--Utilities/cmlibarchive/build/cmake/config.h.in4
-rw-r--r--Utilities/cmlibarchive/build/version2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive.h11
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_acl.c10
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_check_magic.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_cryptor.c23
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_cryptor_private.h9
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_digest.c534
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_digest_private.h4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry.c85
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry.h15
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry_private.h16
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry_stat.34
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_ppmd7.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read.c17
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_add_passphrase.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c48
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_disk_posix.c46
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_filter.312
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_open_filename.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_set_format.c9
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_filter_by_code.c83
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_filter_program.c23
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_by_code.c15
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_empty.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c137
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c14
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_rar5.c13
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c18
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c20
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c19
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c135
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_string.c52
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_string.h2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_util.c6
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write.c42
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c26
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c79
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c52
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_disk_windows.c19
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_open.337
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_open_fd.c10
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_open_file.c10
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_open_filename.c21
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_open_memory.c10
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_private.h1
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio_newc.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_iso9660.c3
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c49
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c7
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c5
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_options.33
-rw-r--r--Utilities/cmlibarchive/libarchive/config_freebsd.h2
-rw-r--r--Utilities/cmlibarchive/libarchive/cpio.52
-rw-r--r--Utilities/cmlibarchive/libarchive/filter_fork.h9
-rw-r--r--Utilities/cmlibarchive/libarchive/filter_fork_posix.c10
-rw-r--r--Utilities/cmlibarchive/libarchive/filter_fork_windows.c17
-rwxr-xr-xbootstrap1
417 files changed, 8491 insertions, 5314 deletions
diff --git a/.gitlab/os-windows.yml b/.gitlab/os-windows.yml
index 90ff0a8..8037b33 100644
--- a/.gitlab/os-windows.yml
+++ b/.gitlab/os-windows.yml
@@ -38,7 +38,7 @@
CMAKE_CONFIGURATION: windows_vs2019_x64_ninja
VCVARSALL: "${VS160COMNTOOLS}\\..\\..\\VC\\Auxiliary\\Build\\vcvarsall.bat"
VCVARSPLATFORM: "x64"
- VCVARSVERSION: "14.29.30037"
+ VCVARSVERSION: "14.29.30133"
### External testing
@@ -49,7 +49,7 @@
CMAKE_CONFIGURATION: windows_vs2019_x64
CMAKE_GENERATOR: "Visual Studio 16 2019"
CMAKE_GENERATOR_PLATFORM: "x64"
- CMAKE_GENERATOR_TOOLSET: "v142,version=14.29.30037"
+ CMAKE_GENERATOR_TOOLSET: "v142,version=14.29.30133"
CMAKE_CI_NIGHTLY_IGNORE_DEPS: "true"
## Tags
@@ -60,7 +60,7 @@
- windows
- shell
- vs2019
- - msvc-19.29-16.10
+ - msvc-19.29-16.11
- nonconcurrent
.windows_builder_ext_tags:
@@ -69,7 +69,7 @@
- windows
- shell
- vs2019
- - msvc-19.29-16.10
+ - msvc-19.29-16.11
- concurrent
## Windows-specific scripts
diff --git a/Help/command/cmake_host_system_information.rst b/Help/command/cmake_host_system_information.rst
index 2b902a9..998e146 100644
--- a/Help/command/cmake_host_system_information.rst
+++ b/Help/command/cmake_host_system_information.rst
@@ -13,46 +13,236 @@ queried. The list of queried values is stored in ``<variable>``.
``<key>`` can be one of the following values:
-============================= ================================================
-Key Description
-============================= ================================================
-``NUMBER_OF_LOGICAL_CORES`` Number of logical cores
-``NUMBER_OF_PHYSICAL_CORES`` Number of physical cores
-``HOSTNAME`` Hostname
-``FQDN`` Fully qualified domain name
-``TOTAL_VIRTUAL_MEMORY`` Total virtual memory in MiB [#mebibytes]_
-``AVAILABLE_VIRTUAL_MEMORY`` Available virtual memory in MiB [#mebibytes]_
-``TOTAL_PHYSICAL_MEMORY`` Total physical memory in MiB [#mebibytes]_
-``AVAILABLE_PHYSICAL_MEMORY`` Available physical memory in MiB [#mebibytes]_
-============================= ================================================
-
-.. versionadded:: 3.10
- Additional ``<key>`` values are available:
-
-============================= ================================================
-Key Description
-============================= ================================================
-``IS_64BIT`` One if processor is 64Bit
-``HAS_FPU`` One if processor has floating point unit
-``HAS_MMX`` One if processor supports MMX instructions
-``HAS_MMX_PLUS`` One if processor supports Ext. MMX instructions
-``HAS_SSE`` One if processor supports SSE instructions
-``HAS_SSE2`` One if processor supports SSE2 instructions
-``HAS_SSE_FP`` One if processor supports SSE FP instructions
-``HAS_SSE_MMX`` One if processor supports SSE MMX instructions
-``HAS_AMD_3DNOW`` One if processor supports 3DNow instructions
-``HAS_AMD_3DNOW_PLUS`` One if processor supports 3DNow+ instructions
-``HAS_IA64`` One if IA64 processor emulating x86
-``HAS_SERIAL_NUMBER`` One if processor has serial number
-``PROCESSOR_SERIAL_NUMBER`` Processor serial number
-``PROCESSOR_NAME`` Human readable processor name
-``PROCESSOR_DESCRIPTION`` Human readable full processor description
-``OS_NAME`` See :variable:`CMAKE_HOST_SYSTEM_NAME`
-``OS_RELEASE`` The OS sub-type e.g. on Windows ``Professional``
-``OS_VERSION`` The OS build ID
-``OS_PLATFORM`` See :variable:`CMAKE_HOST_SYSTEM_PROCESSOR`
-============================= ================================================
+``NUMBER_OF_LOGICAL_CORES``
+ Number of logical cores
+
+``NUMBER_OF_PHYSICAL_CORES``
+ Number of physical cores
+
+``HOSTNAME``
+ Hostname
+
+``FQDN``
+ Fully qualified domain name
+
+``TOTAL_VIRTUAL_MEMORY``
+ Total virtual memory in MiB [#mebibytes]_
+
+``AVAILABLE_VIRTUAL_MEMORY``
+ Available virtual memory in MiB [#mebibytes]_
+
+``TOTAL_PHYSICAL_MEMORY``
+ Total physical memory in MiB [#mebibytes]_
+
+``AVAILABLE_PHYSICAL_MEMORY``
+ Available physical memory in MiB [#mebibytes]_
+
+``IS_64BIT``
+ .. versionadded:: 3.10
+
+ One if processor is 64Bit
+
+``HAS_FPU``
+ .. versionadded:: 3.10
+
+ One if processor has floating point unit
+
+``HAS_MMX``
+ .. versionadded:: 3.10
+
+ One if processor supports MMX instructions
+
+``HAS_MMX_PLUS``
+ .. versionadded:: 3.10
+
+ One if processor supports Ext. MMX instructions
+
+``HAS_SSE``
+ .. versionadded:: 3.10
+
+ One if processor supports SSE instructions
+
+``HAS_SSE2``
+ .. versionadded:: 3.10
+
+ One if processor supports SSE2 instructions
+
+``HAS_SSE_FP``
+ .. versionadded:: 3.10
+
+ One if processor supports SSE FP instructions
+
+``HAS_SSE_MMX``
+ .. versionadded:: 3.10
+
+ One if processor supports SSE MMX instructions
+
+``HAS_AMD_3DNOW``
+ .. versionadded:: 3.10
+
+ One if processor supports 3DNow instructions
+
+``HAS_AMD_3DNOW_PLUS``
+ .. versionadded:: 3.10
+
+ One if processor supports 3DNow+ instructions
+
+``HAS_IA64``
+ .. versionadded:: 3.10
+
+ One if IA64 processor emulating x86
+
+``HAS_SERIAL_NUMBER``
+ .. versionadded:: 3.10
+
+ One if processor has serial number
+
+``PROCESSOR_SERIAL_NUMBER``
+ .. versionadded:: 3.10
+
+ Processor serial number
+
+``PROCESSOR_NAME``
+ .. versionadded:: 3.10
+
+ Human readable processor name
+
+``PROCESSOR_DESCRIPTION``
+ .. versionadded:: 3.10
+
+ Human readable full processor description
+
+``OS_NAME``
+ .. versionadded:: 3.10
+
+ See :variable:`CMAKE_HOST_SYSTEM_NAME`
+
+``OS_RELEASE``
+ .. versionadded:: 3.10
+
+ The OS sub-type e.g. on Windows ``Professional``
+
+``OS_VERSION``
+ .. versionadded:: 3.10
+
+ The OS build ID
+
+``OS_PLATFORM``
+ .. versionadded:: 3.10
+
+ See :variable:`CMAKE_HOST_SYSTEM_PROCESSOR`
+
+``DISTRIB_INFO``
+ .. versionadded:: 3.22
+
+ Read :file:`/etc/os-release` file and define the given ``<variable>``
+ into a list of read variables
+
+``DISTRIB_<name>``
+ .. versionadded:: 3.22
+
+ Get the ``<name>`` variable (see `man 5 os-release`_) if it exists in the
+ :file:`/etc/os-release` file
+
+ Example:
+
+ .. code-block:: cmake
+
+ cmake_host_system_information(RESULT PRETTY_NAME QUERY DISTRIB_PRETTY_NAME)
+ message(STATUS "${PRETTY_NAME}")
+
+ cmake_host_system_information(RESULT DISTRO QUERY DISTRIB_INFO)
+
+ foreach(VAR IN LISTS DISTRO)
+ message(STATUS "${VAR}=`${${VAR}}`")
+ endforeach()
+
+
+ Output::
+
+ -- Ubuntu 20.04.2 LTS
+ -- DISTRO_BUG_REPORT_URL=`https://bugs.launchpad.net/ubuntu/`
+ -- DISTRO_HOME_URL=`https://www.ubuntu.com/`
+ -- DISTRO_ID=`ubuntu`
+ -- DISTRO_ID_LIKE=`debian`
+ -- DISTRO_NAME=`Ubuntu`
+ -- DISTRO_PRETTY_NAME=`Ubuntu 20.04.2 LTS`
+ -- DISTRO_PRIVACY_POLICY_URL=`https://www.ubuntu.com/legal/terms-and-policies/privacy-policy`
+ -- DISTRO_SUPPORT_URL=`https://help.ubuntu.com/`
+ -- DISTRO_UBUNTU_CODENAME=`focal`
+ -- DISTRO_VERSION=`20.04.2 LTS (Focal Fossa)`
+ -- DISTRO_VERSION_CODENAME=`focal`
+ -- DISTRO_VERSION_ID=`20.04`
+
+If :file:`/etc/os-release` file is not found, the command tries to gather OS
+identification via fallback scripts. The fallback script can use `various
+distribution-specific files`_ to collect OS identification data and map it
+into `man 5 os-release`_ variables.
+
+Fallback Interface Variables
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS
+
+ In addition to the scripts shipped with CMake, a user may append full
+ paths to his script(s) to the this list. The script filename has the
+ following format: ``NNN-<name>.cmake``, where ``NNN`` is three digits
+ used to apply collected scripts in a specific order.
+
+.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>
+
+ Variables collected by the user provided fallback script
+ ought to be assigned to CMake variables using this naming
+ convention. Example, the ``ID`` variable from the manual becomes
+ ``CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID``.
+
+.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
+
+ The fallback script ought to store names of all assigned
+ ``CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>`` variables in this list.
+
+Example:
+
+.. code-block:: cmake
+
+ # Try to detect some old distribution
+ # See also
+ # - http://linuxmafia.com/faq/Admin/release-files.html
+ #
+ if(NOT EXISTS "${CMAKE_SYSROOT}/etc/foobar-release")
+ return()
+ endif()
+ # Get the first string only
+ file(
+ STRINGS "${CMAKE_SYSROOT}/etc/foobar-release" CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT
+ LIMIT_COUNT 1
+ )
+ #
+ # Example:
+ #
+ # Foobar distribution release 1.2.3 (server)
+ #
+ if(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT MATCHES "Foobar distribution release ([0-9\.]+) .*")
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME Foobar)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME "${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT}")
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID foobar)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION ${CMAKE_MATCH_1})
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ${CMAKE_MATCH_1})
+ list(
+ APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID
+ )
+ endif()
+ unset(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT)
+
.. rubric:: Footnotes
.. [#mebibytes] One MiB (mebibyte) is equal to 1024x1024 bytes.
+
+.. _man 5 os-release: https://www.freedesktop.org/software/systemd/man/os-release.html
+.. _various distribution-specific files: http://linuxmafia.com/faq/Admin/release-files.html
diff --git a/Help/command/cmake_path.rst b/Help/command/cmake_path.rst
index 565a37b..454c860 100644
--- a/Help/command/cmake_path.rst
+++ b/Help/command/cmake_path.rst
@@ -69,8 +69,8 @@ Synopsis
`Native Conversion`_
cmake_path(`NATIVE_PATH`_ <path-var> [NORMALIZE] <out-var>)
- cmake_path(`CONVERT`_ <input> `TO_CMAKE_PATH_LIST`_ <out-var>)
- cmake_path(`CONVERT`_ <input> `TO_NATIVE_PATH_LIST`_ <out-var>)
+ cmake_path(`CONVERT`_ <input> `TO_CMAKE_PATH_LIST`_ <out-var> [NORMALIZE])
+ cmake_path(`CONVERT`_ <input> `TO_NATIVE_PATH_LIST`_ <out-var> [NORMALIZE])
`Hashing`_
cmake_path(`HASH`_ <path-var> <out-var>)
diff --git a/Help/command/ctest_submit.rst b/Help/command/ctest_submit.rst
index e6d277f..d661825 100644
--- a/Help/command/ctest_submit.rst
+++ b/Help/command/ctest_submit.rst
@@ -30,7 +30,8 @@ The options are:
Build = ctest_build results, in Build.xml
Test = ctest_test results, in Test.xml
Coverage = ctest_coverage results, in Coverage.xml
- MemCheck = ctest_memcheck results, in DynamicAnalysis.xml
+ MemCheck = ctest_memcheck results, in DynamicAnalysis.xml and
+ DynamicAnalysis-Test.xml
Notes = Files listed by CTEST_NOTES_FILES, in Notes.xml
ExtraFiles = Files listed by CTEST_EXTRA_SUBMIT_FILES
Upload = Files prepared for upload by ctest_upload(), in Upload.xml
diff --git a/Help/command/file.rst b/Help/command/file.rst
index f038871..96a55ee 100644
--- a/Help/command/file.rst
+++ b/Help/command/file.rst
@@ -843,6 +843,11 @@ and ``NO_SOURCE_PERMISSIONS`` is default.
Installation scripts generated by the :command:`install` command
use this signature (with some undocumented options for internal use).
+.. versionchanged:: 3.22
+
+ The environment variable :envvar:`CMAKE_INSTALL_MODE` can override the
+ default copying behavior of :command:`file(INSTALL)`.
+
.. _SIZE:
.. code-block:: cmake
diff --git a/Help/command/find_package.rst b/Help/command/find_package.rst
index 7febd5d..8388709 100644
--- a/Help/command/find_package.rst
+++ b/Help/command/find_package.rst
@@ -28,11 +28,26 @@ that the package cannot be found if it is not ``REQUIRED``. The ``REQUIRED``
option stops processing with an error message if the package cannot be found.
A package-specific list of required components may be listed after the
-``COMPONENTS`` option (or after the ``REQUIRED`` option if present).
+``COMPONENTS`` keyword. If any of these components are not able to be
+satisfied, the package overall is considered to be not found. If the
+``REQUIRED`` option is also present, this is treated as a fatal error,
+otherwise execution still continues. As a form of shorthand, if the
+``REQUIRED`` option is present, the ``COMPONENTS`` keyword can be omitted
+and the required components can be listed directly after ``REQUIRED``.
+
Additional optional components may be listed after
-``OPTIONAL_COMPONENTS``. Available components and their influence on
-whether a package is considered to be found are defined by the target
-package.
+``OPTIONAL_COMPONENTS``. If these cannot be satisfied, the package overall
+can still be considered found, as long as all required components are
+satisfied.
+
+The set of available components and their meaning are defined by the
+target package. Formally, it is up to the target package how to
+interpret the component information given to it, but it should follow
+the expectations stated above. For calls where no components are specified,
+there is no single expected behavior and target packages should clearly
+define what occurs in such cases. Common arrangements include assuming it
+should find all components, no components or some well-defined subset of the
+available components.
.. _FIND_PACKAGE_VERSION_FORMAT:
@@ -40,12 +55,13 @@ The ``[version]`` argument requests a version with which the package found
should be compatible. There are two possible forms in which it may be
specified:
- * A single version with the format ``major[.minor[.patch[.tweak]]]``.
+ * A single version with the format ``major[.minor[.patch[.tweak]]]``, where
+ each component is a numeric value.
* A version range with the format ``versionMin...[<]versionMax`` where
- ``versionMin`` and ``versionMax`` have the same format as the single
- version. By default, both end points are included. By specifying ``<``,
- the upper end point will be excluded. Version ranges are only supported
- with CMake 3.19 or later.
+ ``versionMin`` and ``versionMax`` have the same format and constraints
+ on components being integers as the single version. By default, both end
+ points are included. By specifying ``<``, the upper end point will be
+ excluded. Version ranges are only supported with CMake 3.19 or later.
The ``EXACT`` option requests that the version be matched exactly. This option
is incompatible with the specification of a version range.
@@ -432,7 +448,7 @@ enabled.
hard-coded guesses.
.. versionadded:: 3.16
- Added the ``CMAKE_FIND_USE_<CATEGORY>_PATH`` variables to globally disable
+ Added the ``CMAKE_FIND_USE_<CATEGORY>`` variables to globally disable
various search locations.
.. |FIND_XXX| replace:: find_package
@@ -486,7 +502,7 @@ restores their original state before returning):
``<PackageName>_FIND_VERSION_EXACT``
True if ``EXACT`` option was given
``<PackageName>_FIND_COMPONENTS``
- List of requested components
+ List of specified components (required and optional)
``<PackageName>_FIND_REQUIRED_<c>``
True if component ``<c>`` is required,
false if component ``<c>`` is optional
diff --git a/Help/command/get_property.rst b/Help/command/get_property.rst
index f77d8af..46da285 100644
--- a/Help/command/get_property.rst
+++ b/Help/command/get_property.rst
@@ -9,7 +9,7 @@ Get a property.
<GLOBAL |
DIRECTORY [<dir>] |
TARGET <target> |
- SOURCE <source> |
+ SOURCE <source>
[DIRECTORY <dir> | TARGET_DIRECTORY <target>] |
INSTALL <file> |
TEST <test> |
diff --git a/Help/command/if.rst b/Help/command/if.rst
index fbf3e36..6ff8852 100644
--- a/Help/command/if.rst
+++ b/Help/command/if.rst
@@ -171,7 +171,7 @@ Comparisons
``if(<variable|string> MATCHES regex)``
True if the given string or variable's value matches the given regular
- condition. See :ref:`Regex Specification` for regex format.
+ expression. See :ref:`Regex Specification` for regex format.
.. versionadded:: 3.9
``()`` groups are captured in :variable:`CMAKE_MATCH_<n>` variables.
diff --git a/Help/command/install.rst b/Help/command/install.rst
index c6af489..1236f1d 100644
--- a/Help/command/install.rst
+++ b/Help/command/install.rst
@@ -30,6 +30,10 @@ are executed in order during installation.
with those in the parent directory to run in the order declared (see
policy :policy:`CMP0082`).
+.. versionchanged:: 3.22
+ The environment variable :envvar:`CMAKE_INSTALL_MODE` can override the
+ default copying behavior of :command:`install()`.
+
There are multiple signatures for this command. Some of them define
installation options for files and targets. Options common to
multiple signatures are covered here but they are valid only for
diff --git a/Help/command/set_property.rst b/Help/command/set_property.rst
index bf437b4..555520d 100644
--- a/Help/command/set_property.rst
+++ b/Help/command/set_property.rst
@@ -9,8 +9,8 @@ Set a named property in a given scope.
DIRECTORY [<dir>] |
TARGET [<target1> ...] |
SOURCE [<src1> ...]
- [DIRECTORY <dirs> ...] |
- [TARGET_DIRECTORY <targets> ...]
+ [DIRECTORY <dirs> ...]
+ [TARGET_DIRECTORY <targets> ...] |
INSTALL [<file1> ...] |
TEST [<test1> ...] |
CACHE [<entry1> ...] >
diff --git a/Help/envvar/CMAKE_INSTALL_MODE.rst b/Help/envvar/CMAKE_INSTALL_MODE.rst
new file mode 100644
index 0000000..37db0d7
--- /dev/null
+++ b/Help/envvar/CMAKE_INSTALL_MODE.rst
@@ -0,0 +1,37 @@
+CMAKE_INSTALL_MODE
+------------------
+
+.. versionadded:: 3.22
+
+.. include:: ENV_VAR.txt
+
+The ``CMAKE_INSTALL_MODE`` environment variable allows users to operate
+CMake in an alternate mode of :command:`file(INSTALL)` and :command:`install()`.
+
+The default behavior for an installation is to copy a source file from a
+source directory into a destination directory. This environment variable
+however allows the user to override this behavior, causing CMake to create
+symbolic links instead.
+
+.. note::
+ A symbolic link consists of a reference file path rather than contents of its own,
+ hence there are two ways to express the relation, either by a relative or an absolute path.
+
+The following values are allowed for ``CMAKE_INSTALL_MODE``:
+
+* empty, unset or ``COPY``: default behavior, duplicate the file at its destination
+* ``ABS_SYMLINK``: create an *absolute* symbolic link to the source file at the destination *or fail*
+* ``ABS_SYMLINK_OR_COPY``: like ``ABS_SYMLINK`` but silently copy on error
+* ``REL_SYMLINK``: create an *relative* symbolic link to the source file at the destination *or fail*
+* ``REL_SYMLINK_OR_COPY``: like ``REL_SYMLINK`` but silently copy on error
+* ``SYMLINK``: try as if through ``REL_SYMLINK`` and fall back to ``ABS_SYMLINK`` if the referenced
+ file cannot be expressed using a relative path. Fail on error.
+* ``SYMLINK_OR_COPY``: like ``SYMLINK`` but silently copy on error
+
+Installing symbolic links rather than copying files can help conserve storage space because files do
+not have to be duplicated on disk. However, modifications applied to the source immediately affects
+the symbolic link and vice versa. *Use with caution*.
+
+.. note:: ``CMAKE_INSTALL_MODE`` only affects files, *not* directories.
+
+.. note:: Symbolic links are not available on all platforms.
diff --git a/Help/generator/Visual Studio 17 2022.rst b/Help/generator/Visual Studio 17 2022.rst
index 6007365..8b97b9f 100644
--- a/Help/generator/Visual Studio 17 2022.rst
+++ b/Help/generator/Visual Studio 17 2022.rst
@@ -7,7 +7,7 @@ Generates Visual Studio 17 (VS 2022) project files.
.. warning::
- This is experimental and based on "Visual Studio 2022 Preview 2".
+ This is experimental and based on "Visual Studio 2022 Preview 3.1".
As of this version of CMake, VS 2022 has not been released.
Project Types
@@ -51,7 +51,7 @@ name (architecture). For example:
Toolset Selection
^^^^^^^^^^^^^^^^^
-The ``v143`` toolset that comes with VS 17 2022 Preview 2 is selected by
+The ``v143`` toolset that comes with VS 17 2022 Preview 3.1 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-env-variables.7.rst b/Help/manual/cmake-env-variables.7.rst
index 3db189e..0799fdd 100644
--- a/Help/manual/cmake-env-variables.7.rst
+++ b/Help/manual/cmake-env-variables.7.rst
@@ -38,6 +38,7 @@ Environment Variables that Control the Build
/envvar/CMAKE_GENERATOR_INSTANCE
/envvar/CMAKE_GENERATOR_PLATFORM
/envvar/CMAKE_GENERATOR_TOOLSET
+ /envvar/CMAKE_INSTALL_MODE
/envvar/CMAKE_LANG_COMPILER_LAUNCHER
/envvar/CMAKE_LANG_LINKER_LAUNCHER
/envvar/CMAKE_MSVCIDE_RUN_PATH
diff --git a/Help/manual/cmake-packages.7.rst b/Help/manual/cmake-packages.7.rst
index 5262105..5c109ff 100644
--- a/Help/manual/cmake-packages.7.rst
+++ b/Help/manual/cmake-packages.7.rst
@@ -449,7 +449,7 @@ be true. This can be tested with logic in the package configuration file:
set(_supported_components Plot Table)
foreach(_comp ${ClimbingStats_FIND_COMPONENTS})
- if (NOT ";${_supported_components};" MATCHES _comp)
+ if (NOT ";${_supported_components};" MATCHES ";${_comp};")
set(ClimbingStats_FOUND False)
set(ClimbingStats_NOT_FOUND_MESSAGE "Unsupported component: ${_comp}")
endif()
diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst
index b9e3d45..0f0c0ab 100644
--- a/Help/manual/cmake-policies.7.rst
+++ b/Help/manual/cmake-policies.7.rst
@@ -51,6 +51,14 @@ The :variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable may also be used
to determine whether to report an error on use of deprecated macros or
functions.
+Policies Introduced by CMake 3.22
+=================================
+
+.. toctree::
+ :maxdepth: 1
+
+ CMP0127: cmake_dependent_option() supports full Condition Syntax. </policy/CMP0127>
+
Policies Introduced by CMake 3.21
=================================
diff --git a/Help/policy/CMP0127.rst b/Help/policy/CMP0127.rst
new file mode 100644
index 0000000..8560bbf
--- /dev/null
+++ b/Help/policy/CMP0127.rst
@@ -0,0 +1,32 @@
+CMP0127
+-------
+
+:command:`cmake_dependent_option` supports full :ref:`Condition Syntax`.
+
+The ``<depends>`` parameter accepts a :ref:`semicolon-separated list <CMake
+Language Lists>` of conditions. CMake 3.21 and lower evaluates each
+``condition`` as ``if(${condition})``, which does not properly handle
+conditions with nested paren groups. CMake 3.22 and above instead prefer
+to evaluate each ``condition`` as ``if(<condition>)``, where ``<condition>``
+is re-parsed as if literally written in a call to :command:`if`. This
+allows expressions like::
+
+ "A AND (B OR C)"
+
+but requires expressions like::
+
+ "FOO MATCHES (UPPER|lower)"
+
+to be re-written as::
+
+ "FOO MATCHES \"(UPPER|lower)\""
+
+Policy ``CMP0127`` provides compatibility for projects that have not
+been updated to expect the new behavior.
+
+This policy was introduced in CMake version 3.22. CMake version
+|release| warns when the policy is not set and uses ``OLD`` behavior.
+Use the :command:`cmake_policy` command to set it to ``OLD`` or ``NEW``
+explicitly.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/prop_sf/VS_SETTINGS.rst b/Help/prop_sf/VS_SETTINGS.rst
index 322f5a6..871e36e 100644
--- a/Help/prop_sf/VS_SETTINGS.rst
+++ b/Help/prop_sf/VS_SETTINGS.rst
@@ -3,7 +3,12 @@ VS_SETTINGS
.. versionadded:: 3.18
-Set any item metadata on a non-built file.
+Set any item metadata on a file.
+
+.. versionadded:: 3.22
+
+ This property is honored for all source file types.
+ Previously it worked only for non-built files.
Takes a list of ``Key=Value`` pairs. Tells the Visual Studio generator to set
``Key`` to ``Value`` as item metadata on the file.
diff --git a/Help/prop_tgt/AUTOMOC.rst b/Help/prop_tgt/AUTOMOC.rst
index 52d96e0..ed8b262 100644
--- a/Help/prop_tgt/AUTOMOC.rst
+++ b/Help/prop_tgt/AUTOMOC.rst
@@ -4,9 +4,9 @@ AUTOMOC
Should the target be processed with auto-moc (for Qt projects).
:prop_tgt:`AUTOMOC` is a boolean specifying whether CMake will handle the Qt
-``moc`` preprocessor automatically, i.e. without having to use the
-:module:`QT4_WRAP_CPP() <FindQt4>` or ``QT5_WRAP_CPP()`` macro.
-Currently Qt4 and Qt5 are supported.
+``moc`` preprocessor automatically, i.e. without having to use commands like
+:module:`QT4_WRAP_CPP() <FindQt4>`, ``QT5_WRAP_CPP()``, etc.
+Currently, Qt versions 4 to 6 are supported.
This property is initialized by the value of the :variable:`CMAKE_AUTOMOC`
variable if it is set when a target is created.
@@ -148,10 +148,13 @@ Qt version detection
:prop_tgt:`AUTOMOC` enabled targets need to know the Qt major and minor
version they're working with. The major version usually is provided by the
-``INTERFACE_QT_MAJOR_VERSION`` property of the ``Qt[45]Core`` library,
+``INTERFACE_QT_MAJOR_VERSION`` property of the ``Qt[456]Core`` library,
that the target links to. To find the minor version, CMake builds a list of
available Qt versions from
+- ``Qt6Core_VERSION_MAJOR`` and ``Qt6Core_VERSION_MINOR`` variables
+ (usually set by ``find_package(Qt6...)``)
+- ``Qt6Core_VERSION_MAJOR`` and ``Qt6Core_VERSION_MINOR`` directory properties
- ``Qt5Core_VERSION_MAJOR`` and ``Qt5Core_VERSION_MINOR`` variables
(usually set by ``find_package(Qt5...)``)
- ``Qt5Core_VERSION_MAJOR`` and ``Qt5Core_VERSION_MINOR`` directory properties
@@ -167,13 +170,13 @@ version was found, an error is generated.
If ``INTERFACE_QT_MAJOR_VERSION`` is not a valid number, the first
entry in the list is taken.
-A ``find_package(Qt[45]...)`` call sets the ``QT/Qt5Core_VERSION_MAJOR/MINOR``
+A ``find_package(Qt[456]...)`` call sets the ``QT/Qt[56]Core_VERSION_MAJOR/MINOR``
variables. If the call is in a different context than the
:command:`add_executable` or :command:`add_library` call, e.g. in a function,
then the version variables might not be available to the :prop_tgt:`AUTOMOC`
enabled target.
In that case the version variables can be forwarded from the
-``find_package(Qt[45]...)`` calling context to the :command:`add_executable`
+``find_package(Qt[456]...)`` calling context to the :command:`add_executable`
or :command:`add_library` calling context as directory properties.
The following Qt5 example demonstrates the procedure.
diff --git a/Help/prop_tgt/AUTORCC.rst b/Help/prop_tgt/AUTORCC.rst
index 9a98f44..0a0c2a1 100644
--- a/Help/prop_tgt/AUTORCC.rst
+++ b/Help/prop_tgt/AUTORCC.rst
@@ -5,8 +5,8 @@ Should the target be processed with auto-rcc (for Qt projects).
:prop_tgt:`AUTORCC` is a boolean specifying whether CMake will handle
the Qt ``rcc`` code generator automatically, i.e. without having to use
-the :module:`QT4_ADD_RESOURCES() <FindQt4>` or ``QT5_ADD_RESOURCES()``
-macro. Currently Qt4 and Qt5 are supported.
+commands like :module:`QT4_ADD_RESOURCES() <FindQt4>`, ``QT5_ADD_RESOURCES()``,
+etc. Currently, Qt versions 4 to 6 are supported.
When this property is ``ON``, CMake will handle ``.qrc`` files added
as target sources at build time and invoke ``rcc`` accordingly.
diff --git a/Help/prop_tgt/AUTOUIC.rst b/Help/prop_tgt/AUTOUIC.rst
index cd24f5e..e0cea97 100644
--- a/Help/prop_tgt/AUTOUIC.rst
+++ b/Help/prop_tgt/AUTOUIC.rst
@@ -5,8 +5,8 @@ Should the target be processed with auto-uic (for Qt projects).
:prop_tgt:`AUTOUIC` is a boolean specifying whether CMake will handle
the Qt ``uic`` code generator automatically, i.e. without having to use
-the :module:`QT4_WRAP_UI() <FindQt4>` or ``QT5_WRAP_UI()`` macro. Currently
-Qt4 and Qt5 are supported.
+commands like :module:`QT4_WRAP_UI() <FindQt4>`, ``QT5_WRAP_UI()``, etc.
+Currently, Qt versions 4 to 6 are supported.
This property is initialized by the value of the :variable:`CMAKE_AUTOUIC`
variable if it is set when a target is created.
diff --git a/Help/release/3.21.rst b/Help/release/3.21.rst
index fc5d6ac..a5125ac 100644
--- a/Help/release/3.21.rst
+++ b/Help/release/3.21.rst
@@ -27,7 +27,7 @@ Generators
----------
* The :generator:`Visual Studio 17 2022` generator was added. This is
- experimental and based on "Visual Studio 2022 Preview 2" because this
+ experimental and based on "Visual Studio 2022 Preview 3.1" because this
version of VS has not been released.
* The :ref:`Makefile Generators` and the :generator:`Ninja` generator
@@ -310,3 +310,6 @@ Changes made since CMake 3.21.0 include the following.
* ``CUDA`` targets with :prop_tgt:`CUDA_SEPARABLE_COMPILATION` enabled are now
correctly generated in non-root directories.
+
+* The :generator:`Visual Studio 17 2022` generator is now based on
+ "Visual Studio 2022 Preview 3.1". Previously it was based on "Preview 2".
diff --git a/Help/release/dev/GoogleTest-gtest-filter.rst b/Help/release/dev/GoogleTest-gtest-filter.rst
new file mode 100644
index 0000000..48b97a7
--- /dev/null
+++ b/Help/release/dev/GoogleTest-gtest-filter.rst
@@ -0,0 +1,6 @@
+GoogleTest-gtest-filter
+-----------------------
+
+* The :module:`GoogleTest` module :command:`gtest_discover_tests`
+ function gained a ``TEST_FILTER`` option to filter tests using
+ ``--gtest_filter`` during test discovery.
diff --git a/Help/release/dev/cmake-install-mode-symlink.rst b/Help/release/dev/cmake-install-mode-symlink.rst
new file mode 100644
index 0000000..a5f75ca
--- /dev/null
+++ b/Help/release/dev/cmake-install-mode-symlink.rst
@@ -0,0 +1,16 @@
+cmake-install-mode-symlink
+--------------------------
+
+* The :envvar:`CMAKE_INSTALL_MODE` environment variable was added to
+ allow users to override the default file-copying behavior of
+ :command:`install` and :command:`file(INSTALL)` into creating
+ symbolic links. This can aid in lowering storage space requirements
+ and avoiding redundancy.
+
+* The :command:`file(INSTALL)` can now be affected / modified by the
+ :envvar:`CMAKE_INSTALL_MODE` environment variable causing installation
+ of symbolic links instead of copying of files.
+
+* The :command:`install` can now be affected / modified by the
+ :envvar:`CMAKE_INSTALL_MODE` environment variable causing installation
+ of symbolic links instead of copying of files.
diff --git a/Help/release/dev/cmake_dependent_option_policy.rst b/Help/release/dev/cmake_dependent_option_policy.rst
new file mode 100644
index 0000000..c131170
--- /dev/null
+++ b/Help/release/dev/cmake_dependent_option_policy.rst
@@ -0,0 +1,6 @@
+cmake_dependent_option_policy
+-----------------------------
+
+* The :module:`CMakeDependentOption` module :command:`cmake_dependent_option`
+ macro now supports full :ref:`Condition Syntax`.
+ See policy :policy:`CMP0127`.
diff --git a/Help/release/dev/ctest_memcheck-generate-test.xml.rst b/Help/release/dev/ctest_memcheck-generate-test.xml.rst
new file mode 100644
index 0000000..fac02d8
--- /dev/null
+++ b/Help/release/dev/ctest_memcheck-generate-test.xml.rst
@@ -0,0 +1,6 @@
+ctest_memcheck-generate-test.xml
+--------------------------------
+
+* The :command:`ctest_memcheck` command now also generates a
+ `DynamicAnalysis-Test.xml` file which may be used to submit test results to
+ CDash.
diff --git a/Help/release/dev/find-matlab-imported-targets.rst b/Help/release/dev/find-matlab-imported-targets.rst
new file mode 100644
index 0000000..33a93ff
--- /dev/null
+++ b/Help/release/dev/find-matlab-imported-targets.rst
@@ -0,0 +1,4 @@
+find-matlab-imported-targets
+----------------------------
+
+* The :module:`FindMatlab` module now provides imported targets.
diff --git a/Help/release/dev/os-release.rst b/Help/release/dev/os-release.rst
new file mode 100644
index 0000000..cce6aee
--- /dev/null
+++ b/Help/release/dev/os-release.rst
@@ -0,0 +1,6 @@
+os-release
+----------
+
+* The :command:`cmake_host_system_information` command query operating system
+ identification `variables <https://www.freedesktop.org/software/systemd/man/os-release.html>`_
+ from the :file:`/etc/os-release` file.
diff --git a/Help/release/dev/vs_settings.rst b/Help/release/dev/vs_settings.rst
new file mode 100644
index 0000000..64f3ced
--- /dev/null
+++ b/Help/release/dev/vs_settings.rst
@@ -0,0 +1,5 @@
+vs_settings
+-----------
+
+* The :prop_sf:`VS_SETTINGS` source file property is now supported for
+ all source file types. Previously it worked only for non-built sources.
diff --git a/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst b/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst
index e9e04be..081c4da 100644
--- a/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst
+++ b/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst
@@ -6,8 +6,20 @@ Implicit linker search path detected for language ``<LANG>``.
Compilers typically pass directories containing language runtime
libraries and default library search paths when they invoke a linker.
These paths are implicit linker search directories for the compiler's
-language. CMake automatically detects these directories for each
-language and reports the results in this variable.
+language. For each language enabled by the :command:`project` or
+:command:`enable_language` command, CMake automatically detects these
+directories and reports the results in this variable.
+
+When linking to a static library, CMake adds the implicit link directories
+from this variable for each language used in the static library (except
+the language whose compiler is used to drive linking). In the case of an
+imported static library, the :prop_tgt:`IMPORTED_LINK_INTERFACE_LANGUAGES`
+target property lists the languages whose implicit link information is
+needed. If any of the languages is not enabled, its value for the
+``CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES`` variable may instead be provided
+by the project. Or, a :variable:`toolchain file <CMAKE_TOOLCHAIN_FILE>`
+may set the variable to a value known for the specified toolchain. It will
+either be overridden when the language is enabled, or used as a fallback.
Some toolchains read implicit directories from an environment variable such as
``LIBRARY_PATH``. If using such an environment variable, keep its value
@@ -18,3 +30,5 @@ If policy :policy:`CMP0060` is not set to ``NEW``, then when a library in one
of these directories is given by full path to :command:`target_link_libraries`
CMake will generate the ``-l<name>`` form on link lines for historical
purposes.
+
+See also the :variable:`CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES` variable.
diff --git a/Help/variable/CMAKE_LANG_IMPLICIT_LINK_LIBRARIES.rst b/Help/variable/CMAKE_LANG_IMPLICIT_LINK_LIBRARIES.rst
index ec16477..0c25489 100644
--- a/Help/variable/CMAKE_LANG_IMPLICIT_LINK_LIBRARIES.rst
+++ b/Help/variable/CMAKE_LANG_IMPLICIT_LINK_LIBRARIES.rst
@@ -5,6 +5,20 @@ Implicit link libraries and flags detected for language ``<LANG>``.
Compilers typically pass language runtime library names and other
flags when they invoke a linker. These flags are implicit link
-options for the compiler's language. CMake automatically detects
-these libraries and flags for each language and reports the results in
-this variable.
+options for the compiler's language. For each language enabled
+by the :command:`project` or :command:`enable_language` command,
+CMake automatically detects these libraries and flags and reports
+the results in this variable.
+
+When linking to a static library, CMake adds the implicit link libraries and
+flags from this variable for each language used in the static library (except
+the language whose compiler is used to drive linking). In the case of an
+imported static library, the :prop_tgt:`IMPORTED_LINK_INTERFACE_LANGUAGES`
+target property lists the languages whose implicit link information is
+needed. If any of the languages is not enabled, its value for the
+``CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES`` variable may instead be provided
+by the project. Or, a :variable:`toolchain file <CMAKE_TOOLCHAIN_FILE>`
+may set the variable to a value known for the specified toolchain. It will
+either be overridden when the language is enabled, or used as a fallback.
+
+See also the :variable:`CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES` variable.
diff --git a/Modules/CMakeASM_MASMInformation.cmake b/Modules/CMakeASM_MASMInformation.cmake
index 6d1e174..656b75e 100644
--- a/Modules/CMakeASM_MASMInformation.cmake
+++ b/Modules/CMakeASM_MASMInformation.cmake
@@ -8,7 +8,7 @@ set(ASM_DIALECT "_MASM")
set(CMAKE_ASM${ASM_DIALECT}_SOURCE_FILE_EXTENSIONS asm)
-set(CMAKE_ASM${ASM_DIALECT}_COMPILE_OBJECT "<CMAKE_ASM${ASM_DIALECT}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> /c /Fo <OBJECT> <SOURCE>")
+set(CMAKE_ASM${ASM_DIALECT}_COMPILE_OBJECT "<CMAKE_ASM${ASM_DIALECT}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -c -Fo <OBJECT> <SOURCE>")
# The ASM_MASM compiler id for this compiler is "MSVC", so fill out the runtime library table.
set(CMAKE_ASM${ASM_DIALECT}_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreaded "")
diff --git a/Modules/CMakeDependentOption.cmake b/Modules/CMakeDependentOption.cmake
index 96855d2..b7c478f 100644
--- a/Modules/CMakeDependentOption.cmake
+++ b/Modules/CMakeDependentOption.cmake
@@ -10,44 +10,62 @@ Macro to provide an option dependent on other options.
This macro presents an option to the user only if a set of other
conditions are true.
-Usage:
+.. command:: cmake_dependent_option
-.. code-block:: cmake
+ .. code-block:: cmake
- cmake_dependent_option(<option> "<help_text>" <value> <depends> <force>)
+ cmake_dependent_option(<option> "<help_text>" <value> <depends> <force>)
-Where ``<option>`` is available to the user if ``<depends>`` is true. When
-``<option>`` is available, the given ``<help_text>`` and initial ``<value>``
-are used. If the ``<depends>`` condition is not true, ``<option>`` will not be
-presented and will always have the value given by ``<force>``. Any value set by
-the user is preserved for when the option is presented again. Each element in
-the fourth parameter is evaluated as an if-condition, so
-:ref:`Condition Syntax` can be used.
+ Makes ``<option>`` available to the user if ``<depends>`` is true. When
+ ``<option>`` is available, the given ``<help_text>`` and initial ``<value>``
+ are used. If the ``<depends>`` condition is not true, ``<option>`` will not be
+ presented and will always have the value given by ``<force>``. Any value set by
+ the user is preserved for when the option is presented again. In case ``<depends>``
+ is a :ref:`semicolon-separated list <CMake Language Lists>`, all elements must
+ be true in order to initialize ``<option>`` with ``<value>``.
Example invocation:
.. code-block:: cmake
- cmake_dependent_option(USE_FOO "Use Foo" ON
- "USE_BAR;NOT USE_ZOT" OFF)
+ cmake_dependent_option(USE_FOO "Use Foo" ON "USE_BAR;NOT USE_ZOT" OFF)
If ``USE_BAR`` is true and ``USE_ZOT`` is false, this provides an option called
``USE_FOO`` that defaults to ON. Otherwise, it sets ``USE_FOO`` to OFF and
hides the option from the user. If the status of ``USE_BAR`` or ``USE_ZOT``
ever changes, any value for the ``USE_FOO`` option is saved so that when the
option is re-enabled it retains its old value.
+
+.. versionadded:: 3.22
+
+ Full :ref:`Condition Syntax` is now supported. See policy :policy:`CMP0127`.
+
#]=======================================================================]
macro(CMAKE_DEPENDENT_OPTION option doc default depends force)
+ cmake_policy(GET CMP0127 _CDO_CMP0127
+ PARENT_SCOPE # undocumented, do not use outside of CMake
+ )
if(${option}_ISSET MATCHES "^${option}_ISSET$")
set(${option}_AVAILABLE 1)
- foreach(d ${depends})
- string(REGEX REPLACE " +" ";" CMAKE_DEPENDENT_OPTION_DEP "${d}")
- if(${CMAKE_DEPENDENT_OPTION_DEP})
- else()
- set(${option}_AVAILABLE 0)
- endif()
- endforeach()
+ if("x${_CDO_CMP0127}x" STREQUAL "xNEWx")
+ foreach(d ${depends})
+ cmake_language(EVAL CODE "
+ if (${d})
+ else()
+ set(${option}_AVAILABLE 0)
+ endif()"
+ )
+ endforeach()
+ else()
+ foreach(d ${depends})
+ string(REGEX REPLACE " +" ";" CMAKE_DEPENDENT_OPTION_DEP "${d}")
+ if(${CMAKE_DEPENDENT_OPTION_DEP})
+ else()
+ set(${option}_AVAILABLE 0)
+ endif()
+ endforeach()
+ endif()
if(${option}_AVAILABLE)
option(${option} "${doc}" "${default}")
set(${option} "${${option}}" CACHE BOOL "${doc}" FORCE)
@@ -61,4 +79,9 @@ macro(CMAKE_DEPENDENT_OPTION option doc default depends force)
else()
set(${option} "${${option}_ISSET}")
endif()
+ if("x${_CDO_CMP0127}x" STREQUAL "xx" AND "x${depends}x" MATCHES "[^A-Za-z0-9_; ]")
+ cmake_policy(GET_WARNING CMP0127 _CDO_CMP0127_WARNING)
+ message(AUTHOR_WARNING "${_CDO_CMP0127_WARNING}")
+ endif()
+ unset(_CDO_CMP0127)
endmacro()
diff --git a/Modules/CMakeDetermineASMCompiler.cmake b/Modules/CMakeDetermineASMCompiler.cmake
index e8b9db7..a1814b7 100644
--- a/Modules/CMakeDetermineASMCompiler.cmake
+++ b/Modules/CMakeDetermineASMCompiler.cmake
@@ -125,6 +125,7 @@ if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
include(CMakeDetermineCompilerId)
set(userflags)
CMAKE_DETERMINE_COMPILER_ID_VENDOR(ASM${ASM_DIALECT} "${userflags}")
+ set(_variant "")
if("x${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}" STREQUAL "xIAR")
# primary necessary to detect architecture, so the right archiver and linker can be picked
# eg. "IAR Assembler V8.10.1.12857/W32 for ARM" or "IAR Assembler V4.11.1.4666 for Renesas RX"
@@ -137,6 +138,19 @@ if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
if(_all_compileid_matches)
list(GET _all_compileid_matches "-1" CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID)
endif()
+ elseif("x${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}" STREQUAL "xClang")
+ # Test whether an MSVC-like command-line option works.
+ execute_process(COMMAND ${CMAKE_ASM${ASM_DIALECT}_COMPILER} -?
+ OUTPUT_VARIABLE _clang_output
+ ERROR_VARIABLE _clang_output
+ RESULT_VARIABLE _clang_result)
+ if(_clang_result EQUAL 0)
+ set(CMAKE_ASM${ASM_DIALECT}_COMPILER_FRONTEND_VARIANT "MSVC")
+ set(CMAKE_ASM${ASM_DIALECT}_SIMULATE_ID MSVC)
+ else()
+ set(CMAKE_ASM${ASM_DIALECT}_COMPILER_FRONTEND_VARIANT "GNU")
+ endif()
+ set(_variant " with ${CMAKE_ASM${ASM_DIALECT}_COMPILER_FRONTEND_VARIANT}-like command-line")
endif()
_cmake_find_compiler_sysroot(ASM${ASM_DIALECT})
@@ -144,6 +158,8 @@ if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
unset(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_OUTPUT)
unset(_all_compileid_matches)
unset(_compileid)
+ unset(_clang_result)
+ unset(_clang_output)
endif()
if(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
@@ -157,9 +173,10 @@ if(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
else()
set(_archid "")
endif()
- message(STATUS "The ASM${ASM_DIALECT} compiler identification is ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}${_archid}${_version}")
+ message(STATUS "The ASM${ASM_DIALECT} compiler identification is ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}${_archid}${_version}${_variant}")
unset(_archid)
unset(_version)
+ unset(_variant)
else()
message(STATUS "The ASM${ASM_DIALECT} compiler identification is unknown")
endif()
diff --git a/Modules/CMakeFindBinUtils.cmake b/Modules/CMakeFindBinUtils.cmake
index f139ff4..bb97f4a 100644
--- a/Modules/CMakeFindBinUtils.cmake
+++ b/Modules/CMakeFindBinUtils.cmake
@@ -33,7 +33,7 @@ function(__resolve_tool_path CMAKE_TOOL SEARCH_PATH DOCSTRING)
if(NOT _CMAKE_USER_TOOL_PATH)
# Find CMAKE_TOOL in the SEARCH_PATH directory by user-defined name.
- find_program(_CMAKE_TOOL_WITH_PATH NAMES ${${CMAKE_TOOL}} HINTS ${SEARCH_PATH})
+ find_program(_CMAKE_TOOL_WITH_PATH NAMES ${${CMAKE_TOOL}} HINTS ${SEARCH_PATH} NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH)
if(_CMAKE_TOOL_WITH_PATH)
# Overwrite CMAKE_TOOL with full path found in SEARCH_PATH.
@@ -165,9 +165,9 @@ else()
# Prepend toolchain-specific names.
if("${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ID}" STREQUAL Clang)
if("x${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_SIMULATE_ID}" STREQUAL "xMSVC")
- set(_CMAKE_LINKER_NAMES "lld-link")
+ list(PREPEND _CMAKE_LINKER_NAMES "lld-link")
else()
- set(_CMAKE_LINKER_NAMES "ld.lld")
+ list(PREPEND _CMAKE_LINKER_NAMES "ld.lld")
endif()
list(PREPEND _CMAKE_AR_NAMES "llvm-ar")
list(PREPEND _CMAKE_RANLIB_NAMES "llvm-ranlib")
@@ -202,7 +202,7 @@ foreach(_CMAKE_TOOL IN LISTS _CMAKE_TOOL_VARS)
endforeach()
list(REMOVE_DUPLICATES _CMAKE_${_CMAKE_TOOL}_FIND_NAMES)
- find_program(CMAKE_${_CMAKE_TOOL} NAMES ${_CMAKE_${_CMAKE_TOOL}_FIND_NAMES} HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
+ find_program(CMAKE_${_CMAKE_TOOL} NAMES ${_CMAKE_${_CMAKE_TOOL}_FIND_NAMES} HINTS ${_CMAKE_TOOLCHAIN_LOCATION} NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH)
unset(_CMAKE_${_CMAKE_TOOL}_FIND_NAMES)
endforeach()
@@ -212,7 +212,7 @@ endif()
if(CMAKE_PLATFORM_HAS_INSTALLNAME)
- find_program(CMAKE_INSTALL_NAME_TOOL NAMES ${_CMAKE_TOOLCHAIN_PREFIX}install_name_tool HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
+ find_program(CMAKE_INSTALL_NAME_TOOL NAMES ${_CMAKE_TOOLCHAIN_PREFIX}install_name_tool HINTS ${_CMAKE_TOOLCHAIN_LOCATION} NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH)
if(NOT CMAKE_INSTALL_NAME_TOOL)
message(FATAL_ERROR "Could not find install_name_tool, please check your installation.")
diff --git a/Modules/CMakeFindPackageMode.cmake b/Modules/CMakeFindPackageMode.cmake
index 815dfc9..726e2a2 100644
--- a/Modules/CMakeFindPackageMode.cmake
+++ b/Modules/CMakeFindPackageMode.cmake
@@ -78,7 +78,7 @@ if(UNIX)
# from the outside
if(NOT CMAKE_SIZEOF_VOID_P)
set(CMAKE_SIZEOF_VOID_P 4)
- if(EXISTS /usr/lib64)
+ if(EXISTS ${CMAKE_SYSROOT}/usr/lib64)
set(CMAKE_SIZEOF_VOID_P 8)
else()
# use the file utility to check whether itself is 64 bit:
diff --git a/Modules/CheckCXXSymbolExists.cmake b/Modules/CheckCXXSymbolExists.cmake
index b4da4fa..7b13c3a 100644
--- a/Modules/CheckCXXSymbolExists.cmake
+++ b/Modules/CheckCXXSymbolExists.cmake
@@ -25,7 +25,7 @@ Check if a symbol exists as a function, variable, or macro in ``C++``.
as a function or variable then the symbol must also be available for
linking. If the symbol is a type, enum value, or C++ template it will
not be recognized: consider using the :module:`CheckTypeSize`
- or :module:`CheckCXXSourceCompiles` module instead.
+ or :module:`CheckSourceCompiles` module instead.
.. note::
diff --git a/Modules/CheckFortranFunctionExists.cmake b/Modules/CheckFortranFunctionExists.cmake
index ad72e2f..8f1ca9d 100644
--- a/Modules/CheckFortranFunctionExists.cmake
+++ b/Modules/CheckFortranFunctionExists.cmake
@@ -20,6 +20,12 @@ Check if a Fortran function exists.
``<result>``
variable to store the result; will be created as an internal cache variable.
+.. note::
+
+ This command does not detect functions in Fortran modules. In general it is
+ recommended to use :module:`CheckSourceCompiles` instead to determine if a
+ Fortran function or subroutine is available.
+
The following variables may be set before calling this macro to modify
the way the check is run:
diff --git a/Modules/CheckLanguage.cmake b/Modules/CheckLanguage.cmake
index 928881c..559c103 100644
--- a/Modules/CheckLanguage.cmake
+++ b/Modules/CheckLanguage.cmake
@@ -36,6 +36,9 @@ Example:
include_guard(GLOBAL)
+cmake_policy(PUSH)
+cmake_policy(SET CMP0126 NEW)
+
macro(check_language lang)
if(NOT DEFINED CMAKE_${lang}_COMPILER)
set(_desc "Looking for a ${lang} compiler")
@@ -110,3 +113,5 @@ file(WRITE \"\${CMAKE_CURRENT_BINARY_DIR}/result.cmake\"
endif()
endmacro()
+
+cmake_policy(POP)
diff --git a/Modules/CheckSymbolExists.cmake b/Modules/CheckSymbolExists.cmake
index f8ca584..48ee3c4 100644
--- a/Modules/CheckSymbolExists.cmake
+++ b/Modules/CheckSymbolExists.cmake
@@ -24,7 +24,7 @@ available and assumed to work. If the header files declare the symbol
as a function or variable then the symbol must also be available for
linking (so intrinsics may not be detected).
If the symbol is a type, enum value, or intrinsic it will not be recognized
-(consider using :module:`CheckTypeSize` or :module:`CheckCSourceCompiles`).
+(consider using :module:`CheckTypeSize` or :module:`CheckSourceCompiles`).
If the check needs to be done in C++, consider using
:module:`CheckCXXSymbolExists` instead.
diff --git a/Modules/Compiler/ARMClang-C.cmake b/Modules/Compiler/ARMClang-C.cmake
index 0a64a8a..01c4cea 100644
--- a/Modules/Compiler/ARMClang-C.cmake
+++ b/Modules/Compiler/ARMClang-C.cmake
@@ -2,6 +2,14 @@ include(Compiler/Clang-C)
include(Compiler/ARMClang)
__compiler_armclang(C)
+if((NOT DEFINED CMAKE_DEPENDS_USE_COMPILER OR CMAKE_DEPENDS_USE_COMPILER)
+ AND CMAKE_GENERATOR MATCHES "Makefiles|WMake"
+ AND CMAKE_DEPFILE_FLAGS_C)
+ # dependencies are computed by the compiler itself
+ set(CMAKE_C_DEPFILE_FORMAT gcc)
+ set(CMAKE_C_DEPENDS_USE_COMPILER TRUE)
+endif()
+
set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c90")
set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu90")
set(CMAKE_C90_STANDARD__HAS_FULL_SUPPORT ON)
diff --git a/Modules/Compiler/ARMClang-CXX.cmake b/Modules/Compiler/ARMClang-CXX.cmake
index 5dfb401..045b783 100644
--- a/Modules/Compiler/ARMClang-CXX.cmake
+++ b/Modules/Compiler/ARMClang-CXX.cmake
@@ -1,3 +1,11 @@
include(Compiler/Clang-CXX)
include(Compiler/ARMClang)
__compiler_armclang(CXX)
+
+if((NOT DEFINED CMAKE_DEPENDS_USE_COMPILER OR CMAKE_DEPENDS_USE_COMPILER)
+ AND CMAKE_GENERATOR MATCHES "Makefiles|WMake"
+ AND CMAKE_DEPFILE_FLAGS_CXX)
+ # dependencies are computed by the compiler itself
+ set(CMAKE_CXX_DEPFILE_FORMAT gcc)
+ set(CMAKE_CXX_DEPENDS_USE_COMPILER TRUE)
+endif()
diff --git a/Modules/Compiler/Clang-C.cmake b/Modules/Compiler/Clang-C.cmake
index cf493d7..1b765ad 100644
--- a/Modules/Compiler/Clang-C.cmake
+++ b/Modules/Compiler/Clang-C.cmake
@@ -9,6 +9,7 @@ endif()
if("x${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "xMSVC")
set(CMAKE_C_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -TC)
set(CMAKE_C_CLANG_TIDY_DRIVER_MODE "cl")
+ set(CMAKE_C_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if((NOT DEFINED CMAKE_DEPENDS_USE_COMPILER OR CMAKE_DEPENDS_USE_COMPILER)
AND CMAKE_GENERATOR MATCHES "Makefiles|WMake"
AND CMAKE_DEPFILE_FLAGS_C)
diff --git a/Modules/Compiler/Clang-CXX.cmake b/Modules/Compiler/Clang-CXX.cmake
index 98828e0..84b05d7 100644
--- a/Modules/Compiler/Clang-CXX.cmake
+++ b/Modules/Compiler/Clang-CXX.cmake
@@ -22,6 +22,7 @@ endif()
if("x${CMAKE_CXX_COMPILER_FRONTEND_VARIANT}" STREQUAL "xMSVC")
set(CMAKE_CXX_CLANG_TIDY_DRIVER_MODE "cl")
+ set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if((NOT DEFINED CMAKE_DEPENDS_USE_COMPILER OR CMAKE_DEPENDS_USE_COMPILER)
AND CMAKE_GENERATOR MATCHES "Makefiles"
AND CMAKE_DEPFILE_FLAGS_CXX)
diff --git a/Modules/Compiler/Clang-FindBinUtils.cmake b/Modules/Compiler/Clang-FindBinUtils.cmake
index e6c469a..125ae78 100644
--- a/Modules/Compiler/Clang-FindBinUtils.cmake
+++ b/Modules/Compiler/Clang-FindBinUtils.cmake
@@ -28,6 +28,7 @@ find_program(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_AR NAMES
"${_CMAKE_TOOLCHAIN_PREFIX}llvm-ar-${__version_x}"
"${_CMAKE_TOOLCHAIN_PREFIX}llvm-ar"
HINTS ${__clang_hints}
+ NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
DOC "LLVM archiver"
)
mark_as_advanced(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_AR)
@@ -38,6 +39,7 @@ find_program(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_RANLIB NAMES
"${_CMAKE_TOOLCHAIN_PREFIX}llvm-ranlib-${__version_x}"
"${_CMAKE_TOOLCHAIN_PREFIX}llvm-ranlib"
HINTS ${__clang_hints}
+ NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
DOC "Generate index for LLVM archive"
)
mark_as_advanced(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_RANLIB)
diff --git a/Modules/Compiler/GNU-FindBinUtils.cmake b/Modules/Compiler/GNU-FindBinUtils.cmake
index 097fbf3..4dcdd53 100644
--- a/Modules/Compiler/GNU-FindBinUtils.cmake
+++ b/Modules/Compiler/GNU-FindBinUtils.cmake
@@ -20,6 +20,7 @@ find_program(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_AR NAMES
"${_CMAKE_TOOLCHAIN_PREFIX}gcc-ar-${__version_x}"
"${_CMAKE_TOOLCHAIN_PREFIX}gcc-ar${_CMAKE_COMPILER_SUFFIX}"
HINTS ${__gcc_hints}
+ NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
DOC "A wrapper around 'ar' adding the appropriate '--plugin' option for the GCC compiler"
)
mark_as_advanced(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_AR)
@@ -30,6 +31,7 @@ find_program(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_RANLIB NAMES
"${_CMAKE_TOOLCHAIN_PREFIX}gcc-ranlib-${__version_x}"
"${_CMAKE_TOOLCHAIN_PREFIX}gcc-ranlib${_CMAKE_COMPILER_SUFFIX}"
HINTS ${__gcc_hints}
+ NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH
DOC "A wrapper around 'ranlib' adding the appropriate '--plugin' option for the GCC compiler"
)
mark_as_advanced(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_RANLIB)
diff --git a/Modules/Compiler/Intel-C.cmake b/Modules/Compiler/Intel-C.cmake
index ead9069..9884b58 100644
--- a/Modules/Compiler/Intel-C.cmake
+++ b/Modules/Compiler/Intel-C.cmake
@@ -17,6 +17,7 @@ if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC")
set(CMAKE_C_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -TC)
set(CMAKE_C_CLANG_TIDY_DRIVER_MODE "cl")
+ set(CMAKE_C_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 16.0.0)
set(CMAKE_C11_STANDARD_COMPILE_OPTION "-Qstd=c11")
diff --git a/Modules/Compiler/Intel-CXX.cmake b/Modules/Compiler/Intel-CXX.cmake
index 37f339a..7c9cca9 100644
--- a/Modules/Compiler/Intel-CXX.cmake
+++ b/Modules/Compiler/Intel-CXX.cmake
@@ -16,6 +16,7 @@ endif()
if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
set(CMAKE_CXX_CLANG_TIDY_DRIVER_MODE "cl")
+ set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.0)
set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-Qstd=c++20")
diff --git a/Modules/Compiler/IntelLLVM-C.cmake b/Modules/Compiler/IntelLLVM-C.cmake
index d69d064..d7346f6 100644
--- a/Modules/Compiler/IntelLLVM-C.cmake
+++ b/Modules/Compiler/IntelLLVM-C.cmake
@@ -4,6 +4,7 @@ __compiler_intel_llvm(C)
if("x${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "xMSVC")
set(CMAKE_C_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -TC)
set(CMAKE_C_CLANG_TIDY_DRIVER_MODE "cl")
+ set(CMAKE_C_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if((NOT DEFINED CMAKE_DEPENDS_USE_COMPILER OR CMAKE_DEPENDS_USE_COMPILER)
AND CMAKE_GENERATOR MATCHES "Makefiles|WMake"
AND CMAKE_DEPFILE_FLAGS_C)
diff --git a/Modules/Compiler/IntelLLVM-CXX.cmake b/Modules/Compiler/IntelLLVM-CXX.cmake
index 9799888..cae1f11 100644
--- a/Modules/Compiler/IntelLLVM-CXX.cmake
+++ b/Modules/Compiler/IntelLLVM-CXX.cmake
@@ -4,6 +4,7 @@ __compiler_intel_llvm(CXX)
if("x${CMAKE_CXX_COMPILER_FRONTEND_VARIANT}" STREQUAL "xMSVC")
set(CMAKE_CXX_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -TP)
set(CMAKE_CXX_CLANG_TIDY_DRIVER_MODE "cl")
+ set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if((NOT DEFINED CMAKE_DEPENDS_USE_COMPILER OR CMAKE_DEPENDS_USE_COMPILER)
AND CMAKE_GENERATOR MATCHES "Makefiles|WMake"
AND CMAKE_DEPFILE_FLAGS_CXX)
diff --git a/Modules/Compiler/MSVC-C.cmake b/Modules/Compiler/MSVC-C.cmake
index 73cca36..4ba1eea 100644
--- a/Modules/Compiler/MSVC-C.cmake
+++ b/Modules/Compiler/MSVC-C.cmake
@@ -29,6 +29,7 @@ endif()
set(CMAKE_C_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -TC)
set(CMAKE_C_CLANG_TIDY_DRIVER_MODE "cl")
+set(CMAKE_C_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
# There are no C compiler modes so we hard-code the known compiler supported
# features. Override the default macro for this special case. Pretend that
diff --git a/Modules/Compiler/MSVC-CXX.cmake b/Modules/Compiler/MSVC-CXX.cmake
index 09fe851..9bb7722 100644
--- a/Modules/Compiler/MSVC-CXX.cmake
+++ b/Modules/Compiler/MSVC-CXX.cmake
@@ -4,6 +4,7 @@
include(Compiler/CMakeCommonCompilerMacros)
set(CMAKE_CXX_CLANG_TIDY_DRIVER_MODE "cl")
+set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE_DRIVER_MODE "cl")
if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND
CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) OR
diff --git a/Modules/Compiler/NVHPC-C.cmake b/Modules/Compiler/NVHPC-C.cmake
index 72c2656..e37aad5 100644
--- a/Modules/Compiler/NVHPC-C.cmake
+++ b/Modules/Compiler/NVHPC-C.cmake
@@ -4,4 +4,9 @@ include(Compiler/NVHPC)
# Needed so that we support `LANGUAGE` property correctly
set(CMAKE_C_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -x c)
+if(CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 20.11)
+ set(CMAKE_C17_STANDARD_COMPILE_OPTION -std=c17)
+ set(CMAKE_C17_EXTENSION_COMPILE_OPTION -std=gnu17)
+endif()
+
__compiler_nvhpc(C)
diff --git a/Modules/Compiler/NVHPC-CXX.cmake b/Modules/Compiler/NVHPC-CXX.cmake
index ac75b53..534e822 100644
--- a/Modules/Compiler/NVHPC-CXX.cmake
+++ b/Modules/Compiler/NVHPC-CXX.cmake
@@ -4,4 +4,9 @@ include(Compiler/NVHPC)
# Needed so that we support `LANGUAGE` property correctly
set(CMAKE_CXX_COMPILE_OPTIONS_EXPLICIT_LANGUAGE -x c++)
+if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 20.11)
+ set(CMAKE_CXX20_STANDARD_COMPILE_OPTION -std=c++20)
+ set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION -std=gnu++20)
+endif()
+
__compiler_nvhpc(CXX)
diff --git a/Modules/FetchContent.cmake b/Modules/FetchContent.cmake
index bd82a90..5ea8b2a 100644
--- a/Modules/FetchContent.cmake
+++ b/Modules/FetchContent.cmake
@@ -21,13 +21,14 @@ supported by the :module:`ExternalProject` module. Whereas
configure step to use the content in commands like :command:`add_subdirectory`,
:command:`include` or :command:`file` operations.
-Content population details would normally be defined separately from the
-command that performs the actual population. This separation ensures that
-all of the dependency details are defined before anything may try to use those
-details to populate content. This is particularly important in more complex
-project hierarchies where dependencies may be shared between multiple projects.
+Content population details should be defined separately from the command that
+performs the actual population. This separation ensures that all the
+dependency details are defined before anything might try to use them to
+populate content. This is particularly important in more complex project
+hierarchies where dependencies may be shared between multiple projects.
-The following shows a typical example of declaring content details:
+The following shows a typical example of declaring content details for some
+dependencies and then ensuring they are populated with a separate call:
.. code-block:: cmake
@@ -36,57 +37,67 @@ The following shows a typical example of declaring content details:
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
+ FetchContent_Declare(
+ myCompanyIcons
+ URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
+ URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
+ )
+
+ FetchContent_MakeAvailable(googletest secret_sauce)
+
+The :command:`FetchContent_MakeAvailable` command ensures the named
+dependencies have been populated, either by an earlier call or by populating
+them itself. When performing the population, it will also add them to the
+main build, if possible, so that the main build can use the populated
+projects' targets, etc. See the command's documentation for how these steps
+are performed.
+
+When using a hierarchical project arrangement, projects at higher levels in
+the hierarchy are able to override the declared details of content specified
+anywhere lower in the project hierarchy. The first details to be declared
+for a given dependency take precedence, regardless of where in the project
+hierarchy that occurs. Similarly, the first call that tries to populate a
+dependency "wins", with subsequent populations reusing the result of the
+first instead of repeating the population again.
+See the :ref:`Examples <fetch-content-examples>` which demonstrate
+this scenario.
-For most typical cases, populating the content can then be done with a single
-command like so:
+In some cases, the main project may need to have more precise control over
+the population, or it may be required to explicitly define the population
+steps in a way that cannot be captured by the declared details alone.
+For such situations, the lower level :command:`FetchContent_GetProperties` and
+:command:`FetchContent_Populate` commands can be used. These lack the richer
+features provided by :command:`FetchContent_MakeAvailable` though, so their
+direct use should be considered a last resort. The typical pattern of such
+custom steps looks like this:
.. code-block:: cmake
- FetchContent_MakeAvailable(googletest)
+ # NOTE: Where possible, prefer to use FetchContent_MakeAvailable()
+ # instead of custom logic like this
-The above command not only populates the content, it also adds it to the main
-build (if possible) so that the main build can use the populated project's
-targets, etc. In some cases, the main project may need to have more precise
-control over the population or may be required to explicitly define the
-population steps (e.g. if CMake versions earlier than 3.14 need to be
-supported). The typical pattern of such custom steps looks like this:
+ # Check if population has already been performed
+ FetchContent_GetProperties(depname)
+ if(NOT depname_POPULATED)
+ # Fetch the content using previously declared details
+ FetchContent_Populate(depname)
-.. code-block:: cmake
+ # Set custom variables, policies, etc.
+ # ...
- FetchContent_GetProperties(googletest)
- if(NOT googletest_POPULATED)
- FetchContent_Populate(googletest)
- add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
+ # Bring the populated content into the build
+ add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
endif()
-Regardless of which population method is used, when using the
-declare-populate pattern with a hierarchical project arrangement, projects at
-higher levels in the hierarchy are able to override the population details of
-content specified anywhere lower in the project hierarchy. The ability to
-detect whether content has already been populated ensures that even if
-multiple child projects want certain content to be available, the first one
-to populate it wins. The other child project can simply make use of the
-already available content instead of repeating the population for itself.
-See the :ref:`Examples <fetch-content-examples>` section which demonstrates
-this scenario.
-
The ``FetchContent`` module also supports defining and populating
content in a single call, with no check for whether the content has been
-populated elsewhere in the project already. This is a more low level
-operation and would not normally be the way the module is used, but it is
-sometimes useful as part of implementing some higher level feature or to
-populate some content in CMake's script mode.
-
-.. versionchanged:: 3.14
- ``FetchContent`` commands can access the terminal. This is necessary
- for password prompts and real-time progress displays to work.
+populated elsewhere already. This should not be done in projects, but may
+be appropriate for populating content in CMake's script mode.
+See :command:`FetchContent_Populate` for details.
Commands
^^^^^^^^
-Declaring Content Details
-"""""""""""""""""""""""""
-
.. command:: FetchContent_Declare
.. code-block:: cmake
@@ -94,7 +105,7 @@ Declaring Content Details
FetchContent_Declare(<name> <contentOptions>...)
The ``FetchContent_Declare()`` function records the options that describe
- how to populate the specified content, but if such details have already
+ how to populate the specified content. If such details have already
been recorded earlier in this project (regardless of where in the project
hierarchy), this and all later calls for the same content ``<name>`` are
ignored. This "first to record, wins" approach is what allows hierarchical
@@ -110,7 +121,7 @@ Declaring Content Details
projects needing that same content will use the same name, leading to
the content being populated multiple times.
- The ``<contentOptions>`` can be any of the download or update/patch options
+ The ``<contentOptions>`` can be any of the download, update or patch options
that the :command:`ExternalProject_Add` command understands. The configure,
build, install and test steps are explicitly disabled and therefore options
related to them will be ignored. The ``SOURCE_SUBDIR`` option is an
@@ -146,47 +157,88 @@ Declaring Content Details
than a branch or tag name. A commit hash is more secure and helps to
confirm that the downloaded contents are what you expected.
-Populating The Content
-""""""""""""""""""""""
+ .. versionchanged:: 3.14
+ Commands for the download, update or patch steps can access the terminal.
+ This may be needed for things like password prompts or real-time display
+ of command progress.
-For most common scenarios, population means making content available to the
-main build according to previously declared details for that dependency.
-There are two main patterns for populating content, one based on calling
-:command:`FetchContent_GetProperties` and
-:command:`FetchContent_Populate` for more precise control and the other on
-calling :command:`FetchContent_MakeAvailable` for a simpler, more automated
-approach. The former generally follows this canonical pattern:
+.. command:: FetchContent_MakeAvailable
-.. _`fetch-content-canonical-pattern`:
+ .. versionadded:: 3.14
-.. code-block:: cmake
+ .. code-block:: cmake
- # Check if population has already been performed
- FetchContent_GetProperties(<name>)
- string(TOLOWER "<name>" lcName)
- if(NOT ${lcName}_POPULATED)
- # Fetch the content using previously declared details
- FetchContent_Populate(<name>)
+ FetchContent_MakeAvailable(<name1> [<name2>...])
+
+ This command ensures that each of the named dependencies are populated and
+ potentially added to the build by the time it returns. It iterates over
+ the list, and for each dependency, the following logic is applied:
+
+ * If the dependency has already been populated earlier in this run, set
+ the ``<lowercaseName>_POPULATED``, ``<lowercaseName>_SOURCE_DIR`` and
+ ``<lowercaseName>_BINARY_DIR`` variables in the same way as a call to
+ :command:`FetchContent_GetProperties`, then skip the remaining steps
+ below and move on to the next dependency in the list.
+
+ * Call :command:`FetchContent_Populate` to populate the dependency using
+ the details recorded by an earlier call to :command:`FetchContent_Declare`.
+ Halt with a fatal error if no such details have been recorded.
+ :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>` can be used to override
+ the declared details and use content provided at the specified location
+ instead.
+
+ * If the top directory of the populated content contains a ``CMakeLists.txt``
+ file, call :command:`add_subdirectory` to add it to the main build.
+ It is not an error for there to be no ``CMakeLists.txt`` file, which
+ allows the command to be used for dependencies that make downloaded
+ content available at a known location, but which do not need or support
+ being added directly to the build.
+
+ .. versionadded:: 3.18
+ The ``SOURCE_SUBDIR`` option can be given in the declared details to
+ look somewhere below the top directory instead (i.e. the same way that
+ ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add`
+ command). The path provided with ``SOURCE_SUBDIR`` must be relative
+ and will be treated as relative to the top directory. It can also
+ point to a directory that does not contain a ``CMakeLists.txt`` file
+ or even to a directory that doesn't exist. This can be used to avoid
+ adding a project that contains a ``CMakeLists.txt`` file in its top
+ directory.
+
+ Projects should aim to declare the details of all dependencies they might
+ use before they call ``FetchContent_MakeAvailable()`` for any of them.
+ This ensures that if any of the dependencies are also sub-dependencies of
+ one or more of the others, the main project still controls the details
+ that will be used (because it will declare them first before the
+ dependencies get a chance to). In the following code samples, assume that
+ the ``uses_other`` dependency also uses ``FetchContent`` to add the ``other``
+ dependency internally:
- # Set custom variables, policies, etc.
- # ...
+ .. code-block:: cmake
- # Bring the populated content into the build
- add_subdirectory(${${lcName}_SOURCE_DIR} ${${lcName}_BINARY_DIR})
- endif()
+ # WRONG: Should declare all details first
+ FetchContent_Declare(uses_other ...)
+ FetchContent_MakeAvailable(uses_other)
+
+ FetchContent_Declare(other ...) # Will be ignored, uses_other beat us to it
+ FetchContent_MakeAvailable(other) # Would use details declared by uses_other
-The above is such a common pattern that, where no custom steps are needed
-between the calls to :command:`FetchContent_Populate` and
-:command:`add_subdirectory`, equivalent logic can be obtained by calling
-:command:`FetchContent_MakeAvailable` instead. Where it meets the needs of
-the project, :command:`FetchContent_MakeAvailable` should be preferred, as it
-is simpler and provides additional features over the pattern above.
+ .. code-block:: cmake
+
+ # CORRECT: All details declared first, so they will take priority
+ FetchContent_Declare(uses_other ...)
+ FetchContent_Declare(other ...)
+ FetchContent_MakeAvailable(uses_other other)
.. command:: FetchContent_Populate
+ .. note::
+ Where possible, prefer to use :command:`FetchContent_MakeAvailable`
+ instead of implementing population manually with this command.
+
.. code-block:: cmake
- FetchContent_Populate( <name> )
+ FetchContent_Populate(<name>)
In most cases, the only argument given to ``FetchContent_Populate()`` is the
``<name>``. When used this way, the command assumes the content details have
@@ -211,88 +263,29 @@ is simpler and provides additional features over the pattern above.
``FetchContent_Populate()``.
``FetchContent_Populate()`` will set three variables in the scope of the
- caller; ``<lcName>_POPULATED``, ``<lcName>_SOURCE_DIR`` and
- ``<lcName>_BINARY_DIR``, where ``<lcName>`` is the lowercased ``<name>``.
- ``<lcName>_POPULATED`` will always be set to ``True`` by the call.
- ``<lcName>_SOURCE_DIR`` is the location where the
- content can be found upon return (it will have already been populated), while
- ``<lcName>_BINARY_DIR`` is a directory intended for use as a corresponding
- build directory. The main use case for the two directory variables is to
- call :command:`add_subdirectory` immediately after population, i.e.:
+ caller:
+
+ ``<lowercaseName>_POPULATED``
+ This will always be set to ``TRUE`` by the call.
+
+ ``<lowercaseName>_SOURCE_DIR``
+ The location where the populated content can be found upon return.
+
+ ``<lowercaseName>_BINARY_DIR``
+ A directory intended for use as a corresponding build directory.
+
+ The main use case for the ``<lowercaseName>_SOURCE_DIR`` and
+ ``<lowercaseName>_BINARY_DIR`` variables is to call
+ :command:`add_subdirectory` immediately after population:
.. code-block:: cmake
- FetchContent_Populate(FooBar ...)
+ FetchContent_Populate(FooBar)
add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
The values of the three variables can also be retrieved from anywhere in the
project hierarchy using the :command:`FetchContent_GetProperties` command.
- A number of cache variables influence the behavior of all content population
- performed using details saved from a :command:`FetchContent_Declare` call:
-
- ``FETCHCONTENT_BASE_DIR``
- In most cases, the saved details do not specify any options relating to the
- directories to use for the internal sub-build, final source and build areas.
- It is generally best to leave these decisions up to the ``FetchContent``
- module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
- cache variable controls the point under which all content population
- directories are collected, but in most cases developers would not need to
- change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
- developers change this value, they should aim to keep the path short and
- just below the top level of the build tree to avoid running into path
- length problems on Windows.
-
- ``FETCHCONTENT_QUIET``
- The logging output during population can be quite verbose, making the
- configure stage quite noisy. This cache option (``ON`` by default) hides
- all population output unless an error is encountered. If experiencing
- problems with hung downloads, temporarily switching this option off may
- help diagnose which content population is causing the issue.
-
- ``FETCHCONTENT_FULLY_DISCONNECTED``
- When this option is enabled, no attempt is made to download or update
- any content. It is assumed that all content has already been populated in
- a previous run or the source directories have been pointed at existing
- contents the developer has provided manually (using options described
- further below). When the developer knows that no changes have been made to
- any content details, turning this option ``ON`` can significantly speed up
- the configure stage. It is ``OFF`` by default.
-
- ``FETCHCONTENT_UPDATES_DISCONNECTED``
- This is a less severe download/update control compared to
- ``FETCHCONTENT_FULLY_DISCONNECTED``. Instead of bypassing all download and
- update logic, the ``FETCHCONTENT_UPDATES_DISCONNECTED`` only disables the
- update stage. Therefore, if content has not been downloaded previously,
- it will still be downloaded when this option is enabled. This can speed up
- the configure stage, but not as much as
- ``FETCHCONTENT_FULLY_DISCONNECTED``. It is ``OFF`` by default.
-
- In addition to the above cache variables, the following cache variables are
- also defined for each content name (``<ucName>`` is the uppercased value of
- ``<name>``):
-
- ``FETCHCONTENT_SOURCE_DIR_<ucName>``
- If this is set, no download or update steps are performed for the specified
- content and the ``<lcName>_SOURCE_DIR`` variable returned to the caller is
- pointed at this location. This gives developers a way to have a separate
- checkout of the content that they can modify freely without interference
- from the build. The build simply uses that existing source, but it still
- defines ``<lcName>_BINARY_DIR`` to point inside its own build area.
- Developers are strongly encouraged to use this mechanism rather than
- editing the sources populated in the default location, as changes to
- sources in the default location can be lost when content population details
- are changed by the project.
-
- ``FETCHCONTENT_UPDATES_DISCONNECTED_<ucName>``
- This is the per-content equivalent of
- ``FETCHCONTENT_UPDATES_DISCONNECTED``. If the global option or this option
- is ``ON``, then updates will be disabled for the named content.
- Disabling updates for individual content can be useful for content whose
- details rarely change, while still leaving other frequently changing
- content with updates enabled.
-
-
The ``FetchContent_Populate()`` command also supports a syntax allowing the
content details to be specified directly rather than using any saved
details. This is more low-level and use of this form is generally to be
@@ -303,7 +296,8 @@ is simpler and provides additional features over the pattern above.
.. code-block:: cmake
- FetchContent_Populate( <name>
+ FetchContent_Populate(
+ <name>
[QUIET]
[SUBBUILD_DIR <subBuildDir>]
[SOURCE_DIR <srcDir>]
@@ -325,16 +319,17 @@ is simpler and provides additional features over the pattern above.
- The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
- The ``<lcName>_SOURCE_DIR`` and ``<lcName>_BINARY_DIR`` variables are still
- returned to the caller, but since these locations are not stored as global
- properties when this form is used, they are only available to the calling
- scope and below rather than the entire project hierarchy. No
- ``<lcName>_POPULATED`` variable is set in the caller's scope with this form.
+ The ``<lowercaseName>_SOURCE_DIR`` and ``<lowercaseName>_BINARY_DIR``
+ variables are still returned to the caller, but since these locations are
+ not stored as global properties when this form is used, they are only
+ available to the calling scope and below rather than the entire project
+ hierarchy. No ``<lowercaseName>_POPULATED`` variable is set in the caller's
+ scope with this form.
The supported options for ``FetchContent_Populate()`` are the same as those
for :command:`FetchContent_Declare()`. Those few options shown just
above are either specific to ``FetchContent_Populate()`` or their behavior is
- slightly modified from how :command:`ExternalProject_Add` treats them.
+ slightly modified from how :command:`ExternalProject_Add` treats them:
``QUIET``
The ``QUIET`` option can be given to hide the output associated with
@@ -347,9 +342,9 @@ is simpler and provides additional features over the pattern above.
``SUBBUILD_DIR``
The ``SUBBUILD_DIR`` argument can be provided to change the location of the
sub-build created to perform the population. The default value is
- ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-subbuild`` and it would be unusual
- to need to override this default. If a relative path is specified, it will
- be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
+ ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild`` and it would be
+ unusual to need to override this default. If a relative path is specified,
+ it will be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
This option should not be confused with the ``SOURCE_SUBDIR`` option which
only affects the :command:`FetchContent_MakeAvailable` command.
@@ -357,9 +352,9 @@ is simpler and provides additional features over the pattern above.
The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
:command:`ExternalProject_Add`, but different default values are used by
``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
- ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-src`` and ``BINARY_DIR`` defaults to
- ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-build``. If a relative path is
- specified, it will be interpreted as relative to
+ ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src`` and ``BINARY_DIR``
+ defaults to ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build``.
+ If a relative path is specified, it will be interpreted as relative to
:variable:`CMAKE_CURRENT_BINARY_DIR`.
In addition to the above explicit options, any other unrecognized options are
@@ -380,11 +375,12 @@ is simpler and provides additional features over the pattern above.
on the command line invoking the script.
.. versionadded:: 3.18
- Added support for ``DOWNLOAD_NO_EXTRACT`` and ``SOURCE_SUBDIR`` options.
+ Added support for the ``DOWNLOAD_NO_EXTRACT`` option.
.. command:: FetchContent_GetProperties
- When using saved content details, a call to :command:`FetchContent_Populate`
+ When using saved content details, a call to
+ :command:`FetchContent_MakeAvailable` or :command:`FetchContent_Populate`
records information in global properties which can be queried at any time.
This information includes the source and binary directories associated with
the content and also whether or not the content population has been processed
@@ -392,7 +388,8 @@ is simpler and provides additional features over the pattern above.
.. code-block:: cmake
- FetchContent_GetProperties( <name>
+ FetchContent_GetProperties(
+ <name>
[SOURCE_DIR <srcDirVar>]
[BINARY_DIR <binDirVar>]
[POPULATED <doneVar>]
@@ -403,49 +400,104 @@ is simpler and provides additional features over the pattern above.
which is the name of the variable in which to store that property. Most of
the time though, only ``<name>`` is given, in which case the call will then
set the same variables as a call to
- :command:`FetchContent_Populate(name) <FetchContent_Populate>`. This allows
- the following canonical pattern to be used, which ensures that the relevant
- variables will always be defined regardless of whether or not the population
- has been performed elsewhere in the project already:
-
- .. code-block:: cmake
-
- FetchContent_GetProperties(foobar)
- if(NOT foobar_POPULATED)
- FetchContent_Populate(foobar)
- ...
- endif()
+ :command:`FetchContent_MakeAvailable(name) <FetchContent_MakeAvailable>` or
+ :command:`FetchContent_Populate(name) <FetchContent_Populate>`.
- The above pattern allows other parts of the overall project hierarchy to
- re-use the same content and ensure that it is only populated once.
-
-
-.. command:: FetchContent_MakeAvailable
+ This command is rarely needed when using
+ :command:`FetchContent_MakeAvailable`. It is more commonly used as part of
+ implementing the following pattern with :command:`FetchContent_Populate`,
+ which ensures that the relevant variables will always be defined regardless
+ of whether or not the population has been performed elsewhere in the project
+ already:
.. code-block:: cmake
- FetchContent_MakeAvailable( <name1> [<name2>...] )
+ # Check if population has already been performed
+ FetchContent_GetProperties(depname)
+ if(NOT depname_POPULATED)
+ # Fetch the content using previously declared details
+ FetchContent_Populate(depname)
- .. versionadded:: 3.14
+ # Set custom variables, policies, etc.
+ # ...
- This command implements the common pattern typically needed for most
- dependencies. It iterates over each of the named dependencies in turn
- and for each one it loosely follows the
- :ref:`canonical pattern <fetch-content-canonical-pattern>` as
- presented at the beginning of this section. An important difference is
- that :command:`add_subdirectory` will only be called on the
- populated content if there is a ``CMakeLists.txt`` file in its top level
- source directory. This allows the command to be used for dependencies
- that make downloaded content available at a known location but which do
- not need or support being added directly to the build.
-
- The ``SOURCE_SUBDIR`` option can be given in the declared details to
- instruct ``FetchContent_MakeAvailable()`` to look for a ``CMakeLists.txt``
- file in a subdirectory below the top level (i.e. the same way that
- ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add` command).
- ``SOURCE_SUBDIR`` must always be a relative path. See the next section
- for an example of this option.
+ # Bring the populated content into the build
+ add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
+ endif()
+Variables
+^^^^^^^^^
+
+A number of cache variables can influence the behavior where details from a
+:command:`FetchContent_Declare` call are used to populate content.
+The variables are all intended for the developer to customize behavior and
+should not normally be set by the project.
+
+.. variable:: FETCHCONTENT_BASE_DIR
+
+ In most cases, the saved details do not specify any options relating to the
+ directories to use for the internal sub-build, final source and build areas.
+ It is generally best to leave these decisions up to the ``FetchContent``
+ module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
+ cache variable controls the point under which all content population
+ directories are collected, but in most cases, developers would not need to
+ change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
+ developers change this value, they should aim to keep the path short and
+ just below the top level of the build tree to avoid running into path
+ length problems on Windows.
+
+.. variable:: FETCHCONTENT_QUIET
+
+ The logging output during population can be quite verbose, making the
+ configure stage quite noisy. This cache option (``ON`` by default) hides
+ all population output unless an error is encountered. If experiencing
+ problems with hung downloads, temporarily switching this option off may
+ help diagnose which content population is causing the issue.
+
+.. variable:: FETCHCONTENT_FULLY_DISCONNECTED
+
+ When this option is enabled, no attempt is made to download or update
+ any content. It is assumed that all content has already been populated in
+ a previous run or the source directories have been pointed at existing
+ contents the developer has provided manually (using options described
+ further below). When the developer knows that no changes have been made to
+ any content details, turning this option ``ON`` can significantly speed up
+ the configure stage. It is ``OFF`` by default.
+
+.. variable:: FETCHCONTENT_UPDATES_DISCONNECTED
+
+ This is a less severe download/update control compared to
+ :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. Instead of bypassing all
+ download and update logic, ``FETCHCONTENT_UPDATES_DISCONNECTED`` only
+ disables the update stage. Therefore, if content has not been downloaded
+ previously, it will still be downloaded when this option is enabled.
+ This can speed up the configure stage, but not as much as
+ :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. It is ``OFF`` by default.
+
+In addition to the above cache variables, the following cache variables are
+also defined for each content name:
+
+.. variable:: FETCHCONTENT_SOURCE_DIR_<uppercaseName>
+
+ If this is set, no download or update steps are performed for the specified
+ content and the ``<lowercaseName>_SOURCE_DIR`` variable returned to the
+ caller is pointed at this location. This gives developers a way to have a
+ separate checkout of the content that they can modify freely without
+ interference from the build. The build simply uses that existing source,
+ but it still defines ``<lowercaseName>_BINARY_DIR`` to point inside its own
+ build area. Developers are strongly encouraged to use this mechanism rather
+ than editing the sources populated in the default location, as changes to
+ sources in the default location can be lost when content population details
+ are changed by the project.
+
+.. variable:: FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>
+
+ This is the per-content equivalent of
+ :variable:`FETCHCONTENT_UPDATES_DISCONNECTED`. If the global option or
+ this option is ``ON``, then updates will be disabled for the named content.
+ Disabling updates for individual content can be useful for content whose
+ details rarely change, while still leaving other frequently changing content
+ with updates enabled.
.. _`fetch-content-examples`:
@@ -470,7 +522,7 @@ frameworks are available to the main build:
)
# After the following call, the CMake targets defined by googletest and
- # Catch2 will be defined and available to the rest of the build
+ # Catch2 will be available to the rest of the build
FetchContent_MakeAvailable(googletest Catch2)
If the sub-project's ``CMakeLists.txt`` file is not at the top level of its
diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake
index f7605c4..38faca2 100644
--- a/Modules/FindBoost.cmake
+++ b/Modules/FindBoost.cmake
@@ -1335,7 +1335,7 @@ function(_Boost_COMPONENT_DEPENDENCIES component _ret)
set(_Boost_TIMER_DEPENDENCIES chrono)
set(_Boost_WAVE_DEPENDENCIES filesystem serialization thread chrono date_time atomic)
set(_Boost_WSERIALIZATION_DEPENDENCIES serialization)
- else()
+ elseif(Boost_VERSION_STRING VERSION_LESS 1.77.0)
set(_Boost_CONTRACT_DEPENDENCIES thread chrono date_time)
set(_Boost_COROUTINE_DEPENDENCIES context)
set(_Boost_FIBER_DEPENDENCIES context)
@@ -1350,7 +1350,22 @@ function(_Boost_COMPONENT_DEPENDENCIES component _ret)
set(_Boost_TIMER_DEPENDENCIES chrono)
set(_Boost_WAVE_DEPENDENCIES filesystem serialization thread chrono date_time atomic)
set(_Boost_WSERIALIZATION_DEPENDENCIES serialization)
- if(Boost_VERSION_STRING VERSION_GREATER_EQUAL 1.77.0 AND NOT Boost_NO_WARN_NEW_VERSIONS)
+ else()
+ set(_Boost_CONTRACT_DEPENDENCIES thread chrono)
+ set(_Boost_COROUTINE_DEPENDENCIES context)
+ set(_Boost_FIBER_DEPENDENCIES context)
+ set(_Boost_IOSTREAMS_DEPENDENCIES regex)
+ set(_Boost_JSON_DEPENDENCIES container)
+ set(_Boost_LOG_DEPENDENCIES date_time log_setup filesystem thread regex chrono atomic)
+ set(_Boost_MATH_DEPENDENCIES math_c99 math_c99f math_c99l math_tr1 math_tr1f math_tr1l)
+ set(_Boost_MPI_DEPENDENCIES serialization)
+ set(_Boost_MPI_PYTHON_DEPENDENCIES python${component_python_version} mpi serialization)
+ set(_Boost_NUMPY_DEPENDENCIES python${component_python_version})
+ set(_Boost_THREAD_DEPENDENCIES chrono atomic)
+ set(_Boost_TIMER_DEPENDENCIES chrono)
+ set(_Boost_WAVE_DEPENDENCIES filesystem serialization thread chrono atomic)
+ set(_Boost_WSERIALIZATION_DEPENDENCIES serialization)
+ if(Boost_VERSION_STRING VERSION_GREATER_EQUAL 1.78.0 AND NOT Boost_NO_WARN_NEW_VERSIONS)
message(WARNING "New Boost version may have incorrect or missing dependencies and imported targets")
endif()
endif()
@@ -1623,7 +1638,7 @@ else()
# _Boost_COMPONENT_HEADERS. See the instructions at the top of
# _Boost_COMPONENT_DEPENDENCIES.
set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS}
- "1.76.0" "1.76" "1.75.0" "1.75" "1.74.0" "1.74"
+ "1.77.0" "1.77" "1.76.0" "1.76" "1.75.0" "1.75" "1.74.0" "1.74"
"1.73.0" "1.73" "1.72.0" "1.72" "1.71.0" "1.71" "1.70.0" "1.70" "1.69.0" "1.69"
"1.68.0" "1.68" "1.67.0" "1.67" "1.66.0" "1.66" "1.65.1" "1.65.0" "1.65"
"1.64.0" "1.64" "1.63.0" "1.63" "1.62.0" "1.62" "1.61.0" "1.61" "1.60.0" "1.60"
diff --git a/Modules/FindICU.cmake b/Modules/FindICU.cmake
index 2bb49ad..1bae825 100644
--- a/Modules/FindICU.cmake
+++ b/Modules/FindICU.cmake
@@ -172,7 +172,7 @@ function(_ICU_FIND)
DOC "ICU ${program} executable"
NO_PACKAGE_ROOT_PATH
)
- mark_as_advanced(cache_var)
+ mark_as_advanced("${cache_var}")
set("${program_var}" "${${cache_var}}" PARENT_SCOPE)
endforeach()
@@ -301,7 +301,7 @@ function(_ICU_FIND)
HINTS ${icu_roots}
PATH_SUFFIXES ${icu_data_suffixes}
DOC "ICU ${data} data file")
- mark_as_advanced(cache_var)
+ mark_as_advanced("${cache_var}")
set("${data_var}" "${${cache_var}}" PARENT_SCOPE)
endforeach()
diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake
index f64c4b8..d4b4a34 100644
--- a/Modules/FindMPI.cmake
+++ b/Modules/FindMPI.cmake
@@ -649,7 +649,8 @@ function (_MPI_interrogate_compiler LANG)
# we won't match the accompanying --param-ssp-size and -Wp,-D_FORTIFY_SOURCE flags and therefore
# produce inconsistent results with the regularly flags.
# Similarly, aliasing flags do not belong into our flag array.
- if(NOT "${_MPI_COMPILE_OPTION}" MATCHES "^-f((no-|)(stack-protector|strict-aliasing)|PI[CE]|pi[ce])")
+ # Also strip out `-framework` flags.
+ if(NOT "${_MPI_COMPILE_OPTION}" MATCHES "^-f((no-|)(stack-protector|strict-aliasing)|PI[CE]|pi[ce]|ramework)")
list(APPEND MPI_COMPILE_OPTIONS_WORK "${_MPI_COMPILE_OPTION}")
endif()
endforeach()
diff --git a/Modules/FindMatlab.cmake b/Modules/FindMatlab.cmake
index c8df670..12a5fde 100644
--- a/Modules/FindMatlab.cmake
+++ b/Modules/FindMatlab.cmake
@@ -93,6 +93,33 @@ behavior:
additional versions of Matlab for the automatic retrieval of the installed
versions.
+Imported targets
+^^^^^^^^^^^^^^^^
+
+.. versionadded:: 3.22
+
+This module defines the following :prop_tgt:`IMPORTED` targets:
+
+``Matlab::mex``
+ The ``mex`` library, always available.
+
+``Matlab::mx``
+ The mx library of Matlab (arrays), always available.
+
+``Matlab::eng``
+ Matlab engine library. Available only if the ``ENG_LIBRARY`` component
+ is requested.
+
+``Matlab::mat``
+ Matlab matrix library. Available only if the ``MAT_LIBRARY`` component
+ is requested.
+
+``Matlab::MatlabEngine``
+ Matlab C++ engine library, always available for R2018a and newer.
+
+``Matlab::MatlabDataArray``
+ Matlab C++ data array library, always available for R2018a and newer.
+
Variables defined by the module
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -1865,6 +1892,32 @@ if(Matlab_DATAARRAY_LIBRARY)
list(APPEND Matlab_LIBRARIES ${Matlab_DATAARRAY_LIBRARY})
endif()
+# internal
+# This small stub permits to add imported targets for the found MATLAB libraries
+function(_Matlab_add_imported_target _matlab_library_variable_name _matlab_library_target_name)
+ if(Matlab_${_matlab_library_variable_name}_LIBRARY)
+ if(NOT TARGET Matlab::${_matlab_library_target_name})
+ add_library(Matlab::${_matlab_library_target_name} UNKNOWN IMPORTED)
+ set_target_properties(Matlab::${_matlab_library_target_name} PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${Matlab_INCLUDE_DIRS}"
+ IMPORTED_LOCATION "${Matlab_${_matlab_library_variable_name}_LIBRARY}")
+ if(_matlab_library_target_name STREQUAL "mex" OR
+ _matlab_library_target_name STREQUAL "eng" OR
+ _matlab_library_target_name STREQUAL "mat")
+ set_target_properties(Matlab::${_matlab_library_target_name} PROPERTIES
+ INTERFACE_LINK_LIBRARIES Matlab::mx)
+ endif()
+ endif()
+ endif()
+endfunction()
+
+_Matlab_add_imported_target(MX mx)
+_Matlab_add_imported_target(MEX mex)
+_Matlab_add_imported_target(ENG eng)
+_Matlab_add_imported_target(MAT mat)
+_Matlab_add_imported_target(ENGINE MatlabEngine)
+_Matlab_add_imported_target(DATAARRAY MatlabDataArray)
+
find_package_handle_standard_args(
Matlab
FOUND_VAR Matlab_FOUND
diff --git a/Modules/FindPkgConfig.cmake b/Modules/FindPkgConfig.cmake
index a28f6bc..4de5331 100644
--- a/Modules/FindPkgConfig.cmake
+++ b/Modules/FindPkgConfig.cmake
@@ -97,10 +97,18 @@ set(PKG_CONFIG_FOUND "${PKGCONFIG_FOUND}")
# Unsets the given variables
macro(_pkgconfig_unset var)
+ # Clear normal variable (possibly set by project code).
+ unset(${var})
+ # Store as cache variable.
+ # FIXME: Add a policy to switch to a normal variable.
set(${var} "" CACHE INTERNAL "")
endmacro()
macro(_pkgconfig_set var value)
+ # Clear normal variable (possibly set by project code).
+ unset(${var})
+ # Store as cache variable.
+ # FIXME: Add a policy to switch to a normal variable.
set(${var} ${value} CACHE INTERNAL "")
endmacro()
diff --git a/Modules/FindPython/Support.cmake b/Modules/FindPython/Support.cmake
index 8e70e11..ce25cfc 100644
--- a/Modules/FindPython/Support.cmake
+++ b/Modules/FindPython/Support.cmake
@@ -98,6 +98,7 @@ macro (_PYTHON_FIND_FRAMEWORKS)
${_pff_CMAKE_FRAMEWORK_PATH}
~/Library/Frameworks
/usr/local/Frameworks
+ /opt/homebrew/Frameworks
${CMAKE_SYSTEM_FRAMEWORK_PATH})
list (REMOVE_DUPLICATES _pff_frameworks)
foreach (_pff_implementation IN LISTS _${_PYTHON_PREFIX}_FIND_IMPLEMENTATIONS)
diff --git a/Modules/FindThreads.cmake b/Modules/FindThreads.cmake
index c6a3451..e4d6cf3 100644
--- a/Modules/FindThreads.cmake
+++ b/Modules/FindThreads.cmake
@@ -106,7 +106,7 @@ endmacro()
# Do NOT even think about using it outside of this file!
macro(_check_pthreads_flag)
if(NOT Threads_FOUND)
- # If we did not found -lpthread, -lpthread, or -lthread, look for -pthread
+ # If we did not find -lpthreads, -lpthread, or -lthread, look for -pthread
if(NOT DEFINED THREADS_HAVE_PTHREAD_ARG)
message(CHECK_START "Check if compiler accepts -pthread")
if(CMAKE_C_COMPILER_LOADED)
diff --git a/Modules/GNUInstallDirs.cmake b/Modules/GNUInstallDirs.cmake
index d81033c..1b9cfce 100644
--- a/Modules/GNUInstallDirs.cmake
+++ b/Modules/GNUInstallDirs.cmake
@@ -216,6 +216,7 @@ if(NOT DEFINED CMAKE_INSTALL_LIBDIR OR (_libdir_set
# Override this default 'lib' with 'lib64' iff:
# - we are on Linux system but NOT cross-compiling
# - we are NOT on debian
+ # - we are NOT building for conda
# - we are on a 64 bits system
# reason is: amd64 ABI: https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI
# For Debian with multiarch, use 'lib/${CMAKE_LIBRARY_ARCHITECTURE}' if
@@ -237,11 +238,34 @@ if(NOT DEFINED CMAKE_INSTALL_LIBDIR OR (_libdir_set
"Unable to determine default CMAKE_INSTALL_LIBDIR directory because no target architecture is known. "
"Please enable at least one language before including GNUInstallDirs.")
endif()
+
if(CMAKE_SYSTEM_NAME MATCHES "^(Linux|kFreeBSD|GNU)$"
- AND NOT CMAKE_CROSSCOMPILING
- AND NOT EXISTS "/etc/alpine-release"
- AND NOT EXISTS "/etc/arch-release")
- if (EXISTS "/etc/debian_version") # is this a debian system ?
+ AND NOT CMAKE_CROSSCOMPILING)
+ unset(__system_type_for_install)
+ if(DEFINED ENV{CONDA_BUILD} AND DEFINED ENV{PREFIX})
+ set(conda_prefix "$ENV{PREFIX}")
+ cmake_path(ABSOLUTE_PATH conda_prefix NORMALIZE)
+ if("${CMAKE_INSTALL_PREFIX}" STREQUAL conda_prefix)
+ set(__system_type_for_install "conda")
+ endif()
+ elseif(DEFINED ENV{CONDA_PREFIX})
+ set(conda_prefix "$ENV{CONDA_PREFIX}")
+ cmake_path(ABSOLUTE_PATH conda_prefix NORMALIZE)
+ if("${CMAKE_INSTALL_PREFIX}" STREQUAL conda_prefix)
+ set(__system_type_for_install "conda")
+ endif()
+ endif()
+ if(NOT __system_type_for_install)
+ if (EXISTS "/etc/alpine-release")
+ set(__system_type_for_install "alpine")
+ elseif (EXISTS "/etc/arch-release")
+ set(__system_type_for_install "arch linux")
+ elseif (EXISTS "/etc/debian_version")
+ set(__system_type_for_install "debian")
+ endif()
+ endif()
+
+ if(__system_type_for_install STREQUAL "debian")
if(CMAKE_LIBRARY_ARCHITECTURE)
if("${CMAKE_INSTALL_PREFIX}" MATCHES "^/usr/?$")
set(_LIBDIR_DEFAULT "lib/${CMAKE_LIBRARY_ARCHITECTURE}")
@@ -251,7 +275,8 @@ if(NOT DEFINED CMAKE_INSTALL_LIBDIR OR (_libdir_set
set(__LAST_LIBDIR_DEFAULT "lib/${CMAKE_LIBRARY_ARCHITECTURE}")
endif()
endif()
- else() # not debian, rely on CMAKE_SIZEOF_VOID_P:
+ elseif(NOT DEFINED __system_type_for_install)
+ # not debian, alpine, arch, or conda so rely on CMAKE_SIZEOF_VOID_P:
if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
set(_LIBDIR_DEFAULT "lib64")
if(DEFINED _GNUInstallDirs_LAST_CMAKE_INSTALL_PREFIX)
@@ -260,6 +285,8 @@ if(NOT DEFINED CMAKE_INSTALL_LIBDIR OR (_libdir_set
endif()
endif()
endif()
+ unset(__system_type_for_install)
+
if(NOT DEFINED CMAKE_INSTALL_LIBDIR)
set(CMAKE_INSTALL_LIBDIR "${_LIBDIR_DEFAULT}" CACHE PATH "Object code libraries (${_LIBDIR_DEFAULT})")
elseif(DEFINED __LAST_LIBDIR_DEFAULT
@@ -350,7 +377,7 @@ mark_as_advanced(
macro(GNUInstallDirs_get_absolute_install_dir absvar var)
set(GGAID_extra_args ${ARGN})
list(LENGTH GGAID_extra_args GGAID_extra_arg_count)
- if(GGAID_extra_arg_count GREATER 0)
+ if(GGAID_extra_arg_count GREATER "0")
list(GET GGAID_extra_args 0 GGAID_dir)
else()
# Historical behavior: use ${dir} from caller's scope
diff --git a/Modules/GoogleTest.cmake b/Modules/GoogleTest.cmake
index 80d8e23..a483c03 100644
--- a/Modules/GoogleTest.cmake
+++ b/Modules/GoogleTest.cmake
@@ -151,6 +151,7 @@ same as the Google Test name (i.e. ``suite.testcase``); see also
[WORKING_DIRECTORY dir]
[TEST_PREFIX prefix]
[TEST_SUFFIX suffix]
+ [TEST_FILTER expr]
[NO_PRETTY_TYPES] [NO_PRETTY_VALUES]
[PROPERTIES name1 value1...]
[TEST_LIST var]
@@ -204,6 +205,12 @@ same as the Google Test name (i.e. ``suite.testcase``); see also
every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
be specified.
+ ``TEST_FILTER expr``
+ .. versionadded:: 3.22
+
+ Filter expression to pass to ``--gtest_filter`` argument during test
+ discovery.
+
``NO_PRETTY_TYPES``
By default, the type index of type-parameterized tests is replaced by the
actual type name in the CTest test name. If this behavior is undesirable
@@ -411,7 +418,7 @@ function(gtest_discover_tests TARGET)
""
"NO_PRETTY_TYPES;NO_PRETTY_VALUES"
"TEST_PREFIX;TEST_SUFFIX;WORKING_DIRECTORY;TEST_LIST;DISCOVERY_TIMEOUT;XML_OUTPUT_DIR;DISCOVERY_MODE"
- "EXTRA_ARGS;PROPERTIES"
+ "EXTRA_ARGS;PROPERTIES;TEST_FILTER"
${ARGN}
)
@@ -475,6 +482,7 @@ function(gtest_discover_tests TARGET)
-D "TEST_PROPERTIES=${_PROPERTIES}"
-D "TEST_PREFIX=${_TEST_PREFIX}"
-D "TEST_SUFFIX=${_TEST_SUFFIX}"
+ -D "TEST_FILTER=${_TEST_FILTER}"
-D "NO_PRETTY_TYPES=${_NO_PRETTY_TYPES}"
-D "NO_PRETTY_VALUES=${_NO_PRETTY_VALUES}"
-D "TEST_LIST=${_TEST_LIST}"
@@ -515,6 +523,7 @@ function(gtest_discover_tests TARGET)
" TEST_PROPERTIES" " [==[" "${_PROPERTIES}" "]==]" "\n"
" TEST_PREFIX" " [==[" "${_TEST_PREFIX}" "]==]" "\n"
" TEST_SUFFIX" " [==[" "${_TEST_SUFFIX}" "]==]" "\n"
+ " TEST_FILTER" " [==[" "${_TEST_FILTER}" "]==]" "\n"
" NO_PRETTY_TYPES" " [==[" "${_NO_PRETTY_TYPES}" "]==]" "\n"
" NO_PRETTY_VALUES" " [==[" "${_NO_PRETTY_VALUES}" "]==]" "\n"
" TEST_LIST" " [==[" "${_TEST_LIST}" "]==]" "\n"
diff --git a/Modules/GoogleTestAddTests.cmake b/Modules/GoogleTestAddTests.cmake
index 0f79c9a..6b3bf34 100644
--- a/Modules/GoogleTestAddTests.cmake
+++ b/Modules/GoogleTestAddTests.cmake
@@ -44,7 +44,7 @@ function(gtest_discover_tests_impl)
cmake_parse_arguments(
""
""
- "NO_PRETTY_TYPES;NO_PRETTY_VALUES;TEST_EXECUTABLE;TEST_WORKING_DIR;TEST_PREFIX;TEST_SUFFIX;TEST_LIST;CTEST_FILE;TEST_DISCOVERY_TIMEOUT;TEST_XML_OUTPUT_DIR"
+ "NO_PRETTY_TYPES;NO_PRETTY_VALUES;TEST_EXECUTABLE;TEST_WORKING_DIR;TEST_PREFIX;TEST_SUFFIX;TEST_LIST;CTEST_FILE;TEST_DISCOVERY_TIMEOUT;TEST_XML_OUTPUT_DIR;TEST_FILTER"
"TEST_EXTRA_ARGS;TEST_PROPERTIES;TEST_EXECUTOR"
${ARGN}
)
@@ -58,6 +58,12 @@ function(gtest_discover_tests_impl)
set(tests)
set(tests_buffer)
+ if(_TEST_FILTER)
+ set(filter "--gtest_filter=${_TEST_FILTER}")
+ else()
+ set(filter)
+ endif()
+
# Run test executable to get list of available tests
if(NOT EXISTS "${_TEST_EXECUTABLE}")
message(FATAL_ERROR
@@ -66,7 +72,7 @@ function(gtest_discover_tests_impl)
)
endif()
execute_process(
- COMMAND ${_TEST_EXECUTOR} "${_TEST_EXECUTABLE}" --gtest_list_tests
+ COMMAND ${_TEST_EXECUTOR} "${_TEST_EXECUTABLE}" --gtest_list_tests ${filter}
WORKING_DIRECTORY "${_TEST_WORKING_DIR}"
TIMEOUT ${_TEST_DISCOVERY_TIMEOUT}
OUTPUT_VARIABLE output
@@ -178,6 +184,7 @@ if(CMAKE_SCRIPT_MODE_FILE)
TEST_WORKING_DIR ${TEST_WORKING_DIR}
TEST_PREFIX ${TEST_PREFIX}
TEST_SUFFIX ${TEST_SUFFIX}
+ TEST_FILTER ${TEST_FILTER}
TEST_LIST ${TEST_LIST}
CTEST_FILE ${CTEST_FILE}
TEST_DISCOVERY_TIMEOUT ${TEST_DISCOVERY_TIMEOUT}
diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake
index b2af6c9..4d3bfe2 100644
--- a/Modules/InstallRequiredSystemLibraries.cmake
+++ b/Modules/InstallRequiredSystemLibraries.cmake
@@ -237,8 +237,12 @@ if(MSVC)
set(_MSVC_IDE_VERSION "")
if(MSVC_VERSION GREATER_EQUAL 2000)
message(WARNING "MSVC ${MSVC_VERSION} not yet supported.")
- elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 143)
+ elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 144)
message(WARNING "MSVC toolset v${MSVC_TOOLSET_VERSION} not yet supported.")
+ elseif(MSVC_TOOLSET_VERSION EQUAL 143)
+ set(MSVC_REDIST_NAME VC142)
+ set(_MSVC_DLL_VERSION 140)
+ set(_MSVC_IDE_VERSION 17)
elseif(MSVC_TOOLSET_VERSION EQUAL 142)
set(MSVC_REDIST_NAME VC142)
set(_MSVC_DLL_VERSION 140)
@@ -279,7 +283,7 @@ if(MSVC)
if(NOT vs VERSION_LESS 15)
set(_vs_redist_paths "")
# The toolset and its redistributables may come with any VS version 15 or newer.
- set(_MSVC_IDE_VERSIONS 16 15)
+ set(_MSVC_IDE_VERSIONS 17 16 15)
foreach(_vs_ver ${_MSVC_IDE_VERSIONS})
set(_vs_glob_redist_paths "")
cmake_host_system_information(RESULT _vs_dir QUERY VS_${_vs_ver}_DIR) # undocumented query
diff --git a/Modules/Internal/OSRelease/010-TryOldCentOS.cmake b/Modules/Internal/OSRelease/010-TryOldCentOS.cmake
new file mode 100644
index 0000000..ff35897
--- /dev/null
+++ b/Modules/Internal/OSRelease/010-TryOldCentOS.cmake
@@ -0,0 +1,41 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# Author: Alex Turbov
+
+if(NOT EXISTS "${CMAKE_SYSROOT}/etc/centos-release")
+ return()
+endif()
+
+# Get the first string only
+file(
+ STRINGS "${CMAKE_SYSROOT}/etc/centos-release" CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT
+ LIMIT_COUNT 1
+ )
+
+#
+# Example:
+# CentOS release 6.10 (Final)
+#
+if(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT MATCHES "CentOS release ([0-9\.]+) .*")
+
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME CentOS)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME "${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT}")
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID centos)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID_LIKE rhel)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION ${CMAKE_MATCH_1})
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ${CMAKE_MATCH_1})
+
+ list(
+ APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID_LIKE
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID
+ )
+
+endif()
+
+unset(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT)
diff --git a/Modules/Internal/OSRelease/020-TryDebianVersion.cmake b/Modules/Internal/OSRelease/020-TryDebianVersion.cmake
new file mode 100644
index 0000000..8ebe19a
--- /dev/null
+++ b/Modules/Internal/OSRelease/020-TryDebianVersion.cmake
@@ -0,0 +1,38 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# Author: Alex Turbov
+
+if(NOT EXISTS "${CMAKE_SYSROOT}/etc/debian_version")
+ return()
+endif()
+
+# Get the first string only
+file(
+ STRINGS "${CMAKE_SYSROOT}/etc/debian_version" CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT
+ LIMIT_COUNT 1
+ )
+
+#
+# Example:
+# 6.0.10 # Old debian
+# wheezy/sid # Ubuntu
+#
+if(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT MATCHES "[0-9]+(\.[0-9]+)*")
+
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME Debian)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID debian)
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION ${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT})
+ set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT})
+
+ list(
+ APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID
+ )
+
+endif()
+
+unset(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT)
diff --git a/Modules/Platform/Android-Determine.cmake b/Modules/Platform/Android-Determine.cmake
index 2d2cd5c..7b67f83 100644
--- a/Modules/Platform/Android-Determine.cmake
+++ b/Modules/Platform/Android-Determine.cmake
@@ -267,7 +267,7 @@ endif()
if(CMAKE_ANDROID_NDK)
# Identify the host platform.
if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
- if(CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "x86_64")
+ if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "64")
set(CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG "darwin-x86_64")
else()
set(CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG "darwin-x86")
diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake
index 4223bde..7d602c3 100644
--- a/Modules/Platform/Windows-MSVC.cmake
+++ b/Modules/Platform/Windows-MSVC.cmake
@@ -67,7 +67,10 @@ if(NOT MSVC_VERSION)
message(FATAL_ERROR "MSVC compiler version not detected properly: ${_compiler_version}")
endif()
- if(MSVC_VERSION GREATER_EQUAL 1920)
+ if(MSVC_VERSION GREATER_EQUAL 1930)
+ # VS 2022 or greater
+ set(MSVC_TOOLSET_VERSION 143)
+ elseif(MSVC_VERSION GREATER_EQUAL 1920)
# VS 2019 or greater
set(MSVC_TOOLSET_VERSION 142)
elseif(MSVC_VERSION GREATER_EQUAL 1910)
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt
index 6775acb..8dc44a0 100644
--- a/Source/CMakeLists.txt
+++ b/Source/CMakeLists.txt
@@ -381,6 +381,7 @@ set(SRCS
cmProcessOutput.h
cmProcessTools.cxx
cmProcessTools.h
+ cmProperty.cxx
cmProperty.h
cmPropertyDefinition.cxx
cmPropertyDefinition.h
@@ -398,8 +399,6 @@ set(SRCS
cmQtAutoMocUic.h
cmQtAutoRcc.cxx
cmQtAutoRcc.h
- cmQtAutoUicHelpers.cxx
- cmQtAutoUicHelpers.h
cmRST.cxx
cmRST.h
cmRuntimeDependencyArchive.cxx
@@ -802,7 +801,7 @@ if (WIN32)
endif ()
# Watcom support
-if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
+if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux" OR CMAKE_SYSTEM_NAME STREQUAL "Darwin")
set_property(SOURCE cmake.cxx APPEND PROPERTY COMPILE_DEFINITIONS CMAKE_USE_WMAKE)
list(APPEND SRCS
cmGlobalWatcomWMakeGenerator.cxx
diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake
index b2abd3d..94e36e8 100644
--- a/Source/CMakeVersion.cmake
+++ b/Source/CMakeVersion.cmake
@@ -1,7 +1,7 @@
# CMake version number components.
set(CMake_VERSION_MAJOR 3)
set(CMake_VERSION_MINOR 21)
-set(CMake_VERSION_PATCH 20210807)
+set(CMake_VERSION_PATCH 20210914)
#set(CMake_VERSION_RC 0)
set(CMake_VERSION_IS_DIRTY 0)
diff --git a/Source/CPack/IFW/cmCPackIFWCommon.cxx b/Source/CPack/IFW/cmCPackIFWCommon.cxx
index 87ebbfe..177a959 100644
--- a/Source/CPack/IFW/cmCPackIFWCommon.cxx
+++ b/Source/CPack/IFW/cmCPackIFWCommon.cxx
@@ -21,7 +21,7 @@ cmCPackIFWCommon::cmCPackIFWCommon()
{
}
-const char* cmCPackIFWCommon::GetOption(const std::string& op) const
+cmProp cmCPackIFWCommon::GetOption(const std::string& op) const
{
return this->Generator ? this->Generator->cmCPackGenerator::GetOption(op)
: nullptr;
diff --git a/Source/CPack/IFW/cmCPackIFWCommon.h b/Source/CPack/IFW/cmCPackIFWCommon.h
index 42deda4..cf243dc 100644
--- a/Source/CPack/IFW/cmCPackIFWCommon.h
+++ b/Source/CPack/IFW/cmCPackIFWCommon.h
@@ -7,6 +7,8 @@
#include <map>
#include <string>
+#include "cmProperty.h"
+
class cmCPackIFWGenerator;
class cmXMLWriter;
@@ -26,7 +28,7 @@ public:
public:
// Internal implementation
- const char* GetOption(const std::string& op) const;
+ cmProp 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;
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
index 2806c61..4993b40 100644
--- a/Source/CPack/IFW/cmCPackIFWGenerator.cxx
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
@@ -14,6 +14,7 @@
#include "cmCPackLog.h" // IWYU pragma: keep
#include "cmDuration.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -250,7 +251,7 @@ const char* cmCPackIFWGenerator::GetPackagingInstallPrefix()
this->SetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX", tmpPref.c_str());
- return this->GetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX");
+ return this->GetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX")->c_str();
}
const char* cmCPackIFWGenerator::GetOutputExtension()
@@ -273,11 +274,11 @@ int cmCPackIFWGenerator::InitializeInternal()
// Look 'binarycreator' executable (needs)
- const char* BinCreatorStr = this->GetOption(BinCreatorOpt);
+ cmProp BinCreatorStr = this->GetOption(BinCreatorOpt);
if (!BinCreatorStr || cmIsNOTFOUND(BinCreatorStr)) {
this->BinCreator.clear();
} else {
- this->BinCreator = BinCreatorStr;
+ this->BinCreator = *BinCreatorStr;
}
if (this->BinCreator.empty()) {
@@ -290,16 +291,16 @@ int cmCPackIFWGenerator::InitializeInternal()
// Look 'repogen' executable (optional)
- const char* RepoGenStr = this->GetOption(RepoGenOpt);
- if (!RepoGenStr || cmIsNOTFOUND(RepoGenStr)) {
+ cmProp repoGen = this->GetOption(RepoGenOpt);
+ if (!repoGen || cmIsNOTFOUND(repoGen)) {
this->RepoGen.clear();
} else {
- this->RepoGen = RepoGenStr;
+ this->RepoGen = *repoGen;
}
// Framework version
- if (const char* FrameworkVersionSrt = this->GetOption(FrameworkVersionOpt)) {
- this->FrameworkVersion = FrameworkVersionSrt;
+ if (cmProp frameworkVersion = this->GetOption(FrameworkVersionOpt)) {
+ this->FrameworkVersion = *frameworkVersion;
} else {
this->FrameworkVersion = "1.9.9";
}
@@ -312,14 +313,13 @@ int cmCPackIFWGenerator::InitializeInternal()
// Additional packages dirs
this->PkgsDirsVector.clear();
- if (const char* dirs = this->GetOption("CPACK_IFW_PACKAGES_DIRECTORIES")) {
+ if (cmProp dirs = this->GetOption("CPACK_IFW_PACKAGES_DIRECTORIES")) {
cmExpandList(dirs, this->PkgsDirsVector);
}
// Additional repositories dirs
this->RepoDirsVector.clear();
- if (const char* dirs =
- this->GetOption("CPACK_IFW_REPOSITORIES_DIRECTORIES")) {
+ if (cmProp dirs = this->GetOption("CPACK_IFW_REPOSITORIES_DIRECTORIES")) {
cmExpandList(dirs, this->RepoDirsVector);
}
@@ -330,23 +330,22 @@ int cmCPackIFWGenerator::InitializeInternal()
// Repository
this->Repository.Generator = this;
this->Repository.Name = "Unspecified";
- if (const char* site = this->GetOption("CPACK_DOWNLOAD_SITE")) {
- this->Repository.Url = site;
+ if (cmProp site = this->GetOption("CPACK_DOWNLOAD_SITE")) {
+ this->Repository.Url = *site;
this->Installer.RemoteRepositories.push_back(&this->Repository);
}
// Repositories
- if (const char* RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL")) {
+ if (cmProp RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL")) {
std::vector<std::string> RepoAllVector = cmExpandedList(RepoAllStr);
for (std::string const& r : RepoAllVector) {
this->GetRepository(r);
}
}
- if (const char* ifwDownloadAll = this->GetOption("CPACK_IFW_DOWNLOAD_ALL")) {
+ if (cmProp ifwDownloadAll = this->GetOption("CPACK_IFW_DOWNLOAD_ALL")) {
this->OnlineOnly = cmIsOn(ifwDownloadAll);
- } else if (const char* cpackDownloadAll =
- this->GetOption("CPACK_DOWNLOAD_ALL")) {
+ } else if (cmProp cpackDownloadAll = this->GetOption("CPACK_DOWNLOAD_ALL")) {
this->OnlineOnly = cmIsOn(cpackDownloadAll);
} else {
this->OnlineOnly = false;
@@ -374,9 +373,8 @@ int cmCPackIFWGenerator::InitializeInternal()
}
// Output extension
- if (const char* optOutExt =
- this->GetOption("CPACK_IFW_PACKAGE_FILE_EXTENSION")) {
- this->OutputExtension = optOutExt;
+ if (cmProp optOutExt = this->GetOption("CPACK_IFW_PACKAGE_FILE_EXTENSION")) {
+ this->OutputExtension = *optOutExt;
} else if (sysName == "Darwin") {
this->OutputExtension = ".dmg";
} else {
@@ -508,21 +506,20 @@ std::string cmCPackIFWGenerator::GetRootPackageName()
{
// Default value
std::string name = "root";
- if (const char* optIFW_PACKAGE_GROUP =
+ if (cmProp optIFW_PACKAGE_GROUP =
this->GetOption("CPACK_IFW_PACKAGE_GROUP")) {
// Configure from root group
cmCPackIFWPackage package;
package.Generator = this;
package.ConfigureFromGroup(optIFW_PACKAGE_GROUP);
name = package.Name;
- } else if (const char* optIFW_PACKAGE_NAME =
+ } else if (cmProp optIFW_PACKAGE_NAME =
this->GetOption("CPACK_IFW_PACKAGE_NAME")) {
// Configure from root package name
- name = optIFW_PACKAGE_NAME;
- } else if (const char* optPACKAGE_NAME =
- this->GetOption("CPACK_PACKAGE_NAME")) {
+ name = *optIFW_PACKAGE_NAME;
+ } else if (cmProp optPACKAGE_NAME = this->GetOption("CPACK_PACKAGE_NAME")) {
// Configure from package name
- name = optPACKAGE_NAME;
+ name = *optPACKAGE_NAME;
}
return name;
}
@@ -537,10 +534,10 @@ std::string cmCPackIFWGenerator::GetGroupPackageName(
if (cmCPackIFWPackage* package = this->GetGroupPackage(group)) {
return package->Name;
}
- const char* option =
+ cmProp option =
this->GetOption("CPACK_IFW_COMPONENT_GROUP_" +
cmsys::SystemTools::UpperCase(group->Name) + "_NAME");
- name = option ? option : group->Name;
+ name = option ? *option : group->Name;
if (group->ParentGroup) {
cmCPackIFWPackage* package = this->GetGroupPackage(group->ParentGroup);
bool dot = !this->ResolveDuplicateNames;
@@ -563,8 +560,8 @@ std::string cmCPackIFWGenerator::GetComponentPackageName(
}
std::string prefix = "CPACK_IFW_COMPONENT_" +
cmsys::SystemTools::UpperCase(component->Name) + "_";
- const char* option = this->GetOption(prefix + "NAME");
- name = option ? option : component->Name;
+ cmProp option = this->GetOption(prefix + "NAME");
+ name = option ? *option : component->Name;
if (component->Group) {
cmCPackIFWPackage* package = this->GetGroupPackage(component->Group);
if ((this->componentPackageMethod ==
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
index bf8b457..23b73ff 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
@@ -12,6 +12,7 @@
#include "cmCPackIFWRepository.h"
#include "cmCPackLog.h" // IWYU pragma: keep
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmXMLParser.h"
@@ -33,61 +34,59 @@ void cmCPackIFWInstaller::printSkippedOptionWarning(
void cmCPackIFWInstaller::ConfigureFromOptions()
{
// Name;
- if (const char* optIFW_PACKAGE_NAME =
- this->GetOption("CPACK_IFW_PACKAGE_NAME")) {
- this->Name = optIFW_PACKAGE_NAME;
- } else if (const char* optPACKAGE_NAME =
- this->GetOption("CPACK_PACKAGE_NAME")) {
- this->Name = optPACKAGE_NAME;
+ if (cmProp optIFW_PACKAGE_NAME = this->GetOption("CPACK_IFW_PACKAGE_NAME")) {
+ this->Name = *optIFW_PACKAGE_NAME;
+ } else if (cmProp optPACKAGE_NAME = this->GetOption("CPACK_PACKAGE_NAME")) {
+ this->Name = *optPACKAGE_NAME;
} else {
this->Name = "Your package";
}
// Title;
- if (const char* optIFW_PACKAGE_TITLE =
+ if (cmProp optIFW_PACKAGE_TITLE =
this->GetOption("CPACK_IFW_PACKAGE_TITLE")) {
- this->Title = optIFW_PACKAGE_TITLE;
- } else if (const char* optPACKAGE_DESCRIPTION_SUMMARY =
+ this->Title = *optIFW_PACKAGE_TITLE;
+ } else if (cmProp optPACKAGE_DESCRIPTION_SUMMARY =
this->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY")) {
- this->Title = optPACKAGE_DESCRIPTION_SUMMARY;
+ this->Title = *optPACKAGE_DESCRIPTION_SUMMARY;
} else {
this->Title = "Your package description";
}
// Version;
- if (const char* option = this->GetOption("CPACK_PACKAGE_VERSION")) {
- this->Version = option;
+ if (cmProp option = this->GetOption("CPACK_PACKAGE_VERSION")) {
+ this->Version = *option;
} else {
this->Version = "1.0.0";
}
// Publisher
- if (const char* optIFW_PACKAGE_PUBLISHER =
+ if (cmProp optIFW_PACKAGE_PUBLISHER =
this->GetOption("CPACK_IFW_PACKAGE_PUBLISHER")) {
- this->Publisher = optIFW_PACKAGE_PUBLISHER;
- } else if (const char* optPACKAGE_VENDOR =
+ this->Publisher = *optIFW_PACKAGE_PUBLISHER;
+ } else if (cmProp optPACKAGE_VENDOR =
this->GetOption("CPACK_PACKAGE_VENDOR")) {
- this->Publisher = optPACKAGE_VENDOR;
+ this->Publisher = *optPACKAGE_VENDOR;
}
// ProductUrl
- if (const char* option = this->GetOption("CPACK_IFW_PRODUCT_URL")) {
- this->ProductUrl = option;
+ if (cmProp option = this->GetOption("CPACK_IFW_PRODUCT_URL")) {
+ this->ProductUrl = *option;
}
// ApplicationIcon
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_ICON")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_ICON")) {
if (cmSystemTools::FileExists(option)) {
- this->InstallerApplicationIcon = option;
+ this->InstallerApplicationIcon = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_ICON", option);
}
}
// WindowIcon
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_WINDOW_ICON")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_WINDOW_ICON")) {
if (cmSystemTools::FileExists(option)) {
- this->InstallerWindowIcon = option;
+ this->InstallerWindowIcon = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_WINDOW_ICON", option);
}
@@ -103,45 +102,45 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
}
// Logo
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_LOGO")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_LOGO")) {
if (cmSystemTools::FileExists(option)) {
- this->Logo = option;
+ this->Logo = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_LOGO", option);
}
}
// Watermark
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_WATERMARK")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_WATERMARK")) {
if (cmSystemTools::FileExists(option)) {
- this->Watermark = option;
+ this->Watermark = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_WATERMARK", option);
}
}
// Banner
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_BANNER")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_BANNER")) {
if (cmSystemTools::FileExists(option)) {
- this->Banner = option;
+ this->Banner = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_BANNER", option);
}
}
// Background
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_BACKGROUND")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_BACKGROUND")) {
if (cmSystemTools::FileExists(option)) {
- this->Background = option;
+ this->Background = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_BACKGROUND", option);
}
}
// WizardStyle
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_WIZARD_STYLE")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_WIZARD_STYLE")) {
// Setting the user value in any case
- this->WizardStyle = option;
+ this->WizardStyle = *option;
// Check known values
if (this->WizardStyle != "Modern" && this->WizardStyle != "Aero" &&
this->WizardStyle != "Mac" && this->WizardStyle != "Classic") {
@@ -154,28 +153,28 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
}
// StyleSheet
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_STYLE_SHEET")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_STYLE_SHEET")) {
if (cmSystemTools::FileExists(option)) {
- this->StyleSheet = option;
+ this->StyleSheet = *option;
} else {
this->printSkippedOptionWarning("CPACK_IFW_PACKAGE_STYLE_SHEET", option);
}
}
// WizardDefaultWidth
- if (const char* option =
+ if (cmProp option =
this->GetOption("CPACK_IFW_PACKAGE_WIZARD_DEFAULT_WIDTH")) {
- this->WizardDefaultWidth = option;
+ this->WizardDefaultWidth = *option;
}
// WizardDefaultHeight
- if (const char* option =
+ if (cmProp option =
this->GetOption("CPACK_IFW_PACKAGE_WIZARD_DEFAULT_HEIGHT")) {
- this->WizardDefaultHeight = option;
+ this->WizardDefaultHeight = *option;
}
// WizardShowPageList
- if (const char* option =
+ if (cmProp option =
this->GetOption("CPACK_IFW_PACKAGE_WIZARD_SHOW_PAGE_LIST")) {
if (!this->IsVersionLess("4.0")) {
if (this->IsSetToOff("CPACK_IFW_PACKAGE_WIZARD_SHOW_PAGE_LIST")) {
@@ -204,23 +203,23 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
}
// TitleColor
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_TITLE_COLOR")) {
- this->TitleColor = option;
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_TITLE_COLOR")) {
+ this->TitleColor = *option;
}
// Start menu
- if (const char* optIFW_START_MENU_DIR =
+ if (cmProp optIFW_START_MENU_DIR =
this->GetOption("CPACK_IFW_PACKAGE_START_MENU_DIRECTORY")) {
- this->StartMenuDir = optIFW_START_MENU_DIR;
+ this->StartMenuDir = *optIFW_START_MENU_DIR;
} else {
this->StartMenuDir = this->Name;
}
// Default target directory for installation
- if (const char* optIFW_TARGET_DIRECTORY =
+ if (cmProp optIFW_TARGET_DIRECTORY =
this->GetOption("CPACK_IFW_TARGET_DIRECTORY")) {
- this->TargetDir = optIFW_TARGET_DIRECTORY;
- } else if (const char* optPACKAGE_INSTALL_DIRECTORY =
+ this->TargetDir = *optIFW_TARGET_DIRECTORY;
+ } else if (cmProp optPACKAGE_INSTALL_DIRECTORY =
this->GetOption("CPACK_PACKAGE_INSTALL_DIRECTORY")) {
this->TargetDir =
cmStrCat("@ApplicationsDir@/", optPACKAGE_INSTALL_DIRECTORY);
@@ -229,21 +228,20 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
}
// Default target directory for installation with administrator rights
- if (const char* option =
- this->GetOption("CPACK_IFW_ADMIN_TARGET_DIRECTORY")) {
- this->AdminTargetDir = option;
+ if (cmProp option = this->GetOption("CPACK_IFW_ADMIN_TARGET_DIRECTORY")) {
+ this->AdminTargetDir = *option;
}
// Maintenance tool
- if (const char* optIFW_MAINTENANCE_TOOL =
+ if (cmProp optIFW_MAINTENANCE_TOOL =
this->GetOption("CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_NAME")) {
- this->MaintenanceToolName = optIFW_MAINTENANCE_TOOL;
+ this->MaintenanceToolName = *optIFW_MAINTENANCE_TOOL;
}
// Maintenance tool ini file
- if (const char* optIFW_MAINTENANCE_TOOL_INI =
+ if (cmProp optIFW_MAINTENANCE_TOOL_INI =
this->GetOption("CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_INI_FILE")) {
- this->MaintenanceToolIniFile = optIFW_MAINTENANCE_TOOL_INI;
+ this->MaintenanceToolIniFile = *optIFW_MAINTENANCE_TOOL_INI;
}
// Allow non-ASCII characters
@@ -265,13 +263,13 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
}
// Control script
- if (const char* optIFW_CONTROL_SCRIPT =
+ if (cmProp optIFW_CONTROL_SCRIPT =
this->GetOption("CPACK_IFW_PACKAGE_CONTROL_SCRIPT")) {
- this->ControlScript = optIFW_CONTROL_SCRIPT;
+ this->ControlScript = *optIFW_CONTROL_SCRIPT;
}
// Resources
- if (const char* optIFW_PACKAGE_RESOURCES =
+ if (cmProp optIFW_PACKAGE_RESOURCES =
this->GetOption("CPACK_IFW_PACKAGE_RESOURCES")) {
this->Resources.clear();
cmExpandList(optIFW_PACKAGE_RESOURCES, this->Resources);
@@ -541,7 +539,7 @@ void cmCPackIFWInstaller::GeneratePackageFiles()
package.Generator = this->Generator;
package.Installer = this;
// Check package group
- if (const char* option = this->GetOption("CPACK_IFW_PACKAGE_GROUP")) {
+ if (cmProp option = this->GetOption("CPACK_IFW_PACKAGE_GROUP")) {
package.ConfigureFromGroup(option);
std::string forcedOption = "CPACK_IFW_COMPONENT_GROUP_" +
cmsys::SystemTools::UpperCase(option) + "_FORCED_INSTALLATION";
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx
index 1429c46..c1e11d2 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.cxx
+++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx
@@ -15,6 +15,7 @@
#include "cmCPackIFWInstaller.h"
#include "cmCPackLog.h" // IWYU pragma: keep
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmTimestamp.h"
@@ -124,10 +125,10 @@ std::string cmCPackIFWPackage::GetComponentName(cmCPackComponent* component)
if (!component) {
return "";
}
- const char* option =
+ cmProp option =
this->GetOption("CPACK_IFW_COMPONENT_" +
cmsys::SystemTools::UpperCase(component->Name) + "_NAME");
- return option ? option : component->Name;
+ return option ? *option : component->Name;
}
void cmCPackIFWPackage::DefaultConfiguration()
@@ -159,23 +160,22 @@ int cmCPackIFWPackage::ConfigureFromOptions()
this->Name = this->Generator->GetRootPackageName();
// Display name
- if (const char* option = this->GetOption("CPACK_PACKAGE_NAME")) {
- this->DisplayName[""] = option;
+ if (cmProp option = this->GetOption("CPACK_PACKAGE_NAME")) {
+ this->DisplayName[""] = *option;
} else {
this->DisplayName[""] = "Your package";
}
// Description
- if (const char* option =
- this->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY")) {
- this->Description[""] = option;
+ if (cmProp option = this->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY")) {
+ this->Description[""] = *option;
} else {
this->Description[""] = "Your package description";
}
// Version
- if (const char* option = this->GetOption("CPACK_PACKAGE_VERSION")) {
- this->Version = option;
+ if (cmProp option = this->GetOption("CPACK_PACKAGE_VERSION")) {
+ this->Version = *option;
} else {
this->Version = "1.0.0";
}
@@ -204,22 +204,22 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
this->Description[""] = component->Description;
// Version
- if (const char* optVERSION = this->GetOption(prefix + "VERSION")) {
- this->Version = optVERSION;
- } else if (const char* optPACKAGE_VERSION =
+ if (cmProp optVERSION = this->GetOption(prefix + "VERSION")) {
+ this->Version = *optVERSION;
+ } else if (cmProp optPACKAGE_VERSION =
this->GetOption("CPACK_PACKAGE_VERSION")) {
- this->Version = optPACKAGE_VERSION;
+ this->Version = *optPACKAGE_VERSION;
} else {
this->Version = "1.0.0";
}
// Script
- if (const char* option = this->GetOption(prefix + "SCRIPT")) {
- this->Script = option;
+ if (cmProp option = this->GetOption(prefix + "SCRIPT")) {
+ this->Script = *option;
}
// User interfaces
- if (const char* option = this->GetOption(prefix + "USER_INTERFACES")) {
+ if (cmProp option = this->GetOption(prefix + "USER_INTERFACES")) {
this->UserInterfaces.clear();
cmExpandList(option, this->UserInterfaces);
}
@@ -232,7 +232,7 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
}
// Licenses
- if (const char* option = this->GetOption(prefix + "LICENSES")) {
+ if (cmProp option = this->GetOption(prefix + "LICENSES")) {
this->Licenses.clear();
cmExpandList(option, this->Licenses);
if (this->Licenses.size() % 2 != 0) {
@@ -246,8 +246,8 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
}
// Priority
- if (const char* option = this->GetOption(prefix + "PRIORITY")) {
- this->SortingPriority = option;
+ if (cmProp option = this->GetOption(prefix + "PRIORITY")) {
+ this->SortingPriority = *option;
cmCPackIFWLogger(
WARNING,
"The \"PRIORITY\" option is set "
@@ -289,28 +289,28 @@ int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
this->Description[""] = group->Description;
// Version
- if (const char* optVERSION = this->GetOption(prefix + "VERSION")) {
- this->Version = optVERSION;
- } else if (const char* optPACKAGE_VERSION =
+ if (cmProp optVERSION = this->GetOption(prefix + "VERSION")) {
+ this->Version = *optVERSION;
+ } else if (cmProp optPACKAGE_VERSION =
this->GetOption("CPACK_PACKAGE_VERSION")) {
- this->Version = optPACKAGE_VERSION;
+ this->Version = *optPACKAGE_VERSION;
} else {
this->Version = "1.0.0";
}
// Script
- if (const char* option = this->GetOption(prefix + "SCRIPT")) {
- this->Script = option;
+ if (cmProp option = this->GetOption(prefix + "SCRIPT")) {
+ this->Script = *option;
}
// User interfaces
- if (const char* option = this->GetOption(prefix + "USER_INTERFACES")) {
+ if (cmProp option = this->GetOption(prefix + "USER_INTERFACES")) {
this->UserInterfaces.clear();
cmExpandList(option, this->UserInterfaces);
}
// Licenses
- if (const char* option = this->GetOption(prefix + "LICENSES")) {
+ if (cmProp option = this->GetOption(prefix + "LICENSES")) {
this->Licenses.clear();
cmExpandList(option, this->Licenses);
if (this->Licenses.size() % 2 != 0) {
@@ -324,8 +324,8 @@ int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
}
// Priority
- if (const char* option = this->GetOption(prefix + "PRIORITY")) {
- this->SortingPriority = option;
+ if (cmProp option = this->GetOption(prefix + "PRIORITY")) {
+ this->SortingPriority = *option;
cmCPackIFWLogger(
WARNING,
"The \"PRIORITY\" option is set "
@@ -346,14 +346,14 @@ int cmCPackIFWPackage::ConfigureFromGroup(const std::string& groupName)
std::string prefix =
"CPACK_COMPONENT_GROUP_" + cmsys::SystemTools::UpperCase(groupName) + "_";
- if (const char* option = this->GetOption(prefix + "DISPLAY_NAME")) {
- group.DisplayName = option;
+ if (cmProp option = this->GetOption(prefix + "DISPLAY_NAME")) {
+ group.DisplayName = *option;
} else {
group.DisplayName = group.Name;
}
- if (const char* option = this->GetOption(prefix + "DESCRIPTION")) {
- group.Description = option;
+ if (cmProp option = this->GetOption(prefix + "DESCRIPTION")) {
+ group.Description = *option;
}
group.IsBold = this->IsOn(prefix + "BOLD_TITLE");
group.IsExpandedByDefault = this->IsOn(prefix + "EXPANDED");
@@ -381,7 +381,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
option = prefix + "DISPLAY_NAME";
if (this->IsSetToEmpty(option)) {
this->DisplayName.clear();
- } else if (const char* value = this->GetOption(option)) {
+ } else if (cmProp value = this->GetOption(option)) {
cmCPackIFWPackage::ExpandListArgument(value, this->DisplayName);
}
@@ -389,7 +389,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
option = prefix + "DESCRIPTION";
if (this->IsSetToEmpty(option)) {
this->Description.clear();
- } else if (const char* value = this->GetOption(option)) {
+ } else if (cmProp value = this->GetOption(option)) {
cmCPackIFWPackage::ExpandListArgument(value, this->Description);
}
@@ -397,31 +397,31 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
option = prefix + "RELEASE_DATE";
if (this->IsSetToEmpty(option)) {
this->ReleaseDate.clear();
- } else if (const char* value = this->GetOption(option)) {
- this->ReleaseDate = value;
+ } else if (cmProp value = this->GetOption(option)) {
+ this->ReleaseDate = *value;
}
// Sorting priority
option = prefix + "SORTING_PRIORITY";
if (this->IsSetToEmpty(option)) {
this->SortingPriority.clear();
- } else if (const char* value = this->GetOption(option)) {
- this->SortingPriority = value;
+ } else if (cmProp value = this->GetOption(option)) {
+ this->SortingPriority = *value;
}
// Update text
option = prefix + "UPDATE_TEXT";
if (this->IsSetToEmpty(option)) {
this->UpdateText.clear();
- } else if (const char* value = this->GetOption(option)) {
- this->UpdateText = value;
+ } else if (cmProp value = this->GetOption(option)) {
+ this->UpdateText = *value;
}
// Translations
option = prefix + "TRANSLATIONS";
if (this->IsSetToEmpty(option)) {
this->Translations.clear();
- } else if (const char* value = this->GetOption(option)) {
+ } else if (cmProp value = this->GetOption(option)) {
this->Translations.clear();
cmExpandList(value, this->Translations);
}
@@ -429,11 +429,11 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
// QtIFW dependencies
std::vector<std::string> deps;
option = prefix + "DEPENDS";
- if (const char* value = this->GetOption(option)) {
+ if (cmProp value = this->GetOption(option)) {
cmExpandList(value, deps);
}
option = prefix + "DEPENDENCIES";
- if (const char* value = this->GetOption(option)) {
+ if (cmProp value = this->GetOption(option)) {
cmExpandList(value, deps);
}
for (std::string const& d : deps) {
@@ -454,7 +454,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
option = prefix + "AUTO_DEPEND_ON";
if (this->IsSetToEmpty(option)) {
this->AlienAutoDependOn.clear();
- } else if (const char* value = this->GetOption(option)) {
+ } else if (cmProp value = this->GetOption(option)) {
std::vector<std::string> depsOn = cmExpandedList(value);
for (std::string const& d : depsOn) {
DependenceStruct dep(d);
@@ -483,7 +483,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
option = prefix + "DEFAULT";
if (this->IsSetToEmpty(option)) {
this->Default.clear();
- } else if (const char* value = this->GetOption(option)) {
+ } else if (cmProp value = this->GetOption(option)) {
std::string lowerValue = cmsys::SystemTools::LowerCase(value);
if (lowerValue == "true") {
this->Default = "true";
@@ -492,7 +492,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
} else if (lowerValue == "script") {
this->Default = "script";
} else {
- this->Default = value;
+ this->Default = *value;
}
}
@@ -510,7 +510,7 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
option = prefix + "REPLACES";
if (this->IsSetToEmpty(option)) {
this->Replaces.clear();
- } else if (const char* value = this->GetOption(option)) {
+ } else if (cmProp value = this->GetOption(option)) {
this->Replaces.clear();
cmExpandList(value, this->Replaces);
}
diff --git a/Source/CPack/IFW/cmCPackIFWRepository.cxx b/Source/CPack/IFW/cmCPackIFWRepository.cxx
index 7ec2256..cc64e93 100644
--- a/Source/CPack/IFW/cmCPackIFWRepository.cxx
+++ b/Source/CPack/IFW/cmCPackIFWRepository.cxx
@@ -6,6 +6,7 @@
#include "cmCPackIFWGenerator.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmSystemTools.h"
#include "cmXMLParser.h"
#include "cmXMLWriter.h"
@@ -55,22 +56,22 @@ bool cmCPackIFWRepository::ConfigureFromOptions()
}
// Url
- if (const char* url = this->GetOption(prefix + "URL")) {
- this->Url = url;
+ if (cmProp url = this->GetOption(prefix + "URL")) {
+ this->Url = *url;
} else {
this->Url.clear();
}
// Old url
- if (const char* oldUrl = this->GetOption(prefix + "OLD_URL")) {
- this->OldUrl = oldUrl;
+ if (cmProp oldUrl = this->GetOption(prefix + "OLD_URL")) {
+ this->OldUrl = *oldUrl;
} else {
this->OldUrl.clear();
}
// New url
- if (const char* newUrl = this->GetOption(prefix + "NEW_URL")) {
- this->NewUrl = newUrl;
+ if (cmProp newUrl = this->GetOption(prefix + "NEW_URL")) {
+ this->NewUrl = *newUrl;
} else {
this->NewUrl.clear();
}
@@ -83,22 +84,22 @@ bool cmCPackIFWRepository::ConfigureFromOptions()
}
// Username
- if (const char* username = this->GetOption(prefix + "USERNAME")) {
- this->Username = username;
+ if (cmProp username = this->GetOption(prefix + "USERNAME")) {
+ this->Username = *username;
} else {
this->Username.clear();
}
// Password
- if (const char* password = this->GetOption(prefix + "PASSWORD")) {
- this->Password = password;
+ if (cmProp password = this->GetOption(prefix + "PASSWORD")) {
+ this->Password = *password;
} else {
this->Password.clear();
}
// DisplayName
- if (const char* displayName = this->GetOption(prefix + "DISPLAY_NAME")) {
- this->DisplayName = displayName;
+ if (cmProp displayName = this->GetOption(prefix + "DISPLAY_NAME")) {
+ this->DisplayName = *displayName;
} else {
this->DisplayName.clear();
}
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
index 8b3644f..7ec2c3f 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
@@ -18,6 +18,7 @@
#include "cmCryptoHash.h"
#include "cmGeneratedFileStream.h"
#include "cmInstalledFile.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmUuid.h"
@@ -125,7 +126,7 @@ bool cmCPackWIXGenerator::RunLightCommand(std::string const& objectFiles)
command << " -ext " << QuotePath(ext);
}
- const char* const cultures = GetOption("CPACK_WIX_CULTURES");
+ cmProp const cultures = GetOption("CPACK_WIX_CULTURES");
if (cultures) {
command << " -cultures:" << cultures;
}
@@ -156,7 +157,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
return false;
}
- if (GetOption("CPACK_WIX_PRODUCT_GUID") == 0) {
+ if (!GetOption("CPACK_WIX_PRODUCT_GUID")) {
std::string guid = GenerateGUID();
SetOption("CPACK_WIX_PRODUCT_GUID", guid.c_str());
@@ -165,7 +166,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
<< std::endl);
}
- if (GetOption("CPACK_WIX_UPGRADE_GUID") == 0) {
+ if (!GetOption("CPACK_WIX_UPGRADE_GUID")) {
std::string guid = GenerateGUID();
SetOption("CPACK_WIX_UPGRADE_GUID", guid.c_str());
@@ -182,7 +183,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
return false;
}
- if (GetOption("CPACK_WIX_LICENSE_RTF") == 0) {
+ if (!GetOption("CPACK_WIX_LICENSE_RTF")) {
std::string licenseFilename = this->CPackTopLevel + "/License.rtf";
SetOption("CPACK_WIX_LICENSE_RTF", licenseFilename.c_str());
@@ -191,7 +192,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
}
}
- if (GetOption("CPACK_PACKAGE_VENDOR") == 0) {
+ if (!GetOption("CPACK_PACKAGE_VENDOR")) {
std::string defaultVendor = "Humanity";
SetOption("CPACK_PACKAGE_VENDOR", defaultVendor.c_str());
@@ -200,7 +201,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
<< defaultVendor << " . " << std::endl);
}
- if (GetOption("CPACK_WIX_UI_REF") == 0) {
+ if (!GetOption("CPACK_WIX_UI_REF")) {
std::string defaultRef = "WixUI_InstallDir";
if (!this->Components.empty()) {
@@ -210,9 +211,9 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
SetOption("CPACK_WIX_UI_REF", defaultRef.c_str());
}
- const char* packageContact = GetOption("CPACK_PACKAGE_CONTACT");
- if (packageContact != 0 && GetOption("CPACK_WIX_PROPERTY_ARPCONTACT") == 0) {
- SetOption("CPACK_WIX_PROPERTY_ARPCONTACT", packageContact);
+ cmProp packageContact = GetOption("CPACK_PACKAGE_CONTACT");
+ if (packageContact && !GetOption("CPACK_WIX_PROPERTY_ARPCONTACT")) {
+ SetOption("CPACK_WIX_PROPERTY_ARPCONTACT", packageContact->c_str());
}
CollectExtensions("CPACK_WIX_EXTENSIONS", this->CandleExtensions);
@@ -223,7 +224,7 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
CollectExtensions("CPACK_WIX_LIGHT_EXTENSIONS", this->LightExtensions);
CollectXmlNamespaces("CPACK_WIX_CUSTOM_XMLNS", this->CustomXmlNamespaces);
- const char* patchFilePath = GetOption("CPACK_WIX_PATCH_FILE");
+ cmProp patchFilePath = GetOption("CPACK_WIX_PATCH_FILE");
if (patchFilePath) {
std::vector<std::string> patchFilePaths = cmExpandedList(patchFilePath);
@@ -295,7 +296,7 @@ bool cmCPackWIXGenerator::PackageFilesImpl()
void cmCPackWIXGenerator::AppendUserSuppliedExtraSources()
{
- const char* cpackWixExtraSources = GetOption("CPACK_WIX_EXTRA_SOURCES");
+ cmProp cpackWixExtraSources = GetOption("CPACK_WIX_EXTRA_SOURCES");
if (!cpackWixExtraSources)
return;
@@ -304,7 +305,7 @@ void cmCPackWIXGenerator::AppendUserSuppliedExtraSources()
void cmCPackWIXGenerator::AppendUserSuppliedExtraObjects(std::ostream& stream)
{
- const char* cpackWixExtraObjects = GetOption("CPACK_WIX_EXTRA_OBJECTS");
+ cmProp cpackWixExtraObjects = GetOption("CPACK_WIX_EXTRA_OBJECTS");
if (!cpackWixExtraObjects)
return;
@@ -335,7 +336,7 @@ void cmCPackWIXGenerator::CreateWiXVariablesIncludeFile()
CopyDefinition(includeFile, "CPACK_WIX_UI_BANNER", DefinitionType::PATH);
CopyDefinition(includeFile, "CPACK_WIX_UI_DIALOG", DefinitionType::PATH);
SetOptionIfNotSet("CPACK_WIX_PROGRAM_MENU_FOLDER",
- GetOption("CPACK_PACKAGE_NAME"));
+ GetOption("CPACK_PACKAGE_NAME").GetCStr());
CopyDefinition(includeFile, "CPACK_WIX_PROGRAM_MENU_FOLDER");
CopyDefinition(includeFile, "CPACK_WIX_UI_REF");
}
@@ -355,7 +356,7 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
for (std::string const& name : options) {
if (cmHasPrefix(name, prefix)) {
std::string id = name.substr(prefix.length());
- std::string value = GetOption(name.c_str());
+ std::string value = GetOption(name);
includeFile.BeginElement("Property");
includeFile.AddAttribute("Id", id);
@@ -364,7 +365,7 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
}
}
- if (GetOption("CPACK_WIX_PROPERTY_ARPINSTALLLOCATION") == 0) {
+ if (!GetOption("CPACK_WIX_PROPERTY_ARPINSTALLLOCATION")) {
includeFile.BeginElement("Property");
includeFile.AddAttribute("Id", "INSTALL_ROOT");
includeFile.AddAttribute("Secure", "yes");
@@ -405,7 +406,7 @@ void cmCPackWIXGenerator::CopyDefinition(cmWIXSourceWriter& source,
std::string const& name,
DefinitionType type)
{
- const char* value = GetOption(name.c_str());
+ cmProp value = GetOption(name);
if (value) {
if (type == DefinitionType::PATH) {
AddDefinition(source, name, CMakeToWixPath(value));
@@ -485,17 +486,17 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
}
std::string featureTitle = cpackPackageName;
- if (const char* title = GetOption("CPACK_WIX_ROOT_FEATURE_TITLE")) {
- featureTitle = title;
+ if (cmProp title = GetOption("CPACK_WIX_ROOT_FEATURE_TITLE")) {
+ featureTitle = *title;
}
featureDefinitions.AddAttribute("Title", featureTitle);
- if (const char* desc = GetOption("CPACK_WIX_ROOT_FEATURE_DESCRIPTION")) {
+ if (cmProp desc = GetOption("CPACK_WIX_ROOT_FEATURE_DESCRIPTION")) {
featureDefinitions.AddAttribute("Description", desc);
}
featureDefinitions.AddAttribute("Level", "1");
this->Patch->ApplyFragment("#PRODUCTFEATURE", featureDefinitions);
- const char* package = GetOption("CPACK_WIX_CMAKE_PACKAGE_REGISTRY");
+ cmProp package = GetOption("CPACK_WIX_CMAKE_PACKAGE_REGISTRY");
if (package) {
featureDefinitions.CreateCMakePackageRegistryEntry(
package, GetOption("CPACK_WIX_UPGRADE_GUID"));
@@ -540,10 +541,9 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
}
bool emitUninstallShortcut = true;
- const char* cpackWixProgramMenuFolder =
+ cmProp cpackWixProgramMenuFolder =
GetOption("CPACK_WIX_PROGRAM_MENU_FOLDER");
- if (cpackWixProgramMenuFolder &&
- cm::string_view(cpackWixProgramMenuFolder) == ".") {
+ if (cpackWixProgramMenuFolder && cpackWixProgramMenuFolder == ".") {
emitUninstallShortcut = false;
} else if (emittedShortcutTypes.find(cmWIXShortcuts::START_MENU) ==
emittedShortcutTypes.end()) {
@@ -595,9 +595,9 @@ std::string cmCPackWIXGenerator::GetRootFolderId() const
std::string result = "ProgramFiles<64>Folder";
- const char* rootFolderId = GetOption("CPACK_WIX_ROOT_FOLDER_ID");
+ cmProp rootFolderId = GetOption("CPACK_WIX_ROOT_FOLDER_ID");
if (rootFolderId) {
- result = rootFolderId;
+ result = *rootFolderId;
}
if (GetArchitecture() == "x86") {
@@ -612,8 +612,8 @@ std::string cmCPackWIXGenerator::GetRootFolderId() const
bool cmCPackWIXGenerator::GenerateMainSourceFileFromTemplate()
{
std::string wixTemplate = FindTemplate("WIX.template.in");
- if (GetOption("CPACK_WIX_TEMPLATE") != 0) {
- wixTemplate = GetOption("CPACK_WIX_TEMPLATE");
+ if (cmProp wixtpl = GetOption("CPACK_WIX_TEMPLATE")) {
+ wixTemplate = *wixtpl;
}
if (wixTemplate.empty()) {
@@ -669,7 +669,7 @@ bool cmCPackWIXGenerator::AddComponentsToFeature(
featureDefinitions.AddAttribute("Id", featureId);
std::vector<std::string> cpackPackageExecutablesList;
- const char* cpackPackageExecutables = GetOption("CPACK_PACKAGE_EXECUTABLES");
+ cmProp cpackPackageExecutables = GetOption("CPACK_PACKAGE_EXECUTABLES");
if (cpackPackageExecutables) {
cmExpandList(cpackPackageExecutables, cpackPackageExecutablesList);
if (cpackPackageExecutablesList.size() % 2 != 0) {
@@ -683,8 +683,7 @@ bool cmCPackWIXGenerator::AddComponentsToFeature(
}
std::vector<std::string> cpackPackageDesktopLinksList;
- const char* cpackPackageDesktopLinks =
- GetOption("CPACK_CREATE_DESKTOP_LINKS");
+ cmProp cpackPackageDesktopLinks = GetOption("CPACK_CREATE_DESKTOP_LINKS");
if (cpackPackageDesktopLinks) {
cmExpandList(cpackPackageDesktopLinks, cpackPackageDesktopLinksList);
}
@@ -743,10 +742,9 @@ bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
std::string directoryId;
switch (type) {
case cmWIXShortcuts::START_MENU: {
- const char* cpackWixProgramMenuFolder =
+ cmProp cpackWixProgramMenuFolder =
GetOption("CPACK_WIX_PROGRAM_MENU_FOLDER");
- if (cpackWixProgramMenuFolder &&
- cm::string_view(cpackWixProgramMenuFolder) == ".") {
+ if (cpackWixProgramMenuFolder && cpackWixProgramMenuFolder == ".") {
directoryId = "ProgramMenuFolder";
} else {
directoryId = "PROGRAM_MENU_FOLDER";
@@ -805,10 +803,9 @@ bool cmCPackWIXGenerator::CreateShortcutsOfSpecificType(
fileDefinitions);
if (type == cmWIXShortcuts::START_MENU) {
- const char* cpackWixProgramMenuFolder =
+ cmProp cpackWixProgramMenuFolder =
GetOption("CPACK_WIX_PROGRAM_MENU_FOLDER");
- if (cpackWixProgramMenuFolder &&
- cm::string_view(cpackWixProgramMenuFolder) != ".") {
+ if (cpackWixProgramMenuFolder && cpackWixProgramMenuFolder != ".") {
fileDefinitions.EmitRemoveFolder("CM_REMOVE_PROGRAM_MENU_FOLDER" +
idSuffix);
}
@@ -973,9 +970,9 @@ void cmCPackWIXGenerator::AddDirectoryAndFileDefinitions(
bool cmCPackWIXGenerator::RequireOption(std::string const& name,
std::string& value) const
{
- const char* tmp = GetOption(name.c_str());
+ cmProp tmp = GetOption(name);
if (tmp) {
- value = tmp;
+ value = *tmp;
return true;
} else {
@@ -1146,7 +1143,7 @@ bool cmCPackWIXGenerator::IsLegalIdCharacter(char c)
void cmCPackWIXGenerator::CollectExtensions(std::string const& variableName,
extension_set_t& extensions)
{
- const char* variableContent = GetOption(variableName.c_str());
+ cmProp variableContent = GetOption(variableName);
if (!variableContent)
return;
@@ -1157,7 +1154,7 @@ void cmCPackWIXGenerator::CollectExtensions(std::string const& variableName,
void cmCPackWIXGenerator::CollectXmlNamespaces(std::string const& variableName,
xmlns_map_t& namespaces)
{
- const char* variableContent = GetOption(variableName.c_str());
+ cmProp variableContent = GetOption(variableName);
if (!variableContent) {
return;
}
@@ -1186,7 +1183,7 @@ void cmCPackWIXGenerator::CollectXmlNamespaces(std::string const& variableName,
void cmCPackWIXGenerator::AddCustomFlags(std::string const& variableName,
std::ostream& stream)
{
- const char* variableContent = GetOption(variableName.c_str());
+ cmProp variableContent = GetOption(variableName);
if (!variableContent)
return;
diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx
index d9234e6..4f90ba2 100644
--- a/Source/CPack/cmCPackArchiveGenerator.cxx
+++ b/Source/CPack/cmCPackArchiveGenerator.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackArchiveGenerator.h"
-#include <cstdlib>
#include <cstring>
#include <map>
#include <ostream>
@@ -13,6 +12,7 @@
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmWorkingDirectory.h"
@@ -77,7 +77,7 @@ std::string cmCPackArchiveGenerator::GetArchiveComponentFileName(
if (this->IsSet("CPACK_ARCHIVE_" + componentUpper + "_FILE_NAME")) {
packageFileName +=
- this->GetOption("CPACK_ARCHIVE_" + componentUpper + "_FILE_NAME");
+ *this->GetOption("CPACK_ARCHIVE_" + componentUpper + "_FILE_NAME");
} else if (this->IsSet("CPACK_ARCHIVE_FILE_NAME")) {
packageFileName += this->GetComponentPackageFileName(
this->GetOption("CPACK_ARCHIVE_FILE_NAME"), component, isGroupName);
@@ -118,11 +118,11 @@ int cmCPackArchiveGenerator::addOneComponentToArchive(
if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY")) {
filePrefix = cmStrCat(this->GetOption("CPACK_PACKAGE_FILE_NAME"), '/');
}
- const char* installPrefix =
- this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
- if (installPrefix && installPrefix[0] == '/' && installPrefix[1] != 0) {
+ cmProp installPrefix = this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
+ if (installPrefix && installPrefix->size() > 1 &&
+ (*installPrefix)[0] == '/') {
// add to file prefix and remove the leading '/'
- filePrefix += installPrefix + 1;
+ filePrefix += installPrefix->substr(1);
filePrefix += "/";
}
for (std::string const& file : component->Files) {
@@ -257,9 +257,9 @@ int cmCPackArchiveGenerator::PackageComponentsAllInOne()
this->packageFileNames[0] += "/";
if (this->IsSet("CPACK_ARCHIVE_FILE_NAME")) {
- this->packageFileNames[0] += this->GetOption("CPACK_ARCHIVE_FILE_NAME");
+ this->packageFileNames[0] += *this->GetOption("CPACK_ARCHIVE_FILE_NAME");
} else {
- this->packageFileNames[0] += this->GetOption("CPACK_PACKAGE_FILE_NAME");
+ this->packageFileNames[0] += *this->GetOption("CPACK_PACKAGE_FILE_NAME");
}
this->packageFileNames[0] += this->GetOutputExtension();
@@ -345,9 +345,9 @@ int cmCPackArchiveGenerator::GetThreadCount() const
// CPACK_ARCHIVE_THREADS overrides CPACK_THREADS
if (this->IsSet("CPACK_ARCHIVE_THREADS")) {
- threads = std::atoi(this->GetOption("CPACK_ARCHIVE_THREADS"));
+ threads = std::stoi(this->GetOption("CPACK_ARCHIVE_THREADS"));
} else if (this->IsSet("CPACK_THREADS")) {
- threads = std::atoi(this->GetOption("CPACK_THREADS"));
+ threads = std::stoi(this->GetOption("CPACK_THREADS"));
}
return threads;
diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx
index 4d5f43f..a2e0be4 100644
--- a/Source/CPack/cmCPackBundleGenerator.cxx
+++ b/Source/CPack/cmCPackBundleGenerator.cxx
@@ -6,6 +6,7 @@
#include <vector>
#include "cmCPackLog.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -15,8 +16,8 @@ cmCPackBundleGenerator::~cmCPackBundleGenerator() = default;
int cmCPackBundleGenerator::InitializeInternal()
{
- const char* name = this->GetOption("CPACK_BUNDLE_NAME");
- if (nullptr == name) {
+ cmProp name = this->GetOption("CPACK_BUNDLE_NAME");
+ if (!name) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_NAME must be set to use the Bundle generator."
<< std::endl);
@@ -51,30 +52,24 @@ int cmCPackBundleGenerator::ConstructBundle()
{
// Get required arguments ...
- const std::string cpack_bundle_name = this->GetOption("CPACK_BUNDLE_NAME")
- ? this->GetOption("CPACK_BUNDLE_NAME")
- : "";
- if (cpack_bundle_name.empty()) {
+ cmProp cpack_bundle_name = this->GetOption("CPACK_BUNDLE_NAME");
+ if (cpack_bundle_name->empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_NAME must be set." << std::endl);
return 0;
}
- const std::string cpack_bundle_plist = this->GetOption("CPACK_BUNDLE_PLIST")
- ? this->GetOption("CPACK_BUNDLE_PLIST")
- : "";
- if (cpack_bundle_plist.empty()) {
+ cmProp cpack_bundle_plist = this->GetOption("CPACK_BUNDLE_PLIST");
+ if (cpack_bundle_plist->empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_PLIST must be set." << std::endl);
return 0;
}
- const std::string cpack_bundle_icon = this->GetOption("CPACK_BUNDLE_ICON")
- ? this->GetOption("CPACK_BUNDLE_ICON")
- : "";
- if (cpack_bundle_icon.empty()) {
+ cmProp cpack_bundle_icon = this->GetOption("CPACK_BUNDLE_ICON");
+ if (cpack_bundle_icon->empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_ICON must be set." << std::endl);
@@ -82,10 +77,8 @@ int cmCPackBundleGenerator::ConstructBundle()
}
// Get optional arguments ...
- const std::string cpack_bundle_startup_command =
- this->GetOption("CPACK_BUNDLE_STARTUP_COMMAND")
- ? this->GetOption("CPACK_BUNDLE_STARTUP_COMMAND")
- : "";
+ cmProp cpack_bundle_startup_command =
+ this->GetOption("CPACK_BUNDLE_STARTUP_COMMAND");
// The staging directory contains everything that will end-up inside the
// final disk image ...
@@ -138,7 +131,7 @@ int cmCPackBundleGenerator::ConstructBundle()
// Optionally a user-provided startup command (could be an
// executable or a script) ...
- if (!cpack_bundle_startup_command.empty()) {
+ if (!cpack_bundle_startup_command->empty()) {
std::ostringstream command_source;
command_source << cpack_bundle_startup_command;
@@ -180,13 +173,10 @@ bool cmCPackBundleGenerator::SupportsComponentInstallation() const
int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
{
- const std::string cpack_apple_cert_app =
- this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP")
- ? this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP")
- : "";
+ cmProp cpack_apple_cert_app = this->GetOption("CPACK_BUNDLE_APPLE_CERT_APP");
// codesign the application.
- if (!cpack_apple_cert_app.empty()) {
+ if (!cpack_apple_cert_app->empty()) {
std::string output;
std::string bundle_path;
bundle_path =
@@ -195,13 +185,10 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
// A list of additional files to sign, ie. frameworks and plugins.
const std::string sign_parameter =
this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_PARAMETER")
- ? this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_PARAMETER")
+ ? *this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_PARAMETER")
: "--deep -f";
- const std::string sign_files =
- this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_FILES")
- ? this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_FILES")
- : "";
+ cmProp sign_files = this->GetOption("CPACK_BUNDLE_APPLE_CODESIGN_FILES");
std::vector<std::string> relFiles = cmExpandedList(sign_files);
diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx
index b5abd5a..1de5e1c 100644
--- a/Source/CPack/cmCPackCygwinBinaryGenerator.cxx
+++ b/Source/CPack/cmCPackCygwinBinaryGenerator.cxx
@@ -8,6 +8,7 @@
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
+#include "cmProperty.h"
#include "cmSystemTools.h"
#include "cmake.h"
@@ -59,14 +60,15 @@ int cmCPackCygwinBinaryGenerator::PackageFiles()
const char* cmCPackCygwinBinaryGenerator::GetOutputExtension()
{
this->OutputExtension = "-";
- const char* patchNumber = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
+ cmProp patchNumber = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if (!patchNumber) {
- patchNumber = "1";
+ this->OutputExtension += "1";
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_CYGWIN_PATCH_NUMBER not specified using 1"
<< std::endl);
+ } else {
+ this->OutputExtension += patchNumber;
}
- this->OutputExtension += patchNumber;
this->OutputExtension += ".tar.bz2";
return this->OutputExtension.c_str();
}
diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.cxx b/Source/CPack/cmCPackCygwinSourceGenerator.cxx
index 64a88eb..684a988 100644
--- a/Source/CPack/cmCPackCygwinSourceGenerator.cxx
+++ b/Source/CPack/cmCPackCygwinSourceGenerator.cxx
@@ -8,6 +8,7 @@
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
+#include "cmProperty.h"
#include "cmSystemTools.h"
#include "cmake.h"
@@ -94,14 +95,15 @@ int cmCPackCygwinSourceGenerator::PackageFiles()
}
std::string outerTarFile =
cmStrCat(this->GetOption("CPACK_TEMPORARY_DIRECTORY"), '-');
- const char* patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
+ cmProp patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if (!patch) {
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_CYGWIN_PATCH_NUMBER"
<< " not specified, defaulting to 1\n");
- patch = "1";
+ outerTarFile += "1";
+ } else {
+ outerTarFile += patch;
}
- outerTarFile += patch;
outerTarFile += "-src.tar.bz2";
std::string tmpDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
std::string buildScript =
@@ -145,14 +147,15 @@ const char* cmCPackCygwinSourceGenerator::GetPackagingInstallPrefix()
const char* cmCPackCygwinSourceGenerator::GetOutputExtension()
{
this->OutputExtension = "-";
- const char* patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
+ cmProp patch = this->GetOption("CPACK_CYGWIN_PATCH_NUMBER");
if (!patch) {
cmCPackLogger(cmCPackLog::LOG_WARNING,
"CPACK_CYGWIN_PATCH_NUMBER"
<< " not specified, defaulting to 1\n");
- patch = "1";
+ this->OutputExtension += "1";
+ } else {
+ this->OutputExtension += patch;
}
- this->OutputExtension += patch;
this->OutputExtension += "-src.tar.bz2";
return this->OutputExtension.c_str();
}
diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx
index 5f0f153..52b94c4 100644
--- a/Source/CPack/cmCPackDebGenerator.cxx
+++ b/Source/CPack/cmCPackDebGenerator.cxx
@@ -20,6 +20,7 @@
#include "cmCPackLog.h"
#include "cmCryptoHash.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -30,12 +31,12 @@ class DebGenerator
public:
DebGenerator(cmCPackLog* logger, std::string outputName, std::string workDir,
std::string topLevelDir, std::string temporaryDir,
- const char* debianCompressionType, const char* numThreads,
- const char* debianArchiveType,
+ cmProp debianCompressionType, cmProp numThreads,
+ cmProp debianArchiveType,
std::map<std::string, std::string> controlValues,
bool genShLibs, std::string shLibsFilename, bool genPostInst,
std::string postInst, bool genPostRm, std::string postRm,
- const char* controlExtra, bool permissionStrctPolicy,
+ cmProp controlExtra, bool permissionStrctPolicy,
std::vector<std::string> packageFiles);
bool generate() const;
@@ -54,7 +55,7 @@ private:
std::string CompressionSuffix;
const std::string TopLevelDir;
const std::string TemporaryDir;
- const char* DebianArchiveType;
+ const std::string DebianArchiveType;
long NumThreads;
const std::map<std::string, std::string> ControlValues;
const bool GenShLibs;
@@ -63,27 +64,28 @@ private:
const std::string PostInst;
const bool GenPostRm;
const std::string PostRm;
- const char* ControlExtra;
+ cmProp ControlExtra;
const bool PermissionStrictPolicy;
const std::vector<std::string> PackageFiles;
cmArchiveWrite::Compress TarCompressionType;
};
-DebGenerator::DebGenerator(
- cmCPackLog* logger, std::string outputName, std::string workDir,
- std::string topLevelDir, std::string temporaryDir,
- const char* debianCompressionType, const char* numThreads,
- const char* debianArchiveType,
- std::map<std::string, std::string> controlValues, bool genShLibs,
- std::string shLibsFilename, bool genPostInst, std::string postInst,
- bool genPostRm, std::string postRm, const char* controlExtra,
- bool permissionStrictPolicy, std::vector<std::string> packageFiles)
+DebGenerator::DebGenerator(cmCPackLog* logger, std::string outputName,
+ std::string workDir, std::string topLevelDir,
+ std::string temporaryDir, cmProp debCompressionType,
+ cmProp numThreads, cmProp debianArchiveType,
+ std::map<std::string, std::string> controlValues,
+ bool genShLibs, std::string shLibsFilename,
+ bool genPostInst, std::string postInst,
+ bool genPostRm, std::string postRm,
+ cmProp controlExtra, bool permissionStrictPolicy,
+ std::vector<std::string> packageFiles)
: Logger(logger)
, OutputName(std::move(outputName))
, WorkDir(std::move(workDir))
, TopLevelDir(std::move(topLevelDir))
, TemporaryDir(std::move(temporaryDir))
- , DebianArchiveType(debianArchiveType ? debianArchiveType : "gnutar")
+ , DebianArchiveType(debianArchiveType ? *debianArchiveType : "gnutar")
, ControlValues(std::move(controlValues))
, GenShLibs(genShLibs)
, ShLibsFilename(std::move(shLibsFilename))
@@ -95,26 +97,27 @@ DebGenerator::DebGenerator(
, PermissionStrictPolicy(permissionStrictPolicy)
, PackageFiles(std::move(packageFiles))
{
- if (!debianCompressionType) {
- debianCompressionType = "gzip";
+ std::string debianCompressionType = "gzip";
+ if (debCompressionType) {
+ debianCompressionType = *debCompressionType;
}
- if (!std::strcmp(debianCompressionType, "lzma")) {
+ if (debianCompressionType == "lzma") {
this->CompressionSuffix = ".lzma";
this->TarCompressionType = cmArchiveWrite::CompressLZMA;
- } else if (!std::strcmp(debianCompressionType, "xz")) {
+ } else if (debianCompressionType == "xz") {
this->CompressionSuffix = ".xz";
this->TarCompressionType = cmArchiveWrite::CompressXZ;
- } else if (!std::strcmp(debianCompressionType, "bzip2")) {
+ } else if (debianCompressionType == "bzip2") {
this->CompressionSuffix = ".bz2";
this->TarCompressionType = cmArchiveWrite::CompressBZip2;
- } else if (!std::strcmp(debianCompressionType, "gzip")) {
+ } else if (debianCompressionType == "gzip") {
this->CompressionSuffix = ".gz";
this->TarCompressionType = cmArchiveWrite::CompressGZip;
- } else if (!std::strcmp(debianCompressionType, "zstd")) {
+ } else if (debianCompressionType == "zstd") {
this->CompressionSuffix = ".zst";
this->TarCompressionType = cmArchiveWrite::CompressZstd;
- } else if (!std::strcmp(debianCompressionType, "none")) {
+ } else if (debianCompressionType == "none") {
this->CompressionSuffix.clear();
this->TarCompressionType = cmArchiveWrite::CompressNone;
} else {
@@ -192,7 +195,13 @@ bool DebGenerator::generateDataTar() const
cmArchiveWrite data_tar(fileStream_data_tar, this->TarCompressionType,
this->DebianArchiveType, 0,
static_cast<int>(this->NumThreads));
- data_tar.Open();
+ if (!data_tar.Open()) {
+ cmCPackLogger(cmCPackLog::LOG_ERROR,
+ "Error opening the archive \""
+ << filename_data_tar
+ << "\", ERROR = " << data_tar.GetError() << std::endl);
+ return false;
+ }
// uid/gid should be the one of the root user, and this root user has
// always uid/gid equal to 0.
@@ -317,7 +326,13 @@ bool DebGenerator::generateControlTar(std::string const& md5Filename) const
cmArchiveWrite control_tar(fileStream_control_tar,
cmArchiveWrite::CompressGZip,
this->DebianArchiveType);
- control_tar.Open();
+ if (!control_tar.Open()) {
+ cmCPackLogger(cmCPackLog::LOG_ERROR,
+ "Error opening the archive \""
+ << filename_control_tar
+ << "\", ERROR = " << control_tar.GetError() << std::endl);
+ return false;
+ }
// sets permissions and uid/gid for the files
control_tar.SetUIDAndGID(0u, 0u);
@@ -457,7 +472,13 @@ bool DebGenerator::generateDeb() const
cmGeneratedFileStream debStream;
debStream.Open(outputPath, false, true);
cmArchiveWrite deb(debStream, cmArchiveWrite::CompressNone, "arbsd");
- deb.Open();
+ if (!deb.Open()) {
+ cmCPackLogger(cmCPackLog::LOG_ERROR,
+ "Error opening the archive \""
+ << outputPath << "\", ERROR = " << deb.GetError()
+ << std::endl);
+ return false;
+ }
// uid/gid should be the one of the root user, and this root user has
// always uid/gid equal to 0.
@@ -521,9 +542,8 @@ int cmCPackDebGenerator::PackageOnePack(std::string const& initialTopLevel,
std::string localToplevel(initialTopLevel);
std::string packageFileName(
cmSystemTools::GetParentDirectory(this->toplevel));
- std::string outputFileName(
- std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) + "-" +
- packageName + this->GetOutputExtension());
+ std::string outputFileName(*this->GetOption("CPACK_PACKAGE_FILE_NAME") +
+ "-" + packageName + this->GetOutputExtension());
localToplevel += "/" + packageName;
/* replace the TEMP DIRECTORY with the component one */
@@ -609,9 +629,8 @@ int cmCPackDebGenerator::PackageComponentsAllInOne(
std::string localToplevel(initialTopLevel);
std::string packageFileName(
cmSystemTools::GetParentDirectory(this->toplevel));
- std::string outputFileName(
- std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
- this->GetOutputExtension());
+ std::string outputFileName(*this->GetOption("CPACK_PACKAGE_FILE_NAME") +
+ this->GetOutputExtension());
// all GROUP in one vs all COMPONENT in one
// if must be here otherwise non component paths have a trailing / while
// components don't
@@ -666,7 +685,7 @@ int cmCPackDebGenerator::PackageFiles()
bool cmCPackDebGenerator::createDebPackages()
{
- auto make_package = [this](const char* const path,
+ auto make_package = [this](const std::string& path,
const char* const output_var,
bool (cmCPackDebGenerator::*creator)()) -> bool {
try {
@@ -688,7 +707,7 @@ bool cmCPackDebGenerator::createDebPackages()
bool retval =
make_package(this->GetOption("GEN_WDIR"), "GEN_CPACK_OUTPUT_FILE_NAME",
&cmCPackDebGenerator::createDeb);
- const char* const dbgsymdir_path = this->GetOption("GEN_DBGSYMDIR");
+ cmProp dbgsymdir_path = this->GetOption("GEN_DBGSYMDIR");
if (this->IsOn("GEN_CPACK_DEBIAN_DEBUGINFO_PACKAGE") && dbgsymdir_path) {
retval = make_package(dbgsymdir_path, "GEN_CPACK_DBGSYM_OUTPUT_FILE_NAME",
&cmCPackDebGenerator::createDbgsymDDeb) &&
@@ -705,78 +724,75 @@ bool cmCPackDebGenerator::createDeb()
controlValues["Package"] = cmsys::SystemTools::LowerCase(
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME"));
controlValues["Version"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
controlValues["Section"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SECTION");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SECTION");
controlValues["Priority"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PRIORITY");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PRIORITY");
controlValues["Architecture"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
controlValues["Maintainer"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
controlValues["Description"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DESCRIPTION");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DESCRIPTION");
- const char* debian_pkg_source =
+ cmProp debian_pkg_source =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SOURCE");
if (cmNonempty(debian_pkg_source)) {
- controlValues["Source"] = debian_pkg_source;
+ controlValues["Source"] = *debian_pkg_source;
}
- const char* debian_pkg_dep =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DEPENDS");
+ cmProp debian_pkg_dep = this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DEPENDS");
if (cmNonempty(debian_pkg_dep)) {
- controlValues["Depends"] = debian_pkg_dep;
+ controlValues["Depends"] = *debian_pkg_dep;
}
- const char* debian_pkg_rec =
+ cmProp debian_pkg_rec =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_RECOMMENDS");
if (cmNonempty(debian_pkg_rec)) {
- controlValues["Recommends"] = debian_pkg_rec;
+ controlValues["Recommends"] = *debian_pkg_rec;
}
- const char* debian_pkg_sug =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SUGGESTS");
+ cmProp debian_pkg_sug = this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SUGGESTS");
if (cmNonempty(debian_pkg_sug)) {
- controlValues["Suggests"] = debian_pkg_sug;
+ controlValues["Suggests"] = *debian_pkg_sug;
}
- const char* debian_pkg_url =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_HOMEPAGE");
+ cmProp debian_pkg_url = this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_HOMEPAGE");
if (cmNonempty(debian_pkg_url)) {
- controlValues["Homepage"] = debian_pkg_url;
+ controlValues["Homepage"] = *debian_pkg_url;
}
- const char* debian_pkg_predep =
+ cmProp debian_pkg_predep =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PREDEPENDS");
if (cmNonempty(debian_pkg_predep)) {
- controlValues["Pre-Depends"] = debian_pkg_predep;
+ controlValues["Pre-Depends"] = *debian_pkg_predep;
}
- const char* debian_pkg_enhances =
+ cmProp debian_pkg_enhances =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ENHANCES");
if (cmNonempty(debian_pkg_enhances)) {
- controlValues["Enhances"] = debian_pkg_enhances;
+ controlValues["Enhances"] = *debian_pkg_enhances;
}
- const char* debian_pkg_breaks =
+ cmProp debian_pkg_breaks =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_BREAKS");
if (cmNonempty(debian_pkg_breaks)) {
- controlValues["Breaks"] = debian_pkg_breaks;
+ controlValues["Breaks"] = *debian_pkg_breaks;
}
- const char* debian_pkg_conflicts =
+ cmProp debian_pkg_conflicts =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_CONFLICTS");
if (cmNonempty(debian_pkg_conflicts)) {
- controlValues["Conflicts"] = debian_pkg_conflicts;
+ controlValues["Conflicts"] = *debian_pkg_conflicts;
}
- const char* debian_pkg_provides =
+ cmProp debian_pkg_provides =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PROVIDES");
if (cmNonempty(debian_pkg_provides)) {
- controlValues["Provides"] = debian_pkg_provides;
+ controlValues["Provides"] = *debian_pkg_provides;
}
- const char* debian_pkg_replaces =
+ cmProp debian_pkg_replaces =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_REPLACES");
if (cmNonempty(debian_pkg_replaces)) {
- controlValues["Replaces"] = debian_pkg_replaces;
+ controlValues["Replaces"] = *debian_pkg_replaces;
}
const std::string strGenWDIR(this->GetOption("GEN_WDIR"));
const std::string shlibsfilename = strGenWDIR + "/shlibs";
- const char* debian_pkg_shlibs =
+ cmProp debian_pkg_shlibs =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SHLIBS");
const bool gen_shibs = this->IsOn("CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS") &&
cmNonempty(debian_pkg_shlibs);
@@ -833,32 +849,33 @@ bool cmCPackDebGenerator::createDbgsymDDeb()
// debian policy enforce lower case for package name
std::string packageNameLower = cmsys::SystemTools::LowerCase(
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME"));
- const char* debian_pkg_version =
+ cmProp debian_pkg_version =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
controlValues["Package"] = packageNameLower + "-dbgsym";
controlValues["Package-Type"] = "ddeb";
- controlValues["Version"] = debian_pkg_version;
+ controlValues["Version"] = *debian_pkg_version;
controlValues["Auto-Built-Package"] = "debug-symbols";
- controlValues["Depends"] = this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME") +
- std::string(" (= ") + debian_pkg_version + ")";
+ controlValues["Depends"] =
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME") + std::string(" (= ") +
+ *debian_pkg_version + ")";
controlValues["Section"] = "debug";
controlValues["Priority"] = "optional";
controlValues["Architecture"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
controlValues["Maintainer"] =
- this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
+ *this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
controlValues["Description"] =
std::string("debug symbols for ") + packageNameLower;
- const char* debian_pkg_source =
+ cmProp debian_pkg_source =
this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SOURCE");
if (cmNonempty(debian_pkg_source)) {
- controlValues["Source"] = debian_pkg_source;
+ controlValues["Source"] = *debian_pkg_source;
}
- const char* debian_build_ids = this->GetOption("GEN_BUILD_IDS");
+ cmProp debian_build_ids = this->GetOption("GEN_BUILD_IDS");
if (cmNonempty(debian_build_ids)) {
- controlValues["Build-Ids"] = debian_build_ids;
+ controlValues["Build-Ids"] = *debian_build_ids;
}
DebGenerator gen(
@@ -896,7 +913,7 @@ std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
if (nullptr != this->GetOption(groupVar)) {
- return std::string(this->GetOption(groupVar));
+ return *this->GetOption(groupVar);
}
return componentName;
}
diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx
index b71c969..a4e4ab3 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.cxx
+++ b/Source/CPack/cmCPackDragNDropGenerator.cxx
@@ -18,6 +18,7 @@
#include "cmCPackLog.h"
#include "cmDuration.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
@@ -260,48 +261,35 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
const std::string& output_file)
{
// Get optional arguments ...
- const std::string cpack_package_icon = this->GetOption("CPACK_PACKAGE_ICON")
- ? this->GetOption("CPACK_PACKAGE_ICON")
- : "";
+ cmProp cpack_package_icon = this->GetOption("CPACK_PACKAGE_ICON");
const std::string cpack_dmg_volume_name =
this->GetOption("CPACK_DMG_VOLUME_NAME")
- ? this->GetOption("CPACK_DMG_VOLUME_NAME")
- : this->GetOption("CPACK_PACKAGE_FILE_NAME");
+ ? *this->GetOption("CPACK_DMG_VOLUME_NAME")
+ : *this->GetOption("CPACK_PACKAGE_FILE_NAME");
const std::string cpack_dmg_format = this->GetOption("CPACK_DMG_FORMAT")
- ? this->GetOption("CPACK_DMG_FORMAT")
+ ? *this->GetOption("CPACK_DMG_FORMAT")
: "UDZO";
const std::string cpack_dmg_filesystem =
this->GetOption("CPACK_DMG_FILESYSTEM")
- ? this->GetOption("CPACK_DMG_FILESYSTEM")
+ ? *this->GetOption("CPACK_DMG_FILESYSTEM")
: "HFS+";
// Get optional arguments ...
std::string cpack_license_file =
- this->GetOption("CPACK_RESOURCE_FILE_LICENSE")
- ? this->GetOption("CPACK_RESOURCE_FILE_LICENSE")
- : "";
+ *this->GetOption("CPACK_RESOURCE_FILE_LICENSE");
- const std::string cpack_dmg_background_image =
- this->GetOption("CPACK_DMG_BACKGROUND_IMAGE")
- ? this->GetOption("CPACK_DMG_BACKGROUND_IMAGE")
- : "";
+ cmProp cpack_dmg_background_image =
+ this->GetOption("CPACK_DMG_BACKGROUND_IMAGE");
- const std::string cpack_dmg_ds_store = this->GetOption("CPACK_DMG_DS_STORE")
- ? this->GetOption("CPACK_DMG_DS_STORE")
- : "";
+ cmProp cpack_dmg_ds_store = this->GetOption("CPACK_DMG_DS_STORE");
- const std::string cpack_dmg_languages =
- this->GetOption("CPACK_DMG_SLA_LANGUAGES")
- ? this->GetOption("CPACK_DMG_SLA_LANGUAGES")
- : "";
+ cmProp cpack_dmg_languages = this->GetOption("CPACK_DMG_SLA_LANGUAGES");
- const std::string cpack_dmg_ds_store_setup_script =
- this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT")
- ? this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT")
- : "";
+ cmProp cpack_dmg_ds_store_setup_script =
+ this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT");
const bool cpack_dmg_disable_applications_symlink =
this->IsOn("CPACK_DMG_DISABLE_APPLICATIONS_SYMLINK");
@@ -332,7 +320,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
}
// Optionally add a custom volume icon ...
- if (!cpack_package_icon.empty()) {
+ if (!cpack_package_icon->empty()) {
std::ostringstream package_icon_source;
package_icon_source << cpack_package_icon;
@@ -351,7 +339,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
// Optionally add a custom .DS_Store file
// (e.g. for setting background/layout) ...
- if (!cpack_dmg_ds_store.empty()) {
+ if (!cpack_dmg_ds_store->empty()) {
std::ostringstream package_settings_source;
package_settings_source << cpack_dmg_ds_store;
@@ -372,7 +360,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
// Optionally add a custom background image ...
// Make sure the background file type is the same as the custom image
// and that the file is hidden so it doesn't show up.
- if (!cpack_dmg_background_image.empty()) {
+ if (!cpack_dmg_background_image->empty()) {
const std::string extension =
cmSystemTools::GetFilenameLastExtension(cpack_dmg_background_image);
std::ostringstream package_background_source;
@@ -394,7 +382,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
}
bool remount_image =
- !cpack_package_icon.empty() || !cpack_dmg_ds_store_setup_script.empty();
+ !cpack_package_icon->empty() || !cpack_dmg_ds_store_setup_script->empty();
std::string temp_image_format = "UDZO";
@@ -471,7 +459,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
}
// Optionally set the custom icon flag for the image ...
- if (!had_error && !cpack_package_icon.empty()) {
+ if (!had_error && !cpack_package_icon->empty()) {
std::string error;
std::ostringstream setfile_command;
setfile_command << this->GetOption("CPACK_COMMAND_SETFILE");
@@ -490,7 +478,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
// Optionally we can execute a custom apple script to generate
// the .DS_Store for the volume folder ...
- if (!had_error && !cpack_dmg_ds_store_setup_script.empty()) {
+ if (!had_error && !cpack_dmg_ds_store_setup_script->empty()) {
std::ostringstream setup_script_command;
setup_script_command << "osascript"
<< " \"" << cpack_dmg_ds_store_setup_script << "\""
@@ -718,7 +706,7 @@ std::string cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix(
// the current COMPONENT belongs to.
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
- const char* _groupName = GetOption(groupVar);
+ cmProp _groupName = this->GetOption(groupVar);
if (_groupName) {
std::string groupName = _groupName;
diff --git a/Source/CPack/cmCPackExternalGenerator.cxx b/Source/CPack/cmCPackExternalGenerator.cxx
index e3521a0..9cdaafe 100644
--- a/Source/CPack/cmCPackExternalGenerator.cxx
+++ b/Source/CPack/cmCPackExternalGenerator.cxx
@@ -16,6 +16,7 @@
#include "cmCPackComponentGroup.h"
#include "cmCPackLog.h"
#include "cmMakefile.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -60,7 +61,7 @@ int cmCPackExternalGenerator::PackageFiles()
return 0;
}
- const char* packageScript = this->GetOption("CPACK_EXTERNAL_PACKAGE_SCRIPT");
+ cmProp packageScript = this->GetOption("CPACK_EXTERNAL_PACKAGE_SCRIPT");
if (cmNonempty(packageScript)) {
if (!cmSystemTools::FileIsFullPath(packageScript)) {
cmCPackLogger(
@@ -76,10 +77,9 @@ int cmCPackExternalGenerator::PackageFiles()
return 0;
}
- const char* builtPackagesStr =
- this->GetOption("CPACK_EXTERNAL_BUILT_PACKAGES");
- if (builtPackagesStr) {
- cmExpandList(builtPackagesStr, this->packageFileNames, false);
+ cmProp builtPackages = this->GetOption("CPACK_EXTERNAL_BUILT_PACKAGES");
+ if (builtPackages) {
+ cmExpandList(builtPackages, this->packageFileNames, false);
}
}
@@ -181,43 +181,42 @@ int cmCPackExternalGenerator::cmCPackExternalVersionGenerator::WriteToJSON(
return 0;
}
- const char* packageName = this->Parent->GetOption("CPACK_PACKAGE_NAME");
+ cmProp packageName = this->Parent->GetOption("CPACK_PACKAGE_NAME");
if (packageName) {
- root["packageName"] = packageName;
+ root["packageName"] = *packageName;
}
- const char* packageVersion =
- this->Parent->GetOption("CPACK_PACKAGE_VERSION");
+ cmProp packageVersion = this->Parent->GetOption("CPACK_PACKAGE_VERSION");
if (packageVersion) {
- root["packageVersion"] = packageVersion;
+ root["packageVersion"] = *packageVersion;
}
- const char* packageDescriptionFile =
+ cmProp packageDescriptionFile =
this->Parent->GetOption("CPACK_PACKAGE_DESCRIPTION_FILE");
if (packageDescriptionFile) {
- root["packageDescriptionFile"] = packageDescriptionFile;
+ root["packageDescriptionFile"] = *packageDescriptionFile;
}
- const char* packageDescriptionSummary =
+ cmProp packageDescriptionSummary =
this->Parent->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY");
if (packageDescriptionSummary) {
- root["packageDescriptionSummary"] = packageDescriptionSummary;
+ root["packageDescriptionSummary"] = *packageDescriptionSummary;
}
- const char* buildConfigCstr = this->Parent->GetOption("CPACK_BUILD_CONFIG");
+ cmProp buildConfigCstr = this->Parent->GetOption("CPACK_BUILD_CONFIG");
if (buildConfigCstr) {
- root["buildConfig"] = buildConfigCstr;
+ root["buildConfig"] = *buildConfigCstr;
}
- const char* defaultDirectoryPermissions =
+ cmProp defaultDirectoryPermissions =
this->Parent->GetOption("CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS");
if (cmNonempty(defaultDirectoryPermissions)) {
- root["defaultDirectoryPermissions"] = defaultDirectoryPermissions;
+ root["defaultDirectoryPermissions"] = *defaultDirectoryPermissions;
}
if (cmIsInternallyOn(this->Parent->GetOption("CPACK_SET_DESTDIR"))) {
root["setDestdir"] = true;
root["packagingInstallPrefix"] =
- this->Parent->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
+ *this->Parent->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
} else {
root["setDestdir"] = false;
}
diff --git a/Source/CPack/cmCPackFreeBSDGenerator.cxx b/Source/CPack/cmCPackFreeBSDGenerator.cxx
index b673006..39ec3c8 100644
--- a/Source/CPack/cmCPackFreeBSDGenerator.cxx
+++ b/Source/CPack/cmCPackFreeBSDGenerator.cxx
@@ -203,11 +203,11 @@ cmGeneratedFileStream& operator<<(cmGeneratedFileStream& s,
// basically a wrapper that handles the NULL-ptr return from GetOption().
std::string cmCPackFreeBSDGenerator::var_lookup(const char* var_name)
{
- const char* pv = this->GetOption(var_name);
+ cmProp pv = this->GetOption(var_name);
if (!pv) {
return std::string();
}
- return pv;
+ return *pv;
}
// Produce UCL in the given @p manifest file for the common
diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx
index 00e274d..1527e80 100644
--- a/Source/CPack/cmCPackGenerator.cxx
+++ b/Source/CPack/cmCPackGenerator.cxx
@@ -78,14 +78,14 @@ int cmCPackGenerator::PrepareNames()
std::string tempDirectory =
cmStrCat(this->GetOption("CPACK_PACKAGE_DIRECTORY"), "/_CPack_Packages/");
- const char* toplevelTag = this->GetOption("CPACK_TOPLEVEL_TAG");
+ cmProp toplevelTag = this->GetOption("CPACK_TOPLEVEL_TAG");
if (toplevelTag) {
- tempDirectory += toplevelTag;
+ tempDirectory += *toplevelTag;
tempDirectory += "/";
}
- tempDirectory += this->GetOption("CPACK_GENERATOR");
+ tempDirectory += *this->GetOption("CPACK_GENERATOR");
std::string topDirectory = tempDirectory;
- const char* pfname = this->GetOption("CPACK_PACKAGE_FILE_NAME");
+ cmProp pfname = this->GetOption("CPACK_PACKAGE_FILE_NAME");
if (!pfname) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_FILE_NAME not specified" << std::endl);
@@ -99,7 +99,7 @@ int cmCPackGenerator::PrepareNames()
return 0;
}
outName += this->GetOutputExtension();
- const char* pdir = this->GetOption("CPACK_PACKAGE_DIRECTORY");
+ cmProp pdir = this->GetOption("CPACK_PACKAGE_DIRECTORY");
if (!pdir) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_PACKAGE_DIRECTORY not specified" << std::endl);
@@ -125,7 +125,7 @@ int cmCPackGenerator::PrepareNames()
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Look for: CPACK_PACKAGE_DESCRIPTION_FILE" << std::endl);
- const char* descFileName = this->GetOption("CPACK_PACKAGE_DESCRIPTION_FILE");
+ cmProp descFileName = this->GetOption("CPACK_PACKAGE_DESCRIPTION_FILE");
if (descFileName && !this->GetOption("CPACK_PACKAGE_DESCRIPTION")) {
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Look for: " << descFileName << std::endl);
@@ -135,7 +135,7 @@ int cmCPackGenerator::PrepareNames()
<< descFileName << "]" << std::endl);
return 0;
}
- cmsys::ifstream ifs(descFileName);
+ cmsys::ifstream ifs(descFileName->c_str());
if (!ifs) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Cannot open description file name: " << descFileName
@@ -151,9 +151,9 @@ int cmCPackGenerator::PrepareNames()
ostr << cmXMLSafe(line) << std::endl;
}
this->SetOption("CPACK_PACKAGE_DESCRIPTION", ostr.str().c_str());
- const char* defFileName =
+ cmProp defFileName =
this->GetOption("CPACK_DEFAULT_PACKAGE_DESCRIPTION_FILE");
- if (defFileName && !strcmp(defFileName, descFileName)) {
+ if (defFileName && (defFileName == descFileName)) {
this->SetOption("CPACK_USED_DEFAULT_PACKAGE_DESCRIPTION_FILE", "ON");
}
}
@@ -165,7 +165,7 @@ int cmCPackGenerator::PrepareNames()
<< std::endl);
return 0;
}
- const char* algoSignature = this->GetOption("CPACK_PACKAGE_CHECKSUM");
+ cmProp algoSignature = this->GetOption("CPACK_PACKAGE_CHECKSUM");
if (algoSignature) {
if (!cmCryptoHash::New(algoSignature)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
@@ -215,7 +215,7 @@ int cmCPackGenerator::InstallProject()
// prepare default created directory permissions
mode_t default_dir_mode_v = 0;
mode_t* default_dir_mode = nullptr;
- const char* default_dir_install_permissions =
+ cmProp default_dir_install_permissions =
this->GetOption("CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS");
if (cmNonempty(default_dir_install_permissions)) {
std::vector<std::string> items =
@@ -266,7 +266,7 @@ int cmCPackGenerator::InstallProject()
}
// Run pre-build actions
- const char* preBuildScripts = this->GetOption("CPACK_PRE_BUILD_SCRIPTS");
+ cmProp preBuildScripts = this->GetOption("CPACK_PRE_BUILD_SCRIPTS");
if (preBuildScripts) {
const auto scripts = cmExpandedList(preBuildScripts, false);
for (const auto& script : scripts) {
@@ -293,7 +293,7 @@ int cmCPackGenerator::InstallProjectViaInstallCommands(
bool setDestDir, const std::string& tempInstallDirectory)
{
(void)setDestDir;
- const char* installCommands = this->GetOption("CPACK_INSTALL_COMMANDS");
+ cmProp installCommands = this->GetOption("CPACK_INSTALL_COMMANDS");
if (cmNonempty(installCommands)) {
std::string tempInstallDirectoryEnv =
cmStrCat("CMAKE_INSTALL_PREFIX=", tempInstallDirectory);
@@ -333,7 +333,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
(void)setDestDir;
(void)tempInstallDirectory;
std::vector<cmsys::RegularExpression> ignoreFilesRegex;
- const char* cpackIgnoreFiles = this->GetOption("CPACK_IGNORE_FILES");
+ cmProp cpackIgnoreFiles = this->GetOption("CPACK_IGNORE_FILES");
if (cpackIgnoreFiles) {
std::vector<std::string> ignoreFilesRegexString =
cmExpandedList(cpackIgnoreFiles);
@@ -343,8 +343,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
ignoreFilesRegex.emplace_back(ifr);
}
}
- const char* installDirectories =
- this->GetOption("CPACK_INSTALLED_DIRECTORIES");
+ cmProp installDirectories = this->GetOption("CPACK_INSTALLED_DIRECTORIES");
if (cmNonempty(installDirectories)) {
std::vector<std::string> installDirectoriesVector =
cmExpandedList(installDirectories);
@@ -472,9 +471,9 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
int cmCPackGenerator::InstallProjectViaInstallScript(
bool setDestDir, const std::string& tempInstallDirectory)
{
- const char* cmakeScripts = this->GetOption("CPACK_INSTALL_SCRIPTS");
+ cmProp cmakeScripts = this->GetOption("CPACK_INSTALL_SCRIPTS");
{
- const char* const cmakeScript = this->GetOption("CPACK_INSTALL_SCRIPT");
+ cmProp const cmakeScript = this->GetOption("CPACK_INSTALL_SCRIPT");
if (cmakeScript && cmakeScripts) {
cmCPackLogger(
cmCPackLog::LOG_WARNING,
@@ -485,7 +484,7 @@ int cmCPackGenerator::InstallProjectViaInstallScript(
cmakeScripts = cmakeScript;
}
}
- if (cmakeScripts && *cmakeScripts) {
+ if (cmakeScripts && !cmakeScripts->empty()) {
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install scripts: " << cmakeScripts << std::endl);
std::vector<std::string> cmakeScriptsVector = cmExpandedList(cmakeScripts);
@@ -502,7 +501,7 @@ int cmCPackGenerator::InstallProjectViaInstallScript(
std::string dir;
if (this->GetOption("CPACK_INSTALL_PREFIX")) {
- dir += this->GetOption("CPACK_INSTALL_PREFIX");
+ dir += *this->GetOption("CPACK_INSTALL_PREFIX");
}
this->SetOption("CMAKE_INSTALL_PREFIX", dir.c_str());
cmCPackLogger(
@@ -540,8 +539,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
bool setDestDir, const std::string& baseTempInstallDirectory,
const mode_t* default_dir_mode)
{
- const char* cmakeProjects = this->GetOption("CPACK_INSTALL_CMAKE_PROJECTS");
- const char* cmakeGenerator = this->GetOption("CPACK_CMAKE_GENERATOR");
+ cmProp cmakeProjects = this->GetOption("CPACK_INSTALL_CMAKE_PROJECTS");
+ cmProp cmakeGenerator = this->GetOption("CPACK_CMAKE_GENERATOR");
std::string absoluteDestFiles;
if (cmNonempty(cmakeProjects)) {
if (!cmakeGenerator) {
@@ -595,7 +594,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
// Determine the installation types for this project (if provided).
std::string installTypesVar = "CPACK_" +
cmSystemTools::UpperCase(project.Component) + "_INSTALL_TYPES";
- const char* installTypes = this->GetOption(installTypesVar);
+ cmProp installTypes = this->GetOption(installTypesVar);
if (cmNonempty(installTypes)) {
std::vector<std::string> installTypesVector =
cmExpandedList(installTypes);
@@ -608,7 +607,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
// Determine the set of components that will be used in this project
std::string componentsVar =
"CPACK_COMPONENTS_" + cmSystemTools::UpperCase(project.Component);
- const char* components = this->GetOption(componentsVar);
+ cmProp components = this->GetOption(componentsVar);
if (cmNonempty(components)) {
cmExpandList(components, componentsVector);
for (std::string const& comp : componentsVector) {
@@ -625,12 +624,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
std::vector<std::string> buildConfigs;
// Try get configuration names given via `-C` CLI option
- {
- const char* const buildConfigCstr =
- this->GetOption("CPACK_BUILD_CONFIG");
- auto buildConfig = buildConfigCstr ? buildConfigCstr : std::string{};
- cmExpandList(buildConfig, buildConfigs);
- }
+ cmExpandList(this->GetOption("CPACK_BUILD_CONFIG"), buildConfigs);
// Remove duplicates
std::sort(buildConfigs.begin(), buildConfigs.end());
@@ -767,11 +761,11 @@ int cmCPackGenerator::InstallCMakeProject(
tempInstallDirectory += this->GetComponentInstallDirNameSuffix(component);
if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY")) {
tempInstallDirectory += "/";
- tempInstallDirectory += this->GetOption("CPACK_PACKAGE_FILE_NAME");
+ tempInstallDirectory += *this->GetOption("CPACK_PACKAGE_FILE_NAME");
}
}
- const char* default_dir_inst_permissions =
+ cmProp default_dir_inst_permissions =
this->GetOption("CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS");
if (cmNonempty(default_dir_inst_permissions)) {
mf.AddDefinition("CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS",
@@ -795,12 +789,13 @@ int cmCPackGenerator::InstallCMakeProject(
// I know this is tricky and awkward but it's the price for
// CPACK_SET_DESTDIR backward compatibility.
if (cmIsInternallyOn(this->GetOption("CPACK_SET_DESTDIR"))) {
- this->SetOption("CPACK_INSTALL_PREFIX",
- this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX"));
+ this->SetOption(
+ "CPACK_INSTALL_PREFIX",
+ this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX").GetCStr());
}
std::string dir;
if (this->GetOption("CPACK_INSTALL_PREFIX")) {
- dir += this->GetOption("CPACK_INSTALL_PREFIX");
+ dir += *this->GetOption("CPACK_INSTALL_PREFIX");
}
mf.AddDefinition("CMAKE_INSTALL_PREFIX", dir);
@@ -979,7 +974,7 @@ int cmCPackGenerator::InstallCMakeProject(
} else {
this->SetOption(
absoluteDestFileComponent,
- cmToCStr(mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")));
+ mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES").GetCStr());
}
}
}
@@ -1038,8 +1033,7 @@ int cmCPackGenerator::DoPackage()
}
if (cmIsOn(this->GetOption("CPACK_REMOVE_TOPLEVEL_DIRECTORY"))) {
- const char* toplevelDirectory =
- this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
+ cmProp toplevelDirectory = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
if (cmSystemTools::FileExists(toplevelDirectory)) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Remove toplevel directory: " << toplevelDirectory
@@ -1060,9 +1054,9 @@ int cmCPackGenerator::DoPackage()
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Done install project " << std::endl);
- const char* tempPackageFileName =
+ cmProp tempPackageFileName =
this->GetOption("CPACK_TEMPORARY_PACKAGE_FILE_NAME");
- const char* tempDirectory = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
+ cmProp tempDirectory = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl);
cmsys::Glob gl;
@@ -1079,7 +1073,7 @@ int cmCPackGenerator::DoPackage()
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "Create package" << std::endl);
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Package files to: "
- << (tempPackageFileName ? tempPackageFileName : "(NULL)")
+ << (tempPackageFileName ? *tempPackageFileName : "(NULL)")
<< std::endl);
if (cmSystemTools::FileExists(tempPackageFileName)) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
@@ -1099,9 +1093,8 @@ int cmCPackGenerator::DoPackage()
* may update this during PackageFiles.
* (either putting several names or updating the provided one)
*/
- this->packageFileNames.emplace_back(tempPackageFileName ? tempPackageFileName
- : "");
- this->toplevel = tempDirectory;
+ this->packageFileNames.emplace_back(tempPackageFileName);
+ this->toplevel = *tempDirectory;
{ // scope that enables package generators to run internal scripts with
// latest CMake policies enabled
cmMakefile::ScopePushPop pp{ this->MakefileMap };
@@ -1115,7 +1108,7 @@ int cmCPackGenerator::DoPackage()
}
}
// Run post-build actions
- const char* postBuildScripts = this->GetOption("CPACK_POST_BUILD_SCRIPTS");
+ cmProp postBuildScripts = this->GetOption("CPACK_POST_BUILD_SCRIPTS");
if (postBuildScripts) {
this->MakefileMap->AddDefinition("CPACK_PACKAGE_FILES",
cmJoin(this->packageFileNames, ";"));
@@ -1135,8 +1128,8 @@ int cmCPackGenerator::DoPackage()
}
/* Prepare checksum algorithm*/
- const char* algo = this->GetOption("CPACK_PACKAGE_CHECKSUM");
- std::unique_ptr<cmCryptoHash> crypto = cmCryptoHash::New(algo ? algo : "");
+ cmProp algo = this->GetOption("CPACK_PACKAGE_CHECKSUM");
+ std::unique_ptr<cmCryptoHash> crypto = cmCryptoHash::New(algo);
/*
* Copy the generated packages to final destination
@@ -1151,19 +1144,19 @@ int cmCPackGenerator::DoPackage()
for (std::string const& pkgFileName : this->packageFileNames) {
std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
std::string filename(cmSystemTools::GetFilenameName(pkgFileName));
- tempPackageFileName = pkgFileName.c_str();
+ tempPackageFileName = cmProp(pkgFileName);
tmpPF += "/" + filename;
const char* packageFileName = tmpPF.c_str();
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Copy final package(s): "
- << (tempPackageFileName ? tempPackageFileName : "(NULL)")
+ << (tempPackageFileName ? *tempPackageFileName : "(NULL)")
<< " to " << (packageFileName ? packageFileName : "(NULL)")
<< std::endl);
if (!cmSystemTools::CopyFileIfDifferent(pkgFileName, tmpPF)) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
"Problem copying the package: "
- << (tempPackageFileName ? tempPackageFileName : "(NULL)") << " to "
+ << (tempPackageFileName ? *tempPackageFileName : "(NULL)") << " to "
<< (packageFileName ? packageFileName : "(NULL)") << std::endl);
return 0;
}
@@ -1200,7 +1193,7 @@ int cmCPackGenerator::Initialize(const std::string& name, cmMakefile* mf)
// set the running generator name
this->SetOption("CPACK_GENERATOR", this->Name.c_str());
// Load the project specific config file
- const char* config = this->GetOption("CPACK_PROJECT_CONFIG_FILE");
+ cmProp config = this->GetOption("CPACK_PROJECT_CONFIG_FILE");
if (config) {
mf->ReadListFile(config);
}
@@ -1250,15 +1243,14 @@ bool cmCPackGenerator::IsSetToEmpty(const std::string& op) const
return false;
}
-const char* cmCPackGenerator::GetOption(const std::string& op) const
+cmProp cmCPackGenerator::GetOption(const std::string& op) const
{
cmProp ret = this->MakefileMap->GetDefinition(op);
if (!ret) {
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Warning, GetOption return NULL for: " << op << std::endl);
- return nullptr;
}
- return ret->c_str();
+ return ret;
}
std::vector<std::string> cmCPackGenerator::GetOptions() const
@@ -1311,7 +1303,7 @@ const char* cmCPackGenerator::GetPackagingInstallPrefix()
<< this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX") << "'"
<< std::endl);
- return this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
+ return this->GetOption("CPACK_PACKAGING_INSTALL_PREFIX")->c_str();
}
std::string cmCPackGenerator::FindTemplate(const char* name)
@@ -1391,12 +1383,8 @@ int cmCPackGenerator::PrepareGroupingKind()
method = ONE_PACKAGE_PER_GROUP;
}
- std::string groupingType;
-
// Second way to specify grouping
- if (nullptr != this->GetOption("CPACK_COMPONENTS_GROUPING")) {
- groupingType = this->GetOption("CPACK_COMPONENTS_GROUPING");
- }
+ std::string groupingType = *this->GetOption("CPACK_COMPONENTS_GROUPING");
if (!groupingType.empty()) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
@@ -1477,18 +1465,18 @@ std::string cmCPackGenerator::GetComponentPackageFileName(
if (isGroupName) {
std::string groupDispVar = "CPACK_COMPONENT_GROUP_" +
cmSystemTools::UpperCase(groupOrComponentName) + "_DISPLAY_NAME";
- const char* groupDispName = this->GetOption(groupDispVar);
+ cmProp groupDispName = this->GetOption(groupDispVar);
if (groupDispName) {
- suffix = "-" + std::string(groupDispName);
+ suffix = "-" + *groupDispName;
}
}
/* the [single] component case */
else {
std::string dispVar = "CPACK_COMPONENT_" +
cmSystemTools::UpperCase(groupOrComponentName) + "_DISPLAY_NAME";
- const char* dispName = this->GetOption(dispVar);
+ cmProp dispName = this->GetOption(dispVar);
if (dispName) {
- suffix = "-" + std::string(dispName);
+ suffix = "-" + *dispName;
}
}
}
@@ -1531,9 +1519,9 @@ cmCPackInstallationType* cmCPackGenerator::GetInstallationType(
"CPACK_INSTALL_TYPE_" + cmsys::SystemTools::UpperCase(name);
installType->Name = name;
- const char* displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
+ cmProp displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (cmNonempty(displayName)) {
- installType->DisplayName = displayName;
+ installType->DisplayName = *displayName;
} else {
installType->DisplayName = installType->Name;
}
@@ -1553,9 +1541,9 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
std::string macroPrefix =
"CPACK_COMPONENT_" + cmsys::SystemTools::UpperCase(name);
component->Name = name;
- const char* displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
+ cmProp displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (cmNonempty(displayName)) {
- component->DisplayName = displayName;
+ component->DisplayName = *displayName;
} else {
component->DisplayName = component->Name;
}
@@ -1565,17 +1553,17 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
component->IsDownloaded = this->IsOn(macroPrefix + "_DOWNLOADED") ||
cmIsOn(this->GetOption("CPACK_DOWNLOAD_ALL"));
- const char* archiveFile = this->GetOption(macroPrefix + "_ARCHIVE_FILE");
+ cmProp archiveFile = this->GetOption(macroPrefix + "_ARCHIVE_FILE");
if (cmNonempty(archiveFile)) {
- component->ArchiveFile = archiveFile;
+ component->ArchiveFile = *archiveFile;
}
- const char* plist = this->GetOption(macroPrefix + "_PLIST");
+ cmProp plist = this->GetOption(macroPrefix + "_PLIST");
if (cmNonempty(plist)) {
- component->Plist = plist;
+ component->Plist = *plist;
}
- const char* groupName = this->GetOption(macroPrefix + "_GROUP");
+ cmProp groupName = this->GetOption(macroPrefix + "_GROUP");
if (cmNonempty(groupName)) {
component->Group = this->GetComponentGroup(projectName, groupName);
component->Group->Components.push_back(component);
@@ -1583,13 +1571,13 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
component->Group = nullptr;
}
- const char* description = this->GetOption(macroPrefix + "_DESCRIPTION");
+ cmProp description = this->GetOption(macroPrefix + "_DESCRIPTION");
if (cmNonempty(description)) {
- component->Description = description;
+ component->Description = *description;
}
// Determine the installation types.
- const char* installTypes = this->GetOption(macroPrefix + "_INSTALL_TYPES");
+ cmProp installTypes = this->GetOption(macroPrefix + "_INSTALL_TYPES");
if (cmNonempty(installTypes)) {
std::vector<std::string> installTypesVector =
cmExpandedList(installTypes);
@@ -1600,7 +1588,7 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
}
// Determine the component dependencies.
- const char* depends = this->GetOption(macroPrefix + "_DEPENDS");
+ cmProp depends = this->GetOption(macroPrefix + "_DEPENDS");
if (cmNonempty(depends)) {
std::vector<std::string> dependsVector = cmExpandedList(depends);
for (std::string const& depend : dependsVector) {
@@ -1624,21 +1612,20 @@ cmCPackComponentGroup* cmCPackGenerator::GetComponentGroup(
if (!hasGroup) {
// Define the group
group->Name = name;
- const char* displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
+ cmProp displayName = this->GetOption(macroPrefix + "_DISPLAY_NAME");
if (cmNonempty(displayName)) {
- group->DisplayName = displayName;
+ group->DisplayName = *displayName;
} else {
group->DisplayName = group->Name;
}
- const char* description = this->GetOption(macroPrefix + "_DESCRIPTION");
+ cmProp description = this->GetOption(macroPrefix + "_DESCRIPTION");
if (cmNonempty(description)) {
- group->Description = description;
+ group->Description = *description;
}
group->IsBold = this->IsOn(macroPrefix + "_BOLD_TITLE");
group->IsExpandedByDefault = this->IsOn(macroPrefix + "_EXPANDED");
- const char* parentGroupName =
- this->GetOption(macroPrefix + "_PARENT_GROUP");
+ cmProp parentGroupName = this->GetOption(macroPrefix + "_PARENT_GROUP");
if (cmNonempty(parentGroupName)) {
group->ParentGroup =
this->GetComponentGroup(projectName, parentGroupName);
diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h
index 2512d42..1968c35 100644
--- a/Source/CPack/cmCPackGenerator.h
+++ b/Source/CPack/cmCPackGenerator.h
@@ -12,6 +12,7 @@
#include "cm_sys_stat.h"
#include "cmCPackComponentGroup.h"
+#include "cmProperty.h"
#include "cmSystemTools.h"
class cmCPackLog;
@@ -85,7 +86,7 @@ public:
//! Set and get the options
void SetOption(const std::string& op, const char* value);
void SetOptionIfNotSet(const std::string& op, const char* value);
- const char* GetOption(const std::string& op) const;
+ cmProp GetOption(const std::string& op) const;
std::vector<std::string> GetOptions() const;
bool IsSet(const std::string& name) const;
bool IsOn(const std::string& name) const;
diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx
index 395b1df..a3b59ca 100644
--- a/Source/CPack/cmCPackNSISGenerator.cxx
+++ b/Source/CPack/cmCPackNSISGenerator.cxx
@@ -19,6 +19,7 @@
#include "cmCPackLog.h"
#include "cmDuration.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -142,9 +143,9 @@ int cmCPackNSISGenerator::PackageFiles()
}
std::string installerHeaderImage;
if (this->IsSet("CPACK_NSIS_MUI_HEADERIMAGE")) {
- installerHeaderImage = this->GetOption("CPACK_NSIS_MUI_HEADERIMAGE");
+ installerHeaderImage = *this->GetOption("CPACK_NSIS_MUI_HEADERIMAGE");
} else if (this->IsSet("CPACK_PACKAGE_ICON")) {
- installerHeaderImage = this->GetOption("CPACK_PACKAGE_ICON");
+ installerHeaderImage = *this->GetOption("CPACK_PACKAGE_ICON");
}
if (!installerHeaderImage.empty()) {
std::string installerIconCode = cmStrCat(
@@ -479,8 +480,8 @@ int cmCPackNSISGenerator::InitializeInternal()
cmsys::RegularExpression versionRexCVS("v(.*)\\.cvs");
if (!resS || retVal ||
(!versionRex.find(output) && !versionRexCVS.find(output))) {
- const char* topDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
- std::string tmpFile = cmStrCat(topDir ? topDir : ".", "/NSISOutput.log");
+ cmProp topDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
+ std::string tmpFile = cmStrCat(topDir ? *topDir : ".", "/NSISOutput.log");
cmGeneratedFileStream ofs(tmpFile);
ofs << "# Run command: " << nsisCmd << std::endl
<< "# Output:" << std::endl
@@ -512,11 +513,11 @@ int cmCPackNSISGenerator::InitializeInternal()
}
this->SetOptionIfNotSet("CPACK_INSTALLER_PROGRAM", nsisPath.c_str());
this->SetOptionIfNotSet("CPACK_NSIS_EXECUTABLES_DIRECTORY", "bin");
- const char* cpackPackageExecutables =
+ cmProp cpackPackageExecutables =
this->GetOption("CPACK_PACKAGE_EXECUTABLES");
- const char* cpackPackageDeskTopLinks =
+ cmProp cpackPackageDeskTopLinks =
this->GetOption("CPACK_CREATE_DESKTOP_LINKS");
- const char* cpackNsisExecutablesDirectory =
+ cmProp cpackNsisExecutablesDirectory =
this->GetOption("CPACK_NSIS_EXECUTABLES_DIRECTORY");
std::vector<std::string> cpackPackageDesktopLinksVector;
if (cpackPackageDeskTopLinks) {
@@ -589,7 +590,7 @@ int cmCPackNSISGenerator::InitializeInternal()
void cmCPackNSISGenerator::CreateMenuLinks(std::ostream& str,
std::ostream& deleteStr)
{
- const char* cpackMenuLinks = this->GetOption("CPACK_NSIS_MENU_LINKS");
+ cmProp cpackMenuLinks = this->GetOption("CPACK_NSIS_MENU_LINKS");
if (!cpackMenuLinks) {
return;
}
@@ -728,11 +729,10 @@ std::string cmCPackNSISGenerator::CreateComponentDescription(
}
// Create the directory for the upload area
- const char* userUploadDirectory =
- this->GetOption("CPACK_UPLOAD_DIRECTORY");
+ cmProp userUploadDirectory = this->GetOption("CPACK_UPLOAD_DIRECTORY");
std::string uploadDirectory;
if (cmNonempty(userUploadDirectory)) {
- uploadDirectory = userUploadDirectory;
+ uploadDirectory = *userUploadDirectory;
} else {
uploadDirectory =
cmStrCat(this->GetOption("CPACK_PACKAGE_DIRECTORY"), "/CPackUploads");
@@ -968,9 +968,9 @@ std::string cmCPackNSISGenerator::CreateComponentGroupDescription(
std::string cmCPackNSISGenerator::CustomComponentInstallDirectory(
cm::string_view componentName)
{
- const char* outputDir = this->GetOption(
+ cmProp outputDir = this->GetOption(
cmStrCat("CPACK_NSIS_", componentName, "_INSTALL_DIRECTORY"));
- return outputDir ? outputDir : "$INSTDIR";
+ return outputDir ? *outputDir : "$INSTDIR";
}
std::string cmCPackNSISGenerator::TranslateNewlines(std::string str)
diff --git a/Source/CPack/cmCPackNuGetGenerator.cxx b/Source/CPack/cmCPackNuGetGenerator.cxx
index 98dc890..9e7f92a 100644
--- a/Source/CPack/cmCPackNuGetGenerator.cxx
+++ b/Source/CPack/cmCPackNuGetGenerator.cxx
@@ -12,6 +12,7 @@
#include "cmCPackComponentGroup.h"
#include "cmCPackLog.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -120,7 +121,7 @@ void cmCPackNuGetGenerator::SetupGroupComponentVariables(bool ignoreGroup)
void cmCPackNuGetGenerator::AddGeneratedPackageNames()
{
- const char* const files_list = this->GetOption("GEN_CPACK_OUTPUT_FILES");
+ cmProp const files_list = this->GetOption("GEN_CPACK_OUTPUT_FILES");
if (!files_list) {
cmCPackLogger(
cmCPackLog::LOG_ERROR,
@@ -129,7 +130,7 @@ void cmCPackNuGetGenerator::AddGeneratedPackageNames()
return;
}
// add the generated packages to package file names list
- std::string fileNames{ files_list };
+ const std::string& fileNames = *files_list;
const char sep = ';';
std::string::size_type pos1 = 0;
std::string::size_type pos2 = fileNames.find(sep, pos1 + 1);
diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx
index 5de4a6f..262cc6e 100644
--- a/Source/CPack/cmCPackOSXX11Generator.cxx
+++ b/Source/CPack/cmCPackOSXX11Generator.cxx
@@ -10,6 +10,7 @@
#include "cmCPackLog.h"
#include "cmDuration.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -22,7 +23,7 @@ int cmCPackOSXX11Generator::PackageFiles()
// TODO: Use toplevel ?
// It is used! Is this an obsolete comment?
- const char* cpackPackageExecutables =
+ cmProp cpackPackageExecutables =
this->GetOption("CPACK_PACKAGE_EXECUTABLES");
if (cpackPackageExecutables) {
cmCPackLogger(cmCPackLog::LOG_DEBUG,
@@ -70,7 +71,7 @@ int cmCPackOSXX11Generator::PackageFiles()
const char* scrDir = scriptDirectory.c_str();
const char* contDir = contentsDirectory.c_str();
const char* rsrcFile = resourceFileName.c_str();
- const char* iconFile = this->GetOption("CPACK_PACKAGE_ICON");
+ cmProp iconFile = this->GetOption("CPACK_PACKAGE_ICON");
if (iconFile) {
std::string iconFileName = cmsys::SystemTools::GetFilenameName(iconFile);
if (!cmSystemTools::FileExists(iconFile)) {
@@ -103,9 +104,9 @@ int cmCPackOSXX11Generator::PackageFiles()
true) ||
!this->CopyResourcePlistFile("OSXScriptLauncher.rsrc", dir, rsrcFile,
true) ||
- !this->CopyResourcePlistFile("OSXScriptLauncher", appdir,
- this->GetOption("CPACK_PACKAGE_FILE_NAME"),
- true)) {
+ !this->CopyResourcePlistFile(
+ "OSXScriptLauncher", appdir,
+ this->GetOption("CPACK_PACKAGE_FILE_NAME").GetCStr(), true)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem copying the resource files" << std::endl);
return 0;
diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx
index ac3d64d..a1eba56 100644
--- a/Source/CPack/cmCPackPKGGenerator.cxx
+++ b/Source/CPack/cmCPackPKGGenerator.cxx
@@ -7,6 +7,7 @@
#include "cmCPackComponentGroup.h"
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
@@ -56,7 +57,7 @@ void cmCPackPKGGenerator::CreateBackground(const char* themeName,
std::string opt = (themeName == nullptr)
? cmStrCat("CPACK_", genName, "_BACKGROUND")
: cmStrCat("CPACK_", genName, "_BACKGROUND_", paramSuffix);
- const char* bgFileName = this->GetOption(opt);
+ cmProp bgFileName = this->GetOption(opt);
if (bgFileName == nullptr) {
return;
}
@@ -78,7 +79,7 @@ void cmCPackPKGGenerator::CreateBackground(const char* themeName,
xout.Attribute("file", bgFileName);
- const char* param = this->GetOption(cmStrCat(opt, "_ALIGNMENT"));
+ cmProp param = this->GetOption(cmStrCat(opt, "_ALIGNMENT"));
if (param != nullptr) {
xout.Attribute("alignment", param);
}
@@ -315,7 +316,7 @@ bool cmCPackPKGGenerator::CopyCreateResourceFile(const std::string& name,
{
std::string uname = cmSystemTools::UpperCase(name);
std::string cpackVar = "CPACK_RESOURCE_FILE_" + uname;
- const char* inFileName = this->GetOption(cpackVar);
+ cmProp inFileName = this->GetOption(cpackVar);
if (!inFileName) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPack option: " << cpackVar.c_str()
@@ -351,7 +352,7 @@ bool cmCPackPKGGenerator::CopyCreateResourceFile(const std::string& name,
(name + ext).c_str());
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
- "Configure file: " << (inFileName ? inFileName : "(NULL)")
+ "Configure file: " << (inFileName ? *inFileName : "(NULL)")
<< " to " << destFileName << std::endl);
this->ConfigureFile(inFileName, destFileName);
return true;
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx
index f51ea42..33b601c 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.cxx
+++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx
@@ -16,6 +16,7 @@
#include "cmCPackLog.h"
#include "cmDuration.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
@@ -79,9 +80,9 @@ int cmCPackPackageMakerGenerator::PackageFiles()
resDir += "/en.lproj";
}
- const char* preflight = this->GetOption("CPACK_PREFLIGHT_SCRIPT");
- const char* postflight = this->GetOption("CPACK_POSTFLIGHT_SCRIPT");
- const char* postupgrade = this->GetOption("CPACK_POSTUPGRADE_SCRIPT");
+ cmProp preflight = this->GetOption("CPACK_PREFLIGHT_SCRIPT");
+ cmProp postflight = this->GetOption("CPACK_POSTFLIGHT_SCRIPT");
+ cmProp postupgrade = this->GetOption("CPACK_POSTUPGRADE_SCRIPT");
if (this->Components.empty()) {
// Create directory structure
@@ -167,10 +168,9 @@ int cmCPackPackageMakerGenerator::PackageFiles()
// Create the directory where downloaded component packages will
// be placed.
- const char* userUploadDirectory =
- this->GetOption("CPACK_UPLOAD_DIRECTORY");
+ cmProp userUploadDirectory = this->GetOption("CPACK_UPLOAD_DIRECTORY");
std::string uploadDirectory;
- if (userUploadDirectory && *userUploadDirectory) {
+ if (userUploadDirectory && !userUploadDirectory->empty()) {
uploadDirectory = userUploadDirectory;
} else {
uploadDirectory =
@@ -352,8 +352,8 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
"/PackageMaker.app/Contents/MacOS");
std::string pkgPath;
- const char* inst_program = this->GetOption("CPACK_INSTALLER_PROGRAM");
- if (inst_program && *inst_program) {
+ cmProp inst_program = this->GetOption("CPACK_INSTALLER_PROGRAM");
+ if (inst_program && !inst_program->empty()) {
pkgPath = inst_program;
} else {
pkgPath = cmSystemTools::FindProgram("PackageMaker", paths, false);
@@ -427,11 +427,12 @@ int cmCPackPackageMakerGenerator::InitializeInternal()
// Determine the package compatibility version. If it wasn't
// specified by the user, we define it based on which features the
// user requested.
- const char* packageCompat = this->GetOption("CPACK_OSX_PACKAGE_VERSION");
- if (packageCompat && *packageCompat) {
+ cmProp packageCompat = this->GetOption("CPACK_OSX_PACKAGE_VERSION");
+ if (packageCompat && !packageCompat->empty()) {
unsigned int majorVersion = 10;
unsigned int minorVersion = 5;
- int res = sscanf(packageCompat, "%u.%u", &majorVersion, &minorVersion);
+ int res =
+ sscanf(packageCompat->c_str(), "%u.%u", &majorVersion, &minorVersion);
if (res == 2) {
this->PackageCompatibilityVersion =
getVersion(majorVersion, minorVersion);
diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx
index a3e55de..99c55a0 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.cxx
+++ b/Source/CPack/cmCPackProductBuildGenerator.cxx
@@ -10,6 +10,7 @@
#include "cmCPackLog.h"
#include "cmDuration.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -87,11 +88,11 @@ int cmCPackProductBuildGenerator::PackageFiles()
std::string version = this->GetOption("CPACK_PACKAGE_VERSION");
std::string productbuild = this->GetOption("CPACK_COMMAND_PRODUCTBUILD");
std::string identityName;
- if (const char* n = this->GetOption("CPACK_PRODUCTBUILD_IDENTITY_NAME")) {
+ if (cmProp n = this->GetOption("CPACK_PRODUCTBUILD_IDENTITY_NAME")) {
identityName = n;
}
std::string keychainPath;
- if (const char* p = this->GetOption("CPACK_PRODUCTBUILD_KEYCHAIN_PATH")) {
+ if (cmProp p = this->GetOption("CPACK_PRODUCTBUILD_KEYCHAIN_PATH")) {
keychainPath = p;
}
@@ -173,8 +174,8 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage(
const char* comp_name = component ? component->Name.c_str() : nullptr;
- const char* preflight = this->GetComponentScript("PREFLIGHT", comp_name);
- const char* postflight = this->GetComponentScript("POSTFLIGHT", comp_name);
+ cmProp preflight = this->GetComponentScript("PREFLIGHT", comp_name);
+ cmProp postflight = this->GetComponentScript("POSTFLIGHT", comp_name);
std::string resDir = packageFileDir;
if (component) {
@@ -213,11 +214,11 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage(
std::string version = this->GetOption("CPACK_PACKAGE_VERSION");
std::string pkgbuild = this->GetOption("CPACK_COMMAND_PKGBUILD");
std::string identityName;
- if (const char* n = this->GetOption("CPACK_PKGBUILD_IDENTITY_NAME")) {
+ if (cmProp n = this->GetOption("CPACK_PKGBUILD_IDENTITY_NAME")) {
identityName = n;
}
std::string keychainPath;
- if (const char* p = this->GetOption("CPACK_PKGBUILD_KEYCHAIN_PATH")) {
+ if (cmProp p = this->GetOption("CPACK_PKGBUILD_KEYCHAIN_PATH")) {
keychainPath = p;
}
@@ -239,7 +240,7 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage(
return RunProductBuild(pkgCmd.str());
}
-const char* cmCPackProductBuildGenerator::GetComponentScript(
+cmProp cmCPackProductBuildGenerator::GetComponentScript(
const char* script, const char* component_name)
{
std::string scriptname = std::string("CPACK_") + script + "_";
diff --git a/Source/CPack/cmCPackProductBuildGenerator.h b/Source/CPack/cmCPackProductBuildGenerator.h
index 462e2fc..8f169b0 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.h
+++ b/Source/CPack/cmCPackProductBuildGenerator.h
@@ -8,6 +8,7 @@
#include "cmCPackGenerator.h"
#include "cmCPackPKGGenerator.h"
+#include "cmProperty.h"
class cmCPackComponent;
@@ -45,6 +46,5 @@ protected:
const std::string& packageDir,
const cmCPackComponent* component);
- const char* GetComponentScript(const char* script,
- const char* script_component);
+ cmProp GetComponentScript(const char* script, const char* script_component);
};
diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx
index c3f6d59..2765c58 100644
--- a/Source/CPack/cmCPackRPMGenerator.cxx
+++ b/Source/CPack/cmCPackRPMGenerator.cxx
@@ -12,6 +12,7 @@
#include "cmCPackComponentGroup.h"
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -103,7 +104,7 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
this->packageFileNames.clear();
std::string initialTopLevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY"));
- const char* mainComponent = this->GetOption("CPACK_RPM_MAIN_COMPONENT");
+ cmProp mainComponent = this->GetOption("CPACK_RPM_MAIN_COMPONENT");
if (this->IsOn("CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE") &&
!this->IsOn("CPACK_RPM_DEBUGINFO_PACKAGE")) {
diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx
index ad0a3e2..7eb8cc3 100644
--- a/Source/CPack/cmCPackSTGZGenerator.cxx
+++ b/Source/CPack/cmCPackSTGZGenerator.cxx
@@ -14,6 +14,7 @@
#include "cmArchiveWrite.h"
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
+#include "cmProperty.h"
#include "cmSystemTools.h"
cmCPackSTGZGenerator::cmCPackSTGZGenerator()
diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx
index 48cc0e4..bd33055 100644
--- a/Source/CTest/cmCTestGenericHandler.cxx
+++ b/Source/CTest/cmCTestGenericHandler.cxx
@@ -72,13 +72,13 @@ void cmCTestGenericHandler::Initialize()
this->MultiOptions = this->PersistentMultiOptions;
}
-const char* cmCTestGenericHandler::GetOption(const std::string& op)
+cmProp cmCTestGenericHandler::GetOption(const std::string& op)
{
auto remit = this->Options.find(op);
if (remit == this->Options.end()) {
return nullptr;
}
- return remit->second.c_str();
+ return cmProp(remit->second);
}
std::vector<std::string> cmCTestGenericHandler::GetMultiOption(
diff --git a/Source/CTest/cmCTestGenericHandler.h b/Source/CTest/cmCTestGenericHandler.h
index e846fd9..0b8b224 100644
--- a/Source/CTest/cmCTestGenericHandler.h
+++ b/Source/CTest/cmCTestGenericHandler.h
@@ -11,6 +11,7 @@
#include <stddef.h>
#include "cmCTest.h"
+#include "cmProperty.h"
#include "cmSystemTools.h"
class cmGeneratedFileStream;
@@ -87,7 +88,7 @@ public:
*/
void SetPersistentOption(const std::string& op, const char* value);
void SetOption(const std::string& op, const char* value);
- const char* GetOption(const std::string& op);
+ cmProp GetOption(const std::string& op);
/**
* Multi-Options collect one or more values from flags; passing
diff --git a/Source/CTest/cmCTestStartCommand.cxx b/Source/CTest/cmCTestStartCommand.cxx
index 53e1b2f..a8c2403 100644
--- a/Source/CTest/cmCTestStartCommand.cxx
+++ b/Source/CTest/cmCTestStartCommand.cxx
@@ -30,8 +30,8 @@ bool cmCTestStartCommand::InitialPass(std::vector<std::string> const& args,
size_t cnt = 0;
const char* smodel = nullptr;
- const std::string* src_dir = nullptr;
- const std::string* bld_dir = nullptr;
+ cmProp src_dir;
+ cmProp bld_dir;
while (cnt < args.size()) {
if (args[cnt] == "GROUP" || args[cnt] == "TRACK") {
@@ -55,10 +55,10 @@ bool cmCTestStartCommand::InitialPass(std::vector<std::string> const& args,
smodel = args[cnt].c_str();
cnt++;
} else if (!src_dir) {
- src_dir = &args[cnt];
+ src_dir = cmProp(args[cnt]);
cnt++;
} else if (!bld_dir) {
- bld_dir = &args[cnt];
+ bld_dir = cmProp(args[cnt]);
cnt++;
} else {
this->SetError("Too many arguments");
diff --git a/Source/CTest/cmCTestSubmitCommand.cxx b/Source/CTest/cmCTestSubmitCommand.cxx
index bdba0e5..7aeb288 100644
--- a/Source/CTest/cmCTestSubmitCommand.cxx
+++ b/Source/CTest/cmCTestSubmitCommand.cxx
@@ -36,8 +36,8 @@ std::unique_ptr<cmCommand> cmCTestSubmitCommand::Clone()
cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler()
{
- const std::string* submitURL = !this->SubmitURL.empty()
- ? &this->SubmitURL
+ cmProp submitURL = !this->SubmitURL.empty()
+ ? cmProp(this->SubmitURL)
: this->Makefile->GetDefinition("CTEST_SUBMIT_URL");
if (submitURL) {
diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx
index 5b54573..9322bd5 100644
--- a/Source/CTest/cmCTestSubmitHandler.cxx
+++ b/Source/CTest/cmCTestSubmitHandler.cxx
@@ -357,12 +357,8 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(
// If curl failed for any reason, or checksum fails, wait and retry
//
if (res != CURLE_OK || this->HasErrors) {
- std::string retryDelay = this->GetOption("RetryDelay") == nullptr
- ? ""
- : this->GetOption("RetryDelay");
- std::string retryCount = this->GetOption("RetryCount") == nullptr
- ? ""
- : this->GetOption("RetryCount");
+ std::string retryDelay = *this->GetOption("RetryDelay");
+ std::string retryCount = *this->GetOption("RetryCount");
auto delay = cmDuration(
retryDelay.empty()
@@ -522,12 +518,8 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
bool internalTest = cmIsOn(this->GetOption("InternalTest"));
// Get RETRY_COUNT and RETRY_DELAY values if they were set.
- std::string retryDelayString = this->GetOption("RetryDelay") == nullptr
- ? ""
- : this->GetOption("RetryDelay");
- std::string retryCountString = this->GetOption("RetryCount") == nullptr
- ? ""
- : this->GetOption("RetryCount");
+ std::string retryDelayString = *this->GetOption("RetryDelay");
+ std::string retryCountString = *this->GetOption("RetryCount");
auto retryDelay = std::chrono::seconds(0);
if (!retryDelayString.empty()) {
unsigned long retryDelayValue = 0;
@@ -716,8 +708,8 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
int cmCTestSubmitHandler::ProcessHandler()
{
- const char* cdashUploadFile = this->GetOption("CDashUploadFile");
- const char* cdashUploadType = this->GetOption("CDashUploadType");
+ cmProp cdashUploadFile = this->GetOption("CDashUploadFile");
+ cmProp cdashUploadType = this->GetOption("CDashUploadType");
if (cdashUploadFile && cdashUploadType) {
return this->HandleCDashUploadFile(cdashUploadFile, cdashUploadType);
}
@@ -804,6 +796,7 @@ int cmCTestSubmitHandler::ProcessHandler()
}
}
this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis.xml");
+ this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis-Test.xml");
this->CTest->AddIfExists(cmCTest::PartMemCheck, "Purify.xml");
this->CTest->AddIfExists(cmCTest::PartNotes, "Notes.xml");
this->CTest->AddIfExists(cmCTest::PartUpload, "Upload.xml");
diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx
index 1157d10..c41b661 100644
--- a/Source/CTest/cmCTestTestHandler.cxx
+++ b/Source/CTest/cmCTestTestHandler.cxx
@@ -521,7 +521,7 @@ bool cmCTestTestHandler::ProcessOptions()
if (cmIsOn(this->GetOption("ScheduleRandom"))) {
this->CTest->SetScheduleType("Random");
}
- if (const char* repeat = this->GetOption("Repeat")) {
+ if (cmProp repeat = this->GetOption("Repeat")) {
cmsys::RegularExpression repeatRegex(
"^(UNTIL_FAIL|UNTIL_PASS|AFTER_TIMEOUT):([0-9]+)$");
if (repeatRegex.find(repeat)) {
@@ -546,7 +546,7 @@ bool cmCTestTestHandler::ProcessOptions()
}
}
if (this->GetOption("ParallelLevel")) {
- this->CTest->SetParallelLevel(atoi(this->GetOption("ParallelLevel")));
+ this->CTest->SetParallelLevel(std::stoi(this->GetOption("ParallelLevel")));
}
if (this->GetOption("StopOnFailure")) {
@@ -557,7 +557,7 @@ bool cmCTestTestHandler::ProcessOptions()
this->IncludeLabelRegularExpressions);
BuildLabelRE(this->GetMultiOption("ExcludeLabelRegularExpression"),
this->ExcludeLabelRegularExpressions);
- const char* val = this->GetOption("IncludeRegularExpression");
+ cmProp val = this->GetOption("IncludeRegularExpression");
if (val) {
this->UseIncludeRegExp();
this->SetIncludeRegExp(val);
@@ -569,19 +569,19 @@ bool cmCTestTestHandler::ProcessOptions()
}
val = this->GetOption("ExcludeFixtureRegularExpression");
if (val) {
- this->ExcludeFixtureRegExp = val;
+ this->ExcludeFixtureRegExp = *val;
}
val = this->GetOption("ExcludeFixtureSetupRegularExpression");
if (val) {
- this->ExcludeFixtureSetupRegExp = val;
+ this->ExcludeFixtureSetupRegExp = *val;
}
val = this->GetOption("ExcludeFixtureCleanupRegularExpression");
if (val) {
- this->ExcludeFixtureCleanupRegExp = val;
+ this->ExcludeFixtureCleanupRegExp = *val;
}
val = this->GetOption("ResourceSpecFile");
if (val) {
- this->ResourceSpecFile = val;
+ this->ResourceSpecFile = *val;
}
this->SetRerunFailed(cmIsOn(this->GetOption("RerunFailed")));
@@ -705,6 +705,21 @@ bool cmCTestTestHandler::GenerateXML()
this->GenerateCTestXML(xml);
}
+ if (this->MemCheck) {
+ cmGeneratedFileStream xmlfile;
+ if (!this->StartResultingXML(cmCTest::PartTest, "DynamicAnalysis-Test",
+ xmlfile)) {
+ cmCTestLog(this->CTest, ERROR_MESSAGE,
+ "Cannot create testing XML file" << std::endl);
+ this->LogFile = nullptr;
+ return false;
+ }
+ cmXMLWriter xml(xmlfile);
+ // Explicitly call this class' `GenerateCTestXML` method to make `Test.xml`
+ // as well.
+ this->cmCTestTestHandler::GenerateCTestXML(xml);
+ }
+
return true;
}
@@ -2066,26 +2081,26 @@ void cmCTestTestHandler::RecordCustomTestMeasurements(cmXMLWriter& xml,
}
}
-void cmCTestTestHandler::SetIncludeRegExp(const char* arg)
+void cmCTestTestHandler::SetIncludeRegExp(const std::string& arg)
{
this->IncludeRegExp = arg;
}
-void cmCTestTestHandler::SetExcludeRegExp(const char* arg)
+void cmCTestTestHandler::SetExcludeRegExp(const std::string& arg)
{
this->ExcludeRegExp = arg;
}
-void cmCTestTestHandler::SetTestsToRunInformation(const char* in)
+void cmCTestTestHandler::SetTestsToRunInformation(cmProp in)
{
if (!in) {
return;
}
- this->TestsToRunString = in;
+ this->TestsToRunString = *in;
// if the argument is a file, then read it and use the contents as the
// string
if (cmSystemTools::FileExists(in)) {
- cmsys::ifstream fin(in);
+ cmsys::ifstream fin(in->c_str());
unsigned long filelen = cmSystemTools::FileLength(in);
auto buff = cm::make_unique<char[]>(filelen + 1);
fin.getline(buff.get(), filelen);
diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h
index f2da320..585a336 100644
--- a/Source/CTest/cmCTestTestHandler.h
+++ b/Source/CTest/cmCTestTestHandler.h
@@ -22,6 +22,7 @@
#include "cmCTestResourceSpec.h"
#include "cmDuration.h"
#include "cmListFileCache.h"
+#include "cmProperty.h"
class cmMakefile;
class cmXMLWriter;
@@ -65,8 +66,8 @@ public:
/// them on
void UseIncludeRegExp();
void UseExcludeRegExp();
- void SetIncludeRegExp(const char*);
- void SetExcludeRegExp(const char*);
+ void SetIncludeRegExp(const std::string&);
+ void SetExcludeRegExp(const std::string&);
void SetMaxIndex(int n) { this->MaxIndex = n; }
int GetMaxIndex() { return this->MaxIndex; }
@@ -81,7 +82,7 @@ public:
}
//! pass the -I argument down
- void SetTestsToRunInformation(const char*);
+ void SetTestsToRunInformation(cmProp);
cmCTestTestHandler();
diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx
index 57cc024..7c7c380 100644
--- a/Source/CTest/cmCTestUpdateHandler.cxx
+++ b/Source/CTest/cmCTestUpdateHandler.cxx
@@ -17,6 +17,7 @@
#include "cmCTestSVN.h"
#include "cmCTestVC.h"
#include "cmGeneratedFileStream.h"
+#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmVersion.h"
@@ -108,7 +109,7 @@ int cmCTestUpdateHandler::ProcessHandler()
static_cast<void>(fixLocale);
// Get source dir
- const char* sourceDirectory = this->GetOption("SourceDirectory");
+ cmProp sourceDirectory = this->GetOption("SourceDirectory");
if (!sourceDirectory) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find SourceDirectory key in the DartConfiguration.tcl"
@@ -257,7 +258,7 @@ int cmCTestUpdateHandler::ProcessHandler()
return updated && loadedMods ? numUpdated : -1;
}
-int cmCTestUpdateHandler::DetectVCS(const char* dir)
+int cmCTestUpdateHandler::DetectVCS(const std::string& dir)
{
std::string sourceDirectory = dir;
cmCTestOptionalLog(this->CTest, DEBUG,
diff --git a/Source/CTest/cmCTestUpdateHandler.h b/Source/CTest/cmCTestUpdateHandler.h
index 25bbb2f..70269ea 100644
--- a/Source/CTest/cmCTestUpdateHandler.h
+++ b/Source/CTest/cmCTestUpdateHandler.h
@@ -59,6 +59,6 @@ private:
std::string UpdateCommand;
int UpdateType;
- int DetectVCS(const char* dir);
+ int DetectVCS(const std::string& dir);
bool SelectVCS();
};
diff --git a/Source/QtDialog/QCMake.cxx b/Source/QtDialog/QCMake.cxx
index 859c18d..41e8a55 100644
--- a/Source/QtDialog/QCMake.cxx
+++ b/Source/QtDialog/QCMake.cxx
@@ -128,11 +128,11 @@ void QCMake::setBinaryDirectory(const QString& _dir)
}
cmProp gen = state->GetCacheEntryValue("CMAKE_GENERATOR");
if (gen) {
- const std::string* extraGen =
+ cmProp extraGen =
state->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
std::string curGen =
- cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
- *gen, extraGen ? *extraGen : "");
+ cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*gen,
+ *extraGen);
this->setGenerator(QString::fromLocal8Bit(curGen.c_str()));
}
diff --git a/Source/cmAddTestCommand.cxx b/Source/cmAddTestCommand.cxx
index 205c1c7..a0d5732 100644
--- a/Source/cmAddTestCommand.cxx
+++ b/Source/cmAddTestCommand.cxx
@@ -140,7 +140,7 @@ bool cmAddTestCommandHandleNameMode(std::vector<std::string> const& args,
test->SetOldStyle(false);
test->SetCommand(command);
if (!working_directory.empty()) {
- test->SetProperty("WORKING_DIRECTORY", working_directory.c_str());
+ test->SetProperty("WORKING_DIRECTORY", working_directory);
}
test->SetCommandExpandLists(command_expand_lists);
mf.AddTestGenerator(cm::make_unique<cmTestGenerator>(test, configurations));
diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h
index c192e2a..a1830f9 100644
--- a/Source/cmAlgorithms.h
+++ b/Source/cmAlgorithms.h
@@ -60,6 +60,10 @@ class cmListFileBacktrace;
using cmBacktraceRange =
cmRange<std::vector<cmListFileBacktrace>::const_iterator>;
+template <typename T>
+class BT;
+using cmBTStringRange = cmRange<std::vector<BT<std::string>>::const_iterator>;
+
template <typename Range>
typename Range::const_iterator cmRemoveN(Range& r, size_t n)
{
@@ -133,7 +137,13 @@ ForwardIterator cmRemoveDuplicates(ForwardIterator first, ForwardIterator last)
}
template <typename Range>
-typename Range::const_iterator cmRemoveDuplicates(Range& r)
+typename Range::iterator cmRemoveDuplicates(Range& r)
+{
+ return cmRemoveDuplicates(r.begin(), r.end());
+}
+
+template <typename Range>
+typename Range::const_iterator cmRemoveDuplicates(Range const& r)
{
return cmRemoveDuplicates(r.begin(), r.end());
}
diff --git a/Source/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx
index 54b2998..9e0d80c 100644
--- a/Source/cmArchiveWrite.cxx
+++ b/Source/cmArchiveWrite.cxx
@@ -250,6 +250,9 @@ cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c,
bool cmArchiveWrite::Open()
{
+ if (!this->Error.empty()) {
+ return false;
+ }
if (archive_write_open(
this->Archive, this, nullptr,
reinterpret_cast<archive_write_callback*>(&Callback::Write),
diff --git a/Source/cmCMakeHostSystemInformationCommand.cxx b/Source/cmCMakeHostSystemInformationCommand.cxx
index 0550568..74071ff 100644
--- a/Source/cmCMakeHostSystemInformationCommand.cxx
+++ b/Source/cmCMakeHostSystemInformationCommand.cxx
@@ -2,214 +2,510 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCMakeHostSystemInformationCommand.h"
-#include <cstddef>
+#include <algorithm>
+#include <cassert>
+#include <cctype>
+#include <initializer_list>
+#include <map>
+#include <string>
+#include <type_traits>
+#include <utility>
+#include <cm/optional>
+#include <cm/string_view>
+#include <cmext/string_view>
+
+#include "cmsys/FStream.hxx"
+#include "cmsys/Glob.hxx"
#include "cmsys/SystemInformation.hxx"
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
+#include "cmStringAlgorithms.h"
+#include "cmSystemTools.h"
-#if defined(_WIN32)
+#ifdef _WIN32
# include "cmAlgorithms.h"
# include "cmGlobalGenerator.h"
# include "cmGlobalVisualStudioVersionedGenerator.h"
-# include "cmSystemTools.h"
# include "cmVSSetupHelper.h"
# define HAVE_VS_SETUP_HELPER
#endif
namespace {
-bool GetValue(cmExecutionStatus& status, cmsys::SystemInformation& info,
- std::string const& key, std::string& value);
-std::string ValueToString(size_t value);
-std::string ValueToString(const char* value);
-std::string ValueToString(std::string const& value);
-}
+std::string const DELIM[2] = { {}, ";" };
-// cmCMakeHostSystemInformation
-bool cmCMakeHostSystemInformationCommand(std::vector<std::string> const& args,
- cmExecutionStatus& status)
+// BEGIN Private functions
+std::string ValueToString(std::size_t const value)
{
- size_t current_index = 0;
-
- if (args.size() < (current_index + 2) || args[current_index] != "RESULT") {
- status.SetError("missing RESULT specification.");
- return false;
- }
-
- std::string const& variable = args[current_index + 1];
- current_index += 2;
-
- if (args.size() < (current_index + 2) || args[current_index] != "QUERY") {
- status.SetError("missing QUERY specification");
- return false;
- }
-
- cmsys::SystemInformation info;
- info.RunCPUCheck();
- info.RunOSCheck();
- info.RunMemoryCheck();
-
- std::string result_list;
- for (size_t i = current_index + 1; i < args.size(); ++i) {
- std::string const& key = args[i];
- if (i != current_index + 1) {
- result_list += ";";
- }
- std::string value;
- if (!GetValue(status, info, key, value)) {
- return false;
- }
- result_list += value;
- }
-
- status.GetMakefile().AddDefinition(variable, result_list);
+ return std::to_string(value);
+}
- return true;
+std::string ValueToString(const char* const value)
+{
+ return value ? value : std::string{};
}
-namespace {
+std::string ValueToString(std::string const& value)
+{
+ return value;
+}
-bool GetValue(cmExecutionStatus& status, cmsys::SystemInformation& info,
- std::string const& key, std::string& value)
+cm::optional<std::string> GetValue(cmsys::SystemInformation& info,
+ std::string const& key)
{
- if (key == "NUMBER_OF_LOGICAL_CORES") {
- value = ValueToString(info.GetNumberOfLogicalCPU());
- } else if (key == "NUMBER_OF_PHYSICAL_CORES") {
- value = ValueToString(info.GetNumberOfPhysicalCPU());
- } else if (key == "HOSTNAME") {
- value = ValueToString(info.GetHostname());
- } else if (key == "FQDN") {
- value = ValueToString(info.GetFullyQualifiedDomainName());
- } else if (key == "TOTAL_VIRTUAL_MEMORY") {
- value = ValueToString(info.GetTotalVirtualMemory());
- } else if (key == "AVAILABLE_VIRTUAL_MEMORY") {
- value = ValueToString(info.GetAvailableVirtualMemory());
- } else if (key == "TOTAL_PHYSICAL_MEMORY") {
- value = ValueToString(info.GetTotalPhysicalMemory());
- } else if (key == "AVAILABLE_PHYSICAL_MEMORY") {
- value = ValueToString(info.GetAvailablePhysicalMemory());
- } else if (key == "IS_64BIT") {
- value = ValueToString(info.Is64Bits());
- } else if (key == "HAS_FPU") {
- value = ValueToString(
+ if (key == "NUMBER_OF_LOGICAL_CORES"_s) {
+ return ValueToString(info.GetNumberOfLogicalCPU());
+ }
+ if (key == "NUMBER_OF_PHYSICAL_CORES"_s) {
+ return ValueToString(info.GetNumberOfPhysicalCPU());
+ }
+ if (key == "HOSTNAME"_s) {
+ return ValueToString(info.GetHostname());
+ }
+ if (key == "FQDN"_s) {
+ return ValueToString(info.GetFullyQualifiedDomainName());
+ }
+ if (key == "TOTAL_VIRTUAL_MEMORY"_s) {
+ return ValueToString(info.GetTotalVirtualMemory());
+ }
+ if (key == "AVAILABLE_VIRTUAL_MEMORY"_s) {
+ return ValueToString(info.GetAvailableVirtualMemory());
+ }
+ if (key == "TOTAL_PHYSICAL_MEMORY"_s) {
+ return ValueToString(info.GetTotalPhysicalMemory());
+ }
+ if (key == "AVAILABLE_PHYSICAL_MEMORY"_s) {
+ return ValueToString(info.GetAvailablePhysicalMemory());
+ }
+ if (key == "IS_64BIT"_s) {
+ return ValueToString(info.Is64Bits());
+ }
+ if (key == "HAS_FPU"_s) {
+ return ValueToString(
info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_FPU));
- } else if (key == "HAS_MMX") {
- value = ValueToString(
+ }
+ if (key == "HAS_MMX"_s) {
+ return ValueToString(
info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_MMX));
- } else if (key == "HAS_MMX_PLUS") {
- value = ValueToString(info.DoesCPUSupportFeature(
+ }
+ if (key == "HAS_MMX_PLUS"_s) {
+ return ValueToString(info.DoesCPUSupportFeature(
cmsys::SystemInformation::CPU_FEATURE_MMX_PLUS));
- } else if (key == "HAS_SSE") {
- value = ValueToString(
+ }
+ if (key == "HAS_SSE"_s) {
+ return ValueToString(
info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_SSE));
- } else if (key == "HAS_SSE2") {
- value = ValueToString(
+ }
+ if (key == "HAS_SSE2"_s) {
+ return ValueToString(
info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_SSE2));
- } else if (key == "HAS_SSE_FP") {
- value = ValueToString(info.DoesCPUSupportFeature(
+ }
+ if (key == "HAS_SSE_FP"_s) {
+ return ValueToString(info.DoesCPUSupportFeature(
cmsys::SystemInformation::CPU_FEATURE_SSE_FP));
- } else if (key == "HAS_SSE_MMX") {
- value = ValueToString(info.DoesCPUSupportFeature(
+ }
+ if (key == "HAS_SSE_MMX"_s) {
+ return ValueToString(info.DoesCPUSupportFeature(
cmsys::SystemInformation::CPU_FEATURE_SSE_MMX));
- } else if (key == "HAS_AMD_3DNOW") {
- value = ValueToString(info.DoesCPUSupportFeature(
+ }
+ if (key == "HAS_AMD_3DNOW"_s) {
+ return ValueToString(info.DoesCPUSupportFeature(
cmsys::SystemInformation::CPU_FEATURE_AMD_3DNOW));
- } else if (key == "HAS_AMD_3DNOW_PLUS") {
- value = ValueToString(info.DoesCPUSupportFeature(
+ }
+ if (key == "HAS_AMD_3DNOW_PLUS"_s) {
+ return ValueToString(info.DoesCPUSupportFeature(
cmsys::SystemInformation::CPU_FEATURE_AMD_3DNOW_PLUS));
- } else if (key == "HAS_IA64") {
- value = ValueToString(
+ }
+ if (key == "HAS_IA64"_s) {
+ return ValueToString(
info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_IA64));
- } else if (key == "HAS_SERIAL_NUMBER") {
- value = ValueToString(info.DoesCPUSupportFeature(
+ }
+ if (key == "HAS_SERIAL_NUMBER"_s) {
+ return ValueToString(info.DoesCPUSupportFeature(
cmsys::SystemInformation::CPU_FEATURE_SERIALNUMBER));
- } else if (key == "PROCESSOR_NAME") {
- value = ValueToString(info.GetExtendedProcessorName());
- } else if (key == "PROCESSOR_DESCRIPTION") {
- value = info.GetCPUDescription();
- } else if (key == "PROCESSOR_SERIAL_NUMBER") {
- value = ValueToString(info.GetProcessorSerialNumber());
- } else if (key == "OS_NAME") {
- value = ValueToString(info.GetOSName());
- } else if (key == "OS_RELEASE") {
- value = ValueToString(info.GetOSRelease());
- } else if (key == "OS_VERSION") {
- value = ValueToString(info.GetOSVersion());
- } else if (key == "OS_PLATFORM") {
- value = ValueToString(info.GetOSPlatform());
-#ifdef HAVE_VS_SETUP_HELPER
- } else if (key == "VS_15_DIR") {
- // If generating for the VS 15 IDE, use the same instance.
- cmGlobalGenerator* gg = status.GetMakefile().GetGlobalGenerator();
- if (cmHasLiteralPrefix(gg->GetName(), "Visual Studio 15 ")) {
- cmGlobalVisualStudioVersionedGenerator* vs15gen =
- static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg);
- if (vs15gen->GetVSInstance(value)) {
- return true;
- }
+ }
+ if (key == "PROCESSOR_NAME"_s) {
+ return ValueToString(info.GetExtendedProcessorName());
+ }
+ if (key == "PROCESSOR_DESCRIPTION"_s) {
+ return info.GetCPUDescription();
+ }
+ if (key == "PROCESSOR_SERIAL_NUMBER"_s) {
+ return ValueToString(info.GetProcessorSerialNumber());
+ }
+ if (key == "OS_NAME"_s) {
+ return ValueToString(info.GetOSName());
+ }
+ if (key == "OS_RELEASE"_s) {
+ return ValueToString(info.GetOSRelease());
+ }
+ if (key == "OS_VERSION"_s) {
+ return ValueToString(info.GetOSVersion());
+ }
+ if (key == "OS_PLATFORM"_s) {
+ return ValueToString(info.GetOSPlatform());
+ }
+ return {};
+}
+
+cm::optional<std::pair<std::string, std::string>> ParseOSReleaseLine(
+ std::string const& line)
+{
+ std::string key;
+ std::string value;
+
+ char prev = 0;
+ enum ParserState
+ {
+ PARSE_KEY_1ST,
+ PARSE_KEY,
+ FOUND_EQ,
+ PARSE_SINGLE_QUOTE_VALUE,
+ PARSE_DBL_QUOTE_VALUE,
+ PARSE_VALUE,
+ IGNORE_REST
+ } state = PARSE_KEY_1ST;
+
+ for (auto ch : line) {
+ switch (state) {
+ case PARSE_KEY_1ST:
+ if (std::isalpha(ch) || ch == '_') {
+ key += ch;
+ state = PARSE_KEY;
+ } else if (!std::isspace(ch)) {
+ state = IGNORE_REST;
+ }
+ break;
+
+ case PARSE_KEY:
+ if (ch == '=') {
+ state = FOUND_EQ;
+ } else if (std::isalnum(ch) || ch == '_') {
+ key += ch;
+ } else {
+ state = IGNORE_REST;
+ }
+ break;
+
+ case FOUND_EQ:
+ switch (ch) {
+ case '\'':
+ state = PARSE_SINGLE_QUOTE_VALUE;
+ break;
+ case '"':
+ state = PARSE_DBL_QUOTE_VALUE;
+ break;
+ case '#':
+ case '\\':
+ state = IGNORE_REST;
+ break;
+ default:
+ value += ch;
+ state = PARSE_VALUE;
+ }
+ break;
+
+ case PARSE_SINGLE_QUOTE_VALUE:
+ if (ch == '\'') {
+ if (prev != '\\') {
+ state = IGNORE_REST;
+ } else {
+ assert(!value.empty());
+ value[value.size() - 1] = ch;
+ }
+ } else {
+ value += ch;
+ }
+ break;
+
+ case PARSE_DBL_QUOTE_VALUE:
+ if (ch == '"') {
+ if (prev != '\\') {
+ state = IGNORE_REST;
+ } else {
+ assert(!value.empty());
+ value[value.size() - 1] = ch;
+ }
+ } else {
+ value += ch;
+ }
+ break;
+
+ case PARSE_VALUE:
+ if (ch == '#' || std::isspace(ch)) {
+ state = IGNORE_REST;
+ } else {
+ value += ch;
+ }
+ break;
+
+ default:
+ // Unexpected os-release parser state!
+ state = IGNORE_REST;
+ break;
}
- // Otherwise, find a VS 15 instance ourselves.
- cmVSSetupAPIHelper vsSetupAPIHelper(15);
- if (vsSetupAPIHelper.GetVSInstanceInfo(value)) {
- cmSystemTools::ConvertToUnixSlashes(value);
+ if (state == IGNORE_REST) {
+ break;
}
- } else if (key == "VS_16_DIR") {
- // If generating for the VS 16 IDE, use the same instance.
- cmGlobalGenerator* gg = status.GetMakefile().GetGlobalGenerator();
- if (cmHasLiteralPrefix(gg->GetName(), "Visual Studio 16 ")) {
- cmGlobalVisualStudioVersionedGenerator* vs16gen =
- static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg);
- if (vs16gen->GetVSInstance(value)) {
- return true;
+ prev = ch;
+ }
+ if (!(key.empty() || value.empty())) {
+ return std::make_pair(key, value);
+ }
+ return {};
+}
+
+std::map<std::string, std::string> GetOSReleaseVariables(
+ cmExecutionStatus& status)
+{
+ auto& makefile = status.GetMakefile();
+ const auto& sysroot = makefile.GetSafeDefinition("CMAKE_SYSROOT");
+
+ std::map<std::string, std::string> data;
+ // Based on
+ // https://www.freedesktop.org/software/systemd/man/os-release.html
+ for (auto name : { "/etc/os-release"_s, "/usr/lib/os-release"_s }) {
+ const auto& filename = cmStrCat(sysroot, name);
+ if (cmSystemTools::FileExists(filename)) {
+ cmsys::ifstream fin(filename.c_str());
+ for (std::string line; !std::getline(fin, line).fail();) {
+ auto kv = ParseOSReleaseLine(line);
+ if (kv.has_value()) {
+ data.emplace(kv.value());
+ }
}
+ break;
}
+ }
+ // Got smth?
+ if (!data.empty()) {
+ return data;
+ }
+
+ // Ugh, it could be some pre-os-release distro.
+ // Lets try some fallback getters.
+ // See also:
+ // - http://linuxmafia.com/faq/Admin/release-files.html
+
+ // 1. CMake provided
+ cmsys::Glob gl;
+ std::vector<std::string> scripts;
+ auto const findExpr = cmStrCat(cmSystemTools::GetCMakeRoot(),
+ "/Modules/Internal/OSRelease/*.cmake");
+ if (gl.FindFiles(findExpr)) {
+ scripts = gl.GetFiles();
+ }
+
+ // 2. User provided (append to the CMake prvided)
+ makefile.GetDefExpandList("CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS", scripts);
+
+ // Filter out files that are not in format `NNN-name.cmake`
+ auto checkName = [](std::string const& filepath) -> bool {
+ auto const& filename = cmSystemTools::GetFilenameName(filepath);
+ // NOTE Minimum filename length expected:
+ // NNN-<at-least-one-char-name>.cmake --> 11
+ return (filename.size() < 11) || !std::isdigit(filename[0]) ||
+ !std::isdigit(filename[1]) || !std::isdigit(filename[2]) ||
+ filename[3] != '-';
+ };
+ scripts.erase(std::remove_if(scripts.begin(), scripts.end(), checkName),
+ scripts.end());
- // Otherwise, find a VS 16 instance ourselves.
- cmVSSetupAPIHelper vsSetupAPIHelper(16);
- if (vsSetupAPIHelper.GetVSInstanceInfo(value)) {
- cmSystemTools::ConvertToUnixSlashes(value);
+ // Make sure scripts are running in desired order
+ std::sort(scripts.begin(), scripts.end(),
+ [](std::string const& lhs, std::string const& rhs) -> bool {
+ long lhs_order;
+ cmStrToLong(cmSystemTools::GetFilenameName(lhs).substr(0u, 3u),
+ &lhs_order);
+ long rhs_order;
+ cmStrToLong(cmSystemTools::GetFilenameName(rhs).substr(0u, 3u),
+ &rhs_order);
+ return lhs_order < rhs_order;
+ });
+
+ // Name of the variable to put the results
+ auto const result_variable = "CMAKE_GET_OS_RELEASE_FALLBACK_RESULT"_s;
+
+ for (auto const& script : scripts) {
+ // Unset the result variable
+ makefile.RemoveDefinition(result_variable.data());
+
+ // include FATAL_ERROR and ERROR in the return status
+ if (!makefile.ReadListFile(script) ||
+ cmSystemTools::GetErrorOccuredFlag()) {
+ // Ok, no worries... go try the next script.
+ continue;
+ }
+
+ std::vector<std::string> variables;
+ if (!makefile.GetDefExpandList(result_variable.data(), variables)) {
+ // Heh, this script didn't found anything... go try the next one.
+ continue;
}
- } else if (key == "VS_17_DIR") {
- // If generating for the VS 17 IDE, use the same instance.
- cmGlobalGenerator* gg = status.GetMakefile().GetGlobalGenerator();
- if (cmHasLiteralPrefix(gg->GetName(), "Visual Studio 17 ")) {
- cmGlobalVisualStudioVersionedGenerator* vs17gen =
- static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg);
- if (vs17gen->GetVSInstance(value)) {
- return true;
+
+ for (auto const& variable : variables) {
+ auto value = makefile.GetSafeDefinition(variable);
+ makefile.RemoveDefinition(variable);
+
+ if (!cmHasPrefix(variable, cmStrCat(result_variable, '_'))) {
+ // Ignore unknown variable set by the script
+ continue;
}
+
+ auto key = variable.substr(result_variable.size() + 1,
+ variable.size() - result_variable.size() - 1);
+ data.emplace(std::move(key), std::move(value));
}
- // Otherwise, find a VS 17 instance ourselves.
- cmVSSetupAPIHelper vsSetupAPIHelper(17);
- if (vsSetupAPIHelper.GetVSInstanceInfo(value)) {
- cmSystemTools::ConvertToUnixSlashes(value);
+ // Try 'till some script can get anything
+ if (!data.empty()) {
+ data.emplace("USED_FALLBACK_SCRIPT", script);
+ break;
}
-#endif
- } else {
- std::string e = "does not recognize <key> " + key;
- status.SetError(e);
- return false;
}
- return true;
+ makefile.RemoveDefinition(result_variable.data());
+
+ return data;
}
-std::string ValueToString(size_t value)
+cm::optional<std::string> GetValue(cmExecutionStatus& status,
+ std::string const& key,
+ std::string const& variable)
{
- return std::to_string(value);
+ const auto prefix = "DISTRIB_"_s;
+ if (!cmHasPrefix(key, prefix)) {
+ return {};
+ }
+
+ static const std::map<std::string, std::string> s_os_release =
+ GetOSReleaseVariables(status);
+
+ auto& makefile = status.GetMakefile();
+
+ const std::string subkey =
+ key.substr(prefix.size(), key.size() - prefix.size());
+ if (subkey == "INFO"_s) {
+ std::string vars;
+ for (const auto& kv : s_os_release) {
+ auto cmake_var_name = cmStrCat(variable, '_', kv.first);
+ vars += DELIM[!vars.empty()] + cmake_var_name;
+ makefile.AddDefinition(cmake_var_name, kv.second);
+ }
+ return cm::optional<std::string>(std::move(vars));
+ }
+
+ // Query individual variable
+ const auto it = s_os_release.find(subkey);
+ if (it != s_os_release.cend()) {
+ return it->second;
+ }
+
+ // NOTE Empty string means requested variable not set
+ return std::string{};
+}
+
+#ifdef HAVE_VS_SETUP_HELPER
+cm::optional<std::string> GetValue(cmExecutionStatus& status,
+ std::string const& key)
+{
+ auto* const gg = status.GetMakefile().GetGlobalGenerator();
+ for (auto vs : { 15, 16, 17 }) {
+ if (key == cmStrCat("VS_"_s, vs, "_DIR"_s)) {
+ std::string value;
+ // If generating for the VS nn IDE, use the same instance.
+
+ if (cmHasPrefix(gg->GetName(), cmStrCat("Visual Studio "_s, vs, ' '))) {
+ cmGlobalVisualStudioVersionedGenerator* vsNNgen =
+ static_cast<cmGlobalVisualStudioVersionedGenerator*>(gg);
+ if (vsNNgen->GetVSInstance(value)) {
+ return value;
+ }
+ }
+
+ // Otherwise, find a VS nn instance ourselves.
+ cmVSSetupAPIHelper vsSetupAPIHelper(vs);
+ if (vsSetupAPIHelper.GetVSInstanceInfo(value)) {
+ cmSystemTools::ConvertToUnixSlashes(value);
+ }
+ return value;
+ }
+ }
+
+ return {};
}
+#endif
-std::string ValueToString(const char* value)
+cm::optional<std::string> GetValueChained()
{
- std::string safe_string = value ? value : "";
- return safe_string;
+ return {};
}
-std::string ValueToString(std::string const& value)
+template <typename GetterFn, typename... Next>
+cm::optional<std::string> GetValueChained(GetterFn current, Next... chain)
{
- return value;
+ auto value = current();
+ if (value.has_value()) {
+ return value;
+ }
+ return GetValueChained(chain...);
}
+// END Private functions
+} // anonymous namespace
+
+// cmCMakeHostSystemInformation
+bool cmCMakeHostSystemInformationCommand(std::vector<std::string> const& args,
+ cmExecutionStatus& status)
+{
+ std::size_t current_index = 0;
+
+ if (args.size() < (current_index + 2) || args[current_index] != "RESULT"_s) {
+ status.SetError("missing RESULT specification.");
+ return false;
+ }
+
+ auto const& variable = args[current_index + 1];
+ current_index += 2;
+
+ if (args.size() < (current_index + 2) || args[current_index] != "QUERY"_s) {
+ status.SetError("missing QUERY specification");
+ return false;
+ }
+
+ static cmsys::SystemInformation info;
+ static auto initialized = false;
+ if (!initialized) {
+ info.RunCPUCheck();
+ info.RunOSCheck();
+ info.RunMemoryCheck();
+ initialized = true;
+ }
+
+ std::string result_list;
+ for (auto i = current_index + 1; i < args.size(); ++i) {
+ result_list += DELIM[!result_list.empty()];
+
+ auto const& key = args[i];
+ // clang-format off
+ auto value =
+ GetValueChained(
+ [&]() { return GetValue(info, key); }
+ , [&]() { return GetValue(status, key, variable); }
+#ifdef HAVE_VS_SETUP_HELPER
+ , [&]() { return GetValue(status, key); }
+#endif
+ );
+ // clang-format on
+ if (!value) {
+ status.SetError("does not recognize <key> " + key);
+ return false;
+ }
+ result_list += value.value();
+ }
+
+ status.GetMakefile().AddDefinition(variable, result_list);
+
+ return true;
}
diff --git a/Source/cmCMakePolicyCommand.cxx b/Source/cmCMakePolicyCommand.cxx
index 1f99043..b2830e2 100644
--- a/Source/cmCMakePolicyCommand.cxx
+++ b/Source/cmCMakePolicyCommand.cxx
@@ -6,6 +6,7 @@
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmPolicies.h"
+#include "cmProperty.h"
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx
index ace7382..e922ee5 100644
--- a/Source/cmCPluginAPI.cxx
+++ b/Source/cmCPluginAPI.cxx
@@ -173,7 +173,7 @@ void CCONV cmAddLinkDirectoryForTarget(void* arg, const char* tgt,
std::string(tgt) + " for directory " + std::string(d));
return;
}
- t->InsertLinkDirectory(d, mf->GetBacktrace());
+ t->InsertLinkDirectory(BT<std::string>(d, mf->GetBacktrace()));
}
void CCONV cmAddExecutable(void* arg, const char* exename, int numSrcs,
diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx
index 1a950df..17369c8 100644
--- a/Source/cmCacheManager.cxx
+++ b/Source/cmCacheManager.cxx
@@ -232,17 +232,17 @@ bool cmCacheManager::SaveCache(const std::string& path, cmMessenger* messenger)
// before writing the cache, update the version numbers
// to the
this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION",
- std::to_string(cmVersion::GetMajorVersion()).c_str(),
+ std::to_string(cmVersion::GetMajorVersion()),
"Major version of cmake used to create the "
"current loaded cache",
cmStateEnums::INTERNAL);
this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION",
- std::to_string(cmVersion::GetMinorVersion()).c_str(),
+ std::to_string(cmVersion::GetMinorVersion()),
"Minor version of cmake used to create the "
"current loaded cache",
cmStateEnums::INTERNAL);
this->AddCacheEntry("CMAKE_CACHE_PATCH_VERSION",
- std::to_string(cmVersion::GetPatchVersion()).c_str(),
+ std::to_string(cmVersion::GetPatchVersion()),
"Patch version of cmake used to create the "
"current loaded cache",
cmStateEnums::INTERNAL);
@@ -256,7 +256,7 @@ bool cmCacheManager::SaveCache(const std::string& path, cmMessenger* messenger)
currentcwd[0] = static_cast<char>(currentcwd[0] - 'A' + 'a');
}
cmSystemTools::ConvertToUnixSlashes(currentcwd);
- this->AddCacheEntry("CMAKE_CACHEFILE_DIR", currentcwd.c_str(),
+ this->AddCacheEntry("CMAKE_CACHEFILE_DIR", currentcwd,
"This is the directory where this CMakeCache.txt"
" was created",
cmStateEnums::INTERNAL);
@@ -500,7 +500,7 @@ cmProp cmCacheManager::GetInitializedCacheValue(const std::string& key) const
{
if (const auto* entry = this->GetCacheEntry(key)) {
if (entry->Initialized) {
- return &entry->GetValue();
+ return cmProp(entry->GetValue());
}
}
return nullptr;
@@ -521,7 +521,7 @@ void cmCacheManager::PrintCache(std::ostream& out) const
"=================================================\n";
}
-void cmCacheManager::AddCacheEntry(const std::string& key, const char* value,
+void cmCacheManager::AddCacheEntry(const std::string& key, cmProp value,
const char* helpString,
cmStateEnums::CacheEntryType type)
{
@@ -550,10 +550,10 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value,
: "(This variable does not exist and should not be used)");
}
-void cmCacheManager::CacheEntry::SetValue(const char* value)
+void cmCacheManager::CacheEntry::SetValue(cmProp value)
{
if (value) {
- this->Value = value;
+ this->Value = *value;
this->Initialized = true;
} else {
this->Value.clear();
@@ -568,10 +568,10 @@ std::vector<std::string> cmCacheManager::CacheEntry::GetPropertyList() const
cmProp cmCacheManager::CacheEntry::GetProperty(const std::string& prop) const
{
if (prop == "TYPE") {
- return &cmState::CacheEntryTypeToString(this->Type);
+ return cmProp(cmState::CacheEntryTypeToString(this->Type));
}
if (prop == "VALUE") {
- return &this->Value;
+ return cmProp(this->Value);
}
return this->Properties.GetPropertyValue(prop);
}
diff --git a/Source/cmCacheManager.h b/Source/cmCacheManager.h
index 7a9a7dc..eca7150 100644
--- a/Source/cmCacheManager.h
+++ b/Source/cmCacheManager.h
@@ -31,7 +31,7 @@ class cmCacheManager
public:
const std::string& GetValue() const { return this->Value; }
- void SetValue(const char*);
+ void SetValue(cmProp);
cmStateEnums::CacheEntryType GetType() const { return this->Type; }
void SetType(cmStateEnums::CacheEntryType ty) { this->Type = ty; }
@@ -75,7 +75,7 @@ public:
cmProp GetCacheEntryValue(const std::string& key) const
{
if (const auto* entry = this->GetCacheEntry(key)) {
- return &entry->GetValue();
+ return cmProp(entry->GetValue());
}
return nullptr;
}
@@ -83,7 +83,7 @@ public:
void SetCacheEntryValue(std::string const& key, std::string const& value)
{
if (auto* entry = this->GetCacheEntry(key)) {
- entry->SetValue(value.c_str());
+ entry->SetValue(cmProp(value));
}
}
@@ -173,6 +173,18 @@ public:
//! Add an entry into the cache
void AddCacheEntry(const std::string& key, const char* value,
+ const char* helpString, cmStateEnums::CacheEntryType type)
+ {
+ this->AddCacheEntry(key,
+ value ? cmProp(std::string(value)) : cmProp(nullptr),
+ helpString, type);
+ }
+ void AddCacheEntry(const std::string& key, const std::string& value,
+ const char* helpString, cmStateEnums::CacheEntryType type)
+ {
+ this->AddCacheEntry(key, cmProp(value), helpString, type);
+ }
+ void AddCacheEntry(const std::string& key, cmProp value,
const char* helpString,
cmStateEnums::CacheEntryType type);
diff --git a/Source/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx
index deddba8..415f0c0 100644
--- a/Source/cmCommandArgumentParserHelper.cxx
+++ b/Source/cmCommandArgumentParserHelper.cxx
@@ -113,7 +113,7 @@ const char* cmCommandArgumentParserHelper::ExpandVariable(const char* var)
if (this->EscapeQuotes && value) {
return this->AddString(cmEscapeQuotes(*value));
}
- return this->AddString(cmToCStrSafe(value));
+ return this->AddString(value);
}
const char* cmCommandArgumentParserHelper::ExpandVariableForAt(const char* var)
diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx
index 7c2e20c..59e4141 100644
--- a/Source/cmCommonTargetGenerator.cxx
+++ b/Source/cmCommonTargetGenerator.cxx
@@ -39,10 +39,10 @@ std::vector<std::string> const& cmCommonTargetGenerator::GetConfigNames() const
return this->ConfigNames;
}
-const char* cmCommonTargetGenerator::GetFeature(const std::string& feature,
- const std::string& config)
+cmProp cmCommonTargetGenerator::GetFeature(const std::string& feature,
+ const std::string& config)
{
- return this->GeneratorTarget->GetFeature(feature, config)->c_str();
+ return this->GeneratorTarget->GetFeature(feature, config);
}
void cmCommonTargetGenerator::AddModuleDefinitionFlag(
diff --git a/Source/cmCommonTargetGenerator.h b/Source/cmCommonTargetGenerator.h
index e1a4f8b..463a445 100644
--- a/Source/cmCommonTargetGenerator.h
+++ b/Source/cmCommonTargetGenerator.h
@@ -8,6 +8,8 @@
#include <string>
#include <vector>
+#include "cmProperty.h"
+
class cmGeneratorTarget;
class cmGlobalCommonGenerator;
class cmLinkLineComputer;
@@ -28,8 +30,7 @@ public:
protected:
// Feature query methods.
- const char* GetFeature(const std::string& feature,
- const std::string& config);
+ cmProp GetFeature(const std::string& feature, const std::string& config);
// Helper to add flag for windows .def file.
void AddModuleDefinitionFlag(cmLinkLineComputer* linkLineComputer,
diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx
index 0b27e34..15a12ba 100644
--- a/Source/cmComputeLinkDepends.cxx
+++ b/Source/cmComputeLinkDepends.cxx
@@ -607,7 +607,7 @@ cmLinkItem cmComputeLinkDepends::ResolveLinkItem(int depender_index,
from = depender;
}
}
- return from->ResolveLinkItem(name, cmListFileBacktrace());
+ return from->ResolveLinkItem(BT<std::string>(name));
}
void cmComputeLinkDepends::InferDependencies()
diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx
index d15da0c..eda0722 100644
--- a/Source/cmComputeLinkInformation.cxx
+++ b/Source/cmComputeLinkInformation.cxx
@@ -278,13 +278,11 @@ cmComputeLinkInformation::cmComputeLinkInformation(
// On platforms without import libraries there may be a special flag
// to use when creating a plugin (module) that obtains symbols from
// the program that will load it.
- this->LoaderFlag = nullptr;
if (!this->Target->IsDLLPlatform() &&
this->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
std::string loader_flag_var =
cmStrCat("CMAKE_SHARED_MODULE_LOADER_", this->LinkLanguage, "_FLAG");
- this->LoaderFlag =
- cmToCStr(this->Makefile->GetDefinition(loader_flag_var));
+ this->LoaderFlag = this->Makefile->GetDefinition(loader_flag_var);
}
// Get options needed to link libraries.
@@ -660,8 +658,7 @@ void cmComputeLinkInformation::AddItem(BT<std::string> const& item,
// This link item is an executable that may provide symbols
// used by this target. A special flag is needed on this
// platform. Add it now.
- std::string linkItem;
- linkItem = this->LoaderFlag;
+ std::string linkItem = this->LoaderFlag;
cmStateEnums::ArtifactType artifact = tgt->HasImportLibrary(config)
? cmStateEnums::ImportLibraryArtifact
: cmStateEnums::RuntimeBinaryArtifact;
diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h
index 7fe30b3..c3ae345 100644
--- a/Source/cmComputeLinkInformation.h
+++ b/Source/cmComputeLinkInformation.h
@@ -14,6 +14,7 @@
#include "cmsys/RegularExpression.hxx"
#include "cmListFileCache.h"
+#include "cmProperty.h"
class cmGeneratorTarget;
class cmGlobalGenerator;
@@ -137,7 +138,7 @@ private:
SharedDepModeLink // List file on link line
};
- const char* LoaderFlag;
+ cmProp LoaderFlag;
std::string LibLinkFlag;
std::string LibLinkFileFlag;
std::string ObjLinkFileFlag;
diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx
index 76712f4..5d3e04f 100644
--- a/Source/cmComputeTargetDepends.cxx
+++ b/Source/cmComputeTargetDepends.cxx
@@ -323,7 +323,7 @@ void cmComputeTargetDepends::AddObjectDepends(int depender_index,
}
cmGeneratorTarget const* depender = this->Targets[depender_index];
cmLinkItem const& objItem =
- depender->ResolveLinkItem(objLib, cmListFileBacktrace());
+ depender->ResolveLinkItem(BT<std::string>(objLib));
if (emitted.insert(objItem).second) {
if (depender->GetType() != cmStateEnums::EXECUTABLE &&
depender->GetType() != cmStateEnums::STATIC_LIBRARY &&
diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx
index 415f667..68bc4d8 100644
--- a/Source/cmConditionEvaluator.cxx
+++ b/Source/cmConditionEvaluator.cxx
@@ -260,11 +260,17 @@ bool cmConditionEvaluator::IsTrue(
for (auto fn : handlers) {
// Call the reducer 'till there is anything to reduce...
// (i.e., if after an iteration the size becomes smaller)
+ auto levelResult = true;
for (auto beginSize = newArgs.size();
- (this->*fn)(newArgs, errorString, status) &&
+ (levelResult = (this->*fn)(newArgs, errorString, status)) &&
newArgs.size() < beginSize;
beginSize = newArgs.size()) {
}
+
+ if (!levelResult) {
+ // NOTE `errorString` supposed to be set already
+ return false;
+ }
}
// now at the end there should only be one argument left
@@ -317,7 +323,7 @@ cmProp cmConditionEvaluator::GetVariableOrString(
cmProp def = this->GetDefinitionIfUnquoted(argument);
if (!def) {
- def = &argument.GetValue();
+ def = cmProp(argument.GetValue());
}
return def;
@@ -403,7 +409,7 @@ bool cmConditionEvaluator::GetBooleanValueOld(
// Old GetVariableOrNumber behavior.
cmProp def = this->GetDefinitionIfUnquoted(arg);
if (!def && std::atoi(arg.GetValue().c_str())) {
- def = &arg.GetValue();
+ def = cmProp(arg.GetValue());
}
return !cmIsOff(def);
}
@@ -649,13 +655,13 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
std::string def_buf;
if (!def) {
- def = &args.current->GetValue();
+ def = cmProp(args.current->GetValue());
} else if (cmHasLiteralPrefix(args.current->GetValue(),
"CMAKE_MATCH_")) {
// The string to match is owned by our match result variables.
// Move it to our own buffer before clearing them.
def_buf = *def;
- def = &def_buf;
+ def = cmProp(def_buf);
}
this->Makefile.ClearMatches();
diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx
index bf18143..0fd48f0 100644
--- a/Source/cmCoreTryCompile.cxx
+++ b/Source/cmCoreTryCompile.cxx
@@ -606,7 +606,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
std::string langFlags = "CMAKE_" + li + "_FLAGS";
cmProp flags = this->Makefile->GetDefinition(langFlags);
fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
- cmOutputConverter::EscapeForCMake(cmToCStrSafe(flags)).c_str());
+ cmOutputConverter::EscapeForCMake(flags).c_str());
fprintf(fout,
"set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
" ${COMPILE_DEFINITIONS}\")\n",
@@ -644,9 +644,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
std::string const langFlagsCfg =
cmStrCat("CMAKE_", li, "_FLAGS_", cfg);
cmProp flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
- fprintf(
- fout, "set(%s %s)\n", langFlagsCfg.c_str(),
- cmOutputConverter::EscapeForCMake(cmToCStrSafe(flagsCfg)).c_str());
+ fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
+ cmOutputConverter::EscapeForCMake(flagsCfg).c_str());
}
} break;
}
@@ -679,8 +678,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
cmProp exeLinkFlags =
this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
- cmOutputConverter::EscapeForCMake(cmToCStrSafe(exeLinkFlags))
- .c_str());
+ cmOutputConverter::EscapeForCMake(exeLinkFlags).c_str());
}
break;
}
diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx
index 4a4f87d..9e2d7b9 100644
--- a/Source/cmDefinitions.cxx
+++ b/Source/cmDefinitions.cxx
@@ -34,11 +34,11 @@ cmDefinitions::Def const& cmDefinitions::GetInternal(const std::string& key,
return begin->Map.emplace(key, def).first->second;
}
-const std::string* cmDefinitions::Get(const std::string& key, StackIter begin,
- StackIter end)
+cmProp cmDefinitions::Get(const std::string& key, StackIter begin,
+ StackIter end)
{
Def const& def = cmDefinitions::GetInternal(key, begin, end, false);
- return def.Value ? def.Value.str_if_stable() : nullptr;
+ return def.Value ? cmProp(def.Value.str_if_stable()) : nullptr;
}
void cmDefinitions::Raise(const std::string& key, StackIter begin,
diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h
index b650aa8..ee1db7a 100644
--- a/Source/cmDefinitions.h
+++ b/Source/cmDefinitions.h
@@ -12,6 +12,7 @@
#include <cm/string_view>
#include "cmLinkedTree.h"
+#include "cmProperty.h"
#include "cmString.hxx"
/** \class cmDefinitions
@@ -28,8 +29,7 @@ class cmDefinitions
public:
// -- Static member functions
- static const std::string* Get(const std::string& key, StackIter begin,
- StackIter end);
+ static cmProp Get(const std::string& key, StackIter begin, StackIter end);
static void Raise(const std::string& key, StackIter begin, StackIter end);
diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx
index 4a9bf28..6e3f918 100644
--- a/Source/cmExportBuildFileGenerator.cxx
+++ b/Source/cmExportBuildFileGenerator.cxx
@@ -18,6 +18,7 @@
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmPolicies.h"
+#include "cmProperty.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
#include "cmTarget.h"
diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx
index ebdbe38..8b06a15 100644
--- a/Source/cmExportFileGenerator.cxx
+++ b/Source/cmExportFileGenerator.cxx
@@ -917,7 +917,7 @@ void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
// Protect that file against use with older CMake versions.
/* clang-format off */
os << "# Generated by CMake\n\n";
- os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n"
+ os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.6)\n"
<< " message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
<< "endif()\n";
/* clang-format on */
diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx
index 4249cfe..46d2d31 100644
--- a/Source/cmExportInstallFileGenerator.cxx
+++ b/Source/cmExportInstallFileGenerator.cxx
@@ -16,6 +16,7 @@
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
#include "cmPolicies.h"
+#include "cmProperty.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
diff --git a/Source/cmFileAPICodemodel.cxx b/Source/cmFileAPICodemodel.cxx
index a2b5460..adeba74 100644
--- a/Source/cmFileAPICodemodel.cxx
+++ b/Source/cmFileAPICodemodel.cxx
@@ -813,8 +813,7 @@ Json::Value CodemodelConfig::DumpProject(Project& p)
Json::Value CodemodelConfig::DumpMinimumCMakeVersion(cmStateSnapshot s)
{
Json::Value minimumCMakeVersion;
- if (std::string const* def =
- s.GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
+ if (cmProp def = s.GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
minimumCMakeVersion = Json::objectValue;
minimumCMakeVersion["string"] = *def;
}
diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx
index 1e3076f..2730a07 100644
--- a/Source/cmFileCommand.cxx
+++ b/Source/cmFileCommand.cxx
@@ -1850,7 +1850,7 @@ bool HandleDownloadCommand(std::vector<std::string> const& args,
} else if (*i == "TLS_CAINFO") {
++i;
if (i != args.end()) {
- cainfo = &(*i);
+ cainfo = cmProp(*i);
} else {
status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
return false;
@@ -2236,7 +2236,7 @@ bool HandleUploadCommand(std::vector<std::string> const& args,
} else if (*i == "TLS_CAINFO") {
++i;
if (i != args.end()) {
- cainfo = &(*i);
+ cainfo = cmProp(*i);
} else {
status.SetError("UPLOAD missing file value for TLS_CAINFO.");
return false;
diff --git a/Source/cmFileCopier.h b/Source/cmFileCopier.h
index 217d58d..ee9872d 100644
--- a/Source/cmFileCopier.h
+++ b/Source/cmFileCopier.h
@@ -67,8 +67,9 @@ protected:
bool InstallSymlinkChain(std::string& fromFile, std::string& toFile);
bool InstallSymlink(const std::string& fromFile, const std::string& toFile);
- bool InstallFile(const std::string& fromFile, const std::string& toFile,
- MatchProperties match_properties);
+ virtual bool InstallFile(const std::string& fromFile,
+ const std::string& toFile,
+ MatchProperties match_properties);
bool InstallDirectory(const std::string& source,
const std::string& destination,
MatchProperties match_properties);
diff --git a/Source/cmFileInstaller.cxx b/Source/cmFileInstaller.cxx
index c89be96..0d8ba2d 100644
--- a/Source/cmFileInstaller.cxx
+++ b/Source/cmFileInstaller.cxx
@@ -3,7 +3,12 @@
#include "cmFileInstaller.h"
+#include <map>
#include <sstream>
+#include <utility>
+
+#include <cm/string_view>
+#include <cmext/string_view>
#include "cm_sys_stat.h"
@@ -18,6 +23,7 @@ using namespace cmFSPermissions;
cmFileInstaller::cmFileInstaller(cmExecutionStatus& status)
: cmFileCopier(status, "INSTALL")
, InstallType(cmInstallType_FILES)
+ , InstallMode(cmInstallMode::COPY)
, Optional(false)
, MessageAlways(false)
, MessageLazy(false)
@@ -82,6 +88,93 @@ bool cmFileInstaller::Install(const std::string& fromFile,
return this->cmFileCopier::Install(fromFile, toFile);
}
+bool cmFileInstaller::InstallFile(const std::string& fromFile,
+ const std::string& toFile,
+ MatchProperties match_properties)
+{
+ if (this->InstallMode == cmInstallMode::COPY) {
+ return this->cmFileCopier::InstallFile(fromFile, toFile, match_properties);
+ }
+
+ std::string newFromFile;
+
+ if (this->InstallMode == cmInstallMode::REL_SYMLINK ||
+ this->InstallMode == cmInstallMode::REL_SYMLINK_OR_COPY ||
+ this->InstallMode == cmInstallMode::SYMLINK ||
+ this->InstallMode == cmInstallMode::SYMLINK_OR_COPY) {
+ // Try to get a relative path.
+ std::string toDir = cmSystemTools::GetParentDirectory(toFile);
+ newFromFile = cmSystemTools::ForceToRelativePath(toDir, fromFile);
+
+ // Double check that we can restore the original path.
+ std::string reassembled =
+ cmSystemTools::CollapseFullPath(newFromFile, toDir);
+ if (!cmSystemTools::ComparePath(reassembled, fromFile)) {
+ if (this->InstallMode == cmInstallMode::SYMLINK ||
+ this->InstallMode == cmInstallMode::SYMLINK_OR_COPY) {
+ // User does not mind, silently proceed with absolute path.
+ newFromFile = fromFile;
+ } else if (this->InstallMode == cmInstallMode::REL_SYMLINK_OR_COPY) {
+ // User expects a relative symbolic link or a copy.
+ // Since an absolute symlink won't do, copy instead.
+ return this->cmFileCopier::InstallFile(fromFile, toFile,
+ match_properties);
+ } else {
+ // We cannot meet user's expectation (REL_SYMLINK)
+ auto e = cmStrCat(this->Name,
+ " cannot determine relative path for symlink to \"",
+ newFromFile, "\" at \"", toFile, "\".");
+ this->Status.SetError(e);
+ return false;
+ }
+ }
+ } else {
+ newFromFile = fromFile; // stick with absolute path
+ }
+
+ // Compare the symlink value to that at the destination if not
+ // always installing.
+ bool copy = true;
+ if (!this->Always) {
+ std::string oldSymlinkTarget;
+ if (cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget)) {
+ if (newFromFile == oldSymlinkTarget) {
+ copy = false;
+ }
+ }
+ }
+
+ // Inform the user about this file installation.
+ this->ReportCopy(toFile, TypeLink, copy);
+
+ if (copy) {
+ // Remove the destination file so we can always create the symlink.
+ cmSystemTools::RemoveFile(toFile);
+
+ // Create destination directory if it doesn't exist
+ cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(toFile));
+
+ // Create the symlink.
+ if (!cmSystemTools::CreateSymlink(newFromFile, toFile)) {
+ if (this->InstallMode == cmInstallMode::ABS_SYMLINK_OR_COPY ||
+ this->InstallMode == cmInstallMode::REL_SYMLINK_OR_COPY ||
+ this->InstallMode == cmInstallMode::SYMLINK_OR_COPY) {
+ // Failed to create a symbolic link, fall back to copying.
+ return this->cmFileCopier::InstallFile(newFromFile, toFile,
+ match_properties);
+ }
+
+ auto e = cmStrCat(this->Name, " cannot create symlink to \"",
+ newFromFile, "\" at \"", toFile,
+ "\": ", cmSystemTools::GetLastSystemError(), "\".");
+ this->Status.SetError(e);
+ return false;
+ }
+ }
+
+ return true;
+}
+
void cmFileInstaller::DefaultFilePermissions()
{
this->cmFileCopier::DefaultFilePermissions();
@@ -141,6 +234,31 @@ bool cmFileInstaller::Parse(std::vector<std::string> const& args)
return false;
}
+ static const std::map<cm::string_view, cmInstallMode> install_mode_dict{
+ { "ABS_SYMLINK"_s, cmInstallMode::ABS_SYMLINK },
+ { "ABS_SYMLINK_OR_COPY"_s, cmInstallMode::ABS_SYMLINK_OR_COPY },
+ { "REL_SYMLINK"_s, cmInstallMode::REL_SYMLINK },
+ { "REL_SYMLINK_OR_COPY"_s, cmInstallMode::REL_SYMLINK_OR_COPY },
+ { "SYMLINK"_s, cmInstallMode::SYMLINK },
+ { "SYMLINK_OR_COPY"_s, cmInstallMode::SYMLINK_OR_COPY }
+ };
+
+ std::string install_mode;
+ cmSystemTools::GetEnv("CMAKE_INSTALL_MODE", install_mode);
+ if (install_mode.empty() || install_mode == "COPY"_s) {
+ this->InstallMode = cmInstallMode::COPY;
+ } else {
+ auto it = install_mode_dict.find(install_mode);
+ if (it != install_mode_dict.end()) {
+ this->InstallMode = it->second;
+ } else {
+ auto e = cmStrCat("Unrecognized value '", install_mode,
+ "' for environment variable CMAKE_INSTALL_MODE");
+ this->Status.SetError(e);
+ return false;
+ }
+ }
+
return true;
}
diff --git a/Source/cmFileInstaller.h b/Source/cmFileInstaller.h
index 3a905d3..3f6bd45 100644
--- a/Source/cmFileInstaller.h
+++ b/Source/cmFileInstaller.h
@@ -8,6 +8,7 @@
#include <vector>
#include "cmFileCopier.h"
+#include "cmInstallMode.h"
#include "cmInstallType.h"
class cmExecutionStatus;
@@ -19,6 +20,7 @@ struct cmFileInstaller : public cmFileCopier
protected:
cmInstallType InstallType;
+ cmInstallMode InstallMode;
bool Optional;
bool MessageAlways;
bool MessageLazy;
@@ -35,7 +37,8 @@ protected:
bool ReportMissing(const std::string& fromFile) override;
bool Install(const std::string& fromFile,
const std::string& toFile) override;
-
+ bool InstallFile(const std::string& fromFile, const std::string& toFile,
+ MatchProperties match_properties) override;
bool Parse(std::vector<std::string> const& args) override;
enum
{
diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx
index 1038ac2..37f9572 100644
--- a/Source/cmFindBase.cxx
+++ b/Source/cmFindBase.cxx
@@ -311,7 +311,7 @@ bool cmFindBase::CheckForVariableDefined()
if (cached && cacheType != cmStateEnums::UNINITIALIZED) {
this->VariableType = cacheType;
- if (const auto* hs =
+ if (const auto& hs =
state->GetCacheEntryProperty(this->VariableName, "HELPSTRING")) {
this->VariableDocumentation = *hs;
}
@@ -336,7 +336,7 @@ void cmFindBase::NormalizeFindResult()
if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0125) ==
cmPolicies::NEW) {
// ensure the path returned by find_* command is absolute
- const auto* existingValue =
+ const auto& existingValue =
this->Makefile->GetDefinition(this->VariableName);
std::string value;
if (!existingValue->empty()) {
@@ -358,8 +358,8 @@ void cmFindBase::NormalizeFindResult()
// value.
if (value != *existingValue || this->AlreadyInCacheWithoutMetaInfo) {
this->Makefile->GetCMakeInstance()->AddCacheEntry(
- this->VariableName, value.c_str(),
- this->VariableDocumentation.c_str(), this->VariableType);
+ this->VariableName, value, this->VariableDocumentation.c_str(),
+ this->VariableType);
if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
cmPolicies::NEW) {
if (this->Makefile->IsNormalDefinitionSet(this->VariableName)) {
diff --git a/Source/cmForEachCommand.cxx b/Source/cmForEachCommand.cxx
index 4845a6d..b44f797 100644
--- a/Source/cmForEachCommand.cxx
+++ b/Source/cmForEachCommand.cxx
@@ -27,6 +27,7 @@
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmPolicies.h"
+#include "cmProperty.h"
#include "cmRange.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx
index 217ebe5..3e90ead 100644
--- a/Source/cmGeneratorExpressionNode.cxx
+++ b/Source/cmGeneratorExpressionNode.cxx
@@ -1777,7 +1777,7 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
testedFeatures[lang].push_back(p);
if (availableFeatures.find(lang) == availableFeatures.end()) {
- const char* featuresKnown =
+ cmProp featuresKnown =
standardResolver.CompileFeaturesAvailable(lang, &error);
if (!featuresKnown) {
reportError(context, content->GetOriginalExpression(), error);
diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx
index bb751d6..4bad7ab 100644
--- a/Source/cmGeneratorTarget.cxx
+++ b/Source/cmGeneratorTarget.cxx
@@ -62,7 +62,7 @@ cmProp cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
cmGeneratorTarget const* tgt, cmMessenger* /* messenger */,
cmListFileBacktrace const& /* context */)
{
- return &tgt->GetSourcesProperty();
+ return tgt->GetSourcesProperty();
}
template <>
@@ -145,12 +145,10 @@ private:
class TargetPropertyEntryString : public cmGeneratorTarget::TargetPropertyEntry
{
public:
- TargetPropertyEntryString(std::string propertyValue,
- cmListFileBacktrace backtrace,
+ TargetPropertyEntryString(BT<std::string> propertyValue,
cmLinkImplItem const& item = NoLinkImplItem)
: cmGeneratorTarget::TargetPropertyEntry(item)
, PropertyValue(std::move(propertyValue))
- , Backtrace(std::move(backtrace))
{
}
@@ -159,46 +157,46 @@ public:
cmGeneratorExpressionDAGChecker*,
std::string const&) const override
{
- return this->PropertyValue;
+ return this->PropertyValue.Value;
}
- cmListFileBacktrace GetBacktrace() const override { return this->Backtrace; }
- std::string const& GetInput() const override { return this->PropertyValue; }
+ cmListFileBacktrace GetBacktrace() const override
+ {
+ return this->PropertyValue.Backtrace;
+ }
+ std::string const& GetInput() const override
+ {
+ return this->PropertyValue.Value;
+ }
private:
- std::string PropertyValue;
- cmListFileBacktrace Backtrace;
+ BT<std::string> PropertyValue;
};
std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>
-CreateTargetPropertyEntry(
- const std::string& propertyValue,
- cmListFileBacktrace backtrace = cmListFileBacktrace(),
- bool evaluateForBuildsystem = false)
+CreateTargetPropertyEntry(const BT<std::string>& propertyValue,
+ bool evaluateForBuildsystem = false)
{
- if (cmGeneratorExpression::Find(propertyValue) != std::string::npos) {
- cmGeneratorExpression ge(std::move(backtrace));
+ if (cmGeneratorExpression::Find(propertyValue.Value) != std::string::npos) {
+ cmGeneratorExpression ge(propertyValue.Backtrace);
std::unique_ptr<cmCompiledGeneratorExpression> cge =
- ge.Parse(propertyValue);
+ ge.Parse(propertyValue.Value);
cge->SetEvaluateForBuildsystem(evaluateForBuildsystem);
return std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>(
cm::make_unique<TargetPropertyEntryGenex>(std::move(cge)));
}
return std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>(
- cm::make_unique<TargetPropertyEntryString>(propertyValue,
- std::move(backtrace)));
+ cm::make_unique<TargetPropertyEntryString>(propertyValue));
}
void CreatePropertyGeneratorExpressions(
- cmStringRange entries, cmBacktraceRange backtraces,
+ cmBTStringRange entries,
std::vector<std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>>& items,
bool evaluateForBuildsystem = false)
{
- auto btIt = backtraces.begin();
- for (auto it = entries.begin(); it != entries.end(); ++it, ++btIt) {
- items.push_back(
- CreateTargetPropertyEntry(*it, *btIt, evaluateForBuildsystem));
+ for (auto const& entry : entries) {
+ items.push_back(CreateTargetPropertyEntry(entry, evaluateForBuildsystem));
}
}
@@ -289,35 +287,27 @@ cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
this->GlobalGenerator->ComputeTargetObjectDirectory(this);
CreatePropertyGeneratorExpressions(t->GetIncludeDirectoriesEntries(),
- t->GetIncludeDirectoriesBacktraces(),
this->IncludeDirectoriesEntries);
CreatePropertyGeneratorExpressions(t->GetCompileOptionsEntries(),
- t->GetCompileOptionsBacktraces(),
this->CompileOptionsEntries);
CreatePropertyGeneratorExpressions(t->GetCompileFeaturesEntries(),
- t->GetCompileFeaturesBacktraces(),
this->CompileFeaturesEntries);
CreatePropertyGeneratorExpressions(t->GetCompileDefinitionsEntries(),
- t->GetCompileDefinitionsBacktraces(),
this->CompileDefinitionsEntries);
CreatePropertyGeneratorExpressions(t->GetLinkOptionsEntries(),
- t->GetLinkOptionsBacktraces(),
this->LinkOptionsEntries);
CreatePropertyGeneratorExpressions(t->GetLinkDirectoriesEntries(),
- t->GetLinkDirectoriesBacktraces(),
this->LinkDirectoriesEntries);
CreatePropertyGeneratorExpressions(t->GetPrecompileHeadersEntries(),
- t->GetPrecompileHeadersBacktraces(),
this->PrecompileHeadersEntries);
CreatePropertyGeneratorExpressions(t->GetSourceEntries(),
- t->GetSourceBacktraces(),
this->SourceEntries, true);
this->PolicyMap = t->GetPolicyMap();
@@ -332,7 +322,7 @@ cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
cmGeneratorTarget::~cmGeneratorTarget() = default;
-const std::string& cmGeneratorTarget::GetSourcesProperty() const
+cmProp cmGeneratorTarget::GetSourcesProperty() const
{
std::vector<std::string> values;
for (auto const& se : this->SourceEntries) {
@@ -341,7 +331,7 @@ const std::string& cmGeneratorTarget::GetSourcesProperty() const
static std::string value;
value.clear();
value = cmJoin(values, ";");
- return value;
+ return cmProp(value);
}
cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
@@ -396,13 +386,7 @@ cmProp cmGeneratorTarget::GetProperty(const std::string& prop) const
std::string const& cmGeneratorTarget::GetSafeProperty(
std::string const& prop) const
{
- cmProp ret = this->GetProperty(prop);
- if (ret) {
- return *ret;
- }
-
- static std::string const s_empty;
- return s_empty;
+ return this->GetProperty(prop);
}
const char* cmGeneratorTarget::GetOutputTargetType(
@@ -564,7 +548,7 @@ std::string cmGeneratorTarget::GetFilePostfix(const std::string& config) const
// framework postfix.
frameworkPostfix = this->GetFrameworkMultiConfigPostfix(config);
if (!frameworkPostfix.empty()) {
- postfix = &frameworkPostfix;
+ postfix = cmProp(frameworkPostfix);
}
}
return postfix ? *postfix : std::string();
@@ -704,7 +688,8 @@ void cmGeneratorTarget::AddSourceCommon(const std::string& src, bool before)
{
this->SourceEntries.insert(
before ? this->SourceEntries.begin() : this->SourceEntries.end(),
- CreateTargetPropertyEntry(src, this->Makefile->GetBacktrace(), true));
+ CreateTargetPropertyEntry(
+ BT<std::string>(src, this->Makefile->GetBacktrace()), true));
this->ClearSourcesCache();
}
@@ -725,11 +710,13 @@ void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
void cmGeneratorTarget::AddIncludeDirectory(const std::string& src,
bool before)
{
- this->Target->InsertInclude(src, this->Makefile->GetBacktrace(), before);
+ this->Target->InsertInclude(
+ BT<std::string>(src, this->Makefile->GetBacktrace()), before);
this->IncludeDirectoriesEntries.insert(
before ? this->IncludeDirectoriesEntries.begin()
: this->IncludeDirectoriesEntries.end(),
- CreateTargetPropertyEntry(src, this->Makefile->GetBacktrace(), true));
+ CreateTargetPropertyEntry(
+ BT<std::string>(src, this->Makefile->GetBacktrace()), true));
}
std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
@@ -966,7 +953,7 @@ cmProp cmGeneratorTarget::GetLanguageStandard(std::string const& lang,
this->GetLanguageStandardProperty(lang, config);
if (languageStandard) {
- return &(languageStandard->Value);
+ return cmProp(languageStandard->Value);
}
return nullptr;
@@ -1681,9 +1668,9 @@ std::vector<BT<std::string>> cmGeneratorTarget::GetSourceFilePaths(
// for TARGET_OBJECTS instead for backwards compatibility with OLD
// behavior of CMP0024 and CMP0026 only.
- cmStringRange sourceEntries = this->Target->GetSourceEntries();
- for (std::string const& entry : sourceEntries) {
- std::vector<std::string> items = cmExpandedList(entry);
+ cmBTStringRange sourceEntries = this->Target->GetSourceEntries();
+ for (auto const& entry : sourceEntries) {
+ std::vector<std::string> items = cmExpandedList(entry.Value);
for (std::string const& item : items) {
if (cmHasLiteralPrefix(item, "$<TARGET_OBJECTS:") &&
item.back() == '>') {
@@ -4968,11 +4955,11 @@ cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
// The library's soname.
this->ComputeVersionedName(targetNames.SharedObject, prefix,
targetNames.Base, suffix, targetNames.Output,
- cmToCStr(soversion));
+ soversion);
// The library's real name on disk.
this->ComputeVersionedName(targetNames.Real, prefix, targetNames.Base,
- suffix, targetNames.Output, cmToCStr(version));
+ suffix, targetNames.Output, version);
}
// The import library name.
@@ -5005,10 +4992,10 @@ cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
// This versioning is supported only for executables and then only
// when the platform supports symbolic links.
#if defined(_WIN32) && !defined(__CYGWIN__)
- const char* version = nullptr;
+ cmProp version;
#else
// Check for executable version properties.
- const char* version = cmToCStr(this->GetProperty("VERSION"));
+ cmProp version = this->GetProperty("VERSION");
if (this->GetType() != cmStateEnums::EXECUTABLE ||
this->Makefile->IsOn("XCODE")) {
version = nullptr;
@@ -5032,7 +5019,7 @@ cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
#endif
if (version) {
targetNames.Real += "-";
- targetNames.Real += version;
+ targetNames.Real += *version;
}
#if defined(__CYGWIN__)
targetNames.Real += suffix;
@@ -5121,13 +5108,13 @@ void cmGeneratorTarget::GetFullNameInternal(
if (this->IsFrameworkOnApple()) {
fw_prefix =
cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
- targetPrefix = &fw_prefix;
+ targetPrefix = cmProp(fw_prefix);
targetSuffix = nullptr;
}
if (this->IsCFBundleOnApple()) {
fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
- targetPrefix = &fw_prefix;
+ targetPrefix = cmProp(fw_prefix);
targetSuffix = nullptr;
}
@@ -5143,7 +5130,7 @@ void cmGeneratorTarget::GetFullNameInternal(
// EXECUTABLE_SUFFIX attribute.
if (this->IsFrameworkOnApple() &&
this->GetGlobalGenerator()->GetName() == "Xcode") {
- targetSuffix = &configPostfix;
+ targetSuffix = cmProp(configPostfix);
} else {
outBase += configPostfix;
}
@@ -5674,6 +5661,11 @@ std::string valueAsString<std::string>(std::string value)
return value;
}
template <>
+std::string valueAsString<cmProp>(cmProp value)
+{
+ return value ? value : std::string("(unset)");
+}
+template <>
std::string valueAsString<std::nullptr_t>(std::nullptr_t /*unused*/)
{
return "(unset)";
@@ -5749,7 +5741,7 @@ std::string getTypedProperty<std::string>(
cmProp value = tgt->GetProperty(prop);
if (genexInterpreter == nullptr) {
- return valueAsString(cmToCStr(value));
+ return valueAsString(value);
}
return genexInterpreter->Evaluate(value ? *value : "", prop);
@@ -6291,17 +6283,14 @@ std::string cmGeneratorTarget::GetFrameworkVersion() const
return "A";
}
-void cmGeneratorTarget::ComputeVersionedName(std::string& vName,
- std::string const& prefix,
- std::string const& base,
- std::string const& suffix,
- std::string const& name,
- const char* version) const
+void cmGeneratorTarget::ComputeVersionedName(
+ std::string& vName, std::string const& prefix, std::string const& base,
+ std::string const& suffix, std::string const& name, cmProp version) const
{
vName = this->Makefile->IsOn("APPLE") ? (prefix + base) : name;
if (version) {
vName += ".";
- vName += version;
+ vName += *version;
}
vName += this->Makefile->IsOn("APPLE") ? suffix : std::string();
}
@@ -6368,7 +6357,7 @@ cm::optional<cmLinkItem> cmGeneratorTarget::LookupLinkItem(
if (name == this->GetName() || name.empty()) {
return maybeItem;
}
- maybeItem = this->ResolveLinkItem(name, bt, scope->LG);
+ maybeItem = this->ResolveLinkItem(BT<std::string>(name, bt), scope->LG);
return maybeItem;
}
@@ -7381,9 +7370,9 @@ void cmGeneratorTarget::GetObjectLibrariesCMP0026(
// there is no cmGeneratorTarget at configure-time, so search the SOURCES
// for TARGET_OBJECTS instead for backwards compatibility with OLD
// behavior of CMP0024 and CMP0026 only.
- cmStringRange rng = this->Target->GetSourceEntries();
- for (std::string const& entry : rng) {
- std::vector<std::string> files = cmExpandedList(entry);
+ cmBTStringRange rng = this->Target->GetSourceEntries();
+ for (auto const& entry : rng) {
+ std::vector<std::string> files = cmExpandedList(entry.Value);
for (std::string const& li : files) {
if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
std::string objLibName = li.substr(17, li.size() - 18);
@@ -7611,24 +7600,21 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
{
cmLocalGenerator const* lg = this->LocalGenerator;
cmMakefile const* mf = lg->GetMakefile();
- cmStringRange entryRange = this->Target->GetLinkImplementationEntries();
- cmBacktraceRange btRange = this->Target->GetLinkImplementationBacktraces();
- cmBacktraceRange::const_iterator btIt = btRange.begin();
+ cmBTStringRange entryRange = this->Target->GetLinkImplementationEntries();
// Collect libraries directly linked in this configuration.
- for (cmStringRange::const_iterator le = entryRange.begin(),
- end = entryRange.end();
- le != end; ++le, ++btIt) {
+ for (auto const& entry : entryRange) {
std::vector<std::string> llibs;
// Keep this logic in sync with ExpandLinkItems.
cmGeneratorExpressionDAGChecker dagChecker(this, "LINK_LIBRARIES", nullptr,
nullptr);
- cmGeneratorExpression ge(*btIt);
- std::unique_ptr<cmCompiledGeneratorExpression> const cge = ge.Parse(*le);
+ cmGeneratorExpression ge(entry.Backtrace);
+ std::unique_ptr<cmCompiledGeneratorExpression> const cge =
+ ge.Parse(entry.Value);
cge->SetEvaluateForBuildsystem(true);
std::string const& evaluated =
cge->Evaluate(this->LocalGenerator, config, head, &dagChecker, nullptr,
this->LinkerLanguage);
- bool const fromGenex = evaluated != *le;
+ bool const fromGenex = evaluated != entry.Value;
cmExpandList(evaluated, llibs);
if (cge->GetHadHeadSensitiveCondition()) {
impl.HadHeadSensitiveCondition = true;
@@ -7686,7 +7672,8 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
}
// The entry is meant for this configuration.
- cmLinkItem item = this->ResolveLinkItem(name, *btIt, lg);
+ cmLinkItem item =
+ this->ResolveLinkItem(BT<std::string>(name, entry.Backtrace), lg);
if (!item.Target) {
// Report explicitly linked object files separately.
std::string const& maybeObj = item.AsStr();
@@ -7728,7 +7715,7 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
}
// Support OLD behavior for CMP0003.
impl.WrongConfigLibraries.push_back(
- this->ResolveLinkItem(name, cmListFileBacktrace()));
+ this->ResolveLinkItem(BT<std::string>(name)));
}
}
}
@@ -7754,16 +7741,16 @@ cmGeneratorTarget::TargetOrString cmGeneratorTarget::ResolveTargetReference(
}
cmLinkItem cmGeneratorTarget::ResolveLinkItem(
- std::string const& name, cmListFileBacktrace const& bt) const
+ BT<std::string> const& name) const
{
- return this->ResolveLinkItem(name, bt, this->LocalGenerator);
+ return this->ResolveLinkItem(name, this->LocalGenerator);
}
-cmLinkItem cmGeneratorTarget::ResolveLinkItem(std::string const& name,
- cmListFileBacktrace const& bt,
+cmLinkItem cmGeneratorTarget::ResolveLinkItem(BT<std::string> const& name,
cmLocalGenerator const* lg) const
{
- TargetOrString resolved = this->ResolveTargetReference(name, lg);
+ auto bt = name.Backtrace;
+ TargetOrString resolved = this->ResolveTargetReference(name.Value, lg);
if (!resolved.Target) {
return cmLinkItem(resolved.String, false, bt);
diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h
index bd4e08f..0076085 100644
--- a/Source/cmGeneratorTarget.h
+++ b/Source/cmGeneratorTarget.h
@@ -409,10 +409,8 @@ public:
TargetOrString ResolveTargetReference(std::string const& name,
cmLocalGenerator const* lg) const;
- cmLinkItem ResolveLinkItem(std::string const& name,
- cmListFileBacktrace const& bt) const;
- cmLinkItem ResolveLinkItem(std::string const& name,
- cmListFileBacktrace const& bt,
+ cmLinkItem ResolveLinkItem(BT<std::string> const& name) const;
+ cmLinkItem ResolveLinkItem(BT<std::string> const& name,
cmLocalGenerator const* lg) const;
// Compute the set of languages compiled by the target. This is
@@ -837,7 +835,7 @@ public:
std::string GetFortranModuleDirectory(std::string const& working_dir) const;
bool IsFortranBuildingInstrinsicModules() const;
- const std::string& GetSourcesProperty() const;
+ cmProp GetSourcesProperty() const;
void AddISPCGeneratedHeader(std::string const& header,
std::string const& config);
@@ -905,8 +903,7 @@ private:
void ComputeVersionedName(std::string& vName, std::string const& prefix,
std::string const& base, std::string const& suffix,
- std::string const& name,
- const char* version) const;
+ std::string const& name, cmProp version) const;
struct CompatibleInterfacesBase
{
diff --git a/Source/cmGetDirectoryPropertyCommand.cxx b/Source/cmGetDirectoryPropertyCommand.cxx
index 7fbd479..d98f95c 100644
--- a/Source/cmGetDirectoryPropertyCommand.cxx
+++ b/Source/cmGetDirectoryPropertyCommand.cxx
@@ -13,6 +13,8 @@
namespace {
void StoreResult(cmMakefile& makefile, std::string const& variable,
const char* prop);
+void StoreResult(cmMakefile& makefile, std::string const& variable,
+ cmProp prop);
}
// cmGetDirectoryPropertyCommand
@@ -76,7 +78,6 @@ bool cmGetDirectoryPropertyCommand(std::vector<std::string> const& args,
return false;
}
- const char* prop = nullptr;
if (*i == "DEFINITIONS") {
switch (status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0059)) {
case cmPolicies::WARN:
@@ -94,8 +95,7 @@ bool cmGetDirectoryPropertyCommand(std::vector<std::string> const& args,
break;
}
}
- prop = cmToCStr(dir->GetProperty(*i));
- StoreResult(status.GetMakefile(), variable, prop);
+ StoreResult(status.GetMakefile(), variable, dir->GetProperty(*i));
return true;
}
@@ -105,4 +105,9 @@ void StoreResult(cmMakefile& makefile, std::string const& variable,
{
makefile.AddDefinition(variable, prop ? prop : "");
}
+void StoreResult(cmMakefile& makefile, std::string const& variable,
+ cmProp prop)
+{
+ makefile.AddDefinition(variable, prop);
+}
}
diff --git a/Source/cmGetPropertyCommand.cxx b/Source/cmGetPropertyCommand.cxx
index cb657f9..4b380c0 100644
--- a/Source/cmGetPropertyCommand.cxx
+++ b/Source/cmGetPropertyCommand.cxx
@@ -268,6 +268,11 @@ bool StoreResult(OutType infoType, cmMakefile& makefile,
}
return true;
}
+bool StoreResult(OutType infoType, cmMakefile& makefile,
+ const std::string& variable, cmProp value)
+{
+ return StoreResult(infoType, makefile, variable, value.GetCStr());
+}
bool HandleGlobalMode(cmExecutionStatus& status, const std::string& name,
OutType infoType, const std::string& variable,
@@ -280,9 +285,8 @@ bool HandleGlobalMode(cmExecutionStatus& status, const std::string& name,
// Get the property.
cmake* cm = status.GetMakefile().GetCMakeInstance();
- return StoreResult(
- infoType, status.GetMakefile(), variable,
- cmToCStr(cm->GetState()->GetGlobalProperty(propertyName)));
+ return StoreResult(infoType, status.GetMakefile(), variable,
+ cm->GetState()->GetGlobalProperty(propertyName));
}
bool HandleDirectoryMode(cmExecutionStatus& status, const std::string& name,
@@ -329,7 +333,7 @@ bool HandleDirectoryMode(cmExecutionStatus& status, const std::string& name,
// Get the property.
return StoreResult(infoType, status.GetMakefile(), variable,
- cmToCStr(mf->GetProperty(propertyName)));
+ mf->GetProperty(propertyName));
}
bool HandleTargetMode(cmExecutionStatus& status, const std::string& name,
@@ -365,8 +369,7 @@ bool HandleTargetMode(cmExecutionStatus& status, const std::string& name,
if (!prop) {
prop = target->GetProperty(propertyName);
}
- return StoreResult(infoType, status.GetMakefile(), variable,
- cmToCStr(prop));
+ return StoreResult(infoType, status.GetMakefile(), variable, prop);
}
status.SetError(cmStrCat("could not find TARGET ", name,
". Perhaps it has not yet been created."));
@@ -391,7 +394,7 @@ bool HandleSourceMode(cmExecutionStatus& status, const std::string& name,
if (cmSourceFile* sf =
directory_makefile.GetOrCreateSource(source_file_absolute_path)) {
return StoreResult(infoType, status.GetMakefile(), variable,
- cmToCStr(sf->GetPropertyForUser(propertyName)));
+ sf->GetPropertyForUser(propertyName));
}
status.SetError(
cmStrCat("given SOURCE name that could not be found or created: ",
@@ -428,9 +431,8 @@ bool HandleVariableMode(cmExecutionStatus& status, const std::string& name,
return false;
}
- return StoreResult(
- infoType, status.GetMakefile(), variable,
- cmToCStr(status.GetMakefile().GetDefinition(propertyName)));
+ return StoreResult(infoType, status.GetMakefile(), variable,
+ status.GetMakefile().GetDefinition(propertyName));
}
bool HandleCacheMode(cmExecutionStatus& status, const std::string& name,
@@ -447,7 +449,7 @@ bool HandleCacheMode(cmExecutionStatus& status, const std::string& name,
value = status.GetMakefile().GetState()->GetCacheEntryProperty(
name, propertyName);
}
- StoreResult(infoType, status.GetMakefile(), variable, cmToCStr(value));
+ StoreResult(infoType, status.GetMakefile(), variable, value);
return true;
}
diff --git a/Source/cmGetTestPropertyCommand.cxx b/Source/cmGetTestPropertyCommand.cxx
index cf8c1d5..077353e 100644
--- a/Source/cmGetTestPropertyCommand.cxx
+++ b/Source/cmGetTestPropertyCommand.cxx
@@ -4,6 +4,7 @@
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
+#include "cmProperty.h"
#include "cmTest.h"
bool cmGetTestPropertyCommand(std::vector<std::string> const& args,
@@ -19,12 +20,12 @@ bool cmGetTestPropertyCommand(std::vector<std::string> const& args,
cmMakefile& mf = status.GetMakefile();
cmTest* test = mf.GetTest(testName);
if (test) {
- const char* prop = nullptr;
+ cmProp prop;
if (!args[1].empty()) {
prop = test->GetProperty(args[1]);
}
if (prop) {
- mf.AddDefinition(var, prop);
+ mf.AddDefinition(var, prop->c_str());
return true;
}
}
diff --git a/Source/cmGlobalCommonGenerator.cxx b/Source/cmGlobalCommonGenerator.cxx
index a8e0f23..24c8944 100644
--- a/Source/cmGlobalCommonGenerator.cxx
+++ b/Source/cmGlobalCommonGenerator.cxx
@@ -117,7 +117,7 @@ std::string cmGlobalCommonGenerator::GetEditCacheCommand() const
editCacheCommand = cmSystemTools::GetCMakeGUICommand();
}
if (!editCacheCommand.empty()) {
- cm->AddCacheEntry("CMAKE_EDIT_COMMAND", editCacheCommand.c_str(),
+ cm->AddCacheEntry("CMAKE_EDIT_COMMAND", editCacheCommand,
"Path to cache edit program executable.",
cmStateEnums::INTERNAL);
}
diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx
index 15a7304..fd1a197 100644
--- a/Source/cmGlobalGenerator.cxx
+++ b/Source/cmGlobalGenerator.cxx
@@ -242,7 +242,7 @@ void cmGlobalGenerator::ResolveLanguageCompiler(const std::string& lang,
std::vector<std::string> cnameArgVec;
if (cname && !cname->empty()) {
cmExpandList(*cname, cnameArgVec);
- cname = &cnameArgVec.front();
+ cname = cmProp(cnameArgVec.front());
}
std::string changeVars;
@@ -1179,10 +1179,10 @@ void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l,
}
}
-const char* cmGlobalGenerator::GetGlobalSetting(std::string const& name) const
+cmProp cmGlobalGenerator::GetGlobalSetting(std::string const& name) const
{
assert(!this->Makefiles.empty());
- return cmToCStr(this->Makefiles[0]->GetDefinition(name));
+ return this->Makefiles[0]->GetDefinition(name);
}
bool cmGlobalGenerator::GlobalSettingIsOn(std::string const& name) const
@@ -1195,7 +1195,7 @@ std::string cmGlobalGenerator::GetSafeGlobalSetting(
std::string const& name) const
{
assert(!this->Makefiles.empty());
- return this->Makefiles[0]->GetSafeDefinition(name);
+ return this->Makefiles[0]->GetDefinition(name);
}
bool cmGlobalGenerator::IgnoreFile(const char* ext) const
@@ -1718,10 +1718,8 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo()
// Construct per-target generator information.
for (const auto& mf : this->Makefiles) {
- const cmStringRange noconfig_compile_definitions =
+ const cmBTStringRange noconfig_compile_definitions =
mf->GetCompileDefinitionsEntries();
- const cmBacktraceRange noconfig_compile_definitions_bts =
- mf->GetCompileDefinitionsBacktraces();
for (auto& target : mf->GetTargets()) {
cmTarget* t = &target.second;
@@ -1735,12 +1733,8 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo()
continue;
}
- {
- auto btIt = noconfig_compile_definitions_bts.begin();
- auto it = noconfig_compile_definitions.begin();
- for (; it != noconfig_compile_definitions.end(); ++it, ++btIt) {
- t->InsertCompileDefinition(*it, *btIt);
- }
+ for (auto const& def : noconfig_compile_definitions) {
+ t->InsertCompileDefinition(def);
}
cmPolicies::PolicyStatus polSt =
@@ -2191,9 +2185,8 @@ void cmGlobalGenerator::EnableLanguagesFromGenerator(cmGlobalGenerator* gen,
this->TryCompileOuterMakefile = mf;
cmProp make =
gen->GetCMakeInstance()->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
- this->GetCMakeInstance()->AddCacheEntry("CMAKE_MAKE_PROGRAM", cmToCStr(make),
- "make program",
- cmStateEnums::FILEPATH);
+ this->GetCMakeInstance()->AddCacheEntry(
+ "CMAKE_MAKE_PROGRAM", make, "make program", cmStateEnums::FILEPATH);
// copy the enabled languages
this->GetCMakeInstance()->GetState()->SetEnabledLanguages(
gen->GetCMakeInstance()->GetState()->GetEnabledLanguages());
@@ -2749,7 +2742,7 @@ void cmGlobalGenerator::AddGlobalTarget_Install(
singleLine.push_back(cfgArg);
cfgArg = "-DEFFECTIVE_PLATFORM_NAME=$(EFFECTIVE_PLATFORM_NAME)";
} else {
- cfgArg += cmToCStr(mf->GetDefinition("CMAKE_CFG_INTDIR"));
+ cfgArg += *mf->GetDefinition("CMAKE_CFG_INTDIR");
}
singleLine.push_back(cfgArg);
}
diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h
index f0b59bf..34646d9 100644
--- a/Source/cmGlobalGenerator.h
+++ b/Source/cmGlobalGenerator.h
@@ -23,6 +23,7 @@
#include "cmCustomCommandLines.h"
#include "cmDuration.h"
#include "cmExportSet.h"
+#include "cmProperty.h"
#include "cmStateSnapshot.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
@@ -308,7 +309,7 @@ public:
cmExportSetMap& GetExportSets() { return this->ExportSets; }
- const char* GetGlobalSetting(std::string const& name) const;
+ cmProp GetGlobalSetting(std::string const& name) const;
bool GlobalSettingIsOn(std::string const& name) const;
std::string GetSafeGlobalSetting(std::string const& name) const;
diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx
index 7cf3e93..b81f82e 100644
--- a/Source/cmGlobalGhsMultiGenerator.cxx
+++ b/Source/cmGlobalGhsMultiGenerator.cxx
@@ -186,8 +186,7 @@ void cmGlobalGhsMultiGenerator::EnableLanguage(
mf->AddDefinition("GHSMULTI", "1"); // identifier for user CMake files
- const char* tgtPlatform =
- cmToCStrSafe(mf->GetDefinition("GHS_TARGET_PLATFORM"));
+ const char* tgtPlatform = mf->GetDefinition("GHS_TARGET_PLATFORM")->c_str();
if (!tgtPlatform) {
cmSystemTools::Message("Green Hills MULTI: GHS_TARGET_PLATFORM not "
"specified; defaulting to \"integrity\"");
diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx
index 47a931d..c6f82f9 100644
--- a/Source/cmGlobalNinjaGenerator.cxx
+++ b/Source/cmGlobalNinjaGenerator.cxx
@@ -945,6 +945,8 @@ void cmGlobalNinjaGenerator::EnableLanguage(
(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "GNU") ||
(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "Clang") ||
(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "Clang") ||
+ (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "ARMClang") ||
+ (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "ARMClang") ||
(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "QCC") ||
(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "QCC")))) {
this->UsingGCCOnWindows = true;
diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx
index 0083c40..21ea7e6 100644
--- a/Source/cmGlobalVisualStudio71Generator.cxx
+++ b/Source/cmGlobalVisualStudio71Generator.cxx
@@ -157,11 +157,11 @@ void cmGlobalVisualStudio71Generator::WriteProjectDepends(
// executables to the libraries it uses are also done here
void cmGlobalVisualStudio71Generator::WriteExternalProject(
std::ostream& fout, const std::string& name, const std::string& location,
- const char* typeGuid,
- const std::set<BT<std::pair<std::string, bool>>>& depends)
+ cmProp typeGuid, const std::set<BT<std::pair<std::string, bool>>>& depends)
{
fout << "Project(\"{"
- << (typeGuid ? typeGuid : this->ExternalProjectType(location))
+ << (typeGuid ? typeGuid
+ : std::string(this->ExternalProjectType(location)))
<< "}\") = \"" << name << "\", \""
<< this->ConvertToSolutionPath(location) << "\", \"{"
<< this->GetGUID(name) << "}\"\n";
diff --git a/Source/cmGlobalVisualStudio71Generator.h b/Source/cmGlobalVisualStudio71Generator.h
index 7d38199..30ebf08 100644
--- a/Source/cmGlobalVisualStudio71Generator.h
+++ b/Source/cmGlobalVisualStudio71Generator.h
@@ -33,7 +33,7 @@ protected:
const std::string& platformMapping = "") override;
void WriteExternalProject(
std::ostream& fout, const std::string& name, const std::string& path,
- const char* typeGuid,
+ cmProp typeGuid,
const std::set<BT<std::pair<std::string, bool>>>& depends) override;
// Folders are not supported by VS 7.1.
diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx
index 34dba1e..2a142ae 100644
--- a/Source/cmGlobalVisualStudio7Generator.cxx
+++ b/Source/cmGlobalVisualStudio7Generator.cxx
@@ -391,10 +391,9 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
std::string project = target->GetName();
std::string location = *expath;
- this->WriteExternalProject(
- fout, project, location,
- cmToCStr(target->GetProperty("VS_PROJECT_TYPE")),
- target->GetUtilities());
+ this->WriteExternalProject(fout, project, location,
+ target->GetProperty("VS_PROJECT_TYPE"),
+ target->GetUtilities());
written = true;
} else {
cmProp vcprojName = target->GetProperty("GENERATOR_FILE_NAME");
diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h
index 148762e..1e34792 100644
--- a/Source/cmGlobalVisualStudio7Generator.h
+++ b/Source/cmGlobalVisualStudio7Generator.h
@@ -6,6 +6,7 @@
#include "cmGlobalGeneratorFactory.h"
#include "cmGlobalVisualStudioGenerator.h"
+#include "cmProperty.h"
class cmTarget;
struct cmIDEFlagTable;
@@ -142,7 +143,7 @@ protected:
virtual void WriteExternalProject(
std::ostream& fout, const std::string& name, const std::string& path,
- const char* typeGuid,
+ cmProp typeGuid,
const std::set<BT<std::pair<std::string, bool>>>& dependencies) = 0;
std::string ConvertToSolutionPath(const std::string& path);
diff --git a/Source/cmGlobalVisualStudioVersionedGenerator.cxx b/Source/cmGlobalVisualStudioVersionedGenerator.cxx
index 79c06d6..3ecf32e 100644
--- a/Source/cmGlobalVisualStudioVersionedGenerator.cxx
+++ b/Source/cmGlobalVisualStudioVersionedGenerator.cxx
@@ -467,9 +467,9 @@ bool cmGlobalVisualStudioVersionedGenerator::SetGeneratorInstance(
// Save the selected instance persistently.
std::string genInstance = mf->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE");
if (vsInstance != genInstance) {
- this->CMakeInstance->AddCacheEntry(
- "CMAKE_GENERATOR_INSTANCE", vsInstance.c_str(),
- "Generator instance identifier.", cmStateEnums::INTERNAL);
+ this->CMakeInstance->AddCacheEntry("CMAKE_GENERATOR_INSTANCE", vsInstance,
+ "Generator instance identifier.",
+ cmStateEnums::INTERNAL);
}
return true;
@@ -618,6 +618,9 @@ cmGlobalVisualStudioVersionedGenerator::FindAuxToolset(
if (version == "14.29.16.10" && vcToolsetVersion == "14.29.30037") {
return AuxToolset::Default;
}
+ if (version == "14.29.16.11" && vcToolsetVersion == "14.29.30133") {
+ return AuxToolset::Default;
+ }
// The first two components of the default toolset version typically
// match the name used by later VS versions for the SxS props files.
diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx
index 3994816..fa76b01 100644
--- a/Source/cmGlobalXCodeGenerator.cxx
+++ b/Source/cmGlobalXCodeGenerator.cxx
@@ -1667,7 +1667,7 @@ void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
fout << "\n";
}
if (cmSourceFile* sf = mf->GetOrCreateSource(fname)) {
- sf->SetProperty("LANGUAGE", llang.c_str());
+ sf->SetProperty("LANGUAGE", llang);
gtgt->AddSource(fname);
}
}
@@ -3241,9 +3241,8 @@ std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
return *storedGUID;
}
- this->CMakeInstance->AddCacheEntry(guidStoreName, id.c_str(),
- "Stored Xcode object GUID",
- cmStateEnums::INTERNAL);
+ this->CMakeInstance->AddCacheEntry(
+ guidStoreName, id, "Stored Xcode object GUID", cmStateEnums::INTERNAL);
return id;
}
diff --git a/Source/cmIncludeExternalMSProjectCommand.cxx b/Source/cmIncludeExternalMSProjectCommand.cxx
index 5b532ce..c8b4a39 100644
--- a/Source/cmIncludeExternalMSProjectCommand.cxx
+++ b/Source/cmIncludeExternalMSProjectCommand.cxx
@@ -77,9 +77,8 @@ bool cmIncludeExternalMSProjectCommand(std::vector<std::string> const& args,
if (!customGuid.empty()) {
std::string guidVariable = utility_name + "_GUID_CMAKE";
- mf.GetCMakeInstance()->AddCacheEntry(guidVariable, customGuid.c_str(),
- "Stored GUID",
- cmStateEnums::INTERNAL);
+ mf.GetCMakeInstance()->AddCacheEntry(
+ guidVariable, customGuid, "Stored GUID", cmStateEnums::INTERNAL);
}
// Create a target instance for this utility.
diff --git a/Source/cmIncludeGuardCommand.cxx b/Source/cmIncludeGuardCommand.cxx
index aefd098..d48c823 100644
--- a/Source/cmIncludeGuardCommand.cxx
+++ b/Source/cmIncludeGuardCommand.cxx
@@ -4,6 +4,7 @@
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
+#include "cmProperty.h"
#include "cmStateDirectory.h"
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
diff --git a/Source/cmIncludeRegularExpressionCommand.cxx b/Source/cmIncludeRegularExpressionCommand.cxx
index 655ebd6..cdcc7df 100644
--- a/Source/cmIncludeRegularExpressionCommand.cxx
+++ b/Source/cmIncludeRegularExpressionCommand.cxx
@@ -14,7 +14,7 @@ bool cmIncludeRegularExpressionCommand(std::vector<std::string> const& args,
}
cmMakefile& mf = status.GetMakefile();
- mf.SetIncludeRegularExpression(args[0].c_str());
+ mf.SetIncludeRegularExpression(args[0]);
if (args.size() > 1) {
mf.SetComplainRegularExpression(args[1]);
diff --git a/Source/cmInstallMode.h b/Source/cmInstallMode.h
new file mode 100644
index 0000000..5343d34
--- /dev/null
+++ b/Source/cmInstallMode.h
@@ -0,0 +1,17 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#pragma once
+
+/**
+ * Enumerate types known to file(INSTALL).
+ */
+enum class cmInstallMode
+{
+ COPY,
+ ABS_SYMLINK,
+ ABS_SYMLINK_OR_COPY,
+ REL_SYMLINK,
+ REL_SYMLINK_OR_COPY,
+ SYMLINK,
+ SYMLINK_OR_COPY
+};
diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx
index 016653b..8be015e 100644
--- a/Source/cmLocalGenerator.cxx
+++ b/Source/cmLocalGenerator.cxx
@@ -425,27 +425,25 @@ void cmLocalGenerator::ProcessEvaluationFiles(
void cmLocalGenerator::GenerateInstallRules()
{
// Compute the install prefix.
- const char* prefix =
- cmToCStr(this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX"));
+ cmProp installPrefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
+ std::string prefix = installPrefix;
#if defined(_WIN32) && !defined(__CYGWIN__)
- std::string prefix_win32;
- if (!prefix) {
- if (!cmSystemTools::GetEnv("SystemDrive", prefix_win32)) {
- prefix_win32 = "C:";
+ if (!installPrefix) {
+ if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
+ prefix = "C:";
}
cmProp project_name = this->Makefile->GetDefinition("PROJECT_NAME");
if (cmNonempty(project_name)) {
- prefix_win32 += "/Program Files/";
- prefix_win32 += *project_name;
+ prefix += "/Program Files/";
+ prefix += *project_name;
} else {
- prefix_win32 += "/InstalledCMakeProject";
+ prefix += "/InstalledCMakeProject";
}
- prefix = prefix_win32.c_str();
}
#elif defined(__HAIKU__)
char dir[B_PATH_NAME_LENGTH];
- if (!prefix) {
+ if (!installPrefix) {
if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
B_OK) {
prefix = dir;
@@ -454,13 +452,13 @@ void cmLocalGenerator::GenerateInstallRules()
}
}
#else
- if (!prefix) {
+ if (!installPrefix) {
prefix = "/usr/local";
}
#endif
if (cmProp stagingPrefix =
this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
- prefix = stagingPrefix->c_str();
+ prefix = *stagingPrefix;
}
// Compute the set of configurations.
@@ -1869,17 +1867,17 @@ std::string cmLocalGenerator::GetLinkLibsCMP0065(
}
bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
- const std::vector<std::string>& archs, const char* sysroot)
+ const std::vector<std::string>& archs, cmProp sysroot)
{
if (!sysroot) {
return false;
}
return std::all_of(archs.begin(), archs.end(),
- [this, &sysroot](std::string const& arch) -> bool {
+ [this, sysroot](std::string const& arch) -> bool {
std::string const& archSysroot =
this->AppleArchSysroots[arch];
- return cmIsOff(archSysroot) || archSysroot == sysroot;
+ return cmIsOff(archSysroot) || sysroot == archSysroot;
});
}
@@ -1912,7 +1910,7 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
cmProp sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
if (cmNonempty(sysrootFlag)) {
if (!this->AppleArchSysroots.empty() &&
- !this->AllAppleArchSysrootsAreTheSame(archs, cmToCStr(sysroot))) {
+ !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
for (std::string const& arch : archs) {
std::string const& archSysroot = this->AppleArchSysroots[arch];
if (cmIsOff(archSysroot)) {
@@ -2570,10 +2568,10 @@ void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
continue;
}
- const std::string pchExtension =
- this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
+ cmProp pchExtension =
+ this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
- if (pchExtension.empty()) {
+ if (pchExtension.IsEmpty()) {
continue;
}
@@ -2664,7 +2662,7 @@ void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
}
}
} else {
- pch_sf->SetProperty("PCH_EXTENSION", pchExtension.c_str());
+ pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
}
// Add pchHeader to source files, which will
@@ -2805,7 +2803,7 @@ inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
std::string const& filename)
{
target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
- sf->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
+ sf->SetProperty("UNITY_SOURCE_FILE", filename);
}
}
@@ -3003,7 +3001,7 @@ void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
auto* unity = this->GetMakefile()->GetOrCreateSource(file);
target->AddSource(file, true);
unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
- unity->SetProperty("UNITY_SOURCE_FILE", file.c_str());
+ unity->SetProperty("UNITY_SOURCE_FILE", file);
}
}
}
diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h
index 1e09b23..678ef8c 100644
--- a/Source/cmLocalGenerator.h
+++ b/Source/cmLocalGenerator.h
@@ -651,7 +651,7 @@ private:
void ComputeObjectMaxPath();
bool AllAppleArchSysrootsAreTheSame(const std::vector<std::string>& archs,
- const char* sysroot);
+ cmProp sysroot);
void CopyPchCompilePdb(const std::string& config, cmGeneratorTarget* target,
const std::string& ReuseFrom,
diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx
index 151470b..7b5fed6 100644
--- a/Source/cmLocalVisualStudio7Generator.cxx
+++ b/Source/cmLocalVisualStudio7Generator.cxx
@@ -566,7 +566,7 @@ public:
} else {
this->Stream << this->LG->EscapeForXML("\n");
}
- std::string script = this->LG->ConstructScript(ccg);
+ std::string script = this->LG->ConstructScript(ccg, unmanaged);
this->Stream << this->LG->EscapeForXML(script);
}
@@ -1779,7 +1779,7 @@ void cmLocalVisualStudio7Generator::WriteCustomRule(
}
std::string comment = this->ConstructComment(ccg);
- std::string script = this->ConstructScript(ccg);
+ std::string script = this->ConstructScript(ccg, unmanaged);
if (this->FortranProject) {
cmSystemTools::ReplaceString(script, "$(Configuration)", config);
}
@@ -2142,7 +2142,7 @@ void cmLocalVisualStudio7Generator::ReadAndStoreExternalGUID(
std::string guidStoreName = cmStrCat(name, "_GUID_CMAKE");
// save the GUID in the cache
this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry(
- guidStoreName, parser.GUID.c_str(), "Stored GUID", cmStateEnums::INTERNAL);
+ guidStoreName, parser.GUID, "Stored GUID", cmStateEnums::INTERNAL);
}
std::string cmLocalVisualStudio7Generator::GetTargetDirectory(
diff --git a/Source/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx
index 46f9d31..acddfe1 100644
--- a/Source/cmLocalVisualStudioGenerator.cxx
+++ b/Source/cmLocalVisualStudioGenerator.cxx
@@ -124,7 +124,8 @@ const char* cmLocalVisualStudioGenerator::GetReportErrorLabel() const
}
std::string cmLocalVisualStudioGenerator::ConstructScript(
- cmCustomCommandGenerator const& ccg, const std::string& newline_text)
+ cmCustomCommandGenerator const& ccg, IsManaged isManaged,
+ const std::string& newline_text)
{
bool useLocal = this->CustomCommandUseLocal();
std::string workingDirectory = ccg.GetWorkingDirectory();
@@ -236,6 +237,14 @@ std::string cmLocalVisualStudioGenerator::ConstructScript(
script += newline;
script += "if %errorlevel% neq 0 goto ";
script += this->GetReportErrorLabel();
+ if (isManaged == managed) {
+ // These aren't generated by default for C# projects.
+ script += newline;
+ script += this->GetReportErrorLabel();
+ script += newline;
+ script += "exit /b 0";
+ script += newline;
+ }
}
return script;
diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h
index 91fb6b0..0e7f63f 100644
--- a/Source/cmLocalVisualStudioGenerator.h
+++ b/Source/cmLocalVisualStudioGenerator.h
@@ -31,7 +31,13 @@ public:
virtual ~cmLocalVisualStudioGenerator();
/** Construct a script from the given list of command lines. */
+ enum IsManaged
+ {
+ unmanaged,
+ managed
+ };
std::string ConstructScript(cmCustomCommandGenerator const& ccg,
+ IsManaged isManaged,
const std::string& newline = "\n");
/** Label to which to jump in a batch file after a failed step in a
diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx
index 6d477a7..ef31d76 100644
--- a/Source/cmMakefile.cxx
+++ b/Source/cmMakefile.cxx
@@ -212,59 +212,31 @@ void cmMakefile::MaybeWarnCMP0074(std::string const& pkg)
}
}
-cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const
+cmBTStringRange cmMakefile::GetIncludeDirectoriesEntries() const
{
return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
}
-cmBacktraceRange cmMakefile::GetIncludeDirectoriesBacktraces() const
-{
- return this->StateSnapshot.GetDirectory()
- .GetIncludeDirectoriesEntryBacktraces();
-}
-
-cmStringRange cmMakefile::GetCompileOptionsEntries() const
+cmBTStringRange cmMakefile::GetCompileOptionsEntries() const
{
return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
}
-cmBacktraceRange cmMakefile::GetCompileOptionsBacktraces() const
-{
- return this->StateSnapshot.GetDirectory().GetCompileOptionsEntryBacktraces();
-}
-
-cmStringRange cmMakefile::GetCompileDefinitionsEntries() const
+cmBTStringRange cmMakefile::GetCompileDefinitionsEntries() const
{
return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
}
-cmBacktraceRange cmMakefile::GetCompileDefinitionsBacktraces() const
-{
- return this->StateSnapshot.GetDirectory()
- .GetCompileDefinitionsEntryBacktraces();
-}
-
-cmStringRange cmMakefile::GetLinkOptionsEntries() const
+cmBTStringRange cmMakefile::GetLinkOptionsEntries() const
{
return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
}
-cmBacktraceRange cmMakefile::GetLinkOptionsBacktraces() const
-{
- return this->StateSnapshot.GetDirectory().GetLinkOptionsEntryBacktraces();
-}
-
-cmStringRange cmMakefile::GetLinkDirectoriesEntries() const
+cmBTStringRange cmMakefile::GetLinkDirectoriesEntries() const
{
return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
}
-cmBacktraceRange cmMakefile::GetLinkDirectoriesBacktraces() const
-{
- return this->StateSnapshot.GetDirectory()
- .GetLinkDirectoriesEntryBacktraces();
-}
-
cmListFileBacktrace cmMakefile::GetBacktrace() const
{
return this->Backtrace;
@@ -1386,10 +1358,10 @@ void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
{
if (before) {
this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
- directory, this->Backtrace);
+ BT<std::string>(directory, this->Backtrace));
} else {
this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
- directory, this->Backtrace);
+ BT<std::string>(directory, this->Backtrace));
}
}
@@ -1444,7 +1416,7 @@ bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
std::string ndefs = cmJoin(cmMakeRange(defBegin, defEnd), ";");
// Store the new list.
- this->SetProperty("COMPILE_DEFINITIONS", ndefs.c_str());
+ this->SetProperty("COMPILE_DEFINITIONS", ndefs);
}
} else {
// Append the definition to the directory property.
@@ -1465,30 +1437,29 @@ void cmMakefile::InitializeFromParent(cmMakefile* parent)
// Include transform property. There is no per-config version.
{
const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
- this->SetProperty(prop, cmToCStr(parent->GetProperty(prop)));
+ this->SetProperty(prop, parent->GetProperty(prop));
}
// compile definitions property and per-config versions
cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
this->SetProperty("COMPILE_DEFINITIONS",
- cmToCStr(parent->GetProperty("COMPILE_DEFINITIONS")));
+ parent->GetProperty("COMPILE_DEFINITIONS"));
std::vector<std::string> configs =
this->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
for (std::string const& config : configs) {
std::string defPropName =
cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
cmProp prop = parent->GetProperty(defPropName);
- this->SetProperty(defPropName, cmToCStr(prop));
+ this->SetProperty(defPropName, prop);
}
}
// labels
- this->SetProperty("LABELS", cmToCStr(parent->GetProperty("LABELS")));
+ this->SetProperty("LABELS", parent->GetProperty("LABELS"));
// link libraries
- this->SetProperty("LINK_LIBRARIES",
- cmToCStr(parent->GetProperty("LINK_LIBRARIES")));
+ this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
// the initial project name
this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
@@ -1877,16 +1848,16 @@ void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
std::string entryString = cmJoin(incs, ";");
if (before) {
this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
- entryString, this->Backtrace);
+ BT<std::string>(entryString, this->Backtrace));
} else {
this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
- entryString, this->Backtrace);
+ BT<std::string>(entryString, this->Backtrace));
}
// Property on each target:
for (auto& target : this->Targets) {
cmTarget& t = target.second;
- t.InsertInclude(entryString, this->Backtrace, before);
+ t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
}
}
@@ -1956,7 +1927,7 @@ void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
nvalue += files[cc];
}
- this->GetCMakeInstance()->AddCacheEntry(name, nvalue.c_str(), doc, type);
+ this->GetCMakeInstance()->AddCacheEntry(name, nvalue, doc, type);
nvalue = *this->GetState()->GetInitializedCacheValue(name);
value = nvalue.c_str();
}
@@ -2308,7 +2279,7 @@ void cmMakefile::ExpandVariablesCMP0019()
<< " " << dirs << "\n";
/* clang-format on */
}
- this->SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
+ this->SetProperty("INCLUDE_DIRECTORIES", dirs);
}
// Also for each target's INCLUDE_DIRECTORIES property:
@@ -2579,12 +2550,7 @@ cmProp cmMakefile::GetDefinition(const std::string& name) const
const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
{
- static std::string const empty;
- cmProp def = this->GetDefinition(name);
- if (!def) {
- return empty;
- }
- return *def;
+ return this->GetDefinition(name);
}
bool cmMakefile::GetDefExpandList(const std::string& name,
@@ -2967,7 +2933,7 @@ MessageType cmMakefile::ExpandVariablesInStringNew(
break;
case ENVIRONMENT:
if (cmSystemTools::GetEnv(lookup, svalue)) {
- value = &svalue;
+ value = cmProp(svalue);
}
break;
case CACHE:
@@ -3595,13 +3561,13 @@ int cmMakefile::TryCompile(const std::string& srcdir,
// Tell the single-configuration generator which one to use.
// Add this before the user-provided CMake arguments in case
// one of the arguments is -DCMAKE_BUILD_TYPE=...
- cm.AddCacheEntry("CMAKE_BUILD_TYPE", config->c_str(),
- "Build configuration", cmStateEnums::STRING);
+ cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
+ cmStateEnums::STRING);
}
}
cmProp recursionDepth = this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
if (recursionDepth) {
- cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth->c_str(),
+ cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
"Maximum recursion depth", cmStateEnums::STRING);
}
// if cmake args were provided then pass them in
@@ -3991,6 +3957,10 @@ void cmMakefile::SetProperty(const std::string& prop, const char* value)
{
this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
}
+void cmMakefile::SetProperty(const std::string& prop, cmProp value)
+{
+ this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
+}
void cmMakefile::AppendProperty(const std::string& prop,
const std::string& value, bool asString)
@@ -4012,7 +3982,7 @@ cmProp cmMakefile::GetProperty(const std::string& prop) const
return pair.first;
});
output = cmJoin(keys, ";");
- return &output;
+ return cmProp(output);
}
return this->StateSnapshot.GetDirectory().GetProperty(prop);
diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h
index 5886c86..bdcab3b 100644
--- a/Source/cmMakefile.h
+++ b/Source/cmMakefile.h
@@ -33,7 +33,6 @@
#include "cmSourceFileLocationKind.h"
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
-#include "cmStringAlgorithms.h"
// IWYU does not see that 'std::unordered_map<std::string, cmTarget>'
// will not compile without the complete type.
@@ -399,13 +398,13 @@ public:
* Set a regular expression that include files must match
* in order to be considered as part of the depend information.
*/
- void SetIncludeRegularExpression(const char* regex)
+ void SetIncludeRegularExpression(const std::string& regex)
{
- this->SetProperty("INCLUDE_REGULAR_EXPRESSION", regex);
+ this->SetProperty("INCLUDE_REGULAR_EXPRESSION", regex.c_str());
}
- const char* GetIncludeRegularExpression() const
+ const std::string& GetIncludeRegularExpression() const
{
- return cmToCStr(this->GetProperty("INCLUDE_REGULAR_EXPRESSION"));
+ return this->GetProperty("INCLUDE_REGULAR_EXPRESSION");
}
/**
@@ -769,6 +768,11 @@ public:
//! Set/Get a property of this directory
void SetProperty(const std::string& prop, const char* value);
+ void SetProperty(const std::string& prop, cmProp value);
+ void SetProperty(const std::string& prop, const std::string& value)
+ {
+ this->SetProperty(prop, cmProp(value));
+ }
void AppendProperty(const std::string& prop, const std::string& value,
bool asString = false);
cmProp GetProperty(const std::string& prop) const;
@@ -874,16 +878,11 @@ public:
bool CheckCMP0037(std::string const& targetName,
cmStateEnums::TargetType targetType) const;
- cmStringRange GetIncludeDirectoriesEntries() const;
- cmBacktraceRange GetIncludeDirectoriesBacktraces() const;
- cmStringRange GetCompileOptionsEntries() const;
- cmBacktraceRange GetCompileOptionsBacktraces() const;
- cmStringRange GetCompileDefinitionsEntries() const;
- cmBacktraceRange GetCompileDefinitionsBacktraces() const;
- cmStringRange GetLinkOptionsEntries() const;
- cmBacktraceRange GetLinkOptionsBacktraces() const;
- cmStringRange GetLinkDirectoriesEntries() const;
- cmBacktraceRange GetLinkDirectoriesBacktraces() const;
+ cmBTStringRange GetIncludeDirectoriesEntries() const;
+ cmBTStringRange GetCompileOptionsEntries() const;
+ cmBTStringRange GetCompileDefinitionsEntries() const;
+ cmBTStringRange GetLinkOptionsEntries() const;
+ cmBTStringRange GetLinkDirectoriesEntries() const;
std::set<std::string> const& GetSystemIncludeDirectories() const
{
diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx
index 626453f..70b6d27 100644
--- a/Source/cmMakefileTargetGenerator.cxx
+++ b/Source/cmMakefileTargetGenerator.cxx
@@ -293,8 +293,7 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
this->GetConfigName());
for (cmSourceFile const* sf : externalObjects) {
auto const& objectFileName = sf->GetFullPath();
- if (!cmSystemTools::StringEndsWith(objectFileName,
- cmToCStr(pchExtension))) {
+ if (!cmHasSuffix(objectFileName, pchExtension)) {
this->ExternalObjects.push_back(objectFileName);
}
}
@@ -1000,7 +999,25 @@ void cmMakefileTargetGenerator::WriteObjectRuleFiles(
}
if (cmNonempty(iwyu)) {
run_iwyu += " --iwyu=";
- run_iwyu += this->LocalGenerator->EscapeForShell(*iwyu);
+
+ // Only add --driver-mode if it is not already specified, as adding
+ // it unconditionally might override a user-specified driver-mode
+ if (iwyu.Get()->find("--driver-mode=") == std::string::npos) {
+ cmProp p = this->Makefile->GetDefinition(
+ cmStrCat("CMAKE_", lang, "_INCLUDE_WHAT_YOU_USE_DRIVER_MODE"));
+ std::string driverMode;
+
+ if (cmNonempty(p)) {
+ driverMode = *p;
+ } else {
+ driverMode = lang == "C" ? "gcc" : "g++";
+ }
+
+ run_iwyu += this->LocalGenerator->EscapeForShell(
+ cmStrCat(*iwyu, ";--driver-mode=", driverMode));
+ } else {
+ run_iwyu += this->LocalGenerator->EscapeForShell(*iwyu);
+ }
}
if (cmNonempty(tidy)) {
run_iwyu += " --tidy=";
@@ -1732,7 +1749,7 @@ void cmMakefileTargetGenerator::WriteObjectsVariable(
cmProp pchExtension = this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
for (std::string const& obj : this->Objects) {
- if (cmSystemTools::StringEndsWith(obj, cmToCStr(pchExtension))) {
+ if (cmHasSuffix(obj, pchExtension)) {
continue;
}
*this->BuildFileStream << " " << lineContinue;
@@ -1822,7 +1839,7 @@ void cmMakefileTargetGenerator::WriteObjectsStrings(
objStrings, this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
for (std::string const& obj : this->Objects) {
- if (cmSystemTools::StringEndsWith(obj, cmToCStr(pchExtension))) {
+ if (cmHasSuffix(obj, pchExtension)) {
continue;
}
helper.Feed(obj);
diff --git a/Source/cmMarkAsAdvancedCommand.cxx b/Source/cmMarkAsAdvancedCommand.cxx
index 45043fa..5908f74 100644
--- a/Source/cmMarkAsAdvancedCommand.cxx
+++ b/Source/cmMarkAsAdvancedCommand.cxx
@@ -6,6 +6,7 @@
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmPolicies.h"
+#include "cmProperty.h"
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx
index 609848b..7cc1581 100644
--- a/Source/cmNinjaTargetGenerator.cxx
+++ b/Source/cmNinjaTargetGenerator.cxx
@@ -774,8 +774,11 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
cmProp d = mf->GetDefinition("CMAKE_C_COMPILER");
const std::string cl =
d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
- cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang,
- ' ', vars.Source, " $DEP_FILE $out \"",
+ std::string cmcldepsPath;
+ cmSystemTools::GetShortPath(cmSystemTools::GetCMClDepsCommand(),
+ cmcldepsPath);
+ cldeps = cmStrCat(cmcldepsPath, ' ', lang, ' ', vars.Source,
+ " $DEP_FILE $out \"",
mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
"\" \"", cl, "\" ");
}
@@ -874,8 +877,26 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
compilerLauncher.clear();
}
if (cmNonempty(iwyu)) {
- run_iwyu += cmStrCat(" --iwyu=",
- this->GetLocalGenerator()->EscapeForShell(*iwyu));
+ run_iwyu += " --iwyu=";
+
+ // Only add --driver-mode if it is not already specified, as adding
+ // it unconditionally might override a user-specified driver-mode
+ if (iwyu.Get()->find("--driver-mode=") == std::string::npos) {
+ cmProp p = this->Makefile->GetDefinition(
+ cmStrCat("CMAKE_", lang, "_INCLUDE_WHAT_YOU_USE_DRIVER_MODE"));
+ std::string driverMode;
+
+ if (cmNonempty(p)) {
+ driverMode = *p;
+ } else {
+ driverMode = lang == "C" ? "gcc" : "g++";
+ }
+
+ run_iwyu += this->LocalGenerator->EscapeForShell(
+ cmStrCat(*iwyu, ";--driver-mode=", driverMode));
+ } else {
+ run_iwyu += this->LocalGenerator->EscapeForShell(*iwyu);
+ }
}
if (cmNonempty(tidy)) {
run_iwyu += " --tidy=";
@@ -994,8 +1015,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements(
for (cmSourceFile const* sf : externalObjects) {
auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
this->ConvertToNinjaPath(sf->GetFullPath()), config);
- if (!cmSystemTools::StringEndsWith(objectFileName,
- cmToCStr(pchExtension))) {
+ if (!cmHasSuffix(objectFileName, pchExtension)) {
this->Configs[config].Objects.push_back(objectFileName);
}
}
@@ -1260,8 +1280,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
if (firstForConfig) {
cmProp pchExtension =
this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
- if (!cmSystemTools::StringEndsWith(objectFileName,
- cmToCStr(pchExtension))) {
+ if (!cmHasSuffix(objectFileName, pchExtension)) {
// Add this object to the list of object files.
this->Configs[config].Objects.push_back(objectFileName);
}
diff --git a/Source/cmOptionCommand.cxx b/Source/cmOptionCommand.cxx
index bae67e0..014da4d 100644
--- a/Source/cmOptionCommand.cxx
+++ b/Source/cmOptionCommand.cxx
@@ -29,7 +29,7 @@ bool cmOptionCommand(std::vector<std::string> const& args,
{
auto policyStatus =
status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0077);
- const auto* existsBeforeSet =
+ const auto& existsBeforeSet =
status.GetMakefile().GetStateSnapshot().GetDefinition(args[0]);
switch (policyStatus) {
case cmPolicies::WARN:
@@ -77,7 +77,7 @@ bool cmOptionCommand(std::vector<std::string> const& args,
}
if (checkAndWarn) {
- const auto* existsAfterSet =
+ const auto& existsAfterSet =
status.GetMakefile().GetStateSnapshot().GetDefinition(args[0]);
if (!existsAfterSet) {
status.GetMakefile().IssueMessage(
diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx
index 01e8c04..fc839c5 100644
--- a/Source/cmPolicies.cxx
+++ b/Source/cmPolicies.cxx
@@ -10,6 +10,7 @@
#include "cmListFileCache.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
+#include "cmProperty.h"
#include "cmState.h"
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h
index f7c0d25..a98e6c6 100644
--- a/Source/cmPolicies.h
+++ b/Source/cmPolicies.h
@@ -379,7 +379,10 @@ class cmMakefile;
3, 21, 0, cmPolicies::WARN) \
SELECT(POLICY, CMP0126, \
"set(CACHE) does not remove a normal variable of the same name.", 3, \
- 21, 0, cmPolicies::WARN)
+ 21, 0, cmPolicies::WARN) \
+ SELECT(POLICY, CMP0127, \
+ "cmake_dependent_option() supports full Condition Syntax.", 3, 22, \
+ 0, cmPolicies::WARN)
#define CM_SELECT_ID(F, A1, A2, A3, A4, A5, A6) F(A1)
#define CM_FOR_EACH_POLICY_ID(POLICY) \
diff --git a/Source/cmProperty.cxx b/Source/cmProperty.cxx
new file mode 100644
index 0000000..d012630
--- /dev/null
+++ b/Source/cmProperty.cxx
@@ -0,0 +1,113 @@
+
+#include "cmProperty.h"
+
+#include <string>
+
+#include <cmext/string_view>
+
+#include "cmStringAlgorithms.h"
+
+std::string cmProp::Empty;
+
+bool cmProp::IsOn(cm::string_view value) noexcept
+{
+ switch (value.size()) {
+ case 1:
+ return value[0] == '1' || value[0] == 'Y' || value[0] == 'y';
+ case 2:
+ return //
+ (value[0] == 'O' || value[0] == 'o') && //
+ (value[1] == 'N' || value[1] == 'n');
+ case 3:
+ return //
+ (value[0] == 'Y' || value[0] == 'y') && //
+ (value[1] == 'E' || value[1] == 'e') && //
+ (value[2] == 'S' || value[2] == 's');
+ case 4:
+ return //
+ (value[0] == 'T' || value[0] == 't') && //
+ (value[1] == 'R' || value[1] == 'r') && //
+ (value[2] == 'U' || value[2] == 'u') && //
+ (value[3] == 'E' || value[3] == 'e');
+ default:
+ break;
+ }
+
+ return false;
+}
+
+bool cmProp::IsOff(cm::string_view value) noexcept
+{
+ switch (value.size()) {
+ case 0:
+ return true;
+ case 1:
+ return value[0] == '0' || value[0] == 'N' || value[0] == 'n';
+ case 2:
+ return //
+ (value[0] == 'N' || value[0] == 'n') && //
+ (value[1] == 'O' || value[1] == 'o');
+ case 3:
+ return //
+ (value[0] == 'O' || value[0] == 'o') && //
+ (value[1] == 'F' || value[1] == 'f') && //
+ (value[2] == 'F' || value[2] == 'f');
+ case 5:
+ return //
+ (value[0] == 'F' || value[0] == 'f') && //
+ (value[1] == 'A' || value[1] == 'a') && //
+ (value[2] == 'L' || value[2] == 'l') && //
+ (value[3] == 'S' || value[3] == 's') && //
+ (value[4] == 'E' || value[4] == 'e');
+ case 6:
+ return //
+ (value[0] == 'I' || value[0] == 'i') && //
+ (value[1] == 'G' || value[1] == 'g') && //
+ (value[2] == 'N' || value[2] == 'n') && //
+ (value[3] == 'O' || value[3] == 'o') && //
+ (value[4] == 'R' || value[4] == 'r') && //
+ (value[5] == 'E' || value[5] == 'e');
+ default:
+ break;
+ }
+
+ return IsNOTFOUND(value);
+}
+bool cmProp::IsNOTFOUND(cm::string_view value) noexcept
+{
+ return (value == "NOTFOUND"_s) || cmHasSuffix(value, "-NOTFOUND"_s);
+}
+
+int cmProp::Compare(cmProp value) const noexcept
+{
+ if (this->Value == nullptr && !value) {
+ return 0;
+ }
+ if (this->Value == nullptr) {
+ return -1;
+ }
+ if (!value) {
+ return 1;
+ }
+ return this->Value->compare(*value);
+}
+
+int cmProp::Compare(cm::string_view value) const noexcept
+{
+ if (this->Value == nullptr && value.data() == nullptr) {
+ return 0;
+ }
+ if (this->Value == nullptr) {
+ return -1;
+ }
+ if (value.data() == nullptr) {
+ return 1;
+ }
+ return cm::string_view(*this->Value).compare(value);
+}
+
+std::ostream& operator<<(std::ostream& o, cmProp v)
+{
+ o << *v;
+ return o;
+}
diff --git a/Source/cmProperty.h b/Source/cmProperty.h
index 1e03c3f..3a0a5be 100644
--- a/Source/cmProperty.h
+++ b/Source/cmProperty.h
@@ -4,8 +4,12 @@
#include "cmConfigure.h" // IWYU pragma: keep
+#include <cstddef>
+#include <iosfwd>
#include <string>
+#include <cm/string_view>
+
class cmProperty
{
public:
@@ -23,14 +27,210 @@ public:
};
};
-using cmProp = const std::string*;
+class cmProp
+{
+public:
+ cmProp() noexcept = default;
+ cmProp(std::nullptr_t) noexcept {}
+ explicit cmProp(const std::string* value) noexcept
+ : Value(value)
+ {
+ }
+ explicit cmProp(const std::string& value) noexcept
+ : Value(&value)
+ {
+ }
+ cmProp(const cmProp& other) noexcept = default;
-inline const char* cmToCStr(cmProp p)
+ cmProp& operator=(const cmProp& other) noexcept = default;
+ cmProp& operator=(std::nullptr_t) noexcept
+ {
+ this->Value = nullptr;
+ return *this;
+ }
+
+ const std::string* Get() const noexcept { return this->Value; }
+ const char* GetCStr() const noexcept
+ {
+ return this->Value == nullptr ? nullptr : this->Value->c_str();
+ }
+
+ const std::string* operator->() const noexcept
+ {
+ return this->Value == nullptr ? &cmProp::Empty : this->Value;
+ }
+ const std::string& operator*() const noexcept
+ {
+ return this->Value == nullptr ? cmProp::Empty : *this->Value;
+ }
+
+ explicit operator bool() const noexcept { return this->Value != nullptr; }
+ operator const std::string&() const noexcept { return this->operator*(); }
+ operator cm::string_view() const noexcept { return this->operator*(); }
+
+ /**
+ * Does the value indicate a true or ON value?
+ */
+ bool IsOn() const noexcept
+ {
+ return this->Value != nullptr &&
+ cmProp::IsOn(cm::string_view(*this->Value));
+ }
+ /**
+ * Does the value indicate a false or off value ? Note that this is
+ * not the same as !IsOn(...) because there are a number of
+ * ambiguous values such as "/usr/local/bin" a path will result in
+ * IsOn and IsOff both returning false. Note that the special path
+ * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
+ */
+ bool IsOff() const noexcept
+ {
+ return this->Value == nullptr ||
+ cmProp::IsOff(cm::string_view(*this->Value));
+ }
+ /** Return true if value is NOTFOUND or ends in -NOTFOUND. */
+ bool IsNOTFOUND() const noexcept
+ {
+ return this->Value != nullptr &&
+ cmProp::IsNOTFOUND(cm::string_view(*this->Value));
+ }
+ bool IsEmpty() const noexcept
+ {
+ return this->Value == nullptr || this->Value->empty();
+ }
+
+ bool IsSet() const noexcept
+ {
+ return !this->IsEmpty() && !this->IsNOTFOUND();
+ }
+
+ /**
+ * Does a string indicate a true or ON value?
+ */
+ static bool IsOn(const char* value) noexcept
+ {
+ return value != nullptr && IsOn(cm::string_view(value));
+ }
+ static bool IsOn(cm::string_view) noexcept;
+
+ /**
+ * Compare method has same semantic as std::optional::compare
+ */
+ int Compare(cmProp value) const noexcept;
+ int Compare(cm::string_view value) const noexcept;
+
+ /**
+ * Does a string indicate a false or off value ? Note that this is
+ * not the same as !IsOn(...) because there are a number of
+ * ambiguous values such as "/usr/local/bin" a path will result in
+ * IsOn and IsOff both returning false. Note that the special path
+ * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
+ */
+ static bool IsOff(const char* value) noexcept
+ {
+ return value == nullptr || IsOff(cm::string_view(value));
+ }
+ static bool IsOff(cm::string_view) noexcept;
+
+ /** Return true if value is NOTFOUND or ends in -NOTFOUND. */
+ static bool IsNOTFOUND(const char* value) noexcept
+ {
+ return value == nullptr || IsNOTFOUND(cm::string_view(value));
+ }
+ static bool IsNOTFOUND(cm::string_view) noexcept;
+
+ static bool IsEmpty(const char* value) noexcept
+ {
+ return value == nullptr || *value == '\0';
+ }
+ static bool IsEmpty(cm::string_view value) noexcept { return value.empty(); }
+
+private:
+ static std::string Empty;
+ const std::string* Value = nullptr;
+};
+
+std::ostream& operator<<(std::ostream& o, cmProp v);
+
+inline bool operator==(cmProp l, cmProp r) noexcept
+{
+ return l.Compare(r) == 0;
+}
+inline bool operator!=(cmProp l, cmProp r) noexcept
{
- return p ? p->c_str() : nullptr;
+ return l.Compare(r) != 0;
+}
+inline bool operator<(cmProp l, cmProp r) noexcept
+{
+ return l.Compare(r) < 0;
+}
+inline bool operator<=(cmProp l, cmProp r) noexcept
+{
+ return l.Compare(r) <= 0;
+}
+inline bool operator>(cmProp l, cmProp r) noexcept
+{
+ return l.Compare(r) > 0;
+}
+inline bool operator>=(cmProp l, cmProp r) noexcept
+{
+ return l.Compare(r) >= 0;
}
-inline const char* cmToCStrSafe(cmProp p)
+inline bool operator==(cmProp l, cm::string_view r) noexcept
+{
+ return l.Compare(r) == 0;
+}
+inline bool operator!=(cmProp l, cm::string_view r) noexcept
+{
+ return l.Compare(r) != 0;
+}
+inline bool operator<(cmProp l, cm::string_view r) noexcept
+{
+ return l.Compare(r) < 0;
+}
+inline bool operator<=(cmProp l, cm::string_view r) noexcept
+{
+ return l.Compare(r) <= 0;
+}
+inline bool operator>(cmProp l, cm::string_view r) noexcept
+{
+ return l.Compare(r) > 0;
+}
+inline bool operator>=(cmProp l, cm::string_view r) noexcept
+{
+ return l.Compare(r) >= 0;
+}
+
+inline bool operator==(cmProp l, std::nullptr_t) noexcept
+{
+ return l.Compare(cmProp{}) == 0;
+}
+inline bool operator!=(cmProp l, std::nullptr_t) noexcept
+{
+ return l.Compare(cmProp{}) != 0;
+}
+inline bool operator<(cmProp l, std::nullptr_t) noexcept
+{
+ return l.Compare(cmProp{}) < 0;
+}
+inline bool operator<=(cmProp l, std::nullptr_t) noexcept
+{
+ return l.Compare(cmProp{}) <= 0;
+}
+inline bool operator>(cmProp l, std::nullptr_t) noexcept
+{
+ return l.Compare(cmProp{}) > 0;
+}
+inline bool operator>=(cmProp l, std::nullptr_t) noexcept
+{
+ return l.Compare(cmProp{}) >= 0;
+}
+
+/**
+ * Temporary wrapper
+ */
+inline const char* cmToCStr(cmProp p)
{
- return p ? p->c_str() : "";
+ return p.GetCStr();
}
diff --git a/Source/cmPropertyMap.cxx b/Source/cmPropertyMap.cxx
index 06e151a..8ad3c6f 100644
--- a/Source/cmPropertyMap.cxx
+++ b/Source/cmPropertyMap.cxx
@@ -19,6 +19,15 @@ void cmPropertyMap::SetProperty(const std::string& name, const char* value)
this->Map_[name] = value;
}
+void cmPropertyMap::SetProperty(const std::string& name, cmProp value)
+{
+ if (!value) {
+ this->Map_.erase(name);
+ return;
+ }
+
+ this->Map_[name] = *value;
+}
void cmPropertyMap::AppendProperty(const std::string& name,
const std::string& value, bool asString)
@@ -46,7 +55,7 @@ cmProp cmPropertyMap::GetPropertyValue(const std::string& name) const
{
auto it = this->Map_.find(name);
if (it != this->Map_.end()) {
- return &it->second;
+ return cmProp(it->second);
}
return nullptr;
}
diff --git a/Source/cmPropertyMap.h b/Source/cmPropertyMap.h
index cda585a..b28d3c9 100644
--- a/Source/cmPropertyMap.h
+++ b/Source/cmPropertyMap.h
@@ -26,6 +26,11 @@ public:
//! Set the property value
void SetProperty(const std::string& name, const char* value);
+ void SetProperty(const std::string& name, cmProp value);
+ void SetProperty(const std::string& name, const std::string& value)
+ {
+ this->SetProperty(name, cmProp(value));
+ }
//! Append to the property value
void AppendProperty(const std::string& name, const std::string& value,
diff --git a/Source/cmQTWrapCPPCommand.cxx b/Source/cmQTWrapCPPCommand.cxx
index e9670f9..ca0b259 100644
--- a/Source/cmQTWrapCPPCommand.cxx
+++ b/Source/cmQTWrapCPPCommand.cxx
@@ -6,7 +6,6 @@
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
#include "cmPolicies.h"
-#include "cmProperty.h"
#include "cmRange.h"
#include "cmSourceFile.h"
#include "cmStringAlgorithms.h"
@@ -41,7 +40,7 @@ bool cmQTWrapCPPCommand(std::vector<std::string> const& args,
cmStrCat(mf.GetCurrentBinaryDirectory(), "/moc_", srcName, ".cxx");
cmSourceFile* sf = mf.GetOrCreateSource(newName, true);
if (curr) {
- sf->SetProperty("ABSTRACT", cmToCStr(curr->GetProperty("ABSTRACT")));
+ sf->SetProperty("ABSTRACT", curr->GetProperty("ABSTRACT"));
}
// Compute the name of the header from which to generate the file.
diff --git a/Source/cmQtAutoGen.cxx b/Source/cmQtAutoGen.cxx
index 898d862..57fcd2d 100644
--- a/Source/cmQtAutoGen.cxx
+++ b/Source/cmQtAutoGen.cxx
@@ -384,39 +384,3 @@ bool cmQtAutoGen::RccLister::list(std::string const& qrcFile,
}
return true;
}
-
-bool cmQtAutoGen::FileRead(std::string& content, std::string const& filename,
- std::string* error)
-{
- content.clear();
- if (!cmSystemTools::FileExists(filename, true)) {
- if (error != nullptr) {
- *error = "Not a file.";
- }
- return false;
- }
-
- unsigned long const length = cmSystemTools::FileLength(filename);
- cmsys::ifstream ifs(filename.c_str(), (std::ios::in | std::ios::binary));
-
- // Use lambda to save destructor calls of ifs
- return [&ifs, length, &content, error]() -> bool {
- if (!ifs) {
- if (error != nullptr) {
- *error = "Opening the file for reading failed.";
- }
- return false;
- }
- content.reserve(length);
- using IsIt = std::istreambuf_iterator<char>;
- content.assign(IsIt{ ifs }, IsIt{});
- if (!ifs) {
- content.clear();
- if (error != nullptr) {
- *error = "Reading from the file failed.";
- }
- return false;
- }
- return true;
- }();
-}
diff --git a/Source/cmQtAutoGen.h b/Source/cmQtAutoGen.h
index b9ae360..466a954 100644
--- a/Source/cmQtAutoGen.h
+++ b/Source/cmQtAutoGen.h
@@ -100,9 +100,6 @@ public:
std::vector<std::string> const& newOpts,
bool isQt5);
- static bool FileRead(std::string& content, std::string const& filename,
- std::string* error = nullptr);
-
/** @class RccLister
* @brief Lists files in qrc resource files
*/
diff --git a/Source/cmQtAutoGenGlobalInitializer.cxx b/Source/cmQtAutoGenGlobalInitializer.cxx
index 77fe87e..f3ad565 100644
--- a/Source/cmQtAutoGenGlobalInitializer.cxx
+++ b/Source/cmQtAutoGenGlobalInitializer.cxx
@@ -186,7 +186,7 @@ void cmQtAutoGenGlobalInitializer::GetOrCreateGlobalTarget(
cmProp folder =
makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
if (folder) {
- target->SetProperty("FOLDER", *folder);
+ target->SetProperty("FOLDER", folder);
}
}
}
diff --git a/Source/cmQtAutoGenInitializer.cxx b/Source/cmQtAutoGenInitializer.cxx
index 6cc8328..fe038c7 100644
--- a/Source/cmQtAutoGenInitializer.cxx
+++ b/Source/cmQtAutoGenInitializer.cxx
@@ -24,6 +24,7 @@
#include "cmsys/SystemInformation.hxx"
+#include "cmAlgorithms.h"
#include "cmCustomCommand.h"
#include "cmCustomCommandLines.h"
#include "cmGeneratedFileStream.h"
@@ -522,6 +523,8 @@ bool cmQtAutoGenInitializer::InitCustomTargets()
// Filters
cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
this->Moc.MacroNames);
+ this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
+ this->Moc.MacroNames.end());
{
auto filterList = cmExpandedList(
this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
@@ -902,13 +905,6 @@ bool cmQtAutoGenInitializer::InitScanFiles()
// The reason is that their file names might be discovered from source files
// at generation time.
if (this->MocOrUicEnabled()) {
- std::set<std::string> uicIncludes;
- auto collectUicIncludes = [&](std::unique_ptr<cmSourceFile> const& sf) {
- std::string content;
- FileRead(content, sf->GetFullPath());
- this->AutoUicHelpers.CollectUicIncludes(uicIncludes, content);
- };
-
for (const auto& sf : this->Makefile->GetSourceFiles()) {
// sf->GetExtension() is only valid after sf->ResolveFullPath() ...
// Since we're iterating over source files that might be not in the
@@ -921,10 +917,6 @@ bool cmQtAutoGenInitializer::InitScanFiles()
std::string const& extLower =
cmSystemTools::LowerCase(sf->GetExtension());
- bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
- bool const skipUic =
- (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC) ||
- !this->Uic.Enabled);
if (cm->IsAHeaderExtension(extLower)) {
if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
auto muf = makeMUFile(sf.get(), fullPath, {}, false);
@@ -932,9 +924,6 @@ bool cmQtAutoGenInitializer::InitScanFiles()
addMUHeader(std::move(muf), extLower);
}
}
- if (!skipUic && !sf->GetIsGenerated()) {
- collectUicIncludes(sf);
- }
} else if (cm->IsACLikeSourceExtension(extLower)) {
if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
auto muf = makeMUFile(sf.get(), fullPath, {}, false);
@@ -942,11 +931,11 @@ bool cmQtAutoGenInitializer::InitScanFiles()
addMUSource(std::move(muf));
}
}
- if (!skipUic && !sf->GetIsGenerated()) {
- collectUicIncludes(sf);
- }
} else if (this->Uic.Enabled && (extLower == kw.ui)) {
// .ui file
+ bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
+ bool const skipUic =
+ (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
if (!skipUic) {
// Check if the .ui file has uic options
std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
@@ -956,22 +945,35 @@ bool cmQtAutoGenInitializer::InitScanFiles()
this->Uic.UiFilesWithOptions.emplace_back(fullPath,
cmExpandedList(uicOpts));
}
+
+ auto uiHeaderRelativePath = cmSystemTools::RelativePath(
+ this->LocalGen->GetCurrentSourceDirectory(),
+ cmSystemTools::GetFilenamePath(fullPath));
+
+ // Avoid creating a path containing adjacent slashes
+ if (!uiHeaderRelativePath.empty() &&
+ uiHeaderRelativePath.back() != '/') {
+ uiHeaderRelativePath += '/';
+ }
+
+ auto uiHeaderFilePath = cmStrCat(
+ '/', uiHeaderRelativePath, "ui_"_s,
+ cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
+
+ ConfigString uiHeader;
+ std::string uiHeaderGenex;
+ this->ConfigFileNamesAndGenex(
+ uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
+ uiHeaderFilePath);
+
+ this->Uic.UiHeaders.emplace_back(
+ std::make_pair(uiHeader, uiHeaderGenex));
} else {
// Register skipped .ui file
this->Uic.SkipUi.insert(fullPath);
}
}
}
-
- for (const auto& include : uicIncludes) {
- ConfigString uiHeader;
- std::string uiHeaderGenex;
- this->ConfigFileNamesAndGenex(uiHeader, uiHeaderGenex,
- cmStrCat(this->Dir.Build, "/include"_s),
- cmStrCat("/"_s, include));
- this->Uic.UiHeaders.emplace_back(
- std::make_pair(uiHeader, uiHeaderGenex));
- }
}
// Process GENERATED sources and headers
diff --git a/Source/cmQtAutoGenInitializer.h b/Source/cmQtAutoGenInitializer.h
index 3ec87d2..e76817b 100644
--- a/Source/cmQtAutoGenInitializer.h
+++ b/Source/cmQtAutoGenInitializer.h
@@ -17,7 +17,6 @@
#include "cmFilePathChecksum.h"
#include "cmQtAutoGen.h"
-#include "cmQtAutoUicHelpers.h"
class cmGeneratorTarget;
class cmGlobalGenerator;
@@ -171,7 +170,6 @@ private:
std::string ConfigDefault;
std::vector<std::string> ConfigsList;
std::string TargetsFolder;
- cmQtAutoUicHelpers AutoUicHelpers;
/** Common directories. */
struct
diff --git a/Source/cmQtAutoGenerator.cxx b/Source/cmQtAutoGenerator.cxx
index 0c6b5e6..568926e 100644
--- a/Source/cmQtAutoGenerator.cxx
+++ b/Source/cmQtAutoGenerator.cxx
@@ -121,6 +121,43 @@ bool cmQtAutoGenerator::MakeParentDirectory(std::string const& filename)
return success;
}
+bool cmQtAutoGenerator::FileRead(std::string& content,
+ std::string const& filename,
+ std::string* error)
+{
+ content.clear();
+ if (!cmSystemTools::FileExists(filename, true)) {
+ if (error != nullptr) {
+ *error = "Not a file.";
+ }
+ return false;
+ }
+
+ unsigned long const length = cmSystemTools::FileLength(filename);
+ cmsys::ifstream ifs(filename.c_str(), (std::ios::in | std::ios::binary));
+
+ // Use lambda to save destructor calls of ifs
+ return [&ifs, length, &content, error]() -> bool {
+ if (!ifs) {
+ if (error != nullptr) {
+ *error = "Opening the file for reading failed.";
+ }
+ return false;
+ }
+ content.reserve(length);
+ using IsIt = std::istreambuf_iterator<char>;
+ content.assign(IsIt{ ifs }, IsIt{});
+ if (!ifs) {
+ content.clear();
+ if (error != nullptr) {
+ *error = "Reading from the file failed.";
+ }
+ return false;
+ }
+ return true;
+ }();
+}
+
bool cmQtAutoGenerator::FileWrite(std::string const& filename,
std::string const& content,
std::string* error)
diff --git a/Source/cmQtAutoGenerator.h b/Source/cmQtAutoGenerator.h
index 66399d7..5c3a8ad 100644
--- a/Source/cmQtAutoGenerator.h
+++ b/Source/cmQtAutoGenerator.h
@@ -70,6 +70,8 @@ public:
// -- File system methods
static bool MakeParentDirectory(std::string const& filename);
+ static bool FileRead(std::string& content, std::string const& filename,
+ std::string* error = nullptr);
static bool FileWrite(std::string const& filename,
std::string const& content,
std::string* error = nullptr);
diff --git a/Source/cmQtAutoMocUic.cxx b/Source/cmQtAutoMocUic.cxx
index 86d54f9..2753fd5 100644
--- a/Source/cmQtAutoMocUic.cxx
+++ b/Source/cmQtAutoMocUic.cxx
@@ -30,7 +30,6 @@
#include "cmGeneratedFileStream.h"
#include "cmQtAutoGen.h"
#include "cmQtAutoGenerator.h"
-#include "cmQtAutoUicHelpers.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmWorkerPool.h"
@@ -282,7 +281,7 @@ public:
std::vector<std::string> Options;
std::unordered_map<std::string, UiFile> UiFiles;
std::vector<std::string> SearchPaths;
- cmQtAutoUicHelpers AutoUicHelpers;
+ cmsys::RegularExpression RegExpInclude;
};
/** Uic shared variables. */
@@ -762,7 +761,11 @@ std::string cmQtAutoMocUicT::MocSettingsT::MacrosString() const
return res;
}
-cmQtAutoMocUicT::UicSettingsT::UicSettingsT() = default;
+cmQtAutoMocUicT::UicSettingsT::UicSettingsT()
+{
+ this->RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
+ "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
+}
cmQtAutoMocUicT::UicSettingsT::~UicSettingsT() = default;
@@ -1053,7 +1056,16 @@ void cmQtAutoMocUicT::JobParseT::UicIncludes()
}
std::set<std::string> includes;
- this->UicConst().AutoUicHelpers.CollectUicIncludes(includes, this->Content);
+ {
+ const char* contentChars = this->Content.c_str();
+ cmsys::RegularExpression const& regExp = this->UicConst().RegExpInclude;
+ cmsys::RegularExpressionMatch match;
+ while (regExp.find(contentChars, match)) {
+ includes.emplace(match.match(2));
+ // Forward content pointer
+ contentChars += match.end();
+ }
+ }
this->CreateKeys(this->FileHandle->ParseData->Uic.Include, includes,
UiUnderscoreLength);
}
diff --git a/Source/cmQtAutoUicHelpers.cxx b/Source/cmQtAutoUicHelpers.cxx
deleted file mode 100644
index 751ae08..0000000
--- a/Source/cmQtAutoUicHelpers.cxx
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmQtAutoUicHelpers.h"
-
-cmQtAutoUicHelpers::cmQtAutoUicHelpers()
-{
- RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
- "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
-}
-
-void cmQtAutoUicHelpers::CollectUicIncludes(std::set<std::string>& includes,
- const std::string& content) const
-{
- if (content.find("ui_") == std::string::npos) {
- return;
- }
-
- const char* contentChars = content.c_str();
- cmsys::RegularExpressionMatch match;
- while (this->RegExpInclude.find(contentChars, match)) {
- includes.emplace(match.match(2));
- // Forward content pointer
- contentChars += match.end();
- }
-}
diff --git a/Source/cmQtAutoUicHelpers.h b/Source/cmQtAutoUicHelpers.h
deleted file mode 100644
index 6b09a31..0000000
--- a/Source/cmQtAutoUicHelpers.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#pragma once
-
-#include <set>
-#include <string>
-
-#include "cmsys/RegularExpression.hxx"
-
-class cmQtAutoUicHelpers
-{
-public:
- cmQtAutoUicHelpers();
- virtual ~cmQtAutoUicHelpers() = default;
- void CollectUicIncludes(std::set<std::string>& includes,
- const std::string& content) const;
-
-private:
- cmsys::RegularExpression RegExpInclude;
-};
diff --git a/Source/cmSetDirectoryPropertiesCommand.cxx b/Source/cmSetDirectoryPropertiesCommand.cxx
index 07ad246..9adf537 100644
--- a/Source/cmSetDirectoryPropertiesCommand.cxx
+++ b/Source/cmSetDirectoryPropertiesCommand.cxx
@@ -32,7 +32,7 @@ bool cmSetDirectoryPropertiesCommand(std::vector<std::string> const& args,
"Commands and macros cannot be set using SET_CMAKE_PROPERTIES");
return false;
}
- status.GetMakefile().SetProperty(prop, (iter + 1)->c_str());
+ status.GetMakefile().SetProperty(prop, *(iter + 1));
}
return true;
diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx
index c899053..59b4402 100644
--- a/Source/cmSetPropertyCommand.cxx
+++ b/Source/cmSetPropertyCommand.cxx
@@ -294,7 +294,7 @@ bool HandleAndValidateSourceFilePropertyGENERATED(
sf->SetProperty("GENERATED", nullptr);
break;
case PropertyOp::Set:
- sf->SetProperty("GENERATED", propertyValue.c_str());
+ sf->SetProperty("GENERATED", propertyValue);
break;
}
} else {
@@ -474,7 +474,7 @@ bool HandleGlobalMode(cmExecutionStatus& status,
if (remove) {
cm->SetProperty(propertyName, nullptr);
} else {
- cm->SetProperty(propertyName, propertyValue.c_str());
+ cm->SetProperty(propertyName, propertyValue);
}
}
@@ -520,7 +520,7 @@ bool HandleDirectoryMode(cmExecutionStatus& status,
if (remove) {
mf->SetProperty(propertyName, nullptr);
} else {
- mf->SetProperty(propertyName, propertyValue.c_str());
+ mf->SetProperty(propertyName, propertyValue);
}
}
@@ -631,7 +631,7 @@ bool HandleSource(cmSourceFile* sf, const std::string& propertyName,
if (remove) {
sf->SetProperty(propertyName, nullptr);
} else {
- sf->SetProperty(propertyName, propertyValue.c_str());
+ sf->SetProperty(propertyName, propertyValue);
}
}
return true;
@@ -681,7 +681,7 @@ bool HandleTest(cmTest* test, const std::string& propertyName,
if (remove) {
test->SetProperty(propertyName, nullptr);
} else {
- test->SetProperty(propertyName, propertyValue.c_str());
+ test->SetProperty(propertyName, propertyValue);
}
}
diff --git a/Source/cmSetSourceFilesPropertiesCommand.cxx b/Source/cmSetSourceFilesPropertiesCommand.cxx
index 237b67f..ab93ddb 100644
--- a/Source/cmSetSourceFilesPropertiesCommand.cxx
+++ b/Source/cmSetSourceFilesPropertiesCommand.cxx
@@ -173,7 +173,7 @@ static bool RunCommandForScope(
SetPropertyCommand::HandleAndValidateSourceFilePropertyGENERATED(
sf, *(k + 1));
} else {
- sf->SetProperty(*k, (k + 1)->c_str());
+ sf->SetProperty(*k, *(k + 1));
}
}
}
diff --git a/Source/cmSetTestsPropertiesCommand.cxx b/Source/cmSetTestsPropertiesCommand.cxx
index c4bff76..a17c964 100644
--- a/Source/cmSetTestsPropertiesCommand.cxx
+++ b/Source/cmSetTestsPropertiesCommand.cxx
@@ -37,7 +37,7 @@ bool cmSetTestsPropertiesCommand(std::vector<std::string> const& args,
// loop through all the props and set them
for (auto k = propsIter + 1; k != args.end(); k += 2) {
if (!k->empty()) {
- test->SetProperty(*k, (k + 1)->c_str());
+ test->SetProperty(*k, *(k + 1));
}
}
} else {
diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx
index 3f3c8d5..6caae3a 100644
--- a/Source/cmSourceFile.cxx
+++ b/Source/cmSourceFile.cxx
@@ -269,7 +269,8 @@ bool cmSourceFile::Matches(cmSourceFileLocation const& loc)
return this->Location.Matches(loc);
}
-void cmSourceFile::SetProperty(const std::string& prop, const char* value)
+template <typename ValueType>
+void cmSourceFile::StoreProperty(const std::string& prop, ValueType value)
{
if (prop == propINCLUDE_DIRECTORIES) {
this->IncludeDirectories.clear();
@@ -294,6 +295,15 @@ void cmSourceFile::SetProperty(const std::string& prop, const char* value)
}
}
+void cmSourceFile::SetProperty(const std::string& prop, const char* value)
+{
+ this->StoreProperty(prop, value);
+}
+void cmSourceFile::SetProperty(const std::string& prop, cmProp value)
+{
+ this->StoreProperty(prop, value);
+}
+
void cmSourceFile::AppendProperty(const std::string& prop,
const std::string& value, bool asString)
{
@@ -342,7 +352,7 @@ cmProp cmSourceFile::GetPropertyForUser(const std::string& prop)
// if it is requested by the user.
if (prop == propLANGUAGE) {
// The pointer is valid until `this->Language` is modified.
- return &this->GetOrDetermineLanguage();
+ return cmProp(this->GetOrDetermineLanguage());
}
// Special handling for GENERATED property.
@@ -355,9 +365,9 @@ cmProp cmSourceFile::GetPropertyForUser(const std::string& prop)
(policyStatus == cmPolicies::WARN || policyStatus == cmPolicies::OLD)
? CheckScope::GlobalAndLocal
: CheckScope::Global)) {
- return &propTRUE;
+ return cmProp(propTRUE);
}
- return &propFALSE;
+ return cmProp(propFALSE);
}
// Perform the normal property lookup.
@@ -371,7 +381,7 @@ cmProp cmSourceFile::GetProperty(const std::string& prop) const
if (this->FullPath.empty()) {
return nullptr;
}
- return &this->FullPath;
+ return cmProp(this->FullPath);
}
// Check for the properties with backtraces.
@@ -382,7 +392,7 @@ cmProp cmSourceFile::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->IncludeDirectories, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propCOMPILE_OPTIONS) {
@@ -392,7 +402,7 @@ cmProp cmSourceFile::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->CompileOptions, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propCOMPILE_DEFINITIONS) {
@@ -402,7 +412,7 @@ cmProp cmSourceFile::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->CompileDefinitions, ";");
- return &output;
+ return cmProp(output);
}
cmProp retVal = this->Properties.GetPropertyValue(prop);
diff --git a/Source/cmSourceFile.h b/Source/cmSourceFile.h
index 32ed687..78e0d27 100644
--- a/Source/cmSourceFile.h
+++ b/Source/cmSourceFile.h
@@ -42,6 +42,11 @@ public:
//! Set/Get a property of this source file
void SetProperty(const std::string& prop, const char* value);
+ void SetProperty(const std::string& prop, cmProp value);
+ void SetProperty(const std::string& prop, const std::string& value)
+ {
+ this->SetProperty(prop, cmProp(value));
+ }
void AppendProperty(const std::string& prop, const std::string& value,
bool asString = false);
//! Might return a nullptr if the property is not set or invalid
@@ -145,6 +150,9 @@ public:
std::string GetObjectLibrary() const;
private:
+ template <typename ValueType>
+ void StoreProperty(const std::string& prop, ValueType value);
+
cmSourceFileLocation Location;
cmPropertyMap Properties;
std::unique_ptr<cmCustomCommand> CustomCommand;
diff --git a/Source/cmStandardLevelResolver.cxx b/Source/cmStandardLevelResolver.cxx
index da36ed6..499317d 100644
--- a/Source/cmStandardLevelResolver.cxx
+++ b/Source/cmStandardLevelResolver.cxx
@@ -393,7 +393,7 @@ bool cmStandardLevelResolver::CheckCompileFeaturesAvailable(
return true;
}
- const char* features = this->CompileFeaturesAvailable(lang, error);
+ cmProp features = this->CompileFeaturesAvailable(lang, error);
if (!features) {
return false;
}
@@ -471,7 +471,7 @@ bool cmStandardLevelResolver::CompileFeatureKnown(
return false;
}
-const char* cmStandardLevelResolver::CompileFeaturesAvailable(
+cmProp cmStandardLevelResolver::CompileFeaturesAvailable(
const std::string& lang, std::string* error) const
{
if (!this->Makefile->GetGlobalGenerator()->GetLanguageEnabled(lang)) {
@@ -513,7 +513,7 @@ const char* cmStandardLevelResolver::CompileFeaturesAvailable(
}
return nullptr;
}
- return cmToCStr(featuresKnown);
+ return featuresKnown;
}
bool cmStandardLevelResolver::GetNewRequiredStandard(
diff --git a/Source/cmStandardLevelResolver.h b/Source/cmStandardLevelResolver.h
index d84fbcb..c01a3b1 100644
--- a/Source/cmStandardLevelResolver.h
+++ b/Source/cmStandardLevelResolver.h
@@ -30,8 +30,8 @@ public:
const std::string& feature, std::string& lang,
std::string* error) const;
- const char* CompileFeaturesAvailable(const std::string& lang,
- std::string* error) const;
+ cmProp CompileFeaturesAvailable(const std::string& lang,
+ std::string* error) const;
bool GetNewRequiredStandard(const std::string& targetName,
const std::string& feature,
diff --git a/Source/cmState.cxx b/Source/cmState.cxx
index bdb5bda..16718e8 100644
--- a/Source/cmState.cxx
+++ b/Source/cmState.cxx
@@ -206,7 +206,7 @@ bool cmState::GetCacheEntryPropertyAsBool(std::string const& key,
return this->CacheManager->GetCacheEntryPropertyAsBool(key, propertyName);
}
-void cmState::AddCacheEntry(const std::string& key, const char* value,
+void cmState::AddCacheEntry(const std::string& key, cmProp value,
const char* helpString,
cmStateEnums::CacheEntryType type)
{
@@ -277,15 +277,10 @@ cmStateSnapshot cmState::Reset()
cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator it =
this->BuildsystemDirectory.Truncate();
it->IncludeDirectories.clear();
- it->IncludeDirectoryBacktraces.clear();
it->CompileDefinitions.clear();
- it->CompileDefinitionsBacktraces.clear();
it->CompileOptions.clear();
- it->CompileOptionsBacktraces.clear();
it->LinkOptions.clear();
- it->LinkOptionsBacktraces.clear();
it->LinkDirectories.clear();
- it->LinkDirectoriesBacktraces.clear();
it->DirectoryEnd = pos;
it->NormalTargetNames.clear();
it->ImportedTargetNames.clear();
@@ -569,6 +564,10 @@ void cmState::SetGlobalProperty(const std::string& prop, const char* value)
{
this->GlobalProperties.SetProperty(prop, value);
}
+void cmState::SetGlobalProperty(const std::string& prop, cmProp value)
+{
+ this->GlobalProperties.SetProperty(prop, value);
+}
void cmState::AppendGlobalProperty(const std::string& prop,
const std::string& value, bool asString)
@@ -603,47 +602,47 @@ cmProp cmState::GetGlobalProperty(const std::string& prop)
if (prop == "CMAKE_C_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_C_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_C90_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_C90_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_C99_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_C99_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_C11_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_C11_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_CXX_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_CXX_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_CXX98_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_CXX98_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_CXX11_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_CXX11_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_CXX14_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_CXX14_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
if (prop == "CMAKE_CUDA_KNOWN_FEATURES") {
static const std::string s_out(
&FOR_EACH_CUDA_FEATURE(STRING_LIST_ELEMENT)[1]);
- return &s_out;
+ return cmProp(s_out);
}
#undef STRING_LIST_ELEMENT
diff --git a/Source/cmState.h b/Source/cmState.h
index 8561fc0..390f6d6 100644
--- a/Source/cmState.h
+++ b/Source/cmState.h
@@ -178,6 +178,7 @@ public:
std::vector<std::string> GetCommandNames() const;
void SetGlobalProperty(const std::string& prop, const char* value);
+ void SetGlobalProperty(const std::string& prop, cmProp value);
void AppendGlobalProperty(const std::string& prop, const std::string& value,
bool asString = false);
cmProp GetGlobalProperty(const std::string& prop);
@@ -218,6 +219,18 @@ public:
private:
friend class cmake;
void AddCacheEntry(const std::string& key, const char* value,
+ const char* helpString, cmStateEnums::CacheEntryType type)
+ {
+ this->AddCacheEntry(key,
+ value ? cmProp(std::string(value)) : cmProp(nullptr),
+ helpString, type);
+ }
+ void AddCacheEntry(const std::string& key, const std::string& value,
+ const char* helpString, cmStateEnums::CacheEntryType type)
+ {
+ this->AddCacheEntry(key, cmProp(value), helpString, type);
+ }
+ void AddCacheEntry(const std::string& key, cmProp value,
const char* helpString,
cmStateEnums::CacheEntryType type);
diff --git a/Source/cmStateDirectory.cxx b/Source/cmStateDirectory.cxx
index c898dd4..8f83b02 100644
--- a/Source/cmStateDirectory.cxx
+++ b/Source/cmStateDirectory.cxx
@@ -19,6 +19,7 @@
#include "cmState.h"
#include "cmStatePrivate.h"
#include "cmStateTypes.h"
+#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
static std::string const kBINARY_DIR = "BINARY_DIR";
@@ -63,7 +64,7 @@ cmStateDirectory::cmStateDirectory(
}
template <typename T, typename U>
-cmStringRange GetPropertyContent(T const& content, U contentEndPosition)
+cmBTStringRange GetPropertyContent(T const& content, U contentEndPosition)
{
auto end = content.begin() + contentEndPosition;
@@ -73,88 +74,59 @@ cmStringRange GetPropertyContent(T const& content, U contentEndPosition)
return cmMakeRange(rbegin.base(), end);
}
-template <typename T, typename U, typename V>
-cmBacktraceRange GetPropertyBacktraces(T const& content, U const& backtraces,
- V contentEndPosition)
-{
- auto entryEnd = content.begin() + contentEndPosition;
-
- auto rbegin = cm::make_reverse_iterator(entryEnd);
- rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);
-
- auto it = backtraces.begin() + std::distance(content.begin(), rbegin.base());
-
- auto end = backtraces.end();
- return cmMakeRange(it, end);
-}
-
-template <typename T, typename U, typename V>
-void AppendEntry(T& content, U& backtraces, V& endContentPosition,
- const std::string& value, const cmListFileBacktrace& lfbt)
+template <typename T, typename U>
+void AppendEntry(T& content, U& endContentPosition,
+ const BT<std::string>& value)
{
- if (value.empty()) {
+ if (value.Value.empty()) {
return;
}
assert(endContentPosition == content.size());
content.push_back(value);
- backtraces.push_back(lfbt);
endContentPosition = content.size();
}
-template <typename T, typename U, typename V>
-void SetContent(T& content, U& backtraces, V& endContentPosition,
- const std::string& vec, const cmListFileBacktrace& lfbt)
+template <typename T, typename U>
+void SetContent(T& content, U& endContentPosition, const BT<std::string>& vec)
{
assert(endContentPosition == content.size());
content.resize(content.size() + 2);
- backtraces.resize(backtraces.size() + 2);
content.back() = vec;
- backtraces.back() = lfbt;
endContentPosition = content.size();
}
-template <typename T, typename U, typename V>
-void ClearContent(T& content, U& backtraces, V& endContentPosition)
+template <typename T, typename U>
+void ClearContent(T& content, U& endContentPosition)
{
assert(endContentPosition == content.size());
content.resize(content.size() + 1);
- backtraces.resize(backtraces.size() + 1);
endContentPosition = content.size();
}
-cmStringRange cmStateDirectory::GetIncludeDirectoriesEntries() const
+cmBTStringRange cmStateDirectory::GetIncludeDirectoriesEntries() const
{
return GetPropertyContent(
this->DirectoryState->IncludeDirectories,
this->Snapshot_.Position->IncludeDirectoryPosition);
}
-cmBacktraceRange cmStateDirectory::GetIncludeDirectoriesEntryBacktraces() const
-{
- return GetPropertyBacktraces(
- this->DirectoryState->IncludeDirectories,
- this->DirectoryState->IncludeDirectoryBacktraces,
- this->Snapshot_.Position->IncludeDirectoryPosition);
-}
-
void cmStateDirectory::AppendIncludeDirectoriesEntry(
- const std::string& vec, const cmListFileBacktrace& lfbt)
+ const BT<std::string>& vec)
{
AppendEntry(this->DirectoryState->IncludeDirectories,
- this->DirectoryState->IncludeDirectoryBacktraces,
- this->Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
+ this->Snapshot_.Position->IncludeDirectoryPosition, vec);
}
void cmStateDirectory::PrependIncludeDirectoriesEntry(
- const std::string& vec, const cmListFileBacktrace& lfbt)
+ const BT<std::string>& vec)
{
auto entryEnd = this->DirectoryState->IncludeDirectories.begin() +
this->Snapshot_.Position->IncludeDirectoryPosition;
@@ -164,167 +136,111 @@ void cmStateDirectory::PrependIncludeDirectoriesEntry(
rbegin = std::find(rbegin, rend, cmPropertySentinal);
auto entryIt = rbegin.base();
- auto entryBegin = this->DirectoryState->IncludeDirectories.begin();
-
- auto btIt = this->DirectoryState->IncludeDirectoryBacktraces.begin() +
- std::distance(entryBegin, entryIt);
this->DirectoryState->IncludeDirectories.insert(entryIt, vec);
- this->DirectoryState->IncludeDirectoryBacktraces.insert(btIt, lfbt);
this->Snapshot_.Position->IncludeDirectoryPosition =
this->DirectoryState->IncludeDirectories.size();
}
-void cmStateDirectory::SetIncludeDirectories(const std::string& vec,
- const cmListFileBacktrace& lfbt)
+void cmStateDirectory::SetIncludeDirectories(const BT<std::string>& vec)
{
SetContent(this->DirectoryState->IncludeDirectories,
- this->DirectoryState->IncludeDirectoryBacktraces,
- this->Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
+ this->Snapshot_.Position->IncludeDirectoryPosition, vec);
}
void cmStateDirectory::ClearIncludeDirectories()
{
ClearContent(this->DirectoryState->IncludeDirectories,
- this->DirectoryState->IncludeDirectoryBacktraces,
this->Snapshot_.Position->IncludeDirectoryPosition);
}
-cmStringRange cmStateDirectory::GetCompileDefinitionsEntries() const
+cmBTStringRange cmStateDirectory::GetCompileDefinitionsEntries() const
{
return GetPropertyContent(
this->DirectoryState->CompileDefinitions,
this->Snapshot_.Position->CompileDefinitionsPosition);
}
-cmBacktraceRange cmStateDirectory::GetCompileDefinitionsEntryBacktraces() const
-{
- return GetPropertyBacktraces(
- this->DirectoryState->CompileDefinitions,
- this->DirectoryState->CompileDefinitionsBacktraces,
- this->Snapshot_.Position->CompileDefinitionsPosition);
-}
-
void cmStateDirectory::AppendCompileDefinitionsEntry(
- const std::string& vec, const cmListFileBacktrace& lfbt)
+ const BT<std::string>& vec)
{
AppendEntry(this->DirectoryState->CompileDefinitions,
- this->DirectoryState->CompileDefinitionsBacktraces,
- this->Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
+ this->Snapshot_.Position->CompileDefinitionsPosition, vec);
}
-void cmStateDirectory::SetCompileDefinitions(const std::string& vec,
- const cmListFileBacktrace& lfbt)
+void cmStateDirectory::SetCompileDefinitions(const BT<std::string>& vec)
{
SetContent(this->DirectoryState->CompileDefinitions,
- this->DirectoryState->CompileDefinitionsBacktraces,
- this->Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
+ this->Snapshot_.Position->CompileDefinitionsPosition, vec);
}
void cmStateDirectory::ClearCompileDefinitions()
{
ClearContent(this->DirectoryState->CompileDefinitions,
- this->DirectoryState->CompileDefinitionsBacktraces,
this->Snapshot_.Position->CompileDefinitionsPosition);
}
-cmStringRange cmStateDirectory::GetCompileOptionsEntries() const
+cmBTStringRange cmStateDirectory::GetCompileOptionsEntries() const
{
return GetPropertyContent(this->DirectoryState->CompileOptions,
this->Snapshot_.Position->CompileOptionsPosition);
}
-cmBacktraceRange cmStateDirectory::GetCompileOptionsEntryBacktraces() const
-{
- return GetPropertyBacktraces(
- this->DirectoryState->CompileOptions,
- this->DirectoryState->CompileOptionsBacktraces,
- this->Snapshot_.Position->CompileOptionsPosition);
-}
-
-void cmStateDirectory::AppendCompileOptionsEntry(
- const std::string& vec, const cmListFileBacktrace& lfbt)
+void cmStateDirectory::AppendCompileOptionsEntry(const BT<std::string>& vec)
{
AppendEntry(this->DirectoryState->CompileOptions,
- this->DirectoryState->CompileOptionsBacktraces,
- this->Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
+ this->Snapshot_.Position->CompileOptionsPosition, vec);
}
-void cmStateDirectory::SetCompileOptions(const std::string& vec,
- const cmListFileBacktrace& lfbt)
+void cmStateDirectory::SetCompileOptions(const BT<std::string>& vec)
{
SetContent(this->DirectoryState->CompileOptions,
- this->DirectoryState->CompileOptionsBacktraces,
- this->Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
+ this->Snapshot_.Position->CompileOptionsPosition, vec);
}
void cmStateDirectory::ClearCompileOptions()
{
ClearContent(this->DirectoryState->CompileOptions,
- this->DirectoryState->CompileOptionsBacktraces,
this->Snapshot_.Position->CompileOptionsPosition);
}
-cmStringRange cmStateDirectory::GetLinkOptionsEntries() const
+cmBTStringRange cmStateDirectory::GetLinkOptionsEntries() const
{
return GetPropertyContent(this->DirectoryState->LinkOptions,
this->Snapshot_.Position->LinkOptionsPosition);
}
-cmBacktraceRange cmStateDirectory::GetLinkOptionsEntryBacktraces() const
-{
- return GetPropertyBacktraces(this->DirectoryState->LinkOptions,
- this->DirectoryState->LinkOptionsBacktraces,
- this->Snapshot_.Position->LinkOptionsPosition);
-}
-
-void cmStateDirectory::AppendLinkOptionsEntry(const std::string& vec,
- const cmListFileBacktrace& lfbt)
+void cmStateDirectory::AppendLinkOptionsEntry(const BT<std::string>& vec)
{
AppendEntry(this->DirectoryState->LinkOptions,
- this->DirectoryState->LinkOptionsBacktraces,
- this->Snapshot_.Position->LinkOptionsPosition, vec, lfbt);
+ this->Snapshot_.Position->LinkOptionsPosition, vec);
}
-void cmStateDirectory::SetLinkOptions(const std::string& vec,
- const cmListFileBacktrace& lfbt)
+void cmStateDirectory::SetLinkOptions(const BT<std::string>& vec)
{
SetContent(this->DirectoryState->LinkOptions,
- this->DirectoryState->LinkOptionsBacktraces,
- this->Snapshot_.Position->LinkOptionsPosition, vec, lfbt);
+ this->Snapshot_.Position->LinkOptionsPosition, vec);
}
void cmStateDirectory::ClearLinkOptions()
{
ClearContent(this->DirectoryState->LinkOptions,
- this->DirectoryState->LinkOptionsBacktraces,
this->Snapshot_.Position->LinkOptionsPosition);
}
-cmStringRange cmStateDirectory::GetLinkDirectoriesEntries() const
+cmBTStringRange cmStateDirectory::GetLinkDirectoriesEntries() const
{
return GetPropertyContent(this->DirectoryState->LinkDirectories,
this->Snapshot_.Position->LinkDirectoriesPosition);
}
-cmBacktraceRange cmStateDirectory::GetLinkDirectoriesEntryBacktraces() const
-{
- return GetPropertyBacktraces(
- this->DirectoryState->LinkDirectories,
- this->DirectoryState->LinkDirectoriesBacktraces,
- this->Snapshot_.Position->LinkDirectoriesPosition);
-}
-
-void cmStateDirectory::AppendLinkDirectoriesEntry(
- const std::string& vec, const cmListFileBacktrace& lfbt)
+void cmStateDirectory::AppendLinkDirectoriesEntry(const BT<std::string>& vec)
{
AppendEntry(this->DirectoryState->LinkDirectories,
- this->DirectoryState->LinkDirectoriesBacktraces,
- this->Snapshot_.Position->LinkDirectoriesPosition, vec, lfbt);
+ this->Snapshot_.Position->LinkDirectoriesPosition, vec);
}
-void cmStateDirectory::PrependLinkDirectoriesEntry(
- const std::string& vec, const cmListFileBacktrace& lfbt)
+void cmStateDirectory::PrependLinkDirectoriesEntry(const BT<std::string>& vec)
{
auto entryEnd = this->DirectoryState->LinkDirectories.begin() +
this->Snapshot_.Position->LinkDirectoriesPosition;
@@ -334,42 +250,35 @@ void cmStateDirectory::PrependLinkDirectoriesEntry(
rbegin = std::find(rbegin, rend, cmPropertySentinal);
auto entryIt = rbegin.base();
- auto entryBegin = this->DirectoryState->LinkDirectories.begin();
-
- auto btIt = this->DirectoryState->LinkDirectoriesBacktraces.begin() +
- std::distance(entryBegin, entryIt);
this->DirectoryState->LinkDirectories.insert(entryIt, vec);
- this->DirectoryState->LinkDirectoriesBacktraces.insert(btIt, lfbt);
this->Snapshot_.Position->LinkDirectoriesPosition =
this->DirectoryState->LinkDirectories.size();
}
-void cmStateDirectory::SetLinkDirectories(const std::string& vec,
- const cmListFileBacktrace& lfbt)
+void cmStateDirectory::SetLinkDirectories(const BT<std::string>& vec)
{
SetContent(this->DirectoryState->LinkDirectories,
- this->DirectoryState->LinkDirectoriesBacktraces,
- this->Snapshot_.Position->LinkDirectoriesPosition, vec, lfbt);
+ this->Snapshot_.Position->LinkDirectoriesPosition, vec);
}
void cmStateDirectory::ClearLinkDirectories()
{
ClearContent(this->DirectoryState->LinkDirectories,
- this->DirectoryState->LinkDirectoriesBacktraces,
this->Snapshot_.Position->LinkDirectoriesPosition);
}
-void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
- cmListFileBacktrace const& lfbt)
+template <typename ValueType>
+void cmStateDirectory::StoreProperty(const std::string& prop, ValueType value,
+ cmListFileBacktrace const& lfbt)
{
if (prop == "INCLUDE_DIRECTORIES") {
if (!value) {
this->ClearIncludeDirectories();
return;
}
- this->SetIncludeDirectories(value, lfbt);
+ this->SetIncludeDirectories(BT<std::string>(value, lfbt));
return;
}
if (prop == "COMPILE_OPTIONS") {
@@ -377,7 +286,7 @@ void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
this->ClearCompileOptions();
return;
}
- this->SetCompileOptions(value, lfbt);
+ this->SetCompileOptions(BT<std::string>(value, lfbt));
return;
}
if (prop == "COMPILE_DEFINITIONS") {
@@ -385,7 +294,7 @@ void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
this->ClearCompileDefinitions();
return;
}
- this->SetCompileDefinitions(value, lfbt);
+ this->SetCompileDefinitions(BT<std::string>(value, lfbt));
return;
}
if (prop == "LINK_OPTIONS") {
@@ -393,7 +302,7 @@ void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
this->ClearLinkOptions();
return;
}
- this->SetLinkOptions(value, lfbt);
+ this->SetLinkOptions(BT<std::string>(value, lfbt));
return;
}
if (prop == "LINK_DIRECTORIES") {
@@ -401,35 +310,46 @@ void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
this->ClearLinkDirectories();
return;
}
- this->SetLinkDirectories(value, lfbt);
+ this->SetLinkDirectories(BT<std::string>(value, lfbt));
return;
}
this->DirectoryState->Properties.SetProperty(prop, value);
}
+void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
+ cmListFileBacktrace const& lfbt)
+{
+ this->StoreProperty(prop, value, lfbt);
+}
+void cmStateDirectory::SetProperty(const std::string& prop, cmProp value,
+ cmListFileBacktrace const& lfbt)
+{
+ this->StoreProperty(prop, value, lfbt);
+}
+
void cmStateDirectory::AppendProperty(const std::string& prop,
const std::string& value, bool asString,
cmListFileBacktrace const& lfbt)
{
if (prop == "INCLUDE_DIRECTORIES") {
- this->AppendIncludeDirectoriesEntry(value, lfbt);
+ this->AppendIncludeDirectoriesEntry(BT<std::string>(value, lfbt));
return;
}
if (prop == "COMPILE_OPTIONS") {
- this->AppendCompileOptionsEntry(value, lfbt);
+ this->AppendCompileOptionsEntry(BT<std::string>(value, lfbt));
return;
}
if (prop == "COMPILE_DEFINITIONS") {
- this->AppendCompileDefinitionsEntry(value, lfbt);
+ this->AppendCompileDefinitionsEntry(BT<std::string>(value, lfbt));
return;
}
if (prop == "LINK_OPTIONS") {
- this->AppendLinkOptionsEntry(value, lfbt);
+ this->AppendLinkOptionsEntry(BT<std::string>(value, lfbt));
return;
}
if (prop == "LINK_DIRECTORIES") {
- this->AppendLinkDirectoriesEntry(value, lfbt);
+ this->AppendLinkDirectoriesEntry(BT<std::string>(value, lfbt));
return;
}
@@ -450,17 +370,17 @@ cmProp cmStateDirectory::GetProperty(const std::string& prop, bool chain) const
if (prop == "PARENT_DIRECTORY") {
cmStateSnapshot parent = this->Snapshot_.GetBuildsystemDirectoryParent();
if (parent.IsValid()) {
- return &parent.GetDirectory().GetCurrentSource();
+ return cmProp(parent.GetDirectory().GetCurrentSource());
}
- return &output;
+ return cmProp(output);
}
if (prop == kBINARY_DIR) {
output = this->GetCurrentBinary();
- return &output;
+ return cmProp(output);
}
if (prop == kSOURCE_DIR) {
output = this->GetCurrentSource();
- return &output;
+ return cmProp(output);
}
if (prop == kSUBDIRECTORIES) {
std::vector<std::string> child_dirs;
@@ -471,15 +391,15 @@ cmProp cmStateDirectory::GetProperty(const std::string& prop, bool chain) const
child_dirs.push_back(ci.GetDirectory().GetCurrentSource());
}
output = cmJoin(child_dirs, ";");
- return &output;
+ return cmProp(output);
}
if (prop == kBUILDSYSTEM_TARGETS) {
output = cmJoin(this->DirectoryState->NormalTargetNames, ";");
- return &output;
+ return cmProp(output);
}
if (prop == "IMPORTED_TARGETS"_s) {
output = cmJoin(this->DirectoryState->ImportedTargetNames, ";");
- return &output;
+ return cmProp(output);
}
if (prop == "LISTFILE_STACK") {
@@ -491,38 +411,38 @@ cmProp cmStateDirectory::GetProperty(const std::string& prop, bool chain) const
}
std::reverse(listFiles.begin(), listFiles.end());
output = cmJoin(listFiles, ";");
- return &output;
+ return cmProp(output);
}
if (prop == "CACHE_VARIABLES") {
output = cmJoin(this->Snapshot_.State->GetCacheEntryKeys(), ";");
- return &output;
+ return cmProp(output);
}
if (prop == "VARIABLES") {
std::vector<std::string> res = this->Snapshot_.ClosureKeys();
cm::append(res, this->Snapshot_.State->GetCacheEntryKeys());
std::sort(res.begin(), res.end());
output = cmJoin(res, ";");
- return &output;
+ return cmProp(output);
}
if (prop == "INCLUDE_DIRECTORIES") {
output = cmJoin(this->GetIncludeDirectoriesEntries(), ";");
- return &output;
+ return cmProp(output);
}
if (prop == "COMPILE_OPTIONS") {
output = cmJoin(this->GetCompileOptionsEntries(), ";");
- return &output;
+ return cmProp(output);
}
if (prop == "COMPILE_DEFINITIONS") {
output = cmJoin(this->GetCompileDefinitionsEntries(), ";");
- return &output;
+ return cmProp(output);
}
if (prop == "LINK_OPTIONS") {
output = cmJoin(this->GetLinkOptionsEntries(), ";");
- return &output;
+ return cmProp(output);
}
if (prop == "LINK_DIRECTORIES") {
output = cmJoin(this->GetLinkDirectoriesEntries(), ";");
- return &output;
+ return cmProp(output);
}
cmProp retVal = this->DirectoryState->Properties.GetPropertyValue(prop);
diff --git a/Source/cmStateDirectory.h b/Source/cmStateDirectory.h
index b8abccb..fac5d58c 100644
--- a/Source/cmStateDirectory.h
+++ b/Source/cmStateDirectory.h
@@ -14,7 +14,6 @@
#include "cmProperty.h"
#include "cmStatePrivate.h"
#include "cmStateSnapshot.h"
-#include "cmStringAlgorithms.h"
class cmStateDirectory
{
@@ -28,51 +27,37 @@ public:
std::string const& GetCurrentBinary() const;
void SetCurrentBinary(std::string const& dir);
- cmStringRange GetIncludeDirectoriesEntries() const;
- cmBacktraceRange GetIncludeDirectoriesEntryBacktraces() const;
- void AppendIncludeDirectoriesEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void PrependIncludeDirectoriesEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void SetIncludeDirectories(std::string const& vec,
- cmListFileBacktrace const& lfbt);
+ cmBTStringRange GetIncludeDirectoriesEntries() const;
+ void AppendIncludeDirectoriesEntry(BT<std::string> const& vec);
+ void PrependIncludeDirectoriesEntry(BT<std::string> const& vec);
+ void SetIncludeDirectories(BT<std::string> const& vec);
void ClearIncludeDirectories();
- cmStringRange GetCompileDefinitionsEntries() const;
- cmBacktraceRange GetCompileDefinitionsEntryBacktraces() const;
- void AppendCompileDefinitionsEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void SetCompileDefinitions(std::string const& vec,
- cmListFileBacktrace const& lfbt);
+ cmBTStringRange GetCompileDefinitionsEntries() const;
+ void AppendCompileDefinitionsEntry(BT<std::string> const& vec);
+ void SetCompileDefinitions(BT<std::string> const& vec);
void ClearCompileDefinitions();
- cmStringRange GetCompileOptionsEntries() const;
- cmBacktraceRange GetCompileOptionsEntryBacktraces() const;
- void AppendCompileOptionsEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void SetCompileOptions(std::string const& vec,
- cmListFileBacktrace const& lfbt);
+ cmBTStringRange GetCompileOptionsEntries() const;
+ void AppendCompileOptionsEntry(BT<std::string> const& vec);
+ void SetCompileOptions(BT<std::string> const& vec);
void ClearCompileOptions();
- cmStringRange GetLinkOptionsEntries() const;
- cmBacktraceRange GetLinkOptionsEntryBacktraces() const;
- void AppendLinkOptionsEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void PrependLinkDirectoriesEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void SetLinkOptions(std::string const& vec, cmListFileBacktrace const& lfbt);
+ cmBTStringRange GetLinkOptionsEntries() const;
+ void AppendLinkOptionsEntry(BT<std::string> const& vec);
+ void PrependLinkDirectoriesEntry(BT<std::string> const& vec);
+ void SetLinkOptions(BT<std::string> const& vec);
void ClearLinkOptions();
- cmStringRange GetLinkDirectoriesEntries() const;
- cmBacktraceRange GetLinkDirectoriesEntryBacktraces() const;
- void AppendLinkDirectoriesEntry(std::string const& vec,
- cmListFileBacktrace const& lfbt);
- void SetLinkDirectories(std::string const& vec,
- cmListFileBacktrace const& lfbt);
+ cmBTStringRange GetLinkDirectoriesEntries() const;
+ void AppendLinkDirectoriesEntry(BT<std::string> const& vec);
+ void SetLinkDirectories(BT<std::string> const& vecs);
void ClearLinkDirectories();
void SetProperty(const std::string& prop, const char* value,
cmListFileBacktrace const& lfbt);
+ void SetProperty(const std::string& prop, cmProp value,
+ cmListFileBacktrace const& lfbt);
void AppendProperty(const std::string& prop, const std::string& value,
bool asString, cmListFileBacktrace const& lfbt);
cmProp GetProperty(const std::string& prop) const;
@@ -84,6 +69,10 @@ public:
void AddImportedTargetName(std::string const& name);
private:
+ template <typename ValueType>
+ void StoreProperty(const std::string& prop, ValueType value,
+ cmListFileBacktrace const& lfbt);
+
cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator
DirectoryState;
cmStateSnapshot Snapshot_;
diff --git a/Source/cmStatePrivate.h b/Source/cmStatePrivate.h
index 6f475f2..fd46eed 100644
--- a/Source/cmStatePrivate.h
+++ b/Source/cmStatePrivate.h
@@ -67,20 +67,15 @@ struct cmStateDetail::BuildsystemDirectoryStateType
std::string Location;
std::string OutputLocation;
- std::vector<std::string> IncludeDirectories;
- std::vector<cmListFileBacktrace> IncludeDirectoryBacktraces;
+ std::vector<BT<std::string>> IncludeDirectories;
- std::vector<std::string> CompileDefinitions;
- std::vector<cmListFileBacktrace> CompileDefinitionsBacktraces;
+ std::vector<BT<std::string>> CompileDefinitions;
- std::vector<std::string> CompileOptions;
- std::vector<cmListFileBacktrace> CompileOptionsBacktraces;
+ std::vector<BT<std::string>> CompileOptions;
- std::vector<std::string> LinkOptions;
- std::vector<cmListFileBacktrace> LinkOptionsBacktraces;
+ std::vector<BT<std::string>> LinkOptions;
- std::vector<std::string> LinkDirectories;
- std::vector<cmListFileBacktrace> LinkDirectoriesBacktraces;
+ std::vector<BT<std::string>> LinkDirectories;
std::vector<std::string> NormalTargetNames;
std::vector<std::string> ImportedTargetNames;
diff --git a/Source/cmStateSnapshot.cxx b/Source/cmStateSnapshot.cxx
index fbf47ef..bd7db85 100644
--- a/Source/cmStateSnapshot.cxx
+++ b/Source/cmStateSnapshot.cxx
@@ -19,6 +19,10 @@
#include "cmSystemTools.h"
#include "cmVersion.h"
+#if defined(__CYGWIN__)
+# include "cmStringAlgorithms.h"
+#endif
+
cmStateSnapshot::cmStateSnapshot(cmState* state)
: State(state)
{
@@ -201,8 +205,7 @@ bool cmStateSnapshot::HasDefinedPolicyCMP0011()
return !this->Position->Policies->IsEmpty();
}
-std::string const* cmStateSnapshot::GetDefinition(
- std::string const& name) const
+cmProp cmStateSnapshot::GetDefinition(std::string const& name) const
{
assert(this->Position->Vars.IsValid());
return cmDefinitions::Get(name, this->Position->Vars, this->Position->Root);
@@ -260,12 +263,10 @@ bool cmStateSnapshot::RaiseScope(std::string const& var, const char* varDef)
return true;
}
-template <typename T, typename U, typename V>
+template <typename T, typename U>
void InitializeContentFromParent(T& parentContent, T& thisContent,
- U& parentBacktraces, U& thisBacktraces,
- V& contentEndPosition)
+ U& contentEndPosition)
{
- auto parentBegin = parentContent.begin();
auto parentEnd = parentContent.end();
auto parentRbegin = cm::make_reverse_iterator(parentEnd);
@@ -273,12 +274,7 @@ void InitializeContentFromParent(T& parentContent, T& thisContent,
parentRbegin = std::find(parentRbegin, parentRend, cmPropertySentinal);
auto parentIt = parentRbegin.base();
- thisContent = std::vector<std::string>(parentIt, parentEnd);
-
- auto btIt = parentBacktraces.begin() + std::distance(parentBegin, parentIt);
- auto btEnd = parentBacktraces.end();
-
- thisBacktraces = std::vector<cmListFileBacktrace>(btIt, btEnd);
+ thisContent = std::vector<BT<std::string>>(parentIt, parentEnd);
contentEndPosition = thisContent.size();
}
@@ -360,43 +356,33 @@ void cmStateSnapshot::InitializeFromParent()
InitializeContentFromParent(
parent->BuildSystemDirectory->IncludeDirectories,
this->Position->BuildSystemDirectory->IncludeDirectories,
- parent->BuildSystemDirectory->IncludeDirectoryBacktraces,
- this->Position->BuildSystemDirectory->IncludeDirectoryBacktraces,
this->Position->IncludeDirectoryPosition);
InitializeContentFromParent(
parent->BuildSystemDirectory->CompileDefinitions,
this->Position->BuildSystemDirectory->CompileDefinitions,
- parent->BuildSystemDirectory->CompileDefinitionsBacktraces,
- this->Position->BuildSystemDirectory->CompileDefinitionsBacktraces,
this->Position->CompileDefinitionsPosition);
InitializeContentFromParent(
parent->BuildSystemDirectory->CompileOptions,
this->Position->BuildSystemDirectory->CompileOptions,
- parent->BuildSystemDirectory->CompileOptionsBacktraces,
- this->Position->BuildSystemDirectory->CompileOptionsBacktraces,
this->Position->CompileOptionsPosition);
InitializeContentFromParent(
parent->BuildSystemDirectory->LinkOptions,
this->Position->BuildSystemDirectory->LinkOptions,
- parent->BuildSystemDirectory->LinkOptionsBacktraces,
- this->Position->BuildSystemDirectory->LinkOptionsBacktraces,
this->Position->LinkOptionsPosition);
InitializeContentFromParent(
parent->BuildSystemDirectory->LinkDirectories,
this->Position->BuildSystemDirectory->LinkDirectories,
- parent->BuildSystemDirectory->LinkDirectoriesBacktraces,
- this->Position->BuildSystemDirectory->LinkDirectoriesBacktraces,
this->Position->LinkDirectoriesPosition);
cmProp include_regex =
parent->BuildSystemDirectory->Properties.GetPropertyValue(
"INCLUDE_REGULAR_EXPRESSION");
this->Position->BuildSystemDirectory->Properties.SetProperty(
- "INCLUDE_REGULAR_EXPRESSION", cmToCStr(include_regex));
+ "INCLUDE_REGULAR_EXPRESSION", include_regex);
}
cmState* cmStateSnapshot::GetState() const
diff --git a/Source/cmStateSnapshot.h b/Source/cmStateSnapshot.h
index d06cba3..a5fe7e2 100644
--- a/Source/cmStateSnapshot.h
+++ b/Source/cmStateSnapshot.h
@@ -12,6 +12,7 @@
#include "cmLinkedTree.h"
#include "cmPolicies.h"
+#include "cmProperty.h"
#include "cmStateTypes.h"
class cmState;
@@ -23,7 +24,7 @@ public:
cmStateSnapshot(cmState* state = nullptr);
cmStateSnapshot(cmState* state, cmStateDetail::PositionType position);
- std::string const* GetDefinition(std::string const& name) const;
+ cmProp GetDefinition(std::string const& name) const;
bool IsInitialized(std::string const& name) const;
void SetDefinition(std::string const& name, cm::string_view value);
void RemoveDefinition(std::string const& name);
diff --git a/Source/cmStringAlgorithms.cxx b/Source/cmStringAlgorithms.cxx
index 5bb6e7b..acb5e5b 100644
--- a/Source/cmStringAlgorithms.cxx
+++ b/Source/cmStringAlgorithms.cxx
@@ -227,76 +227,6 @@ bool cmIsInternallyOn(cm::string_view val)
(val[3] == 'N' || val[3] == 'n');
}
-bool cmIsNOTFOUND(cm::string_view val)
-{
- return (val == "NOTFOUND") || cmHasLiteralSuffix(val, "-NOTFOUND");
-}
-
-bool cmIsOn(cm::string_view val)
-{
- switch (val.size()) {
- case 1:
- return val[0] == '1' || val[0] == 'Y' || val[0] == 'y';
- case 2:
- return //
- (val[0] == 'O' || val[0] == 'o') && //
- (val[1] == 'N' || val[1] == 'n');
- case 3:
- return //
- (val[0] == 'Y' || val[0] == 'y') && //
- (val[1] == 'E' || val[1] == 'e') && //
- (val[2] == 'S' || val[2] == 's');
- case 4:
- return //
- (val[0] == 'T' || val[0] == 't') && //
- (val[1] == 'R' || val[1] == 'r') && //
- (val[2] == 'U' || val[2] == 'u') && //
- (val[3] == 'E' || val[3] == 'e');
- default:
- break;
- }
-
- return false;
-}
-
-bool cmIsOff(cm::string_view val)
-{
- switch (val.size()) {
- case 0:
- return true;
- case 1:
- return val[0] == '0' || val[0] == 'N' || val[0] == 'n';
- case 2:
- return //
- (val[0] == 'N' || val[0] == 'n') && //
- (val[1] == 'O' || val[1] == 'o');
- case 3:
- return //
- (val[0] == 'O' || val[0] == 'o') && //
- (val[1] == 'F' || val[1] == 'f') && //
- (val[2] == 'F' || val[2] == 'f');
- case 5:
- return //
- (val[0] == 'F' || val[0] == 'f') && //
- (val[1] == 'A' || val[1] == 'a') && //
- (val[2] == 'L' || val[2] == 'l') && //
- (val[3] == 'S' || val[3] == 's') && //
- (val[4] == 'E' || val[4] == 'e');
- case 6:
- return //
- (val[0] == 'I' || val[0] == 'i') && //
- (val[1] == 'G' || val[1] == 'g') && //
- (val[2] == 'N' || val[2] == 'n') && //
- (val[3] == 'O' || val[3] == 'o') && //
- (val[4] == 'R' || val[4] == 'r') && //
- (val[5] == 'E' || val[5] == 'e');
- default:
- break;
- }
-
- return cmIsNOTFOUND(val);
-}
-
bool cmStrToLong(const char* str, long* value)
{
errno = 0;
diff --git a/Source/cmStringAlgorithms.h b/Source/cmStringAlgorithms.h
index 6b458ec..20061e9 100644
--- a/Source/cmStringAlgorithms.h
+++ b/Source/cmStringAlgorithms.h
@@ -14,25 +14,12 @@
#include <cm/string_view>
+#include "cmProperty.h"
#include "cmRange.h"
/** String range type. */
using cmStringRange = cmRange<std::vector<std::string>::const_iterator>;
-/** Check for non-empty string. */
-inline bool cmNonempty(const char* str)
-{
- return str && *str;
-}
-inline bool cmNonempty(cm::string_view str)
-{
- return !str.empty();
-}
-inline bool cmNonempty(std::string const* str)
-{
- return str && !str->empty();
-}
-
/** Returns length of a literal string. */
template <size_t N>
constexpr size_t cmStrLen(const char (&/*str*/)[N])
@@ -175,6 +162,10 @@ public:
cmAlphaNum(unsigned long long int val);
cmAlphaNum(float val);
cmAlphaNum(double val);
+ cmAlphaNum(cmProp value)
+ : View_(*value)
+ {
+ }
cm::string_view View() const { return this->View_; }
@@ -227,20 +218,44 @@ inline bool cmIsInternallyOn(const char* val)
return cmIsInternallyOn(cm::string_view(val));
}
+/** Check for non-empty Property/Variable value. */
+inline bool cmNonempty(cm::string_view val)
+{
+ return !cmProp::IsEmpty(val);
+}
+inline bool cmNonempty(const char* val)
+{
+ return !cmProp::IsEmpty(val);
+}
+inline bool cmNonempty(cmProp val)
+{
+ return !val.IsEmpty();
+}
+
/** Return true if value is NOTFOUND or ends in -NOTFOUND. */
-bool cmIsNOTFOUND(cm::string_view val);
+inline bool cmIsNOTFOUND(cm::string_view val)
+{
+ return cmProp::IsNOTFOUND(val);
+}
+inline bool cmIsNOTFOUND(cmProp val)
+{
+ return val.IsNOTFOUND();
+}
/**
* Does a string indicate a true or ON value? This is not the same as ifdef.
*/
-bool cmIsOn(cm::string_view val);
+inline bool cmIsOn(cm::string_view val)
+{
+ return cmProp::IsOn(val);
+}
inline bool cmIsOn(const char* val)
{
- return val && cmIsOn(cm::string_view(val));
+ return cmProp::IsOn(val);
}
-inline bool cmIsOn(std::string const* val)
+inline bool cmIsOn(cmProp val)
{
- return val && cmIsOn(*val);
+ return val.IsOn();
}
/**
@@ -250,14 +265,17 @@ inline bool cmIsOn(std::string const* val)
* IsON and IsOff both returning false. Note that the special path
* NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
*/
-bool cmIsOff(cm::string_view val);
+inline bool cmIsOff(cm::string_view val)
+{
+ return cmProp::IsOff(val);
+}
inline bool cmIsOff(const char* val)
{
- return !val || cmIsOff(cm::string_view(val));
+ return cmProp::IsOff(val);
}
-inline bool cmIsOff(std::string const* val)
+inline bool cmIsOff(cmProp val)
{
- return !val || cmIsOff(*val);
+ return val.IsOff();
}
/** Returns true if string @a str starts with the character @a prefix. */
@@ -273,6 +291,16 @@ inline bool cmHasPrefix(cm::string_view str, cm::string_view prefix)
}
/** Returns true if string @a str starts with string @a prefix. */
+inline bool cmHasPrefix(cm::string_view str, cmProp prefix)
+{
+ if (!prefix) {
+ return false;
+ }
+
+ return str.compare(0, prefix->size(), prefix) == 0;
+}
+
+/** Returns true if string @a str starts with string @a prefix. */
template <size_t N>
inline bool cmHasLiteralPrefix(cm::string_view str, const char (&prefix)[N])
{
@@ -293,6 +321,17 @@ inline bool cmHasSuffix(cm::string_view str, cm::string_view suffix)
}
/** Returns true if string @a str ends with string @a suffix. */
+inline bool cmHasSuffix(cm::string_view str, cmProp suffix)
+{
+ if (!suffix) {
+ return false;
+ }
+
+ return str.size() >= suffix->size() &&
+ str.compare(str.size() - suffix->size(), suffix->size(), suffix) == 0;
+}
+
+/** Returns true if string @a str ends with string @a suffix. */
template <size_t N>
inline bool cmHasLiteralSuffix(cm::string_view str, const char (&suffix)[N])
{
diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx
index f082ae8..54fe7a1 100644
--- a/Source/cmSystemTools.cxx
+++ b/Source/cmSystemTools.cxx
@@ -1629,7 +1629,10 @@ bool cmSystemTools::CreateTar(const std::string& outFileName,
cmArchiveWrite a(fout, compress, format.empty() ? "paxr" : format,
compressionLevel);
- a.Open();
+ if (!a.Open()) {
+ cmSystemTools::Error(a.GetError());
+ return false;
+ }
a.SetMTime(mtime);
a.SetVerbose(verbose);
bool tarCreatedSuccessfully = true;
diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx
index 70e11a2..af64dce 100644
--- a/Source/cmTarget.cxx
+++ b/Source/cmTarget.cxx
@@ -83,15 +83,15 @@ cmProp cmTargetPropertyComputer::GetSources<cmTarget>(
cmTarget const* tgt, cmMessenger* messenger,
cmListFileBacktrace const& context)
{
- cmStringRange entries = tgt->GetSourceEntries();
+ cmBTStringRange entries = tgt->GetSourceEntries();
if (entries.empty()) {
return nullptr;
}
std::ostringstream ss;
const char* sep = "";
- for (std::string const& entry : entries) {
- std::vector<std::string> files = cmExpandedList(entry);
+ for (auto const& entry : entries) {
+ std::vector<std::string> files = cmExpandedList(entry.Value);
for (std::string const& file : files) {
if (cmHasLiteralPrefix(file, "$<TARGET_OBJECTS:") &&
file.back() == '>') {
@@ -157,7 +157,7 @@ cmProp cmTargetPropertyComputer::GetSources<cmTarget>(
}
static std::string srcs;
srcs = ss.str();
- return &srcs;
+ return cmProp(srcs);
}
class cmTargetInternals
@@ -187,25 +187,16 @@ public:
std::set<std::string> SystemIncludeDirectories;
cmTarget::LinkLibraryVectorType OriginalLinkLibraries;
std::map<std::string, BTs<std::string>> LanguageStandardProperties;
- std::vector<std::string> IncludeDirectoriesEntries;
- std::vector<cmListFileBacktrace> IncludeDirectoriesBacktraces;
+ std::vector<BT<std::string>> IncludeDirectoriesEntries;
std::vector<std::string> InstallIncludeDirectoriesEntries;
- std::vector<std::string> CompileOptionsEntries;
- std::vector<cmListFileBacktrace> CompileOptionsBacktraces;
- std::vector<std::string> CompileFeaturesEntries;
- std::vector<cmListFileBacktrace> CompileFeaturesBacktraces;
- std::vector<std::string> CompileDefinitionsEntries;
- std::vector<cmListFileBacktrace> CompileDefinitionsBacktraces;
- std::vector<std::string> PrecompileHeadersEntries;
- std::vector<cmListFileBacktrace> PrecompileHeadersBacktraces;
- std::vector<std::string> SourceEntries;
- std::vector<cmListFileBacktrace> SourceBacktraces;
- std::vector<std::string> LinkOptionsEntries;
- std::vector<cmListFileBacktrace> LinkOptionsBacktraces;
- std::vector<std::string> LinkDirectoriesEntries;
- std::vector<cmListFileBacktrace> LinkDirectoriesBacktraces;
- std::vector<std::string> LinkImplementationPropertyEntries;
- std::vector<cmListFileBacktrace> LinkImplementationPropertyBacktraces;
+ std::vector<BT<std::string>> CompileOptionsEntries;
+ std::vector<BT<std::string>> CompileFeaturesEntries;
+ std::vector<BT<std::string>> CompileDefinitionsEntries;
+ std::vector<BT<std::string>> PrecompileHeadersEntries;
+ std::vector<BT<std::string>> SourceEntries;
+ std::vector<BT<std::string>> LinkOptionsEntries;
+ std::vector<BT<std::string>> LinkDirectoriesEntries;
+ std::vector<BT<std::string>> LinkImplementationPropertyEntries;
std::vector<std::pair<cmTarget::TLLSignature, cmListFileContext>>
TLLCommands;
cmListFileBacktrace Backtrace;
@@ -267,7 +258,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
// Replace everything after "CMAKE_"
defKey.replace(defKey.begin() + 6, defKey.end(), property);
if (cmProp value = mf->GetDefinition(defKey)) {
- this->SetProperty(property, *value);
+ this->SetProperty(property, value);
}
};
auto initPropValue = [this, mf, &defKey](const std::string& property,
@@ -275,7 +266,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
// Replace everything after "CMAKE_"
defKey.replace(defKey.begin() + 6, defKey.end(), property);
if (cmProp value = mf->GetDefinition(defKey)) {
- this->SetProperty(property, *value);
+ this->SetProperty(property, value);
} else if (default_value) {
this->SetProperty(property, default_value);
}
@@ -482,8 +473,6 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
// of the same directory property:
cm::append(this->impl->IncludeDirectoriesEntries,
this->impl->Makefile->GetIncludeDirectoriesEntries());
- cm::append(this->impl->IncludeDirectoriesBacktraces,
- this->impl->Makefile->GetIncludeDirectoriesBacktraces());
{
auto const& sysInc = this->impl->Makefile->GetSystemIncludeDirectories();
@@ -493,18 +482,12 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
cm::append(this->impl->CompileOptionsEntries,
this->impl->Makefile->GetCompileOptionsEntries());
- cm::append(this->impl->CompileOptionsBacktraces,
- this->impl->Makefile->GetCompileOptionsBacktraces());
cm::append(this->impl->LinkOptionsEntries,
this->impl->Makefile->GetLinkOptionsEntries());
- cm::append(this->impl->LinkOptionsBacktraces,
- this->impl->Makefile->GetLinkOptionsBacktraces());
cm::append(this->impl->LinkDirectoriesEntries,
this->impl->Makefile->GetLinkDirectoriesEntries());
- cm::append(this->impl->LinkDirectoriesBacktraces,
- this->impl->Makefile->GetLinkDirectoriesBacktraces());
}
if (this->impl->TargetType == cmStateEnums::EXECUTABLE) {
@@ -613,11 +596,9 @@ void cmTarget::SetLanguageStandardProperty(std::string const& lang,
const std::string& feature)
{
cmListFileBacktrace featureBacktrace;
- for (size_t i = 0; i < this->impl->CompileFeaturesEntries.size(); i++) {
- if (this->impl->CompileFeaturesEntries[i] == feature) {
- if (i < this->impl->CompileFeaturesBacktraces.size()) {
- featureBacktrace = this->impl->CompileFeaturesBacktraces[i];
- }
+ for (auto const& entry : this->impl->CompileFeaturesEntries) {
+ if (entry.Value == feature) {
+ featureBacktrace = entry.Backtrace;
break;
}
}
@@ -729,8 +710,7 @@ void cmTarget::AddTracedSources(std::vector<std::string> const& srcs)
{
if (!srcs.empty()) {
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->SourceEntries.push_back(cmJoin(srcs, ";"));
- this->impl->SourceBacktraces.push_back(lfbt);
+ this->impl->SourceEntries.emplace_back(cmJoin(srcs, ";"), lfbt);
}
}
@@ -754,8 +734,7 @@ void cmTarget::AddSources(std::vector<std::string> const& srcs)
}
if (!srcFiles.empty()) {
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->SourceEntries.push_back(std::move(srcFiles));
- this->impl->SourceBacktraces.push_back(lfbt);
+ this->impl->SourceEntries.emplace_back(std::move(srcFiles), lfbt);
}
}
@@ -843,9 +822,9 @@ public:
{
}
- bool operator()(std::string const& entry)
+ bool operator()(BT<std::string> const& entry)
{
- std::vector<std::string> files = cmExpandedList(entry);
+ std::vector<std::string> files = cmExpandedList(entry.Value);
std::vector<cmSourceFileLocation> locations;
locations.reserve(files.size());
std::transform(files.begin(), files.end(), std::back_inserter(locations),
@@ -866,11 +845,7 @@ cmSourceFile* cmTarget::AddSource(const std::string& src, bool before)
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
this->impl->SourceEntries.insert(before ? this->impl->SourceEntries.begin()
: this->impl->SourceEntries.end(),
- src);
- this->impl->SourceBacktraces.insert(
- before ? this->impl->SourceBacktraces.begin()
- : this->impl->SourceBacktraces.end(),
- lfbt);
+ BT<std::string>(src, lfbt));
}
if (cmGeneratorExpression::Find(src) != std::string::npos) {
return nullptr;
@@ -1087,122 +1062,104 @@ cmStringRange cmTarget::GetInstallIncludeDirectoriesEntries() const
return cmMakeRange(this->impl->InstallIncludeDirectoriesEntries);
}
-cmStringRange cmTarget::GetIncludeDirectoriesEntries() const
+cmBTStringRange cmTarget::GetIncludeDirectoriesEntries() const
{
return cmMakeRange(this->impl->IncludeDirectoriesEntries);
}
-cmBacktraceRange cmTarget::GetIncludeDirectoriesBacktraces() const
-{
- return cmMakeRange(this->impl->IncludeDirectoriesBacktraces);
-}
-
-cmStringRange cmTarget::GetCompileOptionsEntries() const
+cmBTStringRange cmTarget::GetCompileOptionsEntries() const
{
return cmMakeRange(this->impl->CompileOptionsEntries);
}
-cmBacktraceRange cmTarget::GetCompileOptionsBacktraces() const
-{
- return cmMakeRange(this->impl->CompileOptionsBacktraces);
-}
-
-cmStringRange cmTarget::GetCompileFeaturesEntries() const
+cmBTStringRange cmTarget::GetCompileFeaturesEntries() const
{
return cmMakeRange(this->impl->CompileFeaturesEntries);
}
-cmBacktraceRange cmTarget::GetCompileFeaturesBacktraces() const
-{
- return cmMakeRange(this->impl->CompileFeaturesBacktraces);
-}
-
-cmStringRange cmTarget::GetCompileDefinitionsEntries() const
+cmBTStringRange cmTarget::GetCompileDefinitionsEntries() const
{
return cmMakeRange(this->impl->CompileDefinitionsEntries);
}
-cmBacktraceRange cmTarget::GetCompileDefinitionsBacktraces() const
-{
- return cmMakeRange(this->impl->CompileDefinitionsBacktraces);
-}
-
-cmStringRange cmTarget::GetPrecompileHeadersEntries() const
+cmBTStringRange cmTarget::GetPrecompileHeadersEntries() const
{
return cmMakeRange(this->impl->PrecompileHeadersEntries);
}
-cmBacktraceRange cmTarget::GetPrecompileHeadersBacktraces() const
-{
- return cmMakeRange(this->impl->PrecompileHeadersBacktraces);
-}
-
-cmStringRange cmTarget::GetSourceEntries() const
+cmBTStringRange cmTarget::GetSourceEntries() const
{
return cmMakeRange(this->impl->SourceEntries);
}
-cmBacktraceRange cmTarget::GetSourceBacktraces() const
-{
- return cmMakeRange(this->impl->SourceBacktraces);
-}
-
-cmStringRange cmTarget::GetLinkOptionsEntries() const
+cmBTStringRange cmTarget::GetLinkOptionsEntries() const
{
return cmMakeRange(this->impl->LinkOptionsEntries);
}
-cmBacktraceRange cmTarget::GetLinkOptionsBacktraces() const
+cmBTStringRange cmTarget::GetLinkDirectoriesEntries() const
{
- return cmMakeRange(this->impl->LinkOptionsBacktraces);
+ return cmMakeRange(this->impl->LinkDirectoriesEntries);
}
-cmStringRange cmTarget::GetLinkDirectoriesEntries() const
+cmBTStringRange cmTarget::GetLinkImplementationEntries() const
{
- return cmMakeRange(this->impl->LinkDirectoriesEntries);
+ return cmMakeRange(this->impl->LinkImplementationPropertyEntries);
}
-cmBacktraceRange cmTarget::GetLinkDirectoriesBacktraces() const
-{
- return cmMakeRange(this->impl->LinkDirectoriesBacktraces);
+namespace {
+#define MAKE_PROP(PROP) const std::string prop##PROP = #PROP
+MAKE_PROP(C_STANDARD);
+MAKE_PROP(CXX_STANDARD);
+MAKE_PROP(CUDA_STANDARD);
+MAKE_PROP(HIP_STANDARD);
+MAKE_PROP(OBJC_STANDARD);
+MAKE_PROP(OBJCXX_STANDARD);
+MAKE_PROP(COMPILE_DEFINITIONS);
+MAKE_PROP(COMPILE_FEATURES);
+MAKE_PROP(COMPILE_OPTIONS);
+MAKE_PROP(PRECOMPILE_HEADERS);
+MAKE_PROP(PRECOMPILE_HEADERS_REUSE_FROM);
+MAKE_PROP(CUDA_PTX_COMPILATION);
+MAKE_PROP(EXPORT_NAME);
+MAKE_PROP(IMPORTED);
+MAKE_PROP(IMPORTED_GLOBAL);
+MAKE_PROP(INCLUDE_DIRECTORIES);
+MAKE_PROP(LINK_OPTIONS);
+MAKE_PROP(LINK_DIRECTORIES);
+MAKE_PROP(LINK_LIBRARIES);
+MAKE_PROP(MANUALLY_ADDED_DEPENDENCIES);
+MAKE_PROP(NAME);
+MAKE_PROP(SOURCES);
+MAKE_PROP(TYPE);
+MAKE_PROP(BINARY_DIR);
+MAKE_PROP(SOURCE_DIR);
+MAKE_PROP(FALSE);
+MAKE_PROP(TRUE);
+#undef MAKE_PROP
}
-cmStringRange cmTarget::GetLinkImplementationEntries() const
+namespace {
+// to workaround bug on GCC/AIX
+// Define a template to force conversion to std::string
+template <typename ValueType>
+std::string ConvertToString(ValueType value);
+
+template <>
+std::string ConvertToString<const char*>(const char* value)
{
- return cmMakeRange(this->impl->LinkImplementationPropertyEntries);
+ return std::string(value);
}
-
-cmBacktraceRange cmTarget::GetLinkImplementationBacktraces() const
+template <>
+std::string ConvertToString<cmProp>(cmProp value)
{
- return cmMakeRange(this->impl->LinkImplementationPropertyBacktraces);
+ return std::string(*value);
+}
}
-void cmTarget::SetProperty(const std::string& prop, const char* value)
+template <typename ValueType>
+void cmTarget::StoreProperty(const std::string& prop, ValueType value)
{
-#define MAKE_STATIC_PROP(PROP) static const std::string prop##PROP = #PROP
- MAKE_STATIC_PROP(C_STANDARD);
- MAKE_STATIC_PROP(CXX_STANDARD);
- MAKE_STATIC_PROP(CUDA_STANDARD);
- MAKE_STATIC_PROP(HIP_STANDARD);
- MAKE_STATIC_PROP(OBJC_STANDARD);
- MAKE_STATIC_PROP(OBJCXX_STANDARD);
- MAKE_STATIC_PROP(COMPILE_DEFINITIONS);
- MAKE_STATIC_PROP(COMPILE_FEATURES);
- MAKE_STATIC_PROP(COMPILE_OPTIONS);
- MAKE_STATIC_PROP(PRECOMPILE_HEADERS);
- MAKE_STATIC_PROP(PRECOMPILE_HEADERS_REUSE_FROM);
- MAKE_STATIC_PROP(CUDA_PTX_COMPILATION);
- MAKE_STATIC_PROP(EXPORT_NAME);
- MAKE_STATIC_PROP(IMPORTED_GLOBAL);
- MAKE_STATIC_PROP(INCLUDE_DIRECTORIES);
- MAKE_STATIC_PROP(LINK_OPTIONS);
- MAKE_STATIC_PROP(LINK_DIRECTORIES);
- MAKE_STATIC_PROP(LINK_LIBRARIES);
- MAKE_STATIC_PROP(MANUALLY_ADDED_DEPENDENCIES);
- MAKE_STATIC_PROP(NAME);
- MAKE_STATIC_PROP(SOURCES);
- MAKE_STATIC_PROP(TYPE);
-#undef MAKE_STATIC_PROP
if (prop == propMANUALLY_ADDED_DEPENDENCIES) {
this->impl->Makefile->IssueMessage(
MessageType::FATAL_ERROR,
@@ -1243,75 +1200,57 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
if (prop == propINCLUDE_DIRECTORIES) {
this->impl->IncludeDirectoriesEntries.clear();
- this->impl->IncludeDirectoriesBacktraces.clear();
if (value) {
- this->impl->IncludeDirectoriesEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->IncludeDirectoriesBacktraces.push_back(lfbt);
+ this->impl->IncludeDirectoriesEntries.emplace_back(value, lfbt);
}
} else if (prop == propCOMPILE_OPTIONS) {
this->impl->CompileOptionsEntries.clear();
- this->impl->CompileOptionsBacktraces.clear();
if (value) {
- this->impl->CompileOptionsEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->CompileOptionsBacktraces.push_back(lfbt);
+ this->impl->CompileOptionsEntries.emplace_back(value, lfbt);
}
} else if (prop == propCOMPILE_FEATURES) {
this->impl->CompileFeaturesEntries.clear();
- this->impl->CompileFeaturesBacktraces.clear();
if (value) {
- this->impl->CompileFeaturesEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->CompileFeaturesBacktraces.push_back(lfbt);
+ this->impl->CompileFeaturesEntries.emplace_back(value, lfbt);
}
} else if (prop == propCOMPILE_DEFINITIONS) {
this->impl->CompileDefinitionsEntries.clear();
- this->impl->CompileDefinitionsBacktraces.clear();
if (value) {
- this->impl->CompileDefinitionsEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->CompileDefinitionsBacktraces.push_back(lfbt);
+ this->impl->CompileDefinitionsEntries.emplace_back(value, lfbt);
}
} else if (prop == propLINK_OPTIONS) {
this->impl->LinkOptionsEntries.clear();
- this->impl->LinkOptionsBacktraces.clear();
if (value) {
- this->impl->LinkOptionsEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->LinkOptionsBacktraces.push_back(lfbt);
+ this->impl->LinkOptionsEntries.emplace_back(value, lfbt);
}
} else if (prop == propLINK_DIRECTORIES) {
this->impl->LinkDirectoriesEntries.clear();
- this->impl->LinkDirectoriesBacktraces.clear();
if (value) {
- this->impl->LinkDirectoriesEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->LinkDirectoriesBacktraces.push_back(lfbt);
+ this->impl->LinkDirectoriesEntries.emplace_back(value, lfbt);
}
} else if (prop == propPRECOMPILE_HEADERS) {
this->impl->PrecompileHeadersEntries.clear();
- this->impl->PrecompileHeadersBacktraces.clear();
if (value) {
- this->impl->PrecompileHeadersEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->PrecompileHeadersBacktraces.push_back(lfbt);
+ this->impl->PrecompileHeadersEntries.emplace_back(value, lfbt);
}
} else if (prop == propLINK_LIBRARIES) {
this->impl->LinkImplementationPropertyEntries.clear();
- this->impl->LinkImplementationPropertyBacktraces.clear();
if (value) {
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->LinkImplementationPropertyEntries.emplace_back(value);
- this->impl->LinkImplementationPropertyBacktraces.push_back(lfbt);
+ this->impl->LinkImplementationPropertyEntries.emplace_back(value, lfbt);
}
} else if (prop == propSOURCES) {
this->impl->SourceEntries.clear();
- this->impl->SourceBacktraces.clear();
if (value) {
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->SourceEntries.emplace_back(value);
- this->impl->SourceBacktraces.push_back(lfbt);
+ this->impl->SourceEntries.emplace_back(value, lfbt);
}
} else if (prop == propIMPORTED_GLOBAL) {
if (!cmIsOn(value)) {
@@ -1327,7 +1266,8 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
this->GetGlobalGenerator()->IndexTarget(this);
}
} else if (cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME") &&
- !this->impl->CheckImportedLibName(prop, value ? value : "")) {
+ !this->impl->CheckImportedLibName(
+ prop, value ? value : std::string{})) {
/* error was reported by check method */
} else if (prop == propCUDA_PTX_COMPILATION &&
this->GetType() != cmStateEnums::OBJECT_LIBRARY) {
@@ -1357,17 +1297,17 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
std::string reusedFrom = reusedTarget->GetSafeProperty(prop);
if (reusedFrom.empty()) {
- reusedFrom = value;
+ reusedFrom = ConvertToString(value);
}
- this->impl->Properties.SetProperty(prop, reusedFrom.c_str());
+ this->impl->Properties.SetProperty(prop, reusedFrom);
reusedTarget->SetProperty("COMPILE_PDB_NAME", reusedFrom);
reusedTarget->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
cmStrCat(reusedFrom, ".dir/"));
cmProp tmp = reusedTarget->GetProperty("COMPILE_PDB_NAME");
- this->SetProperty("COMPILE_PDB_NAME", cmToCStr(tmp));
+ this->SetProperty("COMPILE_PDB_NAME", tmp);
this->AddUtility(reusedFrom, false, this->impl->Makefile);
} else if (prop == propC_STANDARD || prop == propCXX_STANDARD ||
prop == propCUDA_STANDARD || prop == propHIP_STANDARD ||
@@ -1415,39 +1355,33 @@ void cmTarget::AppendProperty(const std::string& prop,
}
if (prop == "INCLUDE_DIRECTORIES") {
if (!value.empty()) {
- this->impl->IncludeDirectoriesEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->IncludeDirectoriesBacktraces.push_back(lfbt);
+ this->impl->IncludeDirectoriesEntries.emplace_back(value, lfbt);
}
} else if (prop == "COMPILE_OPTIONS") {
if (!value.empty()) {
- this->impl->CompileOptionsEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->CompileOptionsBacktraces.push_back(lfbt);
+ this->impl->CompileOptionsEntries.emplace_back(value, lfbt);
}
} else if (prop == "COMPILE_FEATURES") {
if (!value.empty()) {
- this->impl->CompileFeaturesEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->CompileFeaturesBacktraces.push_back(lfbt);
+ this->impl->CompileFeaturesEntries.emplace_back(value, lfbt);
}
} else if (prop == "COMPILE_DEFINITIONS") {
if (!value.empty()) {
- this->impl->CompileDefinitionsEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->CompileDefinitionsBacktraces.push_back(lfbt);
+ this->impl->CompileDefinitionsEntries.emplace_back(value, lfbt);
}
} else if (prop == "LINK_OPTIONS") {
if (!value.empty()) {
- this->impl->LinkOptionsEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->LinkOptionsBacktraces.push_back(lfbt);
+ this->impl->LinkOptionsEntries.emplace_back(value, lfbt);
}
} else if (prop == "LINK_DIRECTORIES") {
if (!value.empty()) {
- this->impl->LinkDirectoriesEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->LinkDirectoriesBacktraces.push_back(lfbt);
+ this->impl->LinkDirectoriesEntries.emplace_back(value, lfbt);
}
} else if (prop == "PRECOMPILE_HEADERS") {
if (this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM")) {
@@ -1459,20 +1393,17 @@ void cmTarget::AppendProperty(const std::string& prop,
return;
}
if (!value.empty()) {
- this->impl->PrecompileHeadersEntries.emplace_back(value);
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->PrecompileHeadersBacktraces.push_back(lfbt);
+ this->impl->PrecompileHeadersEntries.emplace_back(value, lfbt);
}
} else if (prop == "LINK_LIBRARIES") {
if (!value.empty()) {
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->LinkImplementationPropertyEntries.emplace_back(value);
- this->impl->LinkImplementationPropertyBacktraces.push_back(lfbt);
+ this->impl->LinkImplementationPropertyEntries.emplace_back(value, lfbt);
}
} else if (prop == "SOURCES") {
cmListFileBacktrace lfbt = this->impl->Makefile->GetBacktrace();
- this->impl->SourceEntries.emplace_back(value);
- this->impl->SourceBacktraces.push_back(lfbt);
+ this->impl->SourceEntries.emplace_back(value, lfbt);
} else if (cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME")) {
this->impl->Makefile->IssueMessage(
MessageType::FATAL_ERROR, prop + " property may not be APPENDed.");
@@ -1486,6 +1417,15 @@ void cmTarget::AppendProperty(const std::string& prop,
}
}
+void cmTarget::SetProperty(const std::string& prop, const char* value)
+{
+ this->StoreProperty(prop, value);
+}
+void cmTarget::SetProperty(const std::string& prop, cmProp value)
+{
+ this->StoreProperty(prop, value);
+}
+
void cmTarget::AppendBuildInterfaceIncludes()
{
if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
@@ -1513,70 +1453,46 @@ void cmTarget::AppendBuildInterfaceIncludes()
}
}
-void cmTarget::InsertInclude(std::string const& entry,
- cmListFileBacktrace const& bt, bool before)
+void cmTarget::InsertInclude(BT<std::string> const& entry, bool before)
{
auto position = before ? this->impl->IncludeDirectoriesEntries.begin()
: this->impl->IncludeDirectoriesEntries.end();
- auto btPosition = before ? this->impl->IncludeDirectoriesBacktraces.begin()
- : this->impl->IncludeDirectoriesBacktraces.end();
-
this->impl->IncludeDirectoriesEntries.insert(position, entry);
- this->impl->IncludeDirectoriesBacktraces.insert(btPosition, bt);
}
-void cmTarget::InsertCompileOption(std::string const& entry,
- cmListFileBacktrace const& bt, bool before)
+void cmTarget::InsertCompileOption(BT<std::string> const& entry, bool before)
{
auto position = before ? this->impl->CompileOptionsEntries.begin()
: this->impl->CompileOptionsEntries.end();
- auto btPosition = before ? this->impl->CompileOptionsBacktraces.begin()
- : this->impl->CompileOptionsBacktraces.end();
-
this->impl->CompileOptionsEntries.insert(position, entry);
- this->impl->CompileOptionsBacktraces.insert(btPosition, bt);
}
-void cmTarget::InsertCompileDefinition(std::string const& entry,
- cmListFileBacktrace const& bt)
+void cmTarget::InsertCompileDefinition(BT<std::string> const& entry)
{
this->impl->CompileDefinitionsEntries.push_back(entry);
- this->impl->CompileDefinitionsBacktraces.push_back(bt);
}
-void cmTarget::InsertLinkOption(std::string const& entry,
- cmListFileBacktrace const& bt, bool before)
+void cmTarget::InsertLinkOption(BT<std::string> const& entry, bool before)
{
auto position = before ? this->impl->LinkOptionsEntries.begin()
: this->impl->LinkOptionsEntries.end();
- auto btPosition = before ? this->impl->LinkOptionsBacktraces.begin()
- : this->impl->LinkOptionsBacktraces.end();
-
this->impl->LinkOptionsEntries.insert(position, entry);
- this->impl->LinkOptionsBacktraces.insert(btPosition, bt);
}
-void cmTarget::InsertLinkDirectory(std::string const& entry,
- cmListFileBacktrace const& bt, bool before)
+void cmTarget::InsertLinkDirectory(BT<std::string> const& entry, bool before)
{
auto position = before ? this->impl->LinkDirectoriesEntries.begin()
: this->impl->LinkDirectoriesEntries.end();
- auto btPosition = before ? this->impl->LinkDirectoriesBacktraces.begin()
- : this->impl->LinkDirectoriesBacktraces.end();
-
this->impl->LinkDirectoriesEntries.insert(position, entry);
- this->impl->LinkDirectoriesBacktraces.insert(btPosition, bt);
}
-void cmTarget::InsertPrecompileHeader(std::string const& entry,
- cmListFileBacktrace const& bt)
+void cmTarget::InsertPrecompileHeader(BT<std::string> const& entry)
{
this->impl->PrecompileHeadersEntries.push_back(entry);
- this->impl->PrecompileHeadersBacktraces.push_back(bt);
}
static void cmTargetCheckLINK_INTERFACE_LIBRARIES(const std::string& prop,
@@ -1693,31 +1609,6 @@ cmProp cmTarget::GetComputedProperty(const std::string& prop,
cmProp cmTarget::GetProperty(const std::string& prop) const
{
-#define MAKE_STATIC_PROP(PROP) static const std::string prop##PROP = #PROP
- MAKE_STATIC_PROP(C_STANDARD);
- MAKE_STATIC_PROP(CXX_STANDARD);
- MAKE_STATIC_PROP(CUDA_STANDARD);
- MAKE_STATIC_PROP(OBJC_STANDARD);
- MAKE_STATIC_PROP(OBJCXX_STANDARD);
- MAKE_STATIC_PROP(LINK_LIBRARIES);
- MAKE_STATIC_PROP(TYPE);
- MAKE_STATIC_PROP(INCLUDE_DIRECTORIES);
- MAKE_STATIC_PROP(COMPILE_FEATURES);
- MAKE_STATIC_PROP(COMPILE_OPTIONS);
- MAKE_STATIC_PROP(COMPILE_DEFINITIONS);
- MAKE_STATIC_PROP(LINK_OPTIONS);
- MAKE_STATIC_PROP(LINK_DIRECTORIES);
- MAKE_STATIC_PROP(PRECOMPILE_HEADERS);
- MAKE_STATIC_PROP(IMPORTED);
- MAKE_STATIC_PROP(IMPORTED_GLOBAL);
- MAKE_STATIC_PROP(MANUALLY_ADDED_DEPENDENCIES);
- MAKE_STATIC_PROP(NAME);
- MAKE_STATIC_PROP(BINARY_DIR);
- MAKE_STATIC_PROP(SOURCE_DIR);
- MAKE_STATIC_PROP(SOURCES);
- MAKE_STATIC_PROP(FALSE);
- MAKE_STATIC_PROP(TRUE);
-#undef MAKE_STATIC_PROP
static std::unordered_set<std::string> const specialProps{
propC_STANDARD,
propCXX_STANDARD,
@@ -1749,7 +1640,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
if (propertyIter == this->impl->LanguageStandardProperties.end()) {
return nullptr;
}
- return &(propertyIter->second.Value);
+ return cmProp(propertyIter->second.Value);
}
if (prop == propLINK_LIBRARIES) {
if (this->impl->LinkImplementationPropertyEntries.empty()) {
@@ -1758,11 +1649,11 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->LinkImplementationPropertyEntries, ";");
- return &output;
+ return cmProp(output);
}
// the type property returns what type the target is
if (prop == propTYPE) {
- return &cmState::GetTargetTypeName(this->GetType());
+ return cmProp(cmState::GetTargetTypeName(this->GetType()));
}
if (prop == propINCLUDE_DIRECTORIES) {
if (this->impl->IncludeDirectoriesEntries.empty()) {
@@ -1771,7 +1662,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->IncludeDirectoriesEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propCOMPILE_FEATURES) {
if (this->impl->CompileFeaturesEntries.empty()) {
@@ -1780,7 +1671,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->CompileFeaturesEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propCOMPILE_OPTIONS) {
if (this->impl->CompileOptionsEntries.empty()) {
@@ -1789,7 +1680,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->CompileOptionsEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propCOMPILE_DEFINITIONS) {
if (this->impl->CompileDefinitionsEntries.empty()) {
@@ -1798,7 +1689,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->CompileDefinitionsEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propLINK_OPTIONS) {
if (this->impl->LinkOptionsEntries.empty()) {
@@ -1807,7 +1698,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->LinkOptionsEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propLINK_DIRECTORIES) {
if (this->impl->LinkDirectoriesEntries.empty()) {
@@ -1817,7 +1708,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->LinkDirectoriesEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propMANUALLY_ADDED_DEPENDENCIES) {
if (this->impl->Utilities.empty()) {
@@ -1834,7 +1725,7 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
return item.Value.first;
});
output = cmJoin(utilities, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propPRECOMPILE_HEADERS) {
if (this->impl->PrecompileHeadersEntries.empty()) {
@@ -1843,26 +1734,27 @@ cmProp cmTarget::GetProperty(const std::string& prop) const
static std::string output;
output = cmJoin(this->impl->PrecompileHeadersEntries, ";");
- return &output;
+ return cmProp(output);
}
if (prop == propIMPORTED) {
- return this->IsImported() ? &propTRUE : &propFALSE;
+ return this->IsImported() ? cmProp(propTRUE) : cmProp(propFALSE);
}
if (prop == propIMPORTED_GLOBAL) {
- return this->IsImportedGloballyVisible() ? &propTRUE : &propFALSE;
+ return this->IsImportedGloballyVisible() ? cmProp(propTRUE)
+ : cmProp(propFALSE);
}
if (prop == propNAME) {
- return &this->GetName();
+ return cmProp(this->GetName());
}
if (prop == propBINARY_DIR) {
- return &this->impl->Makefile->GetStateSnapshot()
- .GetDirectory()
- .GetCurrentBinary();
+ return cmProp(this->impl->Makefile->GetStateSnapshot()
+ .GetDirectory()
+ .GetCurrentBinary());
}
if (prop == propSOURCE_DIR) {
- return &this->impl->Makefile->GetStateSnapshot()
- .GetDirectory()
- .GetCurrentSource();
+ return cmProp(this->impl->Makefile->GetStateSnapshot()
+ .GetDirectory()
+ .GetCurrentSource());
}
}
diff --git a/Source/cmTarget.h b/Source/cmTarget.h
index 29130c7..eced1ae 100644
--- a/Source/cmTarget.h
+++ b/Source/cmTarget.h
@@ -170,9 +170,10 @@ public:
//! Set/Get a property of this target file
void SetProperty(const std::string& prop, const char* value);
+ void SetProperty(const std::string& prop, cmProp value);
void SetProperty(const std::string& prop, const std::string& value)
{
- this->SetProperty(prop, value.c_str());
+ this->SetProperty(prop, cmProp(value));
}
void AppendProperty(const std::string& prop, const std::string& value,
bool asString = false);
@@ -216,18 +217,12 @@ public:
//! Get a backtrace from the creation of the target.
cmListFileBacktrace const& GetBacktrace() const;
- void InsertInclude(std::string const& entry, cmListFileBacktrace const& bt,
- bool before = false);
- void InsertCompileOption(std::string const& entry,
- cmListFileBacktrace const& bt, bool before = false);
- void InsertCompileDefinition(std::string const& entry,
- cmListFileBacktrace const& bt);
- void InsertLinkOption(std::string const& entry,
- cmListFileBacktrace const& bt, bool before = false);
- void InsertLinkDirectory(std::string const& entry,
- cmListFileBacktrace const& bt, bool before = false);
- void InsertPrecompileHeader(std::string const& entry,
- cmListFileBacktrace const& bt);
+ void InsertInclude(BT<std::string> const& entry, bool before = false);
+ void InsertCompileOption(BT<std::string> const& entry, bool before = false);
+ void InsertCompileDefinition(BT<std::string> const& entry);
+ void InsertLinkOption(BT<std::string> const& entry, bool before = false);
+ void InsertLinkDirectory(BT<std::string> const& entry, bool before = false);
+ void InsertPrecompileHeader(BT<std::string> const& entry);
void AppendBuildInterfaceIncludes();
@@ -247,32 +242,23 @@ public:
std::string const& value,
const std::string& feature);
- cmStringRange GetIncludeDirectoriesEntries() const;
- cmBacktraceRange GetIncludeDirectoriesBacktraces() const;
+ cmBTStringRange GetIncludeDirectoriesEntries() const;
- cmStringRange GetCompileOptionsEntries() const;
- cmBacktraceRange GetCompileOptionsBacktraces() const;
+ cmBTStringRange GetCompileOptionsEntries() const;
- cmStringRange GetCompileFeaturesEntries() const;
- cmBacktraceRange GetCompileFeaturesBacktraces() const;
+ cmBTStringRange GetCompileFeaturesEntries() const;
- cmStringRange GetCompileDefinitionsEntries() const;
- cmBacktraceRange GetCompileDefinitionsBacktraces() const;
+ cmBTStringRange GetCompileDefinitionsEntries() const;
- cmStringRange GetPrecompileHeadersEntries() const;
- cmBacktraceRange GetPrecompileHeadersBacktraces() const;
+ cmBTStringRange GetPrecompileHeadersEntries() const;
- cmStringRange GetSourceEntries() const;
- cmBacktraceRange GetSourceBacktraces() const;
+ cmBTStringRange GetSourceEntries() const;
- cmStringRange GetLinkOptionsEntries() const;
- cmBacktraceRange GetLinkOptionsBacktraces() const;
+ cmBTStringRange GetLinkOptionsEntries() const;
- cmStringRange GetLinkDirectoriesEntries() const;
- cmBacktraceRange GetLinkDirectoriesBacktraces() const;
+ cmBTStringRange GetLinkDirectoriesEntries() const;
- cmStringRange GetLinkImplementationEntries() const;
- cmBacktraceRange GetLinkImplementationBacktraces() const;
+ cmBTStringRange GetLinkImplementationEntries() const;
std::string ImportedGetFullPath(const std::string& config,
cmStateEnums::ArtifactType artifact) const;
@@ -283,6 +269,9 @@ public:
};
private:
+ template <typename ValueType>
+ void StoreProperty(const std::string& prop, ValueType value);
+
// Internal representation details.
friend class cmGeneratorTarget;
diff --git a/Source/cmTargetCompileOptionsCommand.cxx b/Source/cmTargetCompileOptionsCommand.cxx
index dee2c10..8ca3842 100644
--- a/Source/cmTargetCompileOptionsCommand.cxx
+++ b/Source/cmTargetCompileOptionsCommand.cxx
@@ -37,7 +37,8 @@ private:
}
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
- tgt->InsertCompileOption(this->Join(content), lfbt, prepend);
+ tgt->InsertCompileOption(BT<std::string>(this->Join(content), lfbt),
+ prepend);
return true; // Successfully handled.
}
diff --git a/Source/cmTargetIncludeDirectoriesCommand.cxx b/Source/cmTargetIncludeDirectoriesCommand.cxx
index 3897499..f31501e 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.cxx
+++ b/Source/cmTargetIncludeDirectoriesCommand.cxx
@@ -63,7 +63,7 @@ bool TargetIncludeDirectoriesImpl::HandleDirectContent(
bool system)
{
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
- tgt->InsertInclude(this->Join(content), lfbt, prepend);
+ tgt->InsertInclude(BT<std::string>(this->Join(content), lfbt), prepend);
if (system) {
std::string prefix = this->Makefile->GetCurrentSourceDirectory() + "/";
std::set<std::string> sdirs;
diff --git a/Source/cmTargetLinkDirectoriesCommand.cxx b/Source/cmTargetLinkDirectoriesCommand.cxx
index 0c68d60..3ba27a8 100644
--- a/Source/cmTargetLinkDirectoriesCommand.cxx
+++ b/Source/cmTargetLinkDirectoriesCommand.cxx
@@ -34,7 +34,8 @@ private:
bool prepend, bool /*system*/) override
{
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
- tgt->InsertLinkDirectory(this->Join(content), lfbt, prepend);
+ tgt->InsertLinkDirectory(BT<std::string>(this->Join(content), lfbt),
+ prepend);
return true; // Successfully handled.
}
};
diff --git a/Source/cmTargetLinkOptionsCommand.cxx b/Source/cmTargetLinkOptionsCommand.cxx
index df9416f..3ea2d71 100644
--- a/Source/cmTargetLinkOptionsCommand.cxx
+++ b/Source/cmTargetLinkOptionsCommand.cxx
@@ -30,7 +30,7 @@ private:
bool prepend, bool /*system*/) override
{
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
- tgt->InsertLinkOption(this->Join(content), lfbt, prepend);
+ tgt->InsertLinkOption(BT<std::string>(this->Join(content), lfbt), prepend);
return true; // Successfully handled.
}
diff --git a/Source/cmTargetPropertyComputer.h b/Source/cmTargetPropertyComputer.h
index f2be318..a749b53 100644
--- a/Source/cmTargetPropertyComputer.h
+++ b/Source/cmTargetPropertyComputer.h
@@ -65,7 +65,7 @@ private:
context)) {
return nullptr;
}
- return &ComputeLocationForBuild(tgt);
+ return cmProp(ComputeLocationForBuild(tgt));
}
// Support "LOCATION_<CONFIG>".
@@ -76,7 +76,7 @@ private:
return nullptr;
}
std::string configName = prop.substr(9);
- return &ComputeLocation(tgt, configName);
+ return cmProp(ComputeLocation(tgt, configName));
}
// Support "<CONFIG>_LOCATION".
@@ -89,7 +89,7 @@ private:
context)) {
return nullptr;
}
- return &ComputeLocation(tgt, configName);
+ return cmProp(ComputeLocation(tgt, configName));
}
}
}
diff --git a/Source/cmTest.cxx b/Source/cmTest.cxx
index a26bef3..9d25ce9 100644
--- a/Source/cmTest.cxx
+++ b/Source/cmTest.cxx
@@ -32,7 +32,7 @@ void cmTest::SetCommand(std::vector<std::string> const& command)
this->Command = command;
}
-const char* cmTest::GetProperty(const std::string& prop) const
+cmProp cmTest::GetProperty(const std::string& prop) const
{
cmProp retVal = this->Properties.GetPropertyValue(prop);
if (!retVal) {
@@ -40,12 +40,12 @@ const char* cmTest::GetProperty(const std::string& prop) const
this->Makefile->GetState()->IsPropertyChained(prop, cmProperty::TEST);
if (chain) {
if (cmProp p = this->Makefile->GetProperty(prop, chain)) {
- return p->c_str();
+ return p;
}
}
return nullptr;
}
- return retVal->c_str();
+ return retVal;
}
bool cmTest::GetPropertyAsBool(const std::string& prop) const
@@ -57,6 +57,10 @@ void cmTest::SetProperty(const std::string& prop, const char* value)
{
this->Properties.SetProperty(prop, value);
}
+void cmTest::SetProperty(const std::string& prop, cmProp value)
+{
+ this->Properties.SetProperty(prop, value);
+}
void cmTest::AppendProperty(const std::string& prop, const std::string& value,
bool asString)
diff --git a/Source/cmTest.h b/Source/cmTest.h
index f33b7e2..a790501 100644
--- a/Source/cmTest.h
+++ b/Source/cmTest.h
@@ -8,6 +8,7 @@
#include <vector>
#include "cmListFileCache.h"
+#include "cmProperty.h"
#include "cmPropertyMap.h"
class cmMakefile;
@@ -34,9 +35,14 @@ public:
//! Set/Get a property of this source file
void SetProperty(const std::string& prop, const char* value);
+ void SetProperty(const std::string& prop, cmProp value);
+ void SetProperty(const std::string& prop, const std::string& value)
+ {
+ this->SetProperty(prop, cmProp(value));
+ }
void AppendProperty(const std::string& prop, const std::string& value,
bool asString = false);
- const char* GetProperty(const std::string& prop) const;
+ cmProp GetProperty(const std::string& prop) const;
bool GetPropertyAsBool(const std::string& prop) const;
cmPropertyMap& GetProperties() { return this->Properties; }
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index 065601b..75fb05f 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -490,10 +490,7 @@ void cmVisualStudio10TargetGenerator::Generate()
e1.Element("Platform", this->Platform);
cmProp projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL");
- if (!projLabel) {
- projLabel = &this->Name;
- }
- e1.Element("ProjectName", *projLabel);
+ e1.Element("ProjectName", projLabel ? projLabel : this->Name);
{
cmProp targetFramework =
this->GeneratorTarget->GetProperty("DOTNET_TARGET_FRAMEWORK");
@@ -511,15 +508,15 @@ void cmVisualStudio10TargetGenerator::Generate()
p = this->GeneratorTarget->GetProperty(
"DOTNET_TARGET_FRAMEWORK_VERSION");
}
- const char* targetFrameworkVersion = cmToCStr(p);
- if (!targetFrameworkVersion && this->ProjectType == csproj &&
+ std::string targetFrameworkVersion = p;
+ if (targetFrameworkVersion.empty() && this->ProjectType == csproj &&
this->GlobalGenerator->TargetsWindowsCE() &&
this->GlobalGenerator->GetVersion() ==
cmGlobalVisualStudioGenerator::VS12) {
// VS12 .NETCF default to .NET framework 3.9
targetFrameworkVersion = "v3.9";
}
- if (targetFrameworkVersion) {
+ if (!targetFrameworkVersion.empty()) {
e1.Element("TargetFrameworkVersion", targetFrameworkVersion);
}
}
@@ -1468,7 +1465,10 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule(
cmCustomCommandGenerator ccg(command, c, lg, true);
std::string comment = lg->ConstructComment(ccg);
comment = cmVS10EscapeComment(comment);
- std::string script = lg->ConstructScript(ccg);
+ cmLocalVisualStudioGenerator::IsManaged isManaged = (this->Managed)
+ ? cmLocalVisualStudioGenerator::managed
+ : cmLocalVisualStudioGenerator::unmanaged;
+ std::string script = lg->ConstructScript(ccg, isManaged);
bool symbolic = false;
// input files for custom command
std::stringstream additional_inputs;
@@ -1799,8 +1799,8 @@ void cmVisualStudio10TargetGenerator::WriteGroupSources(
}
}
-void cmVisualStudio10TargetGenerator::WriteHeaderSource(Elem& e1,
- cmSourceFile const* sf)
+void cmVisualStudio10TargetGenerator::WriteHeaderSource(
+ Elem& e1, cmSourceFile const* sf, ConfigToSettings const& toolSettings)
{
std::string const& fileName = sf->GetFullPath();
Elem e2(e1, "ClInclude");
@@ -1811,6 +1811,7 @@ void cmVisualStudio10TargetGenerator::WriteHeaderSource(Elem& e1,
e2.Element("DependentUpon",
fileName.substr(0, fileName.find_last_of(".")));
}
+ this->FinishWritingSource(e2, toolSettings);
}
void cmVisualStudio10TargetGenerator::ParseSettingsProperty(
@@ -1867,8 +1868,8 @@ bool cmVisualStudio10TargetGenerator::PropertyIsSameInAllConfigs(
return true;
}
-void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1,
- cmSourceFile const* sf)
+void cmVisualStudio10TargetGenerator::WriteExtraSource(
+ Elem& e1, cmSourceFile const* sf, ConfigToSettings& toolSettings)
{
bool toolHasSettings = false;
const char* tool = "None";
@@ -1879,10 +1880,6 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1,
std::string copyToOutDir;
std::string includeInVsix;
std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
- ConfigToSettings toolSettings;
- for (const auto& config : this->Configurations) {
- toolSettings[config];
- }
if (this->ProjectType == csproj && !this->InSourceBuild) {
toolHasSettings = true;
@@ -2050,10 +2047,6 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1,
}
}
- if (cmProp p = sf->GetProperty("VS_SETTINGS")) {
- ParseSettingsProperty(*p, toolSettings);
- }
-
if (!toolSettings.empty()) {
toolHasSettings = true;
}
@@ -2063,27 +2056,7 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(Elem& e1,
if (toolHasSettings) {
e2.SetHasElements();
- std::vector<std::string> writtenSettings;
- for (const auto& configSettings : toolSettings) {
- for (const auto& setting : configSettings.second) {
-
- if (std::find(writtenSettings.begin(), writtenSettings.end(),
- setting.first) != writtenSettings.end()) {
- continue;
- }
-
- if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
- e2.Element(setting.first, setting.second);
- writtenSettings.push_back(setting.first);
- } else {
- e2.WritePlatformConfigTag(setting.first,
- "'$(Configuration)|$(Platform)'=='" +
- configSettings.first + "|" +
- this->Platform + "'",
- setting.second);
- }
- }
- }
+ this->FinishWritingSource(e2, toolSettings);
if (!deployContent.empty()) {
cmGeneratorExpression ge;
@@ -2220,6 +2193,15 @@ void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
// Skip explicit reference to CMakeLists.txt source.
continue;
}
+
+ ConfigToSettings toolSettings;
+ for (const auto& config : this->Configurations) {
+ toolSettings[config];
+ }
+ if (cmProp p = si.Source->GetProperty("VS_SETTINGS")) {
+ ParseSettingsProperty(*p, toolSettings);
+ }
+
const char* tool = nullptr;
switch (si.Kind) {
case cmGeneratorTarget::SourceKindAppManifest:
@@ -2247,10 +2229,10 @@ void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
}
break;
case cmGeneratorTarget::SourceKindExtra:
- this->WriteExtraSource(e1, si.Source);
+ this->WriteExtraSource(e1, si.Source, toolSettings);
break;
case cmGeneratorTarget::SourceKindHeader:
- this->WriteHeaderSource(e1, si.Source);
+ this->WriteHeaderSource(e1, si.Source, toolSettings);
break;
case cmGeneratorTarget::SourceKindIDL:
tool = "Midl";
@@ -2360,6 +2342,8 @@ void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
if (!isCSharp && !exclude_configs.empty()) {
this->WriteExcludeFromBuild(e2, exclude_configs);
}
+
+ this->FinishWritingSource(e2, toolSettings);
}
}
@@ -2368,6 +2352,32 @@ void cmVisualStudio10TargetGenerator::WriteAllSources(Elem& e0)
}
}
+void cmVisualStudio10TargetGenerator::FinishWritingSource(
+ Elem& e2, ConfigToSettings const& toolSettings)
+{
+ std::vector<std::string> writtenSettings;
+ for (const auto& configSettings : toolSettings) {
+ for (const auto& setting : configSettings.second) {
+
+ if (std::find(writtenSettings.begin(), writtenSettings.end(),
+ setting.first) != writtenSettings.end()) {
+ continue;
+ }
+
+ if (PropertyIsSameInAllConfigs(toolSettings, setting.first)) {
+ e2.Element(setting.first, setting.second);
+ writtenSettings.push_back(setting.first);
+ } else {
+ e2.WritePlatformConfigTag(setting.first,
+ "'$(Configuration)|$(Platform)'=='" +
+ configSettings.first + "|" +
+ this->Platform + "'",
+ setting.second);
+ }
+ }
+ }
+}
+
void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
Elem& e2, cmSourceFile const* source)
{
@@ -4208,7 +4218,10 @@ void cmVisualStudio10TargetGenerator::WriteEvent(
comment += lg->ConstructComment(ccg);
script += pre;
pre = "\n";
- script += lg->ConstructScript(ccg);
+ cmLocalVisualStudioGenerator::IsManaged isManaged = (this->Managed)
+ ? cmLocalVisualStudioGenerator::managed
+ : cmLocalVisualStudioGenerator::unmanaged;
+ script += lg->ConstructScript(ccg, isManaged);
stdPipesUTF8 = stdPipesUTF8 || cc.GetStdPipesUTF8();
}
diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h
index 55c5444..a5ce5e5 100644
--- a/Source/cmVisualStudio10TargetGenerator.h
+++ b/Source/cmVisualStudio10TargetGenerator.h
@@ -58,6 +58,10 @@ private:
struct Elem;
struct OptionsHelper;
+ using ConfigToSettings =
+ std::unordered_map<std::string,
+ std::unordered_map<std::string, std::string>>;
+
std::string ConvertPath(std::string const& path, bool forceRelative);
std::string CalcCondition(const std::string& config) const;
void WriteProjectConfigurations(Elem& e0);
@@ -66,12 +70,15 @@ private:
void WriteCEDebugProjectConfigurationValues(Elem& e0);
void WriteMSToolConfigurationValuesManaged(Elem& e1,
std::string const& config);
- void WriteHeaderSource(Elem& e1, cmSourceFile const* sf);
- void WriteExtraSource(Elem& e1, cmSourceFile const* sf);
+ void WriteHeaderSource(Elem& e1, cmSourceFile const* sf,
+ ConfigToSettings const& toolSettings);
+ void WriteExtraSource(Elem& e1, cmSourceFile const* sf,
+ ConfigToSettings& toolSettings);
void WriteNsightTegraConfigurationValues(Elem& e1,
std::string const& config);
void WriteAndroidConfigurationValues(Elem& e1, std::string const& config);
void WriteSource(Elem& e2, cmSourceFile const* sf);
+ void FinishWritingSource(Elem& e2, ConfigToSettings const& toolSettings);
void WriteExcludeFromBuild(Elem& e2,
std::vector<size_t> const& exclude_configs);
void WriteAllSources(Elem& e0);
@@ -252,9 +259,6 @@ private:
void ClassifyAllConfigSources();
void ClassifyAllConfigSource(cmGeneratorTarget::AllConfigSource const& acs);
- using ConfigToSettings =
- std::unordered_map<std::string,
- std::unordered_map<std::string, std::string>>;
std::unordered_map<std::string, ConfigToSettings> ParsedToolTargetSettings;
bool PropertyIsSameInAllConfigs(const ConfigToSettings& toolSettings,
const std::string& propName);
diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx
index 327c1c7..b8297ce 100644
--- a/Source/cmWhileCommand.cxx
+++ b/Source/cmWhileCommand.cxx
@@ -16,13 +16,14 @@
#include "cmListFileCache.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
+#include "cmOutputConverter.h"
#include "cmSystemTools.h"
#include "cmake.h"
class cmWhileFunctionBlocker : public cmFunctionBlocker
{
public:
- cmWhileFunctionBlocker(cmMakefile* mf);
+ cmWhileFunctionBlocker(cmMakefile* mf, std::vector<cmListFileArgument> args);
~cmWhileFunctionBlocker() override;
cm::string_view StartCommandName() const override { return "while"_s; }
@@ -34,14 +35,15 @@ public:
bool Replay(std::vector<cmListFileFunction> functions,
cmExecutionStatus& inStatus) override;
- std::vector<cmListFileArgument> Args;
-
private:
cmMakefile* Makefile;
+ std::vector<cmListFileArgument> Args;
};
-cmWhileFunctionBlocker::cmWhileFunctionBlocker(cmMakefile* mf)
- : Makefile(mf)
+cmWhileFunctionBlocker::cmWhileFunctionBlocker(
+ cmMakefile* const mf, std::vector<cmListFileArgument> args)
+ : Makefile{ mf }
+ , Args{ std::move(args) }
{
this->Makefile->PushLoopBlock();
}
@@ -60,39 +62,29 @@ bool cmWhileFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff,
bool cmWhileFunctionBlocker::Replay(std::vector<cmListFileFunction> functions,
cmExecutionStatus& inStatus)
{
- cmMakefile& mf = inStatus.GetMakefile();
- std::string errorString;
-
- std::vector<cmExpandedCommandArgument> expandedArguments;
- mf.ExpandArguments(this->Args, expandedArguments);
- MessageType messageType;
+ auto& mf = inStatus.GetMakefile();
cmListFileBacktrace whileBT =
mf.GetBacktrace().Push(this->GetStartingContext());
- cmConditionEvaluator conditionEvaluator(mf, whileBT);
-
- bool isTrue =
- conditionEvaluator.IsTrue(expandedArguments, errorString, messageType);
-
- while (isTrue) {
- if (!errorString.empty()) {
- std::string err = "had incorrect arguments: ";
- for (cmListFileArgument const& arg : this->Args) {
- err += (arg.Delim ? "\"" : "");
- err += arg.Value;
- err += (arg.Delim ? "\"" : "");
- err += " ";
- }
- err += "(";
- err += errorString;
- err += ").";
- mf.GetCMakeInstance()->IssueMessage(messageType, err, whileBT);
- if (messageType == MessageType::FATAL_ERROR) {
- cmSystemTools::SetFatalErrorOccured();
- return true;
- }
- }
+ std::vector<cmExpandedCommandArgument> expandedArguments;
+ // At least same size expected for `expandedArguments` as `Args`
+ expandedArguments.reserve(this->Args.size());
+
+ auto expandArgs = [&mf](std::vector<cmListFileArgument> const& args,
+ std::vector<cmExpandedCommandArgument>& out)
+ -> std::vector<cmExpandedCommandArgument>& {
+ out.clear();
+ mf.ExpandArguments(args, out);
+ return out;
+ };
+
+ std::string errorString;
+ MessageType messageType;
+
+ for (cmConditionEvaluator conditionEvaluator(mf, whileBT);
+ conditionEvaluator.IsTrue(expandArgs(this->Args, expandedArguments),
+ errorString, messageType);) {
// Invoke all the functions that were collected in the block.
for (cmListFileFunction const& fn : functions) {
cmExecutionStatus status(mf);
@@ -111,11 +103,22 @@ bool cmWhileFunctionBlocker::Replay(std::vector<cmListFileFunction> functions,
return true;
}
}
- expandedArguments.clear();
- mf.ExpandArguments(this->Args, expandedArguments);
- isTrue =
- conditionEvaluator.IsTrue(expandedArguments, errorString, messageType);
}
+
+ if (!errorString.empty()) {
+ std::string err = "had incorrect arguments:\n ";
+ for (auto const& i : expandedArguments) {
+ err += " ";
+ err += cmOutputConverter::EscapeForCMake(i.GetValue());
+ }
+ err += "\n";
+ err += errorString;
+ mf.GetCMakeInstance()->IssueMessage(messageType, err, whileBT);
+ if (messageType == MessageType::FATAL_ERROR) {
+ cmSystemTools::SetFatalErrorOccured();
+ }
+ }
+
return true;
}
@@ -128,11 +131,9 @@ bool cmWhileCommand(std::vector<cmListFileArgument> const& args,
}
// create a function blocker
- {
- cmMakefile& makefile = status.GetMakefile();
- auto fb = cm::make_unique<cmWhileFunctionBlocker>(&makefile);
- fb->Args = args;
- makefile.AddFunctionBlocker(std::move(fb));
- }
+ auto& makefile = status.GetMakefile();
+ makefile.AddFunctionBlocker(
+ cm::make_unique<cmWhileFunctionBlocker>(&makefile, args));
+
return true;
}
diff --git a/Source/cmake.cxx b/Source/cmake.cxx
index ab8309d..7cafaee 100644
--- a/Source/cmake.cxx
+++ b/Source/cmake.cxx
@@ -114,7 +114,9 @@
# include "cmExtraSublimeTextGenerator.h"
#endif
-#if defined(__linux__) || defined(_WIN32)
+// NOTE: the __linux__ macro is predefined on Android host too, but
+// main CMakeLists.txt filters out this generator by host name.
+#if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
# include "cmGlobalGhsMultiGenerator.h"
#endif
@@ -603,9 +605,8 @@ void cmake::ProcessCacheArg(const std::string& var, const std::string& value,
}
}
- this->AddCacheEntry(var, value.c_str(),
- "No help, variable specified on the command line.",
- type);
+ this->AddCacheEntry(
+ var, value, "No help, variable specified on the command line.", type);
if (this->WarnUnusedCli) {
if (!haveValue ||
@@ -1515,16 +1516,15 @@ void cmake::SetDirectoriesFromFile(const std::string& arg)
int cmake::AddCMakePaths()
{
// Save the value in the cache
- this->AddCacheEntry("CMAKE_COMMAND",
- cmSystemTools::GetCMakeCommand().c_str(),
+ this->AddCacheEntry("CMAKE_COMMAND", cmSystemTools::GetCMakeCommand(),
"Path to CMake executable.", cmStateEnums::INTERNAL);
#ifndef CMAKE_BOOTSTRAP
- this->AddCacheEntry(
- "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
- "Path to ctest program executable.", cmStateEnums::INTERNAL);
- this->AddCacheEntry(
- "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
- "Path to cpack program executable.", cmStateEnums::INTERNAL);
+ this->AddCacheEntry("CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand(),
+ "Path to ctest program executable.",
+ cmStateEnums::INTERNAL);
+ this->AddCacheEntry("CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand(),
+ "Path to cpack program executable.",
+ cmStateEnums::INTERNAL);
#endif
if (!cmSystemTools::FileExists(
(cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
@@ -1536,7 +1536,7 @@ int cmake::AddCMakePaths()
cmSystemTools::GetCMakeRoot());
return 0;
}
- this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
+ this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot(),
"Path to CMake installation.", cmStateEnums::INTERNAL);
return 1;
@@ -1884,7 +1884,7 @@ int cmake::HandleDeleteCacheVariables(const std::string& var)
this->LoadCache();
// restore the changed compilers
for (SaveCacheEntry const& i : saved) {
- this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
+ this->AddCacheEntry(i.key, i.value, i.help.c_str(), i.type);
}
cmSystemTools::Message(warning.str());
// avoid reconfigure if there were errors
@@ -1991,7 +1991,7 @@ int cmake::ActualConfigure()
}
if (!res) {
this->AddCacheEntry(
- "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory().c_str(),
+ "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
"Source directory with the top level CMakeLists.txt file for this "
"project",
cmStateEnums::INTERNAL);
@@ -2036,19 +2036,17 @@ int cmake::ActualConfigure()
}
}
if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
- this->AddCacheEntry("CMAKE_GENERATOR",
- this->GlobalGenerator->GetName().c_str(),
+ this->AddCacheEntry("CMAKE_GENERATOR", this->GlobalGenerator->GetName(),
"Name of generator.", cmStateEnums::INTERNAL);
- this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
- this->GlobalGenerator->GetExtraGeneratorName().c_str(),
- "Name of external makefile project generator.",
- cmStateEnums::INTERNAL);
+ this->AddCacheEntry(
+ "CMAKE_EXTRA_GENERATOR", this->GlobalGenerator->GetExtraGeneratorName(),
+ "Name of external makefile project generator.", cmStateEnums::INTERNAL);
if (!this->State->GetInitializedCacheValue("CMAKE_TOOLCHAIN_FILE")) {
std::string envToolchain;
if (cmSystemTools::GetEnv("CMAKE_TOOLCHAIN_FILE", envToolchain) &&
!envToolchain.empty()) {
- this->AddCacheEntry("CMAKE_TOOLCHAIN_FILE", envToolchain.c_str(),
+ this->AddCacheEntry("CMAKE_TOOLCHAIN_FILE", envToolchain,
"The CMake toolchain file",
cmStateEnums::FILEPATH);
}
@@ -2067,9 +2065,9 @@ int cmake::ActualConfigure()
return -2;
}
} else {
- this->AddCacheEntry(
- "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
- "Generator instance identifier.", cmStateEnums::INTERNAL);
+ this->AddCacheEntry("CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance,
+ "Generator instance identifier.",
+ cmStateEnums::INTERNAL);
}
if (cmProp platformName =
@@ -2085,8 +2083,7 @@ int cmake::ActualConfigure()
return -2;
}
} else {
- this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
- this->GeneratorPlatform.c_str(),
+ this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM", this->GeneratorPlatform,
"Name of generator platform.", cmStateEnums::INTERNAL);
}
@@ -2102,8 +2099,7 @@ int cmake::ActualConfigure()
return -2;
}
} else {
- this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
- this->GeneratorToolset.c_str(),
+ this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET", this->GeneratorToolset,
"Name of generator toolset.", cmStateEnums::INTERNAL);
}
@@ -2414,7 +2410,7 @@ int cmake::Generate()
return 0;
}
-void cmake::AddCacheEntry(const std::string& key, const char* value,
+void cmake::AddCacheEntry(const std::string& key, cmProp value,
const char* helpString, int type)
{
this->State->AddCacheEntry(key, value, helpString,
@@ -2528,7 +2524,7 @@ void cmake::AddDefaultGenerators()
this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
#endif
#if !defined(CMAKE_BOOTSTRAP)
-# if defined(__linux__) || defined(_WIN32)
+# if (defined(__linux__) && !defined(__ANDROID__)) || defined(_WIN32)
this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
# endif
this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
@@ -2917,6 +2913,10 @@ void cmake::SetProperty(const std::string& prop, const char* value)
{
this->State->SetGlobalProperty(prop, value);
}
+void cmake::SetProperty(const std::string& prop, cmProp value)
+{
+ this->State->SetGlobalProperty(prop, value);
+}
void cmake::AppendProperty(const std::string& prop, const std::string& value,
bool asString)
@@ -3534,7 +3534,7 @@ void cmake::SetSuppressDevWarnings(bool b)
value = "FALSE";
}
- this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
+ this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value,
"Suppress Warnings that are meant for"
" the author of the CMakeLists.txt files.",
cmStateEnums::INTERNAL);
@@ -3558,7 +3558,7 @@ void cmake::SetSuppressDeprecatedWarnings(bool b)
value = "TRUE";
}
- this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
+ this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value,
"Whether to issue warnings for deprecated "
"functionality.",
cmStateEnums::INTERNAL);
@@ -3582,7 +3582,7 @@ void cmake::SetDevWarningsAsErrors(bool b)
value = "TRUE";
}
- this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
+ this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value,
"Suppress errors that are meant for"
" the author of the CMakeLists.txt files.",
cmStateEnums::INTERNAL);
@@ -3606,7 +3606,7 @@ void cmake::SetDeprecatedWarningsAsErrors(bool b)
value = "FALSE";
}
- this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
+ this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value,
"Whether to issue deprecation errors for macros"
" and functions.",
cmStateEnums::INTERNAL);
diff --git a/Source/cmake.h b/Source/cmake.h
index 12cce7e..7408044 100644
--- a/Source/cmake.h
+++ b/Source/cmake.h
@@ -332,6 +332,18 @@ public:
cmProp GetCacheDefinition(const std::string&) const;
//! Add an entry into the cache
void AddCacheEntry(const std::string& key, const char* value,
+ const char* helpString, int type)
+ {
+ this->AddCacheEntry(key,
+ value ? cmProp(std::string(value)) : cmProp(nullptr),
+ helpString, type);
+ }
+ void AddCacheEntry(const std::string& key, const std::string& value,
+ const char* helpString, int type)
+ {
+ this->AddCacheEntry(key, cmProp(value), helpString, type);
+ }
+ void AddCacheEntry(const std::string& key, cmProp value,
const char* helpString, int type);
bool DoWriteGlobVerifyTarget() const;
@@ -396,6 +408,11 @@ public:
//! Set/Get a property of this target file
void SetProperty(const std::string& prop, const char* value);
+ void SetProperty(const std::string& prop, cmProp value);
+ void SetProperty(const std::string& prop, const std::string& value)
+ {
+ this->SetProperty(prop, cmProp(value));
+ }
void AppendProperty(const std::string& prop, const std::string& value,
bool asString = false);
cmProp GetProperty(const std::string& prop);
diff --git a/Source/kwsys/Status.hxx.in b/Source/kwsys/Status.hxx.in
index ed46d5c..16efaef 100644
--- a/Source/kwsys/Status.hxx.in
+++ b/Source/kwsys/Status.hxx.in
@@ -55,7 +55,10 @@ public:
#endif
/** Return true on "Success", false otherwise. */
- explicit operator bool() const { return this->Kind_ == Kind::Success; }
+ bool IsSuccess() const { return this->Kind_ == Kind::Success; }
+
+ /** Return true on "Success", false otherwise. */
+ explicit operator bool() const { return this->IsSuccess(); }
/** Return the kind of status. */
Kind GetKind() const { return this->Kind_; }
diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx
index 12f9139..f2bf85f 100644
--- a/Source/kwsys/SystemInformation.cxx
+++ b/Source/kwsys/SystemInformation.cxx
@@ -1356,14 +1356,12 @@ 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 =
- abi::__cxa_demangle(symbol, buffer, &bufferLen, &status);
+ abi::__cxa_demangle(symbol, nullptr, nullptr, &status);
if (!status) {
result = demangledSymbol;
}
- free(buffer);
+ free(demangledSymbol);
# else
(void)symbol;
# endif
diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx
index 7c26974..930d84c 100644
--- a/Source/kwsys/SystemTools.cxx
+++ b/Source/kwsys/SystemTools.cxx
@@ -14,6 +14,10 @@
# endif
#endif
+#if defined(_WIN32) && !defined(_WIN32_WINNT)
+# define _WIN32_WINNT _WIN32_WINNT_VISTA
+#endif
+
#include "kwsysPrivate.h"
#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
@@ -2419,7 +2423,7 @@ Status SystemTools::CopyFileAlways(std::string const& source,
if (SystemTools::FileIsDirectory(source)) {
status = SystemTools::MakeDirectory(destination);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
} else {
@@ -2444,17 +2448,17 @@ Status SystemTools::CopyFileAlways(std::string const& source,
// Create destination directory
if (!destination_dir.empty()) {
status = SystemTools::MakeDirectory(destination_dir);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
}
status = SystemTools::CloneFileContent(source, real_destination);
// if cloning did not succeed, fall back to blockwise copy
- if (!status) {
+ if (!status.IsSuccess()) {
status = SystemTools::CopyFileContentBlockwise(source, real_destination);
}
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
}
@@ -2484,11 +2488,11 @@ Status SystemTools::CopyADirectory(std::string const& source,
Status status;
Directory dir;
status = dir.Load(source);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
status = SystemTools::MakeDirectory(destination);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
@@ -2503,12 +2507,12 @@ Status SystemTools::CopyADirectory(std::string const& source,
fullDestPath += "/";
fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
status = SystemTools::CopyADirectory(fullPath, fullDestPath, always);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
} else {
status = SystemTools::CopyAFile(fullPath, destination, always);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
}
@@ -2660,7 +2664,7 @@ Status SystemTools::RemoveADirectory(std::string const& source)
Status status;
Directory dir;
status = dir.Load(source);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
@@ -2674,12 +2678,12 @@ Status SystemTools::RemoveADirectory(std::string const& source)
if (SystemTools::FileIsDirectory(fullPath) &&
!SystemTools::FileIsSymlink(fullPath)) {
status = SystemTools::RemoveADirectory(fullPath);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
} else {
status = SystemTools::RemoveFile(fullPath);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
}
@@ -3143,7 +3147,7 @@ Status SystemTools::ReadSymlink(std::string const& newName,
status = Status::Windows_GetLastError();
}
CloseHandle(hFile);
- if (!status) {
+ if (!status.IsSuccess()) {
return status;
}
PREPARSE_DATA_BUFFER data =
diff --git a/Source/kwsys/testDirectory.cxx b/Source/kwsys/testDirectory.cxx
index 06a22dc..a847462 100644
--- a/Source/kwsys/testDirectory.cxx
+++ b/Source/kwsys/testDirectory.cxx
@@ -122,7 +122,7 @@ int _copyDirectoryTest()
}
const Status copysuccess = SystemTools::CopyADirectory(source, destination);
const bool destinationexists = SystemTools::PathExists(destination);
- if (copysuccess) {
+ if (copysuccess.IsSuccess()) {
std::cerr << "CopyADirectory should have returned false" << std::endl;
SystemTools::RemoveADirectory(destination);
return 3;
diff --git a/Source/kwsys/testStatus.cxx b/Source/kwsys/testStatus.cxx
index f85ef42..0a767a8 100644
--- a/Source/kwsys/testStatus.cxx
+++ b/Source/kwsys/testStatus.cxx
@@ -31,6 +31,10 @@ int testStatus(int, char* [])
std::cerr << "Status Success constructor does not produce Success\n";
res = false;
}
+ if (!status.IsSuccess()) {
+ std::cerr << "Status Success gives false IsSuccess\n";
+ res = false;
+ }
if (!status) {
std::cerr << "Status Success kind is not true\n";
res = false;
@@ -55,6 +59,10 @@ int testStatus(int, char* [])
std::cerr << "Status POSIX constructor does not produce POSIX\n";
res = false;
}
+ if (status.IsSuccess()) {
+ std::cerr << "Status POSIX gives true IsSuccess\n";
+ res = false;
+ }
if (status) {
std::cerr << "Status POSIX kind is not false\n";
res = false;
@@ -87,6 +95,10 @@ int testStatus(int, char* [])
std::cerr << "Status Windows constructor does not produce Windows\n";
res = false;
}
+ if (status.IsSuccess()) {
+ std::cerr << "Status Windows gives true IsSuccess\n";
+ res = false;
+ }
if (status) {
std::cerr << "Status Windows kind is not false\n";
res = false;
diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx
index 39a19cb..6ccc7a7 100644
--- a/Source/kwsys/testSystemTools.cxx
+++ b/Source/kwsys/testSystemTools.cxx
@@ -436,7 +436,7 @@ static bool CheckFileOperations()
if (symlinkStatus.GetWindows() != ERROR_PRIVILEGE_NOT_HELD)
#endif
{
- if (!symlinkStatus) {
+ if (!symlinkStatus.IsSuccess()) {
std::cerr << "CreateSymlink for: " << testBadSymlink << " -> "
<< testBadSymlinkTgt
<< " failed: " << symlinkStatus.GetString() << std::endl;
diff --git a/Templates/MSBuild/FlagTables/v142_CL.json b/Templates/MSBuild/FlagTables/v142_CL.json
index 64eeac4..4c65ad9 100644
--- a/Templates/MSBuild/FlagTables/v142_CL.json
+++ b/Templates/MSBuild/FlagTables/v142_CL.json
@@ -1214,7 +1214,7 @@
"comment": "Additional Module Dependencies",
"value": "",
"flags": [
- "UserValue",
+ "UserFollowing",
"SemicolonAppendable"
]
},
@@ -1224,7 +1224,7 @@
"comment": "Additional Header Unit Dependencies",
"value": "",
"flags": [
- "UserValue",
+ "UserFollowing",
"SemicolonAppendable"
]
},
diff --git a/Templates/MSBuild/FlagTables/v143_CL.json b/Templates/MSBuild/FlagTables/v143_CL.json
index 8b700aa..96f74b1 100644
--- a/Templates/MSBuild/FlagTables/v143_CL.json
+++ b/Templates/MSBuild/FlagTables/v143_CL.json
@@ -1214,7 +1214,7 @@
"comment": "Additional Module Dependencies",
"value": "",
"flags": [
- "UserValue",
+ "UserFollowing",
"SemicolonAppendable"
]
},
@@ -1224,7 +1224,7 @@
"comment": "Additional Header Unit Dependencies",
"value": "",
"flags": [
- "UserValue",
+ "UserFollowing",
"SemicolonAppendable"
]
},
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index ef8c846..4ccbfeb 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -1551,6 +1551,8 @@ if(BUILD_TESTING)
ADD_TEST_MACRO(FindMatlab.failure_reports ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>)
set(FindMatlab.r2018a_check_BUILD_OPTIONS ${FindMatlab_additional_test_options})
ADD_TEST_MACRO(FindMatlab.r2018a_check ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>)
+ set(FindMatlab.targets_checks_BUILD_OPTIONS ${FindMatlab_additional_test_options})
+ ADD_TEST_MACRO(FindMatlab.targets_checks ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>)
endif()
add_test(ExternalProject ${CMAKE_CTEST_COMMAND}
@@ -1648,6 +1650,53 @@ if(BUILD_TESTING)
WORKING_DIRECTORY ${CMake_SOURCE_DIR}/Tests/ExternalProjectUpdate
DEPENDS ExternalProjectUpdateSetup )
+ execute_process(
+ COMMAND ${CMAKE_COMMAND}
+ "-E" create_symlink
+ "${CMake_SOURCE_DIR}/Tests/CMakeLists.txt" # random source file that exists
+ "${CMake_BINARY_DIR}/Tests/try_to_create_symlink" # random target file in existing directory
+ RESULT_VARIABLE _symlink_result
+ )
+ if(_symlink_result EQUAL 0)
+ file(REMOVE "${CMake_BINARY_DIR}/Tests/try_to_create_symlink")
+ function(add_installmode_test _mode)
+ set(ENV{CMAKE_INSTALL_MODE} _mode)
+ set(_maybe_InstallMode_CTEST_OPTIONS)
+ set(_maybe_BUILD_OPTIONS)
+ if(_isMultiConfig)
+ set(_maybe_CTEST_OPTIONS -C $<CONFIGURATION>)
+ else()
+ set(_maybe_BUILD_OPTIONS "-DCMAKE_BUILD_TYPE=$<CONFIGURATION>")
+ endif()
+ add_test(
+ NAME "InstallMode-${_mode}"
+ COMMAND
+ ${CMAKE_CTEST_COMMAND} -V ${_maybe_CTEST_OPTIONS}
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/InstallMode"
+ "${CMake_BINARY_DIR}/Tests/InstallMode-${_mode}"
+ ${build_generator_args}
+ --build-project superpro
+ --build-exe-dir "${CMake_BINARY_DIR}/Tests/InstallMode-${_mode}"
+ --force-new-ctest-process
+ --build-options
+ ${_maybe_BUILD_OPTIONS}
+ "-DCMAKE_INSTALL_PREFIX:PATH=${CMake_BINARY_DIR}/Tests/InstallMode-${_mode}/install"
+ )
+ list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/InstallMode-${_mode}")
+ unset(ENV{CMAKE_INSTALL_MODE})
+ endfunction()
+
+ add_installmode_test(COPY)
+ add_installmode_test(REL_SYMLINK)
+ add_installmode_test(REL_SYMLINK_OR_COPY)
+ add_installmode_test(ABS_SYMLINK)
+ add_installmode_test(ABS_SYMLINK_OR_COPY)
+ add_installmode_test(SYMLINK)
+ add_installmode_test(SYMLINK_OR_COPY)
+ endif()
+
+
# do each of the tutorial steps
function(add_tutorial_test step_name use_mymath tutorial_arg pass_regex)
set(tutorial_test_name Tutorial${step_name})
diff --git a/Tests/CMakeTests/CMakeLists.txt b/Tests/CMakeTests/CMakeLists.txt
index 52959e6..9e0b891 100644
--- a/Tests/CMakeTests/CMakeLists.txt
+++ b/Tests/CMakeTests/CMakeLists.txt
@@ -31,7 +31,6 @@ AddCMakeTest(CompilerIdVendor "")
AddCMakeTest(ProcessorCount "-DKWSYS_TEST_EXE=$<TARGET_FILE:cmsysTestsCxx>")
AddCMakeTest(PushCheckState "")
AddCMakeTest(While "")
-AddCMakeTest(CMakeHostSystemInformation "")
AddCMakeTest(FileDownload "")
set_tests_properties(CMake.FileDownload PROPERTIES
diff --git a/Tests/FindMatlab/targets_checks/CMakeLists.txt b/Tests/FindMatlab/targets_checks/CMakeLists.txt
new file mode 100644
index 0000000..4af7cc3
--- /dev/null
+++ b/Tests/FindMatlab/targets_checks/CMakeLists.txt
@@ -0,0 +1,44 @@
+cmake_minimum_required (VERSION 2.8.12)
+enable_testing()
+project(targets_checks)
+
+set(MATLAB_FIND_DEBUG TRUE)
+
+if(NOT "${MCR_ROOT}" STREQUAL "")
+ set(Matlab_ROOT_DIR "${MCR_ROOT}")
+ if(NOT EXISTS "${MCR_ROOT}")
+ message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}")
+ endif()
+endif()
+
+# the success of the following command is dependent on the current configuration:
+# - on 32bits builds (cmake is building with 32 bits), it looks for 32 bits Matlab
+# - on 64bits builds (cmake is building with 64 bits), it looks for 64 bits Matlab
+find_package(Matlab REQUIRED COMPONENTS ENG_LIBRARY MAT_LIBRARY
+ OPTIONAL_COMPONENTS MAIN_PROGRAM)
+
+if(NOT TARGET Matlab::mx)
+ message(FATAL_ERROR "Matlab::mx target does not exist")
+endif()
+
+if(NOT TARGET Matlab::mex)
+ message(FATAL_ERROR "Matlab::mex target does not exist")
+endif()
+
+if(NOT TARGET Matlab::eng)
+ message(FATAL_ERROR "Matlab::eng target does not exist")
+endif()
+
+if(NOT TARGET Matlab::mat)
+ message(FATAL_ERROR "Matlab::mat target does not exist")
+endif()
+
+matlab_add_mex(
+ # target name
+ NAME cmake_matlab_test_wrapper1
+ # output name
+ OUTPUT_NAME cmake_matlab_mex1
+ SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper1.cpp
+ DOCUMENTATION ${CMAKE_CURRENT_SOURCE_DIR}/../help_text1.m.txt
+ LINK_TO Matlab::mex
+ )
diff --git a/Tests/InstallMode/CMakeLists.txt b/Tests/InstallMode/CMakeLists.txt
new file mode 100644
index 0000000..96c83a0
--- /dev/null
+++ b/Tests/InstallMode/CMakeLists.txt
@@ -0,0 +1,124 @@
+cmake_minimum_required(VERSION 3.20.0)
+
+project(superpro LANGUAGES NONE)
+
+add_subdirectory(superpro)
+
+include(Subproject.cmake)
+add_subproject(static_lib DIR subpro_a_static_lib)
+add_subproject(shared_lib DIR subpro_b_shared_lib)
+add_subproject(nested_lib DIR subpro_c_nested_lib NO_INSTALL)
+add_subproject(executable DIR subpro_d_executable
+ DEPENDS
+ static_lib
+ shared_lib
+ nested_lib
+)
+
+include(CTest)
+if(BUILD_TESTING)
+ enable_language(CXX) # required by GNUInstallDirs
+ include(GNUInstallDirs)
+
+ macro(testme _name _path _symlink)
+ add_test(
+ NAME "${_name}"
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ COMMAND
+ "${CMAKE_COMMAND}"
+ "-DFILE_PATH=${CMAKE_INSTALL_PREFIX}/${_path}"
+ "-DEXPECT_SYMLINK:BOOL=${_symlink}"
+ "-DEXPECT_ABSOLUTE:BOOL=${ARGN}"
+ "-P" "${CMAKE_SOURCE_DIR}/Test.cmake"
+ )
+ endmacro()
+
+ set(_mode $ENV{CMAKE_INSTALL_MODE})
+ if(NOT "${_mode}" OR "${_mode}" STREQUAL "COPY")
+ set(expect_symlink NO)
+ elseif("${_mode}" MATCHES "(REL_)?SYMLINK(_OR_COPY)?")
+ set(expect_symlink YES)
+ set(expect_absolute NO)
+ elseif("${_mode}" MATCHES "ABS_SYMLINK(_OR_COPY)?")
+ set(expect_symlink YES)
+ set(expect_absolute YES)
+ endif()
+
+ # toplevel project should respect CMAKE_INSTALL_MODE
+
+ testme(superproj_file_copy
+ "file_copy.txt" NO)
+ testme(superproj_file_copy_file
+ "file_copy_file.txt" NO)
+ testme(superproj_file_install
+ "file_install.txt"
+ ${expect_symlink}
+ ${expect_absolute})
+ testme(superproj_file_create_link_symbolic
+ "file_create_link_symbolic.txt" YES YES)
+
+ # subprojects should receive and respect CMAKE_INSTALL_MODE too
+
+ testme(subpro_a_static_lib_header
+ "${CMAKE_INSTALL_INCLUDEDIR}/static_lib.h"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+ testme(subpro_a_static_lib_libfile
+ "${CMAKE_INSTALL_LIBDIR}/${CMAKE_STATIC_LIBRARY_PREFIX}the_static_lib${CMAKE_STATIC_LIBRARY_SUFFIX}"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+
+ testme(subpro_b_shared_lib_header
+ "${CMAKE_INSTALL_INCLUDEDIR}/shared_lib.h"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+
+ if(CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG AND
+ "${CMAKE_CXX_CREATE_SHARED_MODULE}" MATCHES "SONAME_FLAG")
+ # due to semver, this is always a link
+ testme(subpro_b_shared_lib_libfile
+ "${CMAKE_INSTALL_LIBDIR}/${CMAKE_SHARED_LIBRARY_PREFIX}the_shared_lib${CMAKE_SHARED_LIBRARY_SUFFIX}"
+ YES
+ ${expect_absolute}
+ )
+ # this is the actual shared lib, so should follow CMAKE_INSTALL_MODE rules
+ testme(subpro_b_shared_lib_libfile_versuffix
+ "${CMAKE_INSTALL_LIBDIR}/${CMAKE_SHARED_LIBRARY_PREFIX}the_shared_lib${CMAKE_SHARED_LIBRARY_SUFFIX}.2.3.4"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+ endif()
+
+ testme(subpro_d_executable_exefile
+ "${CMAKE_INSTALL_BINDIR}/the_executable${CMAKE_EXECUTABLE_SUFFIX}"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+
+ # nested subprojects should receive and respect CMAKE_INSTALL_MODE too
+
+ testme(subsubpro_c1_header
+ "${CMAKE_INSTALL_INCLUDEDIR}/c1_lib.h"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+ testme(subsubpro_c1_libfile
+ "${CMAKE_INSTALL_LIBDIR}/${CMAKE_STATIC_LIBRARY_PREFIX}the_c1_lib${CMAKE_STATIC_LIBRARY_SUFFIX}"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+
+ testme(subsubpro_c2_header
+ "${CMAKE_INSTALL_INCLUDEDIR}/c2_lib.h"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+ testme(subsubpro_c2_libfile
+ "${CMAKE_INSTALL_LIBDIR}/${CMAKE_STATIC_LIBRARY_PREFIX}the_c2_lib${CMAKE_STATIC_LIBRARY_SUFFIX}"
+ ${expect_symlink}
+ ${expect_absolute}
+ )
+endif()
diff --git a/Tests/InstallMode/README.txt b/Tests/InstallMode/README.txt
new file mode 100644
index 0000000..a4316eb
--- /dev/null
+++ b/Tests/InstallMode/README.txt
@@ -0,0 +1,43 @@
+This is an example superbuild project to demonstrate the use of the
+CMAKE_INSTALL_MODE environment variable on.
+
+The project hierarchy is like (B = Builds / D = Link Dependency):
+
++---------------------------------------------------------------------+
+| Superbuild (Top) |
++---------------------------------------------------------------------+
+ | | | |
+ | | | |
+ (B) (B) (B) (B)
+ | | | |
+ v v v v
++---------------+ +---------------+ +---------------+ +---------------+
+| A: Static Lib | | B: Shared Lib | | C: Nested | | D: Executable |
+| Project | | Project | | Superbuild | | Project |
++---------------+ +---------------+ +---------------+ +---------------+
+ ^ ^ | | | | |
+ | | (B) (B) | | |
+ | | | | | | |
+ | | v | | | |
+ | | +----------------+ | | | |
+ | | | C1: Static Lib | | | | |
+ | | | Project | | (D) (D) (D)
+ | | +----------------+ | | | |
+ | | ^ | | | |
+ | | | v | | |
+ | | (D) +----------------+ | | |
+ | | | | C2: Static Lib |<---+ | |
+ | | +--| Project | | |
+ | | +----------------+ | |
+ | | | |
+ | +------------------------------------+ |
+ | |
+ +--------------------------------------------------------+
+
+The superbuild system is built on top of ExternalProject_Add().
+
+NOTE that the subprojects will configure, build and install
+during the build phase ('make') of the top-level project.
+There is no install target in the top-level project!
+The CMAKE_INSTALL_PREFIX is therefore populated during the build
+phase already.
diff --git a/Tests/InstallMode/Subproject.cmake b/Tests/InstallMode/Subproject.cmake
new file mode 100644
index 0000000..826e61e
--- /dev/null
+++ b/Tests/InstallMode/Subproject.cmake
@@ -0,0 +1,73 @@
+include(ExternalProject)
+
+# add_subproject(<name> [NO_INSTALL] [DIR <dirname>] [DEPENDS [subpro_dep ...]])
+function(add_subproject _name)
+ cmake_parse_arguments(_arg "NO_INSTALL" "DIR" "DEPENDS" ${ARGN})
+
+ if(_arg_UNPARSED_ARGUMENTS)
+ message(FATAL_ERROR "There are unparsed arguments")
+ endif()
+
+ set(_maybe_NO_INSTALL)
+ if(_arg_NO_INSTALL)
+ set(_maybe_NO_INSTALL INSTALL_COMMAND "")
+ endif()
+
+ if(CMAKE_GENERATOR MATCHES "Ninja Multi-Config")
+ # Replace list separator before passing on to ExternalProject_Add
+ string(REPLACE ";" "|" _CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}")
+ string(REPLACE ";" "|" _CROSS_CONFIGS "${CMAKE_CROSS_CONFIGS}")
+ string(REPLACE ";" "|" _DEFAULT_CONFIGS "${CMAKE_DEFAULT_CONFIGS}")
+
+ set(_maybe_NINJA_MULTICONFIG_ARGS
+ "-DCMAKE_CONFIGURATION_TYPES:STRINGS=${_CONFIGURATION_TYPES}"
+ "-DCMAKE_CROSS_CONFIGS:STRINGS=${_CROSS_CONFIGS}"
+ "-DCMAKE_DEFAULT_BUILD_TYPE:STRING=${CMAKE_DEFAULT_BUILD_TYPE}"
+ "-DCMAKE_DEFAULT_CONFIGS:STRINGS=${_DEFAULT_CONFIGS}"
+ )
+ endif()
+
+ ExternalProject_Add("${_name}"
+ DOWNLOAD_COMMAND ""
+ UPDATE_COMMAND ""
+ UPDATE_DISCONNECTED ON
+
+ "${_maybe_NO_INSTALL}"
+
+ BUILD_ALWAYS ON
+
+ LOG_DOWNLOAD OFF
+ LOG_UPDATE OFF
+ LOG_PATCH OFF
+ LOG_CONFIGURE OFF
+ LOG_BUILD OFF
+ LOG_INSTALL OFF
+
+ SOURCE_DIR "${PROJECT_SOURCE_DIR}/${_arg_DIR}"
+
+ # Private build directory per subproject
+ BINARY_DIR "${PROJECT_BINARY_DIR}/subproject/${_arg_DIR}"
+
+ # Common install directory, populated immediately
+ # during build (during build - not install - of superproject)
+ INSTALL_DIR "${CMAKE_INSTALL_PREFIX}"
+
+ DEPENDS
+ ${_arg_DEPENDS}
+
+ LIST_SEPARATOR "|"
+ CMAKE_ARGS
+ "-DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>"
+
+ # We can rely on ExternalProject to pick the right
+ # generator (and architecture/toolset where applicable),
+ # however, we need to explicitly inherit other parent
+ # project's build settings.
+ "-DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}"
+ "${_maybe_NINJA_MULTICONFIG_ARGS}"
+
+ # Subproject progress reports clutter up the output, disable
+ "-DCMAKE_TARGET_MESSAGES:BOOL=OFF"
+ "-DCMAKE_RULE_MESSAGES:BOOL=OFF"
+ )
+endfunction()
diff --git a/Tests/InstallMode/Test.cmake b/Tests/InstallMode/Test.cmake
new file mode 100644
index 0000000..46c8fa1
--- /dev/null
+++ b/Tests/InstallMode/Test.cmake
@@ -0,0 +1,38 @@
+message("Testing...")
+message("FILE_PATH = ${FILE_PATH}")
+message("EXPECT_SYMLINK = ${EXPECT_SYMLINK}")
+message("EXPECT_ABSOLUTE = ${EXPECT_ABSOLUTE}")
+
+if(NOT DEFINED FILE_PATH)
+ message(FATAL_ERROR "FILE_PATH variable must be defined")
+endif()
+
+if(NOT EXISTS "${FILE_PATH}")
+ message(FATAL_ERROR "File ${FILE_PATH} does not exist")
+endif()
+
+if(NOT DEFINED EXPECT_SYMLINK)
+ message(FATAL_ERROR "EXPECT_SYMLINK must be defined")
+endif()
+
+if(EXPECT_SYMLINK)
+ if(NOT DEFINED EXPECT_ABSOLUTE)
+ message(FATAL_ERROR "EXPECT_ABSOLUTE variable must be defined")
+ endif()
+
+ if(NOT IS_SYMLINK "${FILE_PATH}")
+ message(FATAL_ERROR "${FILE_PATH} must be a symlink")
+ endif()
+
+ file(READ_SYMLINK "${FILE_PATH}" TARGET_PATH)
+
+ if(EXPECT_ABSOLUTE AND NOT IS_ABSOLUTE "${TARGET_PATH}")
+ message(FATAL_ERROR "${FILE_PATH} must be an absolute symlink")
+ elseif(NOT EXPECT_ABSOLUTE AND IS_ABSOLUTE "${TARGET_PATH}")
+ message(FATAL_ERROR "${FILE_PATH} must be a relative symlink")
+ endif()
+else()
+ if(IS_SYMLINK "${FILE_PATH}")
+ message(FATAL_ERROR "${FILE_PATH} must NOT be a symlink")
+ endif()
+endif()
diff --git a/Tests/InstallMode/subpro_a_static_lib/CMakeLists.txt b/Tests/InstallMode/subpro_a_static_lib/CMakeLists.txt
new file mode 100644
index 0000000..7cd32cc
--- /dev/null
+++ b/Tests/InstallMode/subpro_a_static_lib/CMakeLists.txt
@@ -0,0 +1,60 @@
+# This CMakeLists.txt is part of the subproject A (ExternalProject_Add).
+
+cmake_minimum_required(VERSION 3.20)
+project(static_lib_project VERSION 1.2.3 LANGUAGES CXX)
+
+include(GNUInstallDirs)
+
+add_library(the_static_lib STATIC
+ "include/static_lib.h"
+ "src/static_lib.cpp"
+)
+
+target_include_directories(the_static_lib PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+)
+
+install(
+ DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/"
+ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
+)
+
+install(
+ TARGETS
+ the_static_lib
+ EXPORT main
+ ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+ LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+)
+
+set(INSTALL_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}")
+
+include(CMakePackageConfigHelpers)
+
+configure_package_config_file(
+ "cmake/PackageConfig.cmake.in"
+ "${PROJECT_NAME}Config.cmake"
+ INSTALL_DESTINATION "${INSTALL_CMAKE_DIR}"
+ PATH_VARS
+ CMAKE_INSTALL_INCLUDEDIR
+ CMAKE_INSTALL_LIBDIR
+)
+
+write_basic_package_version_file("${PROJECT_NAME}Version.cmake"
+ VERSION "${PROJECT_VERSION}"
+ COMPATIBILITY SameMajorVersion
+)
+
+install(
+ EXPORT main
+ FILE "${PROJECT_NAME}Targets.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
+
+install(
+ FILES
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
diff --git a/Tests/InstallMode/subpro_a_static_lib/cmake/PackageConfig.cmake.in b/Tests/InstallMode/subpro_a_static_lib/cmake/PackageConfig.cmake.in
new file mode 100644
index 0000000..0fe72c9
--- /dev/null
+++ b/Tests/InstallMode/subpro_a_static_lib/cmake/PackageConfig.cmake.in
@@ -0,0 +1,8 @@
+set(@PROJECT_NAME@_VERSION @PROJECT_VERSION@)
+
+@PACKAGE_INIT@
+
+include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
+
+set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@")
+set_and_check(@PROJECT_NAME@_LIB_DIR "@PACKAGE_CMAKE_INSTALL_LIBDIR@")
diff --git a/Tests/InstallMode/subpro_a_static_lib/include/static_lib.h b/Tests/InstallMode/subpro_a_static_lib/include/static_lib.h
new file mode 100644
index 0000000..bd82d2e
--- /dev/null
+++ b/Tests/InstallMode/subpro_a_static_lib/include/static_lib.h
@@ -0,0 +1,3 @@
+#pragma once
+
+void static_hello();
diff --git a/Tests/InstallMode/subpro_a_static_lib/src/static_lib.cpp b/Tests/InstallMode/subpro_a_static_lib/src/static_lib.cpp
new file mode 100644
index 0000000..fe1cd85
--- /dev/null
+++ b/Tests/InstallMode/subpro_a_static_lib/src/static_lib.cpp
@@ -0,0 +1,10 @@
+#include <iostream>
+
+#include <static_lib.h>
+
+using namespace std;
+
+void static_hello()
+{
+ cout << "Hello from static_lib" << endl;
+}
diff --git a/Tests/InstallMode/subpro_b_shared_lib/CMakeLists.txt b/Tests/InstallMode/subpro_b_shared_lib/CMakeLists.txt
new file mode 100644
index 0000000..b3d9cb2
--- /dev/null
+++ b/Tests/InstallMode/subpro_b_shared_lib/CMakeLists.txt
@@ -0,0 +1,75 @@
+# This CMakeLists.txt is part of the subproject B (ExternalProject_Add).
+
+cmake_minimum_required(VERSION 3.20)
+project(shared_lib_project VERSION 2.3.4 LANGUAGES CXX)
+
+include(GNUInstallDirs)
+include(GenerateExportHeader)
+
+add_library(the_shared_lib SHARED
+ "include/shared_lib.h"
+ "src/shared_lib.cpp"
+)
+
+generate_export_header(the_shared_lib
+ BASE_NAME shared_lib
+ EXPORT_FILE_NAME include/shared_lib_export.h
+)
+
+set_target_properties(the_shared_lib
+ PROPERTIES
+ VERSION "${PROJECT_VERSION}"
+ SOVERSION "${PROJECT_VERSION}"
+)
+
+target_include_directories(the_shared_lib PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+)
+
+install(
+ DIRECTORY
+ "${CMAKE_CURRENT_SOURCE_DIR}/include/"
+ "${CMAKE_CURRENT_BINARY_DIR}/include/"
+ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
+)
+
+install(
+ TARGETS
+ the_shared_lib
+ EXPORT main
+ ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+ LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+)
+
+set(INSTALL_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}")
+
+include(CMakePackageConfigHelpers)
+
+configure_package_config_file(
+ "cmake/PackageConfig.cmake.in"
+ "${PROJECT_NAME}Config.cmake"
+ INSTALL_DESTINATION "${INSTALL_CMAKE_DIR}"
+ PATH_VARS
+ CMAKE_INSTALL_INCLUDEDIR
+ CMAKE_INSTALL_LIBDIR
+)
+
+write_basic_package_version_file("${PROJECT_NAME}Version.cmake"
+ VERSION "${PROJECT_VERSION}"
+ COMPATIBILITY SameMajorVersion
+)
+
+install(
+ EXPORT main
+ FILE "${PROJECT_NAME}Targets.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
+
+install(
+ FILES
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
diff --git a/Tests/InstallMode/subpro_b_shared_lib/cmake/PackageConfig.cmake.in b/Tests/InstallMode/subpro_b_shared_lib/cmake/PackageConfig.cmake.in
new file mode 100644
index 0000000..0fe72c9
--- /dev/null
+++ b/Tests/InstallMode/subpro_b_shared_lib/cmake/PackageConfig.cmake.in
@@ -0,0 +1,8 @@
+set(@PROJECT_NAME@_VERSION @PROJECT_VERSION@)
+
+@PACKAGE_INIT@
+
+include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
+
+set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@")
+set_and_check(@PROJECT_NAME@_LIB_DIR "@PACKAGE_CMAKE_INSTALL_LIBDIR@")
diff --git a/Tests/InstallMode/subpro_b_shared_lib/include/shared_lib.h b/Tests/InstallMode/subpro_b_shared_lib/include/shared_lib.h
new file mode 100644
index 0000000..550b2b4
--- /dev/null
+++ b/Tests/InstallMode/subpro_b_shared_lib/include/shared_lib.h
@@ -0,0 +1,5 @@
+#pragma once
+
+#include <shared_lib_export.h>
+
+void SHARED_LIB_EXPORT shared_hello();
diff --git a/Tests/InstallMode/subpro_b_shared_lib/src/shared_lib.cpp b/Tests/InstallMode/subpro_b_shared_lib/src/shared_lib.cpp
new file mode 100644
index 0000000..2820d5d
--- /dev/null
+++ b/Tests/InstallMode/subpro_b_shared_lib/src/shared_lib.cpp
@@ -0,0 +1,10 @@
+#include <iostream>
+
+#include <shared_lib.h>
+
+using namespace std;
+
+void shared_hello()
+{
+ cout << "Hello from shared_lib" << endl;
+}
diff --git a/Tests/InstallMode/subpro_c_nested_lib/CMakeLists.txt b/Tests/InstallMode/subpro_c_nested_lib/CMakeLists.txt
new file mode 100644
index 0000000..e397c02
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.20.0)
+
+project(subpro_c_nested_lib LANGUAGES NONE)
+
+include(../Subproject.cmake)
+add_subproject(c1_lib DIR subsubpro_c1_lib)
+add_subproject(c2_lib DIR subsubpro_c2_lib
+ DEPENDS
+ c1_lib
+)
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/CMakeLists.txt b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/CMakeLists.txt
new file mode 100644
index 0000000..89f3755
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/CMakeLists.txt
@@ -0,0 +1,61 @@
+# This CMakeLists.txt is a nested subproject of the
+# subproject C (ExternalProject_Add).
+
+cmake_minimum_required(VERSION 3.20)
+project(c1_lib_project VERSION 1.2.3 LANGUAGES CXX)
+
+include(GNUInstallDirs)
+
+add_library(the_c1_lib STATIC
+ "include/c1_lib.h"
+ "src/c1_lib.cpp"
+)
+
+target_include_directories(the_c1_lib PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+)
+
+install(
+ DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/"
+ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
+)
+
+install(
+ TARGETS
+ the_c1_lib
+ EXPORT main
+ ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+ LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+)
+
+set(INSTALL_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}")
+
+include(CMakePackageConfigHelpers)
+
+configure_package_config_file(
+ "cmake/PackageConfig.cmake.in"
+ "${PROJECT_NAME}Config.cmake"
+ INSTALL_DESTINATION "${INSTALL_CMAKE_DIR}"
+ PATH_VARS
+ CMAKE_INSTALL_INCLUDEDIR
+ CMAKE_INSTALL_LIBDIR
+)
+
+write_basic_package_version_file("${PROJECT_NAME}Version.cmake"
+ VERSION "${PROJECT_VERSION}"
+ COMPATIBILITY SameMajorVersion
+)
+
+install(
+ EXPORT main
+ FILE "${PROJECT_NAME}Targets.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
+
+install(
+ FILES
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/cmake/PackageConfig.cmake.in b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/cmake/PackageConfig.cmake.in
new file mode 100644
index 0000000..0fe72c9
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/cmake/PackageConfig.cmake.in
@@ -0,0 +1,8 @@
+set(@PROJECT_NAME@_VERSION @PROJECT_VERSION@)
+
+@PACKAGE_INIT@
+
+include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
+
+set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@")
+set_and_check(@PROJECT_NAME@_LIB_DIR "@PACKAGE_CMAKE_INSTALL_LIBDIR@")
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/include/c1_lib.h b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/include/c1_lib.h
new file mode 100644
index 0000000..245f9d4
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/include/c1_lib.h
@@ -0,0 +1,3 @@
+#pragma once
+
+void c1_hello();
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/src/c1_lib.cpp b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/src/c1_lib.cpp
new file mode 100644
index 0000000..c405056
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c1_lib/src/c1_lib.cpp
@@ -0,0 +1,10 @@
+#include <iostream>
+
+#include <c1_lib.h>
+
+using namespace std;
+
+void c1_hello()
+{
+ cout << "Hello from c1_lib" << endl;
+}
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/CMakeLists.txt b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/CMakeLists.txt
new file mode 100644
index 0000000..7580c77
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/CMakeLists.txt
@@ -0,0 +1,71 @@
+# This CMakeLists.txt is a nested subproject of the
+# subproject C (ExternalProject_Add).
+
+cmake_minimum_required(VERSION 3.20)
+project(c2_lib_project VERSION 1.2.3 LANGUAGES CXX)
+
+find_package(c1_lib_project REQUIRED)
+
+include(GNUInstallDirs)
+
+add_library(the_c2_lib STATIC
+ "include/c2_lib.h"
+ "src/c2_lib.cpp"
+)
+
+target_link_libraries(the_c2_lib
+ PUBLIC
+ the_c1_lib
+)
+
+# This is to fix an issue on AIX/GCC (see commit 4fc47424)
+set_property(TARGET the_c2_lib PROPERTY NO_SYSTEM_FROM_IMPORTED 1)
+
+target_include_directories(the_c2_lib PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+)
+
+install(
+ DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/"
+ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
+)
+
+install(
+ TARGETS
+ the_c2_lib
+ EXPORT main
+ ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+ LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+)
+
+set(INSTALL_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}")
+
+include(CMakePackageConfigHelpers)
+
+configure_package_config_file(
+ "cmake/PackageConfig.cmake.in"
+ "${PROJECT_NAME}Config.cmake"
+ INSTALL_DESTINATION "${INSTALL_CMAKE_DIR}"
+ PATH_VARS
+ CMAKE_INSTALL_INCLUDEDIR
+ CMAKE_INSTALL_LIBDIR
+)
+
+write_basic_package_version_file("${PROJECT_NAME}Version.cmake"
+ VERSION "${PROJECT_VERSION}"
+ COMPATIBILITY SameMajorVersion
+)
+
+install(
+ EXPORT main
+ FILE "${PROJECT_NAME}Targets.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
+
+install(
+ FILES
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
+ "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Version.cmake"
+ DESTINATION "${INSTALL_CMAKE_DIR}"
+)
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/cmake/PackageConfig.cmake.in b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/cmake/PackageConfig.cmake.in
new file mode 100644
index 0000000..45a177a
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/cmake/PackageConfig.cmake.in
@@ -0,0 +1,11 @@
+set(@PROJECT_NAME@_VERSION @PROJECT_VERSION@)
+
+@PACKAGE_INIT@
+
+include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
+
+set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@")
+set_and_check(@PROJECT_NAME@_LIB_DIR "@PACKAGE_CMAKE_INSTALL_LIBDIR@")
+
+include(CMakeFindDependencyMacro)
+find_dependency(c1_lib_project REQUIRED)
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/include/c2_lib.h b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/include/c2_lib.h
new file mode 100644
index 0000000..5056814
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/include/c2_lib.h
@@ -0,0 +1,3 @@
+#pragma once
+
+void c2_hello();
diff --git a/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/src/c2_lib.cpp b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/src/c2_lib.cpp
new file mode 100644
index 0000000..cd2c932
--- /dev/null
+++ b/Tests/InstallMode/subpro_c_nested_lib/subsubpro_c2_lib/src/c2_lib.cpp
@@ -0,0 +1,12 @@
+#include <iostream>
+
+#include <c1_lib.h>
+#include <c2_lib.h>
+
+using namespace std;
+
+void c2_hello()
+{
+ cout << "Hello from c2_lib and also..." << endl;
+ c1_hello();
+}
diff --git a/Tests/InstallMode/subpro_d_executable/CMakeLists.txt b/Tests/InstallMode/subpro_d_executable/CMakeLists.txt
new file mode 100644
index 0000000..60189e2
--- /dev/null
+++ b/Tests/InstallMode/subpro_d_executable/CMakeLists.txt
@@ -0,0 +1,27 @@
+# This CMakeLists.txt is part of the subproject B (ExternalProject_Add).
+
+cmake_minimum_required(VERSION 3.20)
+project(subpro_d_executable LANGUAGES CXX)
+
+find_package(static_lib_project REQUIRED)
+find_package(shared_lib_project REQUIRED)
+find_package(c2_lib_project REQUIRED)
+
+add_executable(the_executable
+ "src/main.cpp"
+)
+
+target_link_libraries(the_executable PRIVATE
+ the_static_lib
+ the_shared_lib
+ the_c2_lib
+)
+
+# This is to fix an issue on AIX/GCC (see commit 4fc47424)
+set_property(TARGET the_executable PROPERTY NO_SYSTEM_FROM_IMPORTED 1)
+
+install(
+ TARGETS
+ the_executable
+ RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
+)
diff --git a/Tests/InstallMode/subpro_d_executable/src/main.cpp b/Tests/InstallMode/subpro_d_executable/src/main.cpp
new file mode 100644
index 0000000..ec12004
--- /dev/null
+++ b/Tests/InstallMode/subpro_d_executable/src/main.cpp
@@ -0,0 +1,13 @@
+#include <cstdlib>
+
+#include <c2_lib.h>
+#include <shared_lib.h>
+#include <static_lib.h>
+
+int main()
+{
+ static_hello();
+ shared_hello();
+ c2_hello();
+ return EXIT_SUCCESS;
+}
diff --git a/Tests/InstallMode/superpro/CMakeLists.txt b/Tests/InstallMode/superpro/CMakeLists.txt
new file mode 100644
index 0000000..ae4d25c
--- /dev/null
+++ b/Tests/InstallMode/superpro/CMakeLists.txt
@@ -0,0 +1,29 @@
+# This CMakeLists.txt is part of the superproject (add_subdirectory).
+
+# Below file transfers are executed at configuration time!
+
+file(
+ COPY
+ "file_copy.txt"
+ DESTINATION
+ "${CMAKE_INSTALL_PREFIX}"
+)
+
+file(COPY_FILE
+ "${CMAKE_CURRENT_SOURCE_DIR}/file_copy_file.txt"
+ "${CMAKE_INSTALL_PREFIX}/file_copy_file.txt"
+)
+
+file(
+ INSTALL
+ "file_install.txt"
+ DESTINATION
+ "${CMAKE_INSTALL_PREFIX}"
+)
+
+file(
+ CREATE_LINK
+ "${CMAKE_CURRENT_SOURCE_DIR}/file_create_link_symbolic.txt"
+ "${CMAKE_INSTALL_PREFIX}/file_create_link_symbolic.txt"
+ SYMBOLIC
+)
diff --git a/Tests/InstallMode/superpro/file_copy.txt b/Tests/InstallMode/superpro/file_copy.txt
new file mode 100644
index 0000000..aacbb96
--- /dev/null
+++ b/Tests/InstallMode/superpro/file_copy.txt
@@ -0,0 +1 @@
+This file should always be copied into CMAKE_INSTALL_PREFIX.
diff --git a/Tests/InstallMode/superpro/file_copy_file.txt b/Tests/InstallMode/superpro/file_copy_file.txt
new file mode 100644
index 0000000..aacbb96
--- /dev/null
+++ b/Tests/InstallMode/superpro/file_copy_file.txt
@@ -0,0 +1 @@
+This file should always be copied into CMAKE_INSTALL_PREFIX.
diff --git a/Tests/InstallMode/superpro/file_create_link_symbolic.txt b/Tests/InstallMode/superpro/file_create_link_symbolic.txt
new file mode 100644
index 0000000..16a481b
--- /dev/null
+++ b/Tests/InstallMode/superpro/file_create_link_symbolic.txt
@@ -0,0 +1,2 @@
+This file should always be installed into CMAKE_INSTALL_PREFIX
+as a symbolic link to the original file.
diff --git a/Tests/InstallMode/superpro/file_install.txt b/Tests/InstallMode/superpro/file_install.txt
new file mode 100644
index 0000000..eac9782
--- /dev/null
+++ b/Tests/InstallMode/superpro/file_install.txt
@@ -0,0 +1,6 @@
+This file should be placed in CMAKE_INSTALL_PREFIX
+as a copy if the CMAKE_INSTALL_MODE environment variable
+is unset or equals "COPY".
+If the variable's value is "SYMLINK" or "SYMLINK_OR_COPY",
+the CMAKE_INSTALL_PREFIX should rather receive a symbolic
+link to this file.
diff --git a/Tests/QtAutogen/RerunUicOnFileChange/CMakeLists.txt b/Tests/QtAutogen/RerunUicOnFileChange/CMakeLists.txt
index a3ba9fb..9b114e9 100644
--- a/Tests/QtAutogen/RerunUicOnFileChange/CMakeLists.txt
+++ b/Tests/QtAutogen/RerunUicOnFileChange/CMakeLists.txt
@@ -28,12 +28,10 @@ endmacro()
configure_file("${testProjectTemplateDir}/mocwidget.h" "${testProjectSrc}/mocwidget.h" COPYONLY)
configure_file("${testProjectTemplateDir}/mainwindow.h" "${testProjectSrc}/mainwindow.h" COPYONLY)
configure_file("${testProjectTemplateDir}/main.cpp" "${testProjectSrc}/main.cpp" COPYONLY)
-configure_file("${testProjectTemplateDir}/subdir/subdircheck.cpp" "${testProjectSrc}/subdir/subdircheck.cpp" COPYONLY)
configure_file("${testProjectTemplateDir}/CMakeLists.txt.in" "${testProjectSrc}/CMakeLists.txt" @ONLY)
set(Num 1)
configure_file("${testProjectTemplateDir}/mainwindow.ui.in" "${testProjectSrc}/mainwindow.ui" @ONLY)
-configure_file("${testProjectTemplateDir}/subdir/mainwindowsubdir.ui.in" "${testProjectSrc}/subdir/mainwindowsubdir.ui" @ONLY)
if(CMAKE_GENERATOR_INSTANCE)
set(_D_CMAKE_GENERATOR_INSTANCE "-DCMAKE_GENERATOR_INSTANCE=${CMAKE_GENERATOR_INSTANCE}")
@@ -97,7 +95,6 @@ sleep()
set(Num 2)
configure_file("${testProjectTemplateDir}/mainwindow.ui.in" "${testProjectSrc}/mainwindow.ui" @ONLY)
-configure_file("${testProjectTemplateDir}/subdir/mainwindowsubdir.ui.in" "${testProjectSrc}/subdir/mainwindowsubdir.ui" @ONLY)
rebuild(2)
execute_process(COMMAND "${testProjectBinDir}/${extra_bin_path}UicOnFileChange" RESULT_VARIABLE result)
diff --git a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/CMakeLists.txt.in b/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/CMakeLists.txt.in
index c77075c..c787db1 100644
--- a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/CMakeLists.txt.in
+++ b/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/CMakeLists.txt.in
@@ -8,7 +8,6 @@ set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
add_executable(UicOnFileChange main.cpp mainwindow.ui mainwindow.h
- subdir/subdircheck.cpp subdir/mainwindowsubdir.ui
)
target_include_directories(UicOnFileChange PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}"
diff --git a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/main.cpp b/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/main.cpp
index 99de13d..4aab2ad 100644
--- a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/main.cpp
+++ b/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/main.cpp
@@ -1,12 +1,10 @@
#include "mainwindow.h"
#include "ui_mainwindow.h"
-extern bool subdircheck();
-
int main(int argc, char* argv[])
{
MocWidget mw;
Ui::Widget mwUi;
mwUi.setupUi(&mw);
- return mw.objectName() == "Widget2" && subdircheck() ? 0 : 1;
+ return mw.objectName() == "Widget2" ? 0 : 1;
}
diff --git a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/mainwindowsubdir.ui.in b/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/mainwindowsubdir.ui.in
deleted file mode 100644
index a6a31f6..0000000
--- a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/mainwindowsubdir.ui.in
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>WidgetSubdir</class>
- <widget class="MocWidget" name="WidgetSubdir@Num@"/>
- <resources/>
- <connections/>
-</ui>
diff --git a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/subdircheck.cpp b/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/subdircheck.cpp
deleted file mode 100644
index 3b36a10..0000000
--- a/Tests/QtAutogen/RerunUicOnFileChange/UicOnFileChange/subdir/subdircheck.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "ui_mainwindowsubdir.h"
-
-bool subdircheck()
-{
- MocWidget mw;
- Ui::WidgetSubdir mwUi;
- mwUi.setupUi(&mw);
- return mw.objectName() == "WidgetSubdir2";
-}
diff --git a/Tests/RunCMake/CMakeDependentOption/Regex-stdout.txt b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW-stdout.txt
index 15b56a1..15b56a1 100644
--- a/Tests/RunCMake/CMakeDependentOption/Regex-stdout.txt
+++ b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW-stdout.txt
diff --git a/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW.cmake b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW.cmake
new file mode 100644
index 0000000..5a2b018
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-NEW.cmake
@@ -0,0 +1,9 @@
+include(CMakeDependentOption)
+
+cmake_policy(SET CMP0127 NEW)
+
+set(A 1)
+set(B 1)
+set(C 0)
+cmake_dependent_option(USE_FOO "Use Foo" ON "A AND (B OR C)" OFF)
+message(STATUS "USE_FOO='${USE_FOO}'")
diff --git a/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stderr.txt b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stderr.txt
new file mode 100644
index 0000000..b16e84b
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Warning \(dev\) at [^
+]*/Modules/CMakeDependentOption.cmake:[0-9]+ \(message\):
+ Policy CMP0127 is not set: cmake_dependent_option\(\) supports full Condition
+ Syntax. Run "cmake --help-policy CMP0127" for policy details. Use the
+ cmake_policy command to set the policy and suppress this warning.
+Call Stack \(most recent call first\):
+ [^
+]*/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN.cmake:[0-9]+ \(cmake_dependent_option\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stdout.txt b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stdout.txt
new file mode 100644
index 0000000..d89dbd3
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN-stdout.txt
@@ -0,0 +1,2 @@
+-- USE_FOO='OFF'
+-- USE_BAR='ON'
diff --git a/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN.cmake b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN.cmake
new file mode 100644
index 0000000..00d440d
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Parentheses-CMP0127-WARN.cmake
@@ -0,0 +1,9 @@
+include(CMakeDependentOption)
+
+set(A 1)
+set(B 1)
+set(C 0)
+cmake_dependent_option(USE_FOO "Use Foo" ON "A AND (B OR C)" OFF)
+message(STATUS "USE_FOO='${USE_FOO}'")
+cmake_dependent_option(USE_BAR "Use Bar" ON "A;B" OFF)
+message(STATUS "USE_BAR='${USE_BAR}'")
diff --git a/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW-stdout.txt b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW-stdout.txt
new file mode 100644
index 0000000..15b56a1
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW-stdout.txt
@@ -0,0 +1 @@
+-- USE_FOO='ON'
diff --git a/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW.cmake b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW.cmake
new file mode 100644
index 0000000..e92c1e6
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-NEW.cmake
@@ -0,0 +1,7 @@
+include(CMakeDependentOption)
+
+cmake_policy(SET CMP0127 NEW)
+
+set(FOO "lower")
+cmake_dependent_option(USE_FOO "Use Foo" ON "FOO MATCHES \"(UPPER|lower)\"" OFF)
+message(STATUS "USE_FOO='${USE_FOO}'")
diff --git a/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD-stdout.txt b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD-stdout.txt
new file mode 100644
index 0000000..15b56a1
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD-stdout.txt
@@ -0,0 +1 @@
+-- USE_FOO='ON'
diff --git a/Tests/RunCMake/CMakeDependentOption/Regex.cmake b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD.cmake
index 8342a01..81df003 100644
--- a/Tests/RunCMake/CMakeDependentOption/Regex.cmake
+++ b/Tests/RunCMake/CMakeDependentOption/Regex-CMP0127-OLD.cmake
@@ -1,5 +1,7 @@
include(CMakeDependentOption)
+cmake_policy(SET CMP0127 OLD)
+
set(FOO "lower")
cmake_dependent_option(USE_FOO "Use Foo" ON "FOO MATCHES (UPPER|lower)" OFF)
message(STATUS "USE_FOO='${USE_FOO}'")
diff --git a/Tests/RunCMake/CMakeDependentOption/RunCMakeTest.cmake b/Tests/RunCMake/CMakeDependentOption/RunCMakeTest.cmake
index e1045f2..61e046f 100644
--- a/Tests/RunCMake/CMakeDependentOption/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CMakeDependentOption/RunCMakeTest.cmake
@@ -1,3 +1,6 @@
include(RunCMake)
-run_cmake_script(Regex)
+run_cmake_script(Regex-CMP0127-NEW)
+run_cmake_script(Regex-CMP0127-OLD)
+run_cmake_script(Parentheses-CMP0127-NEW)
+run_cmake_script(Parentheses-CMP0127-WARN)
diff --git a/Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD-stdout.txt b/Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD-stdout.txt
new file mode 100644
index 0000000..15b56a1
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD-stdout.txt
@@ -0,0 +1 @@
+-- USE_FOO='ON'
diff --git a/Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD.cmake b/Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD.cmake
new file mode 100644
index 0000000..6db2128
--- /dev/null
+++ b/Tests/RunCMake/CMakeDependentOption/Simple-CMP0127-OLD.cmake
@@ -0,0 +1,6 @@
+include(CMakeDependentOption)
+
+set(A1 1)
+set(bb 1)
+cmake_dependent_option(USE_FOO "Use Foo" ON "A1;bb" OFF)
+message(STATUS "USE_FOO='${USE_FOO}'")
diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt
index ef797f7..eb2c2d9 100644
--- a/Tests/RunCMake/CMakeLists.txt
+++ b/Tests/RunCMake/CMakeLists.txt
@@ -349,6 +349,7 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
endif()
add_RunCMake_test(execute_process)
add_RunCMake_test(export)
+add_RunCMake_test(cmake_host_system_information)
add_RunCMake_test(cmake_language)
add_RunCMake_test(cmake_minimum_required)
add_RunCMake_test(cmake_parse_arguments)
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMP0126_NEW.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMP0126_NEW.cmake
new file mode 100644
index 0000000..a419ab3
--- /dev/null
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_CMP0126_NEW.cmake
@@ -0,0 +1,64 @@
+
+cmake_policy(SET CMP0126 NEW)
+
+# Needed for CMAKE_SYSTEM_NAME, CMAKE_LIBRARY_ARCHITECTURE, FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS
+enable_language(C)
+
+# Prepare environment and variables
+set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH TRUE)
+set(CMAKE_PREFIX_PATH "${CMAKE_CURRENT_SOURCE_DIR}/pc-foo")
+if(WIN32)
+ set(PKG_CONFIG_EXECUTABLE "${CMAKE_CURRENT_SOURCE_DIR}\\dummy-pkg-config.bat")
+ set(ENV{CMAKE_PREFIX_PATH} "${CMAKE_CURRENT_SOURCE_DIR}\\pc-bar;X:\\this\\directory\\should\\not\\exist\\in\\the\\filesystem")
+ set(ENV{PKG_CONFIG_PATH} "C:\\baz")
+else()
+ set(PKG_CONFIG_EXECUTABLE "${CMAKE_CURRENT_SOURCE_DIR}/dummy-pkg-config.sh")
+ set(ENV{CMAKE_PREFIX_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/pc-bar:/this/directory/should/not/exist/in/the/filesystem")
+ set(ENV{PKG_CONFIG_PATH} "/baz")
+endif()
+
+
+find_package(PkgConfig)
+
+
+if(NOT DEFINED CMAKE_SYSTEM_NAME
+ OR (CMAKE_SYSTEM_NAME MATCHES "^(Linux|kFreeBSD|GNU)$"
+ AND NOT CMAKE_CROSSCOMPILING))
+ if(EXISTS "/etc/debian_version") # is this a debian system ?
+ if(CMAKE_LIBRARY_ARCHITECTURE MATCHES "^(i386-linux-gnu|x86_64-linux-gnu)$")
+ # Cannot create directories for all the existing architectures...
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/${CMAKE_LIBRARY_ARCHITECTURE}/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/${CMAKE_LIBRARY_ARCHITECTURE}/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ else()
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ endif()
+ else()
+ # not debian, check the FIND_LIBRARY_USE_LIB32_PATHS and FIND_LIBRARY_USE_LIB64_PATHS properties
+ get_property(uselibx32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIBX32_PATHS)
+ get_property(uselib32 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS)
+ get_property(uselib64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS)
+ if(uselibx32 AND CMAKE_INTERNAL_PLATFORM_ABI STREQUAL "ELF X32")
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/libx32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/libx32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ elseif(uselib32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib32/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ elseif(uselib64 AND CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib64/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ else()
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ endif()
+ endif()
+else()
+ if(WIN32)
+ set(expected_path "C:\\baz;${CMAKE_CURRENT_SOURCE_DIR}\\pc-foo\\lib\\pkgconfig;${CMAKE_CURRENT_SOURCE_DIR}\\pc-bar\\lib\\pkgconfig")
+ else()
+ set(expected_path "/baz:${CMAKE_CURRENT_SOURCE_DIR}/pc-foo/lib/pkgconfig:${CMAKE_CURRENT_SOURCE_DIR}/pc-bar/lib/pkgconfig")
+ endif()
+endif()
+
+
+set(FOO_FOUND FALSE)
+
+pkg_check_modules(FOO "${expected_path}")
+
+if(NOT FOO_FOUND)
+ message(FATAL_ERROR "Expected FOO_FOUND == 1.")
+endif()
diff --git a/Tests/RunCMake/FindPkgConfig/RunCMakeTest.cmake b/Tests/RunCMake/FindPkgConfig/RunCMakeTest.cmake
index 81a4732..f36d1eb 100644
--- a/Tests/RunCMake/FindPkgConfig/RunCMakeTest.cmake
+++ b/Tests/RunCMake/FindPkgConfig/RunCMakeTest.cmake
@@ -7,6 +7,7 @@ set(ENV{CMAKE_FRAMEWORK_PATH} "")
run_cmake(PkgConfigDoesNotExist)
+run_cmake(FindPkgConfig_CMP0126_NEW)
run_cmake(FindPkgConfig_NO_PKGCONFIG_PATH)
run_cmake(FindPkgConfig_PKGCONFIG_PATH)
run_cmake(FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-test3-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test3-stdout.txt
new file mode 100644
index 0000000..cf08267
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test3-stdout.txt
@@ -0,0 +1,16 @@
+Test project .*
+ Start 27: TEST:basic\.case_foo!3
+1/4 Test #27: TEST:basic\.case_foo!3 \.+ +Passed +[0-9.]+ sec
+ Start 28: TEST:basic\.case_bar!3
+2/4 Test #28: TEST:basic\.case_bar!3 \.+ +Passed +[0-9.]+ sec
+ Start 29: TEST:basic\.disabled_case!3
+3/4 Test #29: TEST:basic\.disabled_case!3 \.+\*+Not Run \(Disabled\) +[0-9.]+ sec
+ Start 30: TEST:basic\.DISABLEDnot_really_case!3
+4/4 Test #30: TEST:basic\.DISABLEDnot_really_case!3 \.+ +Passed +[0-9.]+ sec
+
+100% tests passed, 0 tests failed out of 3
+
+Total Test time \(real\) = +[0-9.]+ sec
+
+The following tests did not run:
+.*29 - TEST:basic.disabled_case!3 \(Disabled\)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-test4-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test4-stdout.txt
new file mode 100644
index 0000000..4a9d75b
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test4-stdout.txt
@@ -0,0 +1,9 @@
+Test project .*
+ Start 31: TEST:typed/short\.case!4
+1/2 Test #31: TEST:typed/short\.case!4 \.+ +Passed +[0-9.]+ sec
+ Start 32: TEST:typed/float\.case!4
+2/2 Test #32: TEST:typed/float\.case!4 \.+ +Passed +[0-9.]+ sec
+
+100% tests passed, 0 tests failed out of 2
+
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest.cmake b/Tests/RunCMake/GoogleTest/GoogleTest.cmake
index 8efd117..221d6ad 100644
--- a/Tests/RunCMake/GoogleTest/GoogleTest.cmake
+++ b/Tests/RunCMake/GoogleTest/GoogleTest.cmake
@@ -24,6 +24,24 @@ gtest_discover_tests(
PROPERTIES LABELS TEST2
)
+gtest_discover_tests(
+ fake_gtest
+ TEST_PREFIX TEST:
+ TEST_SUFFIX !3
+ TEST_FILTER basic*
+ EXTRA_ARGS how now "\"brown\" cow"
+ PROPERTIES LABELS TEST3
+)
+
+gtest_discover_tests(
+ fake_gtest
+ TEST_PREFIX TEST:
+ TEST_SUFFIX !4
+ TEST_FILTER typed*
+ EXTRA_ARGS how now "\"brown\" cow"
+ PROPERTIES LABELS TEST4
+)
+
add_executable(no_tests_defined no_tests_defined.cpp)
xcode_sign_adhoc(no_tests_defined)
diff --git a/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake b/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
index 530c8ab..c5c5925 100644
--- a/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
@@ -40,6 +40,20 @@ function(run_GoogleTest DISCOVERY_MODE)
--no-label-summary
)
+ run_cmake_command(GoogleTest-test3
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -L TEST3
+ --no-label-summary
+ )
+
+ run_cmake_command(GoogleTest-test4
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -L TEST4
+ --no-label-summary
+ )
+
run_cmake_command(GoogleTest-test-missing
${CMAKE_CTEST_COMMAND}
-C Debug
diff --git a/Tests/RunCMake/GoogleTest/fake_gtest.cpp b/Tests/RunCMake/GoogleTest/fake_gtest.cpp
index 1956c37..b2a5cb4 100644
--- a/Tests/RunCMake/GoogleTest/fake_gtest.cpp
+++ b/Tests/RunCMake/GoogleTest/fake_gtest.cpp
@@ -7,27 +7,42 @@ int main(int argc, char** argv)
// it only requires that we produces output in the expected format when
// invoked with --gtest_list_tests. Thus, we fake that here. This allows us
// to test the module without actually needing Google Test.
+ bool is_filtered =
+ argc > 2 && std::string(argv[2]).find("--gtest_filter=") == 0;
+ bool is_basic_only =
+ is_filtered && std::string(argv[2]).find("basic*") != std::string::npos;
+ bool is_typed_only =
+ is_filtered && std::string(argv[2]).find("typed*") != std::string::npos;
+
if (argc > 1 && std::string(argv[1]) == "--gtest_list_tests") {
- std::cout << "basic." << std::endl;
- std::cout << " case_foo" << std::endl;
- std::cout << " case_bar" << std::endl;
- std::cout << " DISABLED_disabled_case" << std::endl;
- std::cout << " DISABLEDnot_really_case" << std::endl;
- std::cout << "DISABLED_disabled." << std::endl;
- std::cout << " case" << std::endl;
- std::cout << "DISABLEDnotreally." << std::endl;
- std::cout << " case" << std::endl;
- std::cout << "typed/0. # TypeParam = short" << std::endl;
- std::cout << " case" << std::endl;
- std::cout << "typed/1. # TypeParam = float" << std::endl;
- std::cout << " case" << std::endl;
- std::cout << "value/test." << std::endl;
- std::cout << " case/0 # GetParam() = 1" << std::endl;
- std::cout << " case/1 # GetParam() = \"foo\"" << std::endl;
- std::cout << "param/special." << std::endl;
- std::cout << " case/0 # GetParam() = \"semicolon;\"" << std::endl;
- std::cout << " case/1 # GetParam() = \"backslash\\\"" << std::endl;
- std::cout << " case/2 # GetParam() = \"${var}\"" << std::endl;
+ if (!is_typed_only) {
+ std::cout << "basic." << std::endl;
+ std::cout << " case_foo" << std::endl;
+ std::cout << " case_bar" << std::endl;
+ std::cout << " DISABLED_disabled_case" << std::endl;
+ std::cout << " DISABLEDnot_really_case" << std::endl;
+ }
+ if (!is_basic_only && !is_typed_only) {
+ std::cout << "DISABLED_disabled." << std::endl;
+ std::cout << " case" << std::endl;
+ std::cout << "DISABLEDnotreally." << std::endl;
+ std::cout << " case" << std::endl;
+ }
+ if (!is_basic_only) {
+ std::cout << "typed/0. # TypeParam = short" << std::endl;
+ std::cout << " case" << std::endl;
+ std::cout << "typed/1. # TypeParam = float" << std::endl;
+ std::cout << " case" << std::endl;
+ }
+ if (!is_basic_only && !is_typed_only) {
+ std::cout << "value/test." << std::endl;
+ std::cout << " case/0 # GetParam() = 1" << std::endl;
+ std::cout << " case/1 # GetParam() = \"foo\"" << std::endl;
+ std::cout << "param/special." << std::endl;
+ std::cout << " case/0 # GetParam() = \"semicolon;\"" << std::endl;
+ std::cout << " case/1 # GetParam() = \"backslash\\\"" << std::endl;
+ std::cout << " case/2 # GetParam() = \"${var}\"" << std::endl;
+ }
return 0;
}
diff --git a/Tests/RunCMake/VS10Project/VsSettings-check.cmake b/Tests/RunCMake/VS10Project/VsSettings-check.cmake
index 0f8b26c..13cc8e2 100644
--- a/Tests/RunCMake/VS10Project/VsSettings-check.cmake
+++ b/Tests/RunCMake/VS10Project/VsSettings-check.cmake
@@ -4,20 +4,29 @@ macro(ensure_props_set projectFile)
return()
endif()
- set(SettingFound FALSE)
+ set(Setting1Found FALSE)
+ set(Setting2Found FALSE)
file(STRINGS "${projectFile}" lines)
foreach(line IN LISTS lines)
if(line MATCHES "<SourceProperty1.*Debug.*>SourceProperty1Value</SourceProperty1>")
message("SourceProperty1 setting found")
- set(SettingFound TRUE)
+ set(Setting1Found TRUE)
+ endif()
+ if(line MATCHES "<SourceProperty2.*Debug.*>SourceProperty2Value</SourceProperty2>")
+ message("SourceProperty2 setting found")
+ set(Setting2Found TRUE)
endif()
endforeach()
- if (NOT SettingFound)
+ if (NOT Setting1Found)
set(RunCMake_TEST_FAILED "SourceProperty1 setting was not found")
return()
endif()
+ if (NOT Setting2Found)
+ set(RunCMake_TEST_FAILED "SourceProperty2 setting was not found")
+ return()
+ endif()
endmacro()
ensure_props_set("${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
diff --git a/Tests/RunCMake/VS10Project/VsSettings.cmake b/Tests/RunCMake/VS10Project/VsSettings.cmake
index a4b321b..3a046f1 100644
--- a/Tests/RunCMake/VS10Project/VsSettings.cmake
+++ b/Tests/RunCMake/VS10Project/VsSettings.cmake
@@ -3,3 +3,5 @@ enable_language(CXX)
add_library(foo foo.cpp shader.hlsl)
set_property(SOURCE shader.hlsl PROPERTY VS_SETTINGS
"$<$<CONFIG:DEBUG>:SourceProperty1=SourceProperty1Value>")
+set_property(SOURCE foo.cpp PROPERTY VS_SETTINGS
+ "$<$<CONFIG:DEBUG>:SourceProperty2=SourceProperty2Value>")
diff --git a/Tests/RunCMake/cmake_host_system_information/000-FirstFallbackScript.cmake b/Tests/RunCMake/cmake_host_system_information/000-FirstFallbackScript.cmake
new file mode 100644
index 0000000..ad873eb
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/000-FirstFallbackScript.cmake
@@ -0,0 +1 @@
+message(WARNING "The warning text to match just to make sure the script get executed")
diff --git a/Tests/RunCMake/cmake_host_system_information/999-LastFallbackScript.cmake b/Tests/RunCMake/cmake_host_system_information/999-LastFallbackScript.cmake
new file mode 100644
index 0000000..08d8da8
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/999-LastFallbackScript.cmake
@@ -0,0 +1,21 @@
+if(DEFINED CMAKE_GET_OS_RELEASE_FALLBACK_RESULT)
+ message(FATAL_ERROR "The `CMAKE_GET_OS_RELEASE_FALLBACK_RESULT` expected to be unset at this moment")
+endif()
+
+set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME UnitTest)
+set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME "Just a Unit Test")
+set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID unittest)
+set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID_LIKE nothing)
+set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION 0.0.1)
+set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID 0.0.1)
+
+list(
+ APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME
+ IGNORED_VARIABLE_NAME_WHICH_IS_NOT_STARTED_WITH_EXPECTED_PREFIX
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID_LIKE
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION
+ CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID
+ )
diff --git a/Tests/RunCMake/cmake_host_system_information/BadArg1-result.txt b/Tests/RunCMake/cmake_host_system_information/BadArg1-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_host_system_information/BadArg1-stderr.txt b/Tests/RunCMake/cmake_host_system_information/BadArg1-stderr.txt
new file mode 100644
index 0000000..ed995e6
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg1-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at BadArg1\.cmake:1 \(cmake_host_system_information\):
+ cmake_host_system_information missing RESULT specification.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:7 \(include\)
diff --git a/Tests/CMakeTests/CMakeHostSystemInformation-BadArg1.cmake b/Tests/RunCMake/cmake_host_system_information/BadArg1.cmake
index 1655eb4..1655eb4 100644
--- a/Tests/CMakeTests/CMakeHostSystemInformation-BadArg1.cmake
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg1.cmake
diff --git a/Tests/RunCMake/cmake_host_system_information/BadArg2-result.txt b/Tests/RunCMake/cmake_host_system_information/BadArg2-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_host_system_information/BadArg2-stderr.txt b/Tests/RunCMake/cmake_host_system_information/BadArg2-stderr.txt
new file mode 100644
index 0000000..b78c927
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg2-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at BadArg2\.cmake:1 \(cmake_host_system_information\):
+ cmake_host_system_information missing QUERY specification
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:7 \(include\)
diff --git a/Tests/CMakeTests/CMakeHostSystemInformation-BadArg2.cmake b/Tests/RunCMake/cmake_host_system_information/BadArg2.cmake
index 1f056d5..1f056d5 100644
--- a/Tests/CMakeTests/CMakeHostSystemInformation-BadArg2.cmake
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg2.cmake
diff --git a/Tests/RunCMake/cmake_host_system_information/BadArg3-result.txt b/Tests/RunCMake/cmake_host_system_information/BadArg3-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg3-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_host_system_information/BadArg3-stderr.txt b/Tests/RunCMake/cmake_host_system_information/BadArg3-stderr.txt
new file mode 100644
index 0000000..c3f1314
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg3-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at BadArg3\.cmake:1 \(cmake_host_system_information\):
+ cmake_host_system_information does not recognize <key> FOOBAR
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:7 \(include\)
diff --git a/Tests/CMakeTests/CMakeHostSystemInformation-BadArg3.cmake b/Tests/RunCMake/cmake_host_system_information/BadArg3.cmake
index 9c5a558..9c5a558 100644
--- a/Tests/CMakeTests/CMakeHostSystemInformation-BadArg3.cmake
+++ b/Tests/RunCMake/cmake_host_system_information/BadArg3.cmake
diff --git a/Tests/RunCMake/cmake_host_system_information/CMakeLists.txt b/Tests/RunCMake/cmake_host_system_information/CMakeLists.txt
new file mode 100644
index 0000000..0198f9b
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/CMakeLists.txt
@@ -0,0 +1,7 @@
+cmake_minimum_required(VERSION 3.21)
+
+project(${RunCMake_TEST} NONE)
+
+set(CMAKE_SYSROOT ${PROJECT_SOURCE_DIR}/${RunCMake_TEST})
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/cmake_host_system_information/CentOS6-stdout.txt b/Tests/RunCMake/cmake_host_system_information/CentOS6-stdout.txt
new file mode 100644
index 0000000..50dbb08
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/CentOS6-stdout.txt
@@ -0,0 +1,7 @@
+-- CENTOS6_ID=`centos`
+-- CENTOS6_ID_LIKE=`rhel`
+-- CENTOS6_NAME=`CentOS`
+-- CENTOS6_PRETTY_NAME=`CentOS release 6\.10 \(Final\)`
+-- CENTOS6_USED_FALLBACK_SCRIPT=`.*/Modules/Internal/OSRelease/010-TryOldCentOS.cmake`
+-- CENTOS6_VERSION=`6\.10`
+-- CENTOS6_VERSION_ID=`6\.10`
diff --git a/Tests/RunCMake/cmake_host_system_information/CentOS6.cmake b/Tests/RunCMake/cmake_host_system_information/CentOS6.cmake
new file mode 100644
index 0000000..3bc632b
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/CentOS6.cmake
@@ -0,0 +1,5 @@
+cmake_host_system_information(RESULT CENTOS6 QUERY DISTRIB_INFO)
+
+foreach(VAR IN LISTS CENTOS6)
+ message(STATUS "${VAR}=`${${VAR}}`")
+endforeach()
diff --git a/Tests/RunCMake/cmake_host_system_information/CentOS6/etc/centos-release b/Tests/RunCMake/cmake_host_system_information/CentOS6/etc/centos-release
new file mode 100644
index 0000000..294ccc9
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/CentOS6/etc/centos-release
@@ -0,0 +1 @@
+CentOS release 6.10 (Final)
diff --git a/Tests/RunCMake/cmake_host_system_information/Debian6-stdout.txt b/Tests/RunCMake/cmake_host_system_information/Debian6-stdout.txt
new file mode 100644
index 0000000..4193d6f
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Debian6-stdout.txt
@@ -0,0 +1,5 @@
+-- DEBIAN6_ID=`debian`
+-- DEBIAN6_NAME=`Debian`
+-- DEBIAN6_USED_FALLBACK_SCRIPT=`.*/Modules/Internal/OSRelease/020-TryDebianVersion.cmake`
+-- DEBIAN6_VERSION=`6\.0\.10`
+-- DEBIAN6_VERSION_ID=`6\.0\.10`
diff --git a/Tests/RunCMake/cmake_host_system_information/Debian6.cmake b/Tests/RunCMake/cmake_host_system_information/Debian6.cmake
new file mode 100644
index 0000000..cbf83a9
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Debian6.cmake
@@ -0,0 +1,5 @@
+cmake_host_system_information(RESULT DEBIAN6 QUERY DISTRIB_INFO)
+
+foreach(VAR IN LISTS DEBIAN6)
+ message(STATUS "${VAR}=`${${VAR}}`")
+endforeach()
diff --git a/Tests/RunCMake/cmake_host_system_information/Debian6/etc/debian_version b/Tests/RunCMake/cmake_host_system_information/Debian6/etc/debian_version
new file mode 100644
index 0000000..c7d48f0
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Debian6/etc/debian_version
@@ -0,0 +1 @@
+6.0.10
diff --git a/Tests/RunCMake/cmake_host_system_information/Exherbo-stdout.txt b/Tests/RunCMake/cmake_host_system_information/Exherbo-stdout.txt
new file mode 100644
index 0000000..11ae71f
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Exherbo-stdout.txt
@@ -0,0 +1,9 @@
+-- TEST1_ANSI_COLOR=`0;32`
+-- TEST1_BUG_REPORT_URL=`https://bugs.exherbo.org/`
+-- TEST1_HOME_URL=`https://www.exherbo.org/`
+-- TEST1_ID=`exherbo`
+-- TEST1_NAME=`Exherbo`
+-- TEST1_PRETTY_NAME=`Exherbo Linux`
+-- TEST1_SUPPORT_URL=`irc://irc.freenode.net/#exherbo`
+-- TEST2_ID=`exherbo`
+-- TEST2_VERSION=``
diff --git a/Tests/RunCMake/cmake_host_system_information/Exherbo.cmake b/Tests/RunCMake/cmake_host_system_information/Exherbo.cmake
new file mode 100644
index 0000000..7fc26d8
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Exherbo.cmake
@@ -0,0 +1,11 @@
+cmake_host_system_information(RESULT TEST1 QUERY DISTRIB_INFO)
+
+foreach(VAR IN LISTS TEST1)
+ message(STATUS "${VAR}=`${${VAR}}`")
+endforeach()
+
+# Query individual variables
+cmake_host_system_information(RESULT TEST2 QUERY DISTRIB_ID DISTRIB_VERSION)
+list(POP_FRONT TEST2 TEST2_ID TEST2_VERSION)
+message(STATUS "TEST2_ID=`${TEST2_ID}`")
+message(STATUS "TEST2_VERSION=`${TEST2_VERSION}`")
diff --git a/Tests/RunCMake/cmake_host_system_information/Exherbo/etc/os-release b/Tests/RunCMake/cmake_host_system_information/Exherbo/etc/os-release
new file mode 100644
index 0000000..944c9b4
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Exherbo/etc/os-release
@@ -0,0 +1,7 @@
+NAME="Exherbo"
+PRETTY_NAME="Exherbo Linux"
+ID="exherbo"
+ANSI_COLOR="0;32"
+HOME_URL="https://www.exherbo.org/"
+SUPPORT_URL="irc://irc.freenode.net/#exherbo"
+BUG_REPORT_URL="https://bugs.exherbo.org/"
diff --git a/Tests/RunCMake/cmake_host_system_information/QueryKeys-stdout.txt b/Tests/RunCMake/cmake_host_system_information/QueryKeys-stdout.txt
new file mode 100644
index 0000000..f583deb
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/QueryKeys-stdout.txt
@@ -0,0 +1,27 @@
+-- NUMBER_OF_LOGICAL_CORES=`[0-9]+`
+-- NUMBER_OF_PHYSICAL_CORES=`[0-9]+`
+-- HOSTNAME=`.*`
+-- FQDN=`.*`
+-- TOTAL_VIRTUAL_MEMORY=`[0-9]+`
+-- AVAILABLE_VIRTUAL_MEMORY=`[0-9]+`
+-- TOTAL_PHYSICAL_MEMORY=`[0-9]+`
+-- AVAILABLE_PHYSICAL_MEMORY=`[0-9]+`
+-- IS_64BIT=`[01]`
+-- HAS_FPU=`[01]`
+-- HAS_MMX=`[01]`
+-- HAS_MMX_PLUS=`[01]`
+-- HAS_SSE=`[01]`
+-- HAS_SSE2=`[01]`
+-- HAS_SSE_FP=`[01]`
+-- HAS_SSE_MMX=`[01]`
+-- HAS_AMD_3DNOW=`[01]`
+-- HAS_AMD_3DNOW_PLUS=`[01]`
+-- HAS_IA64=`[01]`
+-- HAS_SERIAL_NUMBER=`[01]`
+-- PROCESSOR_SERIAL_NUMBER=`.*`
+-- PROCESSOR_NAME=`.*`
+-- PROCESSOR_DESCRIPTION=`.*`
+-- OS_NAME=`.*`
+-- OS_RELEASE=`.*`
+-- OS_VERSION=`.*`
+-- OS_PLATFORM=`.*`
diff --git a/Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in b/Tests/RunCMake/cmake_host_system_information/QueryKeys.cmake
index a3c2b05..f22a0ae 100644
--- a/Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in
+++ b/Tests/RunCMake/cmake_host_system_information/QueryKeys.cmake
@@ -1,19 +1,8 @@
-set(BadArg1-RESULT 1)
-set(BadArg1-STDERR "missing RESULT specification")
-set(BadArg2-RESULT 1)
-set(BadArg2-STDERR "missing QUERY specification")
-set(BadArg3-RESULT 1)
-set(BadArg3-STDERR "does not recognize <key> FOOBAR")
-set(QueryList-RESULT 0)
-set(QueryList-STDERR "\\[[0-9]+;[0-9]+\\]")
-
function(try_and_print key)
- cmake_host_system_information(RESULT RESULT QUERY ${key})
- message(STATUS "[${key}] [${RESULT}]")
+ cmake_host_system_information(RESULT RESULT QUERY ${key})
+ message(STATUS "${key}=`${RESULT}`")
endfunction()
-message("CTEST_FULL_OUTPUT (Avoid ctest truncation of output)")
-
try_and_print(NUMBER_OF_LOGICAL_CORES)
try_and_print(NUMBER_OF_PHYSICAL_CORES)
try_and_print(HOSTNAME)
@@ -41,12 +30,3 @@ try_and_print(OS_NAME)
try_and_print(OS_RELEASE)
try_and_print(OS_VERSION)
try_and_print(OS_PLATFORM)
-
-include("@CMAKE_CURRENT_SOURCE_DIR@/CheckCMakeTest.cmake")
-
-check_cmake_test(CMakeHostSystemInformation
- BadArg1
- BadArg2
- BadArg3
- QueryList
-)
diff --git a/Tests/RunCMake/cmake_host_system_information/QueryList-stdout.txt b/Tests/RunCMake/cmake_host_system_information/QueryList-stdout.txt
new file mode 100644
index 0000000..eebe0d4
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/QueryList-stdout.txt
@@ -0,0 +1 @@
+-- \[[0-9]+;[0-9]+\]
diff --git a/Tests/CMakeTests/CMakeHostSystemInformation-QueryList.cmake b/Tests/RunCMake/cmake_host_system_information/QueryList.cmake
index 1c3156d..f24aa2b 100644
--- a/Tests/CMakeTests/CMakeHostSystemInformation-QueryList.cmake
+++ b/Tests/RunCMake/cmake_host_system_information/QueryList.cmake
@@ -2,4 +2,4 @@ cmake_host_system_information(RESULT RESULT
QUERY NUMBER_OF_LOGICAL_CORES NUMBER_OF_PHYSICAL_CORES
)
-message("[${RESULT}]")
+message(STATUS "[${RESULT}]")
diff --git a/Tests/RunCMake/cmake_host_system_information/RunCMakeTest.cmake b/Tests/RunCMake/cmake_host_system_information/RunCMakeTest.cmake
new file mode 100644
index 0000000..189013f
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/RunCMakeTest.cmake
@@ -0,0 +1,17 @@
+include(RunCMake)
+
+run_cmake(BadArg1)
+run_cmake(BadArg2)
+run_cmake(BadArg3)
+
+run_cmake(QueryList)
+run_cmake(QueryKeys)
+
+run_cmake(UnitTest)
+run_cmake(Exherbo)
+run_cmake(Ubuntu)
+
+run_cmake(CentOS6)
+run_cmake(Debian6)
+
+run_cmake(UserFallbackScript)
diff --git a/Tests/RunCMake/cmake_host_system_information/Ubuntu-stdout.txt b/Tests/RunCMake/cmake_host_system_information/Ubuntu-stdout.txt
new file mode 100644
index 0000000..d1a18da
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Ubuntu-stdout.txt
@@ -0,0 +1,14 @@
+-- TEST1_BUG_REPORT_URL=`https://bugs\.launchpad\.net/ubuntu/`
+-- TEST1_HOME_URL=`https://www\.ubuntu\.com/`
+-- TEST1_ID=`ubuntu`
+-- TEST1_ID_LIKE=`debian`
+-- TEST1_NAME=`Ubuntu`
+-- TEST1_PRETTY_NAME=`Ubuntu 20\.04\.2 LTS`
+-- TEST1_PRIVACY_POLICY_URL=`https://www\.ubuntu\.com/legal/terms-and-policies/privacy-policy`
+-- TEST1_SUPPORT_URL=`https://help\.ubuntu\.com/`
+-- TEST1_UBUNTU_CODENAME=`focal`
+-- TEST1_VERSION=`20\.04\.2 LTS \(Focal Fossa\)`
+-- TEST1_VERSION_CODENAME=`focal`
+-- TEST1_VERSION_ID=`20\.04`
+-- TEST2_ID=`ubuntu`
+-- TEST2_VERSION=`20\.04\.2 LTS \(Focal Fossa\)`
diff --git a/Tests/RunCMake/cmake_host_system_information/Ubuntu.cmake b/Tests/RunCMake/cmake_host_system_information/Ubuntu.cmake
new file mode 100644
index 0000000..7fc26d8
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Ubuntu.cmake
@@ -0,0 +1,11 @@
+cmake_host_system_information(RESULT TEST1 QUERY DISTRIB_INFO)
+
+foreach(VAR IN LISTS TEST1)
+ message(STATUS "${VAR}=`${${VAR}}`")
+endforeach()
+
+# Query individual variables
+cmake_host_system_information(RESULT TEST2 QUERY DISTRIB_ID DISTRIB_VERSION)
+list(POP_FRONT TEST2 TEST2_ID TEST2_VERSION)
+message(STATUS "TEST2_ID=`${TEST2_ID}`")
+message(STATUS "TEST2_VERSION=`${TEST2_VERSION}`")
diff --git a/Tests/RunCMake/cmake_host_system_information/Ubuntu/etc/os-release b/Tests/RunCMake/cmake_host_system_information/Ubuntu/etc/os-release
new file mode 100644
index 0000000..f228f22
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/Ubuntu/etc/os-release
@@ -0,0 +1,12 @@
+NAME="Ubuntu"
+VERSION="20.04.2 LTS (Focal Fossa)"
+ID=ubuntu
+ID_LIKE=debian
+PRETTY_NAME="Ubuntu 20.04.2 LTS"
+VERSION_ID="20.04"
+HOME_URL="https://www.ubuntu.com/"
+SUPPORT_URL="https://help.ubuntu.com/"
+BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
+PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
+VERSION_CODENAME=focal
+UBUNTU_CODENAME=focal
diff --git a/Tests/RunCMake/cmake_host_system_information/UnitTest-stdout.txt b/Tests/RunCMake/cmake_host_system_information/UnitTest-stdout.txt
new file mode 100644
index 0000000..db6f487
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/UnitTest-stdout.txt
@@ -0,0 +1,7 @@
+-- UNIT_TEST_A_LIST_LIKE_VARIABLE=`satu;dua;tiga`
+-- UNIT_TEST_DBL_QUOTED_VALUE=`"The" value in double "quotes"`
+-- UNIT_TEST_DBL_QUOTED_VALUE_STIPPED_COMMENT=`Blah blah blah`
+-- UNIT_TEST_NON_SPACE_VALUE=`Blah-blah-blah`
+-- UNIT_TEST_QUOTED_VALUE=`'The' value in single 'quotes'`
+-- UNIT_TEST_QUOTED_VALUE_STIPPED_COMMENT=`The value in single quotes`
+-- UNIT_TEST_THE_URL_WITH_ANCHOR_TEST=`https://blah.blah/resource#anchor`
diff --git a/Tests/RunCMake/cmake_host_system_information/UnitTest.cmake b/Tests/RunCMake/cmake_host_system_information/UnitTest.cmake
new file mode 100644
index 0000000..d9a0aca
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/UnitTest.cmake
@@ -0,0 +1,5 @@
+cmake_host_system_information(RESULT UNIT_TEST QUERY DISTRIB_INFO)
+
+foreach(VAR IN LISTS UNIT_TEST)
+ message(STATUS "${VAR}=`${${VAR}}`")
+endforeach()
diff --git a/Tests/RunCMake/cmake_host_system_information/UnitTest/etc/os-release b/Tests/RunCMake/cmake_host_system_information/UnitTest/etc/os-release
new file mode 100644
index 0000000..66c33b5
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/UnitTest/etc/os-release
@@ -0,0 +1,9 @@
+# Comment string gonna be ignored
+NON_SPACE_VALUE=Blah-blah-blah
+QUOTED_VALUE='\'The\' value in single \'quotes\''
+QUOTED_VALUE_STIPPED_COMMENT='The value in single quotes'# The comment right after `'`
+DBL_QUOTED_VALUE="\"The\" value in double \"quotes\""
+DBL_QUOTED_VALUE_STIPPED_COMMENT="Blah blah blah"# The comment right after `'`
+THE_URL_WITH_ANCHOR_TEST="https://blah.blah/resource#anchor" # And a comment after
+A_LIST_LIKE_VARIABLE='satu;dua;tiga'
+INCORRECT_ESCAPE_IGNORED=\'This line gonna be ignored'
diff --git a/Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stderr.txt b/Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stderr.txt
new file mode 100644
index 0000000..78acea2
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stderr.txt
@@ -0,0 +1,5 @@
+CMake Warning at 000-FirstFallbackScript\.cmake:[0-9]+ \(message\):
+ The warning text to match just to make sure the script get executed
+Call Stack \(most recent call first\):
+ UserFallbackScript\.cmake:[0-9]+ \(cmake_host_system_information\)
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stdout.txt b/Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stdout.txt
new file mode 100644
index 0000000..acaf47e
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/UserFallbackScript-stdout.txt
@@ -0,0 +1,7 @@
+-- UFS_ID=`unittest`
+-- UFS_ID_LIKE=`nothing`
+-- UFS_NAME=`UnitTest`
+-- UFS_PRETTY_NAME=`Just a Unit Test`
+-- UFS_USED_FALLBACK_SCRIPT=`.*/999-LastFallbackScript\.cmake`
+-- UFS_VERSION=`0\.0\.1`
+-- UFS_VERSION_ID=`0\.0\.1`
diff --git a/Tests/RunCMake/cmake_host_system_information/UserFallbackScript.cmake b/Tests/RunCMake/cmake_host_system_information/UserFallbackScript.cmake
new file mode 100644
index 0000000..660aa1c
--- /dev/null
+++ b/Tests/RunCMake/cmake_host_system_information/UserFallbackScript.cmake
@@ -0,0 +1,12 @@
+list(
+ APPEND CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS
+ ${CMAKE_CURRENT_SOURCE_DIR}/000-FirstFallbackScript.cmake
+ ${CMAKE_CURRENT_SOURCE_DIR}/Ignored-Script.cmake
+ ${CMAKE_CURRENT_SOURCE_DIR}/999-LastFallbackScript.cmake
+ )
+
+cmake_host_system_information(RESULT UFS QUERY DISTRIB_INFO)
+
+foreach(VAR IN LISTS UFS)
+ message(STATUS "${VAR}=`${${VAR}}`")
+endforeach()
diff --git a/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-check.cmake b/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-check.cmake
new file mode 100644
index 0000000..9d2a059
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-check.cmake
@@ -0,0 +1,10 @@
+function (find_xml_file name)
+ file(GLOB test_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/${name}.xml")
+ if (NOT test_xml_file)
+ message(FATAL_ERROR
+ "${name}.xml not created.")
+ endif ()
+endfunction ()
+
+find_xml_file(DynamicAnalysis)
+find_xml_file(DynamicAnalysis-Test)
diff --git a/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stderr.txt b/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stderr.txt
new file mode 100644
index 0000000..e1fc77a
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stderr.txt
@@ -0,0 +1 @@
+Cannot find memory tester output file: .*/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-build/Testing/Temporary/MemoryChecker.1.log\.\*
diff --git a/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stdout.txt b/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stdout.txt
new file mode 100644
index 0000000..b3473bf
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/ExpectedOutputs-stdout.txt
@@ -0,0 +1,2 @@
+Memory checking results:
+left shift of negative value -256 - 1
diff --git a/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake b/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
index 6e0a91c..cb8f696 100644
--- a/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
@@ -95,6 +95,19 @@ unset(CMAKELISTS_EXTRA_CODE)
unset(CTEST_EXTRA_CODE)
#-----------------------------------------------------------------------------
+# add output test
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1\")
+")
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"\${CMAKE_COMMAND}\"
+-P \"${RunCMake_SOURCE_DIR}/testUndefinedBehaviorSanitizer.cmake\")
+")
+run_mc_test(ExpectedOutputs "" -DMEMCHECK_TYPE=UndefinedBehaviorSanitizer)
+unset(CMAKELISTS_EXTRA_CODE)
+unset(CTEST_EXTRA_CODE)
+
+#-----------------------------------------------------------------------------
set(CTEST_EXTRA_CODE "string(REPLACE \" \" \"\\\\ \" PRE_POST_COMMAND \"\${CTEST_MEMORYCHECK_COMMAND}\")
set(CTEST_CUSTOM_PRE_MEMCHECK \"\${PRE_POST_COMMAND} pre command\")
diff --git a/Tests/RunCMake/if/RunCMakeTest.cmake b/Tests/RunCMake/if/RunCMakeTest.cmake
index 239c167..6baa840 100644
--- a/Tests/RunCMake/if/RunCMakeTest.cmake
+++ b/Tests/RunCMake/if/RunCMakeTest.cmake
@@ -9,6 +9,8 @@ run_cmake(duplicate-else-after-elseif)
run_cmake(elseif-message)
run_cmake(misplaced-elseif)
+run_cmake(unbalanced-parenthesis)
+
run_cmake(MatchesSelf)
run_cmake(IncompleteMatches)
run_cmake(IncompleteMatchesFail)
diff --git a/Tests/RunCMake/if/unbalanced-parenthesis-result.txt b/Tests/RunCMake/if/unbalanced-parenthesis-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/if/unbalanced-parenthesis-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/if/unbalanced-parenthesis-stderr.txt b/Tests/RunCMake/if/unbalanced-parenthesis-stderr.txt
new file mode 100644
index 0000000..770ccb8
--- /dev/null
+++ b/Tests/RunCMake/if/unbalanced-parenthesis-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at unbalanced-parenthesis\.cmake:[0-9]+ \(if\):
+ if given arguments:
+
+ "NOT" "\(" "IN_LIST" "some_list"
+
+ mismatched parenthesis in condition
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/if/unbalanced-parenthesis.cmake b/Tests/RunCMake/if/unbalanced-parenthesis.cmake
new file mode 100644
index 0000000..c51c755
--- /dev/null
+++ b/Tests/RunCMake/if/unbalanced-parenthesis.cmake
@@ -0,0 +1,8 @@
+set(var_with_paren "(")
+set(some_list "")
+
+if(NOT ${var_with_paren} IN_LIST some_list)
+ message(STATUS "Never prints")
+else()
+ message(STATUS "Never prints")
+endif()
diff --git a/Tests/RunCMake/while/RunCMakeTest.cmake b/Tests/RunCMake/while/RunCMakeTest.cmake
index 7da80ac..bb9b991 100644
--- a/Tests/RunCMake/while/RunCMakeTest.cmake
+++ b/Tests/RunCMake/while/RunCMakeTest.cmake
@@ -5,3 +5,5 @@ run_cmake(EndMissing)
run_cmake(EndMismatch)
run_cmake(EndAlone)
run_cmake(EndAloneArgs)
+
+run_cmake(unbalanced-parenthesis)
diff --git a/Tests/RunCMake/while/unbalanced-parenthesis-result.txt b/Tests/RunCMake/while/unbalanced-parenthesis-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/while/unbalanced-parenthesis-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/while/unbalanced-parenthesis-stderr.txt b/Tests/RunCMake/while/unbalanced-parenthesis-stderr.txt
new file mode 100644
index 0000000..9d4132c
--- /dev/null
+++ b/Tests/RunCMake/while/unbalanced-parenthesis-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at unbalanced-parenthesis.cmake:[0-9]+ \(while\):
+ had incorrect arguments:
+
+ "NOT" "\(" "IN_LIST" "some_list"
+
+ mismatched parenthesis in condition
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/while/unbalanced-parenthesis.cmake b/Tests/RunCMake/while/unbalanced-parenthesis.cmake
new file mode 100644
index 0000000..7a12701
--- /dev/null
+++ b/Tests/RunCMake/while/unbalanced-parenthesis.cmake
@@ -0,0 +1,8 @@
+set(var_with_paren "(")
+set(some_list "")
+
+while(NOT ${var_with_paren} IN_LIST some_list)
+ message(STATUS "Never prints")
+endwhile()
+
+message(STATUS "Never prints")
diff --git a/Utilities/IWYU/mapping.imp b/Utilities/IWYU/mapping.imp
index f1bdcc4..8c55c85 100644
--- a/Utilities/IWYU/mapping.imp
+++ b/Utilities/IWYU/mapping.imp
@@ -101,6 +101,7 @@
# Wrappers for 3rd-party libraries
{ include: [ "@<.*curl/curlver.h>", private, "<cm3p/curl/curl.h>", public ] },
+ { include: [ "@<.*json/config.h>", private, "<cm3p/json/value.h>", public ] },
{ include: [ "@<.*json/forwards.h>", private, "<cm3p/json/value.h>", public ] },
{ include: [ "@<.*uv/.+\\.h>", private, "<cm3p/uv.h>", public ] },
{ include: [ "@<.*expat_external.h>", private, "<cm3p/expat.h>", public ] },
diff --git a/Utilities/KWIML/include/kwiml/int.h b/Utilities/KWIML/include/kwiml/int.h
index b2e14d5..25a063a 100644
--- a/Utilities/KWIML/include/kwiml/int.h
+++ b/Utilities/KWIML/include/kwiml/int.h
@@ -162,7 +162,11 @@ An includer may test the following macros after inclusion:
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
# define KWIML_INT_HAVE_INTTYPES_H 1
#elif defined(_MSC_VER) /* MSVC */
-# define KWIML_INT_NO_INTTYPES_H 1
+# if _MSC_VER >= 1800
+# define KWIML_INT_HAVE_INTTYPES_H 1
+# else
+# define KWIML_INT_NO_INTTYPES_H 1
+# endif
#elif defined(__BORLANDC__) /* Borland */
# define KWIML_INT_NO_INTTYPES_H 1
#elif defined(__WATCOMC__) /* Watcom */
@@ -272,6 +276,15 @@ An includer may test the following macros after inclusion:
# define KWIML_INT_BROKEN_PRIXPTR 1
#endif
+#if defined(_MSC_VER) && _MSC_VER < 1900
+ /* MSVC scanf seems broken on 8-bit sizes until 19.00 */
+# define KWIML_INT_BROKEN_SCNd8 1
+# define KWIML_INT_BROKEN_SCNi8 1
+# define KWIML_INT_BROKEN_SCNo8 1
+# define KWIML_INT_BROKEN_SCNu8 1
+# define KWIML_INT_BROKEN_SCNx8 1
+#endif
+
#if (defined(__SUNPRO_C)||defined(__SUNPRO_CC)) && defined(_CHAR_IS_UNSIGNED)
# define KWIML_INT_BROKEN_INT8_T 1 /* system type defined incorrectly */
#elif defined(__BORLANDC__) && defined(_CHAR_UNSIGNED)
@@ -303,7 +316,7 @@ An includer may test the following macros after inclusion:
#elif defined(__BORLANDC__)
# define KWIML_INT_private_NO_SCN8
# define KWIML_INT_private_NO_SCN64
-#elif defined(_MSC_VER)
+#elif defined(_MSC_VER) && _MSC_VER < 1900
# define KWIML_INT_private_NO_SCN8
#elif defined(__WATCOMC__)
# define KWIML_INT_private_NO_SCN8
diff --git a/Utilities/Scripts/update-jsoncpp.bash b/Utilities/Scripts/update-jsoncpp.bash
index f8fe544..5ed00e7 100755
--- a/Utilities/Scripts/update-jsoncpp.bash
+++ b/Utilities/Scripts/update-jsoncpp.bash
@@ -8,7 +8,7 @@ readonly name="jsoncpp"
readonly ownership="JsonCpp Upstream <kwrobot@kitware.com>"
readonly subtree="Utilities/cmjsoncpp"
readonly repo="https://github.com/open-source-parsers/jsoncpp.git"
-readonly tag="1.8.2"
+readonly tag="1.9.4"
readonly shortlog=false
readonly paths="
LICENSE
diff --git a/Utilities/Scripts/update-libarchive.bash b/Utilities/Scripts/update-libarchive.bash
index 3db89ff..3a24e2b 100755
--- a/Utilities/Scripts/update-libarchive.bash
+++ b/Utilities/Scripts/update-libarchive.bash
@@ -8,7 +8,7 @@ readonly name="LibArchive"
readonly ownership="LibArchive Upstream <libarchive-discuss@googlegroups.com>"
readonly subtree="Utilities/cmlibarchive"
readonly repo="https://github.com/libarchive/libarchive.git"
-readonly tag="v3.4.2"
+readonly tag="v3.5.1"
readonly shortlog=false
readonly paths="
CMakeLists.txt
diff --git a/Utilities/cmThirdPartyChecks.cmake b/Utilities/cmThirdPartyChecks.cmake
index bab3046..7e38df9 100644
--- a/Utilities/cmThirdPartyChecks.cmake
+++ b/Utilities/cmThirdPartyChecks.cmake
@@ -180,6 +180,7 @@ if(WIN32)
set(HAVE_STRERROR_R 0)
set(HAVE_STRNCMPI 0)
set(HAVE_STRNCPY_S 1)
+ set(HAVE_STRNLEN 1)
set(HAVE_STROPTS_H 0)
set(HAVE__STRTOI64 1)
set(HAVE_STRTOLL 1)
diff --git a/Utilities/cmjsoncpp/include/json/allocator.h b/Utilities/cmjsoncpp/include/json/allocator.h
index 9562436..a685da1 100644
--- a/Utilities/cmjsoncpp/include/json/allocator.h
+++ b/Utilities/cmjsoncpp/include/json/allocator.h
@@ -3,8 +3,8 @@
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-#ifndef CPPTL_JSON_ALLOCATOR_H_INCLUDED
-#define CPPTL_JSON_ALLOCATOR_H_INCLUDED
+#ifndef JSON_ALLOCATOR_H_INCLUDED
+#define JSON_ALLOCATOR_H_INCLUDED
#include <cstring>
#include <memory>
@@ -14,89 +14,80 @@
#endif
namespace Json {
-template<typename T>
-class SecureAllocator {
- public:
- // Type definitions
- using value_type = T;
- using pointer = T*;
- using const_pointer = const T*;
- using reference = T&;
- using const_reference = const T&;
- using size_type = std::size_t;
- using difference_type = std::ptrdiff_t;
-
- /**
- * Allocate memory for N items using the standard allocator.
- */
- pointer allocate(size_type n) {
- // allocate using "global operator new"
- return static_cast<pointer>(::operator new(n * sizeof(T)));
- }
-
- /**
- * Release memory which was allocated for N items at pointer P.
- *
- * The memory block is filled with zeroes before being released.
- * The pointer argument is tagged as "volatile" to prevent the
- * compiler optimizing out this critical step.
- */
- void deallocate(volatile pointer p, size_type n) {
- std::memset(p, 0, n * sizeof(T));
- // free using "global operator delete"
- ::operator delete(p);
- }
-
- /**
- * Construct an item in-place at pointer P.
- */
- template<typename... Args>
- void construct(pointer p, Args&&... args) {
- // construct using "placement new" and "perfect forwarding"
- ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
- }
-
- size_type max_size() const {
- return size_t(-1) / sizeof(T);
- }
-
- pointer address( reference x ) const {
- return std::addressof(x);
- }
-
- const_pointer address( const_reference x ) const {
- return std::addressof(x);
- }
-
- /**
- * Destroy an item in-place at pointer P.
- */
- void destroy(pointer p) {
- // destroy using "explicit destructor"
- p->~T();
- }
-
- // Boilerplate
- SecureAllocator() {}
- template<typename U> SecureAllocator(const SecureAllocator<U>&) {}
- template<typename U> struct rebind { using other = SecureAllocator<U>; };
+template <typename T> class SecureAllocator {
+public:
+ // Type definitions
+ using value_type = T;
+ using pointer = T*;
+ using const_pointer = const T*;
+ using reference = T&;
+ using const_reference = const T&;
+ using size_type = std::size_t;
+ using difference_type = std::ptrdiff_t;
+
+ /**
+ * Allocate memory for N items using the standard allocator.
+ */
+ pointer allocate(size_type n) {
+ // allocate using "global operator new"
+ return static_cast<pointer>(::operator new(n * sizeof(T)));
+ }
+
+ /**
+ * Release memory which was allocated for N items at pointer P.
+ *
+ * The memory block is filled with zeroes before being released.
+ * The pointer argument is tagged as "volatile" to prevent the
+ * compiler optimizing out this critical step.
+ */
+ void deallocate(volatile pointer p, size_type n) {
+ std::memset(p, 0, n * sizeof(T));
+ // free using "global operator delete"
+ ::operator delete(p);
+ }
+
+ /**
+ * Construct an item in-place at pointer P.
+ */
+ template <typename... Args> void construct(pointer p, Args&&... args) {
+ // construct using "placement new" and "perfect forwarding"
+ ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
+ }
+
+ size_type max_size() const { return size_t(-1) / sizeof(T); }
+
+ pointer address(reference x) const { return std::addressof(x); }
+
+ const_pointer address(const_reference x) const { return std::addressof(x); }
+
+ /**
+ * Destroy an item in-place at pointer P.
+ */
+ void destroy(pointer p) {
+ // destroy using "explicit destructor"
+ p->~T();
+ }
+
+ // Boilerplate
+ SecureAllocator() {}
+ template <typename U> SecureAllocator(const SecureAllocator<U>&) {}
+ template <typename U> struct rebind { using other = SecureAllocator<U>; };
};
-
-template<typename T, typename U>
+template <typename T, typename U>
bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
- return true;
+ return true;
}
-template<typename T, typename U>
+template <typename T, typename U>
bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
- return false;
+ return false;
}
-} //namespace Json
+} // namespace Json
#if !defined(__SUNPRO_CC)
#pragma pack(pop)
#endif
-#endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED
+#endif // JSON_ALLOCATOR_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/assertions.h b/Utilities/cmjsoncpp/include/json/assertions.h
index f64913f..415c463 100644
--- a/Utilities/cmjsoncpp/include/json/assertions.h
+++ b/Utilities/cmjsoncpp/include/json/assertions.h
@@ -3,14 +3,14 @@
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
-#define CPPTL_JSON_ASSERTIONS_H_INCLUDED
+#ifndef JSON_ASSERTIONS_H_INCLUDED
+#define JSON_ASSERTIONS_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
-#include <stdlib.h>
+#include <cstdlib>
#include <sstream>
/** It should not be possible for a maliciously designed file to
@@ -20,35 +20,42 @@
#if JSON_USE_EXCEPTION
// @todo <= add detail about condition in exception
-# define JSON_ASSERT(condition) \
- {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
-
-# define JSON_FAIL_MESSAGE(message) \
- { \
- JSONCPP_OSTRINGSTREAM oss; oss << message; \
+#define JSON_ASSERT(condition) \
+ do { \
+ if (!(condition)) { \
+ Json::throwLogicError("assert json failed"); \
+ } \
+ } while (0)
+
+#define JSON_FAIL_MESSAGE(message) \
+ do { \
+ OStringStream oss; \
+ oss << message; \
Json::throwLogicError(oss.str()); \
abort(); \
- }
+ } while (0)
#else // JSON_USE_EXCEPTION
-# define JSON_ASSERT(condition) assert(condition)
+#define JSON_ASSERT(condition) assert(condition)
// The call to assert() will show the failure message in debug builds. In
// release builds we abort, for a core-dump or debugger.
-# define JSON_FAIL_MESSAGE(message) \
+#define JSON_FAIL_MESSAGE(message) \
{ \
- JSONCPP_OSTRINGSTREAM oss; oss << message; \
+ OStringStream oss; \
+ oss << message; \
assert(false && oss.str().c_str()); \
abort(); \
}
-
#endif
#define JSON_ASSERT_MESSAGE(condition, message) \
- if (!(condition)) { \
- JSON_FAIL_MESSAGE(message); \
- }
+ do { \
+ if (!(condition)) { \
+ JSON_FAIL_MESSAGE(message); \
+ } \
+ } while (0)
-#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
+#endif // JSON_ASSERTIONS_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/config.h b/Utilities/cmjsoncpp/include/json/config.h
index 2cc8462..f03b746 100644
--- a/Utilities/cmjsoncpp/include/json/config.h
+++ b/Utilities/cmjsoncpp/include/json/config.h
@@ -6,26 +6,18 @@
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
-// Include KWSys Large File Support configuration.
-#include <cmsys/Configure.h>
-
-#include <stddef.h>
-#include <string> //typedef String
-#include <stdint.h> //typedef int64_t, uint64_t
-
#if defined(_MSC_VER)
# pragma warning(push,1)
#endif
-/// If defined, indicates that json library is embedded in CppTL library.
-//# define JSON_IN_CPPTL 1
-
-/// If defined, indicates that json may leverage CppTL library
-//# define JSON_USE_CPPTL 1
-/// If defined, indicates that cpptl vector based map should be used instead of
-/// std::map
-/// as Value container.
-//# define JSON_USE_CPPTL_SMALLMAP 1
+#include <cstddef>
+#include <cstdint>
+#include <istream>
+#include <memory>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <type_traits>
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
@@ -33,108 +25,73 @@
#define JSON_USE_EXCEPTION 1
#endif
-/// If defined, indicates that the source file is amalgated
+// Temporary, tracked for removal with issue #982.
+#ifndef JSON_USE_NULLREF
+#define JSON_USE_NULLREF 1
+#endif
+
+/// If defined, indicates that the source file is amalgamated
/// to prevent private header inclusion.
-/// Remarks: it is automatically defined in the generated amalgated header.
+/// Remarks: it is automatically defined in the generated amalgamated header.
// #define JSON_IS_AMALGAMATION
-#ifdef JSON_IN_CPPTL
-#include <cpptl/config.h>
-#ifndef JSON_USE_CPPTL
-#define JSON_USE_CPPTL 1
-#endif
-#endif
-
-#ifdef JSON_IN_CPPTL
-#define JSON_API CPPTL_API
-#elif defined(JSON_DLL_BUILD)
+// Export macros for DLL visibility
+#if defined(JSON_DLL_BUILD)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#elif defined(__GNUC__) || defined(__clang__)
+#define JSON_API __attribute__((visibility("default")))
#endif // if defined(_MSC_VER)
+
#elif defined(JSON_DLL)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
-#endif // ifdef JSON_IN_CPPTL
+#endif // ifdef JSON_DLL_BUILD
+
#if !defined(JSON_API)
#define JSON_API
#endif
-// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
-// integer
-// Storages, and 64 bits integer support is disabled.
-// #define JSON_NO_INT64 1
+#if defined(_MSC_VER) && _MSC_VER < 1800
+#error \
+ "ERROR: Visual Studio 12 (2013) with _MSC_VER=1800 is the oldest supported compiler with sufficient C++11 capabilities"
+#endif
-#if defined(_MSC_VER) // MSVC
-# if _MSC_VER <= 1200 // MSVC 6
- // Microsoft Visual Studio 6 only support conversion from __int64 to double
- // (no conversion from unsigned __int64).
-# define JSON_USE_INT64_DOUBLE_CONVERSION 1
- // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
- // characters in the debug information)
- // All projects I've ever seen with VS6 were using this globally (not bothering
- // with pragma push/pop).
-# pragma warning(disable : 4786)
-# endif // MSVC 6
-
-#endif // defined(_MSC_VER)
-
-// In c++11 the override keyword allows you to explicity define that a function
-// is intended to override the base-class version. This makes the code more
-// managable and fixes a set of common hard-to-find bugs.
-#if __cplusplus >= 201103L
-# define JSONCPP_OVERRIDE override
-# define JSONCPP_NOEXCEPT noexcept
-#elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900
-# define JSONCPP_OVERRIDE override
-# define JSONCPP_NOEXCEPT throw()
-#elif defined(_MSC_VER) && _MSC_VER >= 1900
-# define JSONCPP_OVERRIDE override
-# define JSONCPP_NOEXCEPT noexcept
+#if defined(_MSC_VER) && _MSC_VER < 1900
+// As recommended at
+// https://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
+extern JSON_API int msvc_pre1900_c99_snprintf(char* outBuf, size_t size,
+ const char* format, ...);
+#define jsoncpp_snprintf msvc_pre1900_c99_snprintf
#else
-# define JSONCPP_OVERRIDE
-# define JSONCPP_NOEXCEPT throw()
+#define jsoncpp_snprintf std::snprintf
#endif
-#ifndef JSON_HAS_RVALUE_REFERENCES
+// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
+// integer
+// Storages, and 64 bits integer support is disabled.
+// #define JSON_NO_INT64 1
-#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
-#define JSON_HAS_RVALUE_REFERENCES 1
-#endif // MSVC >= 2010
+// JSONCPP_OVERRIDE is maintained for backwards compatibility of external tools.
+// C++11 should be used directly in JSONCPP.
+#define JSONCPP_OVERRIDE override
#ifdef __clang__
-#if __has_feature(cxx_rvalue_references)
-#define JSON_HAS_RVALUE_REFERENCES 1
-#endif // has_feature
-
-#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
-#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
-#define JSON_HAS_RVALUE_REFERENCES 1
-#endif // GXX_EXPERIMENTAL
-
-#endif // __clang__ || __GNUC__
-
-#endif // not defined JSON_HAS_RVALUE_REFERENCES
-
-#ifndef JSON_HAS_RVALUE_REFERENCES
-#define JSON_HAS_RVALUE_REFERENCES 0
+#if __has_extension(attribute_deprecated_with_message)
+#define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
#endif
-
-#ifdef __clang__
-# if __has_extension(attribute_deprecated_with_message)
-# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
-# endif
-#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
-# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
-# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
-# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
-# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
-# endif // GNUC version
-#elif defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
- /// Indicates that the following function is deprecated.
-# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+#elif defined(__GNUC__) // not clang (gcc comes later since clang emulates gcc)
+#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
+#define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message)))
+#elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+#define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
+#endif // GNUC version
+#elif defined(_MSC_VER) // MSVC (after clang because clang on Windows emulates
+ // MSVC)
+#define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
#endif // __clang__ || __GNUC__ || _MSC_VER
#undef JSONCPP_DEPRECATED // no deprecations in CMake copy
@@ -142,53 +99,58 @@
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
-#if __GNUC__ >= 6
-# define JSON_USE_INT64_DOUBLE_CONVERSION 1
+#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6))
+#define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif
#if !defined(JSON_IS_AMALGAMATION)
-# include "version.h"
-
-# if JSONCPP_USING_SECURE_MEMORY
-# include "allocator.h" //typedef Allocator
-# endif
+#include "allocator.h"
+#include "version.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
-typedef int Int;
-typedef unsigned int UInt;
+using Int = int;
+using UInt = unsigned int;
#if defined(JSON_NO_INT64)
-typedef int LargestInt;
-typedef unsigned int LargestUInt;
+using LargestInt = int;
+using LargestUInt = unsigned int;
#undef JSON_HAS_INT64
#else // if defined(JSON_NO_INT64)
// For Microsoft Visual use specific types as long long is not supported
#if defined(_MSC_VER) // Microsoft Visual Studio
-typedef __int64 Int64;
-typedef unsigned __int64 UInt64;
+using Int64 = __int64;
+using UInt64 = unsigned __int64;
#else // if defined(_MSC_VER) // Other platforms, use long long
-typedef int64_t Int64;
-typedef uint64_t UInt64;
-#endif // if defined(_MSC_VER)
-typedef Int64 LargestInt;
-typedef UInt64 LargestUInt;
+using Int64 = int64_t;
+using UInt64 = uint64_t;
+#endif // if defined(_MSC_VER)
+using LargestInt = Int64;
+using LargestUInt = UInt64;
#define JSON_HAS_INT64
#endif // if defined(JSON_NO_INT64)
-#if JSONCPP_USING_SECURE_MEMORY
-#define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
-#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
-#define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
-#define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
-#define JSONCPP_ISTREAM std::istream
-#else
-#define JSONCPP_STRING std::string
-#define JSONCPP_OSTRINGSTREAM std::ostringstream
-#define JSONCPP_OSTREAM std::ostream
-#define JSONCPP_ISTRINGSTREAM std::istringstream
-#define JSONCPP_ISTREAM std::istream
-#endif // if JSONCPP_USING_SECURE_MEMORY
-} // end namespace Json
+
+template <typename T>
+using Allocator =
+ typename std::conditional<JSONCPP_USING_SECURE_MEMORY, SecureAllocator<T>,
+ std::allocator<T>>::type;
+using String = std::basic_string<char, std::char_traits<char>, Allocator<char>>;
+using IStringStream =
+ std::basic_istringstream<String::value_type, String::traits_type,
+ String::allocator_type>;
+using OStringStream =
+ std::basic_ostringstream<String::value_type, String::traits_type,
+ String::allocator_type>;
+using IStream = std::istream;
+using OStream = std::ostream;
+} // namespace Json
+
+// Legacy names (formerly macros).
+using JSONCPP_STRING = Json::String;
+using JSONCPP_ISTRINGSTREAM = Json::IStringStream;
+using JSONCPP_OSTRINGSTREAM = Json::OStringStream;
+using JSONCPP_ISTREAM = Json::IStream;
+using JSONCPP_OSTREAM = Json::OStream;
#endif // JSON_CONFIG_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/forwards.h b/Utilities/cmjsoncpp/include/json/forwards.h
index 70bbe19..affe33a 100644
--- a/Utilities/cmjsoncpp/include/json/forwards.h
+++ b/Utilities/cmjsoncpp/include/json/forwards.h
@@ -13,17 +13,23 @@
namespace Json {
// writer.h
+class StreamWriter;
+class StreamWriterBuilder;
+class Writer;
class FastWriter;
class StyledWriter;
+class StyledStreamWriter;
// reader.h
class Reader;
+class CharReader;
+class CharReaderBuilder;
-// features.h
+// json_features.h
class Features;
// value.h
-typedef unsigned int ArrayIndex;
+using ArrayIndex = unsigned int;
class StaticString;
class Path;
class PathArgument;
diff --git a/Utilities/cmjsoncpp/include/json/json.h b/Utilities/cmjsoncpp/include/json/json.h
index 5964672..5c776a1 100644
--- a/Utilities/cmjsoncpp/include/json/json.h
+++ b/Utilities/cmjsoncpp/include/json/json.h
@@ -6,9 +6,10 @@
#ifndef JSON_JSON_H_INCLUDED
#define JSON_JSON_H_INCLUDED
-#include "value.h"
+#include "config.h"
+#include "json_features.h"
#include "reader.h"
+#include "value.h"
#include "writer.h"
-#include "features.h"
#endif // JSON_JSON_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/features.h b/Utilities/cmjsoncpp/include/json/json_features.h
index 365abb3..6b99b4d 100644
--- a/Utilities/cmjsoncpp/include/json/features.h
+++ b/Utilities/cmjsoncpp/include/json/json_features.h
@@ -3,8 +3,8 @@
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-#ifndef CPPTL_JSON_FEATURES_H_INCLUDED
-#define CPPTL_JSON_FEATURES_H_INCLUDED
+#ifndef JSON_FEATURES_H_INCLUDED
+#define JSON_FEATURES_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "forwards.h"
@@ -43,17 +43,17 @@ public:
Features();
/// \c true if comments are allowed. Default: \c true.
- bool allowComments_;
+ bool allowComments_{true};
/// \c true if root must be either an array or an object value. Default: \c
/// false.
- bool strictRoot_;
+ bool strictRoot_{false};
/// \c true if dropped null placeholders are allowed. Default: \c false.
- bool allowDroppedNullPlaceholders_;
+ bool allowDroppedNullPlaceholders_{false};
/// \c true if numeric object key are allowed. Default: \c false.
- bool allowNumericKeys_;
+ bool allowNumericKeys_{false};
};
} // namespace Json
@@ -62,4 +62,4 @@ public:
#pragma pack(pop)
#endif
-#endif // CPPTL_JSON_FEATURES_H_INCLUDED
+#endif // JSON_FEATURES_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/reader.h b/Utilities/cmjsoncpp/include/json/reader.h
index 667246a..7ad0be6 100644
--- a/Utilities/cmjsoncpp/include/json/reader.h
+++ b/Utilities/cmjsoncpp/include/json/reader.h
@@ -3,18 +3,18 @@
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-#ifndef CPPTL_JSON_READER_H_INCLUDED
-#define CPPTL_JSON_READER_H_INCLUDED
+#ifndef JSON_READER_H_INCLUDED
+#define JSON_READER_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
-#include "features.h"
+#include "json_features.h"
#include "value.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <deque>
#include <iosfwd>
+#include <istream>
#include <stack>
#include <string>
-#include <istream>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
@@ -30,132 +30,130 @@
namespace Json {
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
- *Value.
+ * Value.
*
* deprecated Use CharReader and CharReaderBuilder.
*/
-class JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") JSON_API Reader {
+
+class JSONCPP_DEPRECATED(
+ "Use CharReader and CharReaderBuilder instead.") JSON_API Reader {
public:
- typedef char Char;
- typedef const Char* Location;
+ using Char = char;
+ using Location = const Char*;
/** \brief An error tagged with where in the JSON text it was encountered.
*
* The offsets give the [start, limit) range of bytes within the text. Note
* that this is bytes, not codepoints.
- *
*/
struct StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
- JSONCPP_STRING message;
+ String message;
};
- /** \brief Constructs a Reader allowing all features
- * for parsing.
+ /** \brief Constructs a Reader allowing all features for parsing.
*/
+ JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead")
Reader();
- /** \brief Constructs a Reader allowing the specified feature set
- * for parsing.
+ /** \brief Constructs a Reader allowing the specified feature set for parsing.
*/
+ JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead")
Reader(const Features& features);
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
* document.
- * \param document UTF-8 encoded string containing the document to read.
- * \param root [out] Contains the root value of the document if it was
- * successfully parsed.
- * \param collectComments \c true to collect comment and allow writing them
- * back during
- * serialization, \c false to discard comments.
- * This parameter is ignored if
- * Features::allowComments_
- * is \c false.
+ *
+ * \param document UTF-8 encoded string containing the document
+ * to read.
+ * \param[out] root Contains the root value of the document if it
+ * was successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing
+ * them back during serialization, \c false to
+ * discard comments. This parameter is ignored
+ * if Features::allowComments_ is \c false.
* \return \c true if the document was successfully parsed, \c false if an
* error occurred.
*/
- bool
- parse(const std::string& document, Value& root, bool collectComments = true);
+ bool parse(const std::string& document, Value& root,
+ bool collectComments = true);
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
- document.
- * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
- document to read.
- * \param endDoc Pointer on the end of the UTF-8 encoded string of the
- document to read.
- * Must be >= beginDoc.
- * \param root [out] Contains the root value of the document if it was
- * successfully parsed.
- * \param collectComments \c true to collect comment and allow writing them
- back during
- * serialization, \c false to discard comments.
- * This parameter is ignored if
- Features::allowComments_
- * is \c false.
+ * document.
+ *
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded
+ * string of the document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string
+ * of the document to read. Must be >= beginDoc.
+ * \param[out] root Contains the root value of the document if it
+ * was successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing
+ * them back during serialization, \c false to
+ * discard comments. This parameter is ignored
+ * if Features::allowComments_ is \c false.
* \return \c true if the document was successfully parsed, \c false if an
- error occurred.
+ * error occurred.
*/
- bool parse(const char* beginDoc,
- const char* endDoc,
- Value& root,
+ bool parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments = true);
/// \brief Parse from input stream.
/// \see Json::operator>>(std::istream&, Json::Value&).
- bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
+ bool parse(IStream& is, Value& root, bool collectComments = true);
/** \brief Returns a user friendly string that list errors in the parsed
* document.
- * \return Formatted error message with the list of errors with their location
- * in
- * the parsed document. An empty string is returned if no error
- * occurred
- * during parsing.
+ *
+ * \return Formatted error message with the list of errors with their
+ * location in the parsed document. An empty string is returned if no error
+ * occurred during parsing.
* deprecated Use getFormattedErrorMessages() instead (typo fix).
*/
JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
- JSONCPP_STRING getFormatedErrorMessages() const;
+ String getFormatedErrorMessages() const;
/** \brief Returns a user friendly string that list errors in the parsed
* document.
- * \return Formatted error message with the list of errors with their location
- * in
- * the parsed document. An empty string is returned if no error
- * occurred
- * during parsing.
+ *
+ * \return Formatted error message with the list of errors with their
+ * location in the parsed document. An empty string is returned if no error
+ * occurred during parsing.
*/
- JSONCPP_STRING getFormattedErrorMessages() const;
+ String getFormattedErrorMessages() const;
- /** \brief Returns a vector of structured erros encounted while parsing.
+ /** \brief Returns a vector of structured errors encountered while parsing.
+ *
* \return A (possibly empty) vector of StructuredError objects. Currently
- * only one error can be returned, but the caller should tolerate
- * multiple
- * errors. This can occur if the parser recovers from a non-fatal
- * parse error and then encounters additional errors.
+ * only one error can be returned, but the caller should tolerate multiple
+ * errors. This can occur if the parser recovers from a non-fatal parse
+ * error and then encounters additional errors.
*/
std::vector<StructuredError> getStructuredErrors() const;
/** \brief Add a semantic error message.
- * \param value JSON Value location associated with the error
+ *
+ * \param value JSON Value location associated with the error
* \param message The error message.
- * \return \c true if the error was successfully added, \c false if the
- * Value offset exceeds the document size.
+ * \return \c true if the error was successfully added, \c false if the Value
+ * offset exceeds the document size.
*/
- bool pushError(const Value& value, const JSONCPP_STRING& message);
+ bool pushError(const Value& value, const String& message);
/** \brief Add a semantic error message with extra context.
- * \param value JSON Value location associated with the error
+ *
+ * \param value JSON Value location associated with the error
* \param message The error message.
- * \param extra Additional JSON Value location to contextualize the error
+ * \param extra Additional JSON Value location to contextualize the error
* \return \c true if the error was successfully added, \c false if either
* Value offset exceeds the document size.
*/
- bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
+ bool pushError(const Value& value, const String& message, const Value& extra);
/** \brief Return whether there are any errors.
- * \return \c true if there are no errors to report \c false if
- * errors have occurred.
+ *
+ * \return \c true if there are no errors to report \c false if errors have
+ * occurred.
*/
bool good() const;
@@ -187,15 +185,15 @@ private:
class ErrorInfo {
public:
Token token_;
- JSONCPP_STRING message_;
+ String message_;
Location extra_;
};
- typedef std::deque<ErrorInfo> Errors;
+ using Errors = std::deque<ErrorInfo>;
bool readToken(Token& token);
void skipSpaces();
- bool match(Location pattern, int patternLength);
+ bool match(const Char* pattern, int patternLength);
bool readComment();
bool readCStyleComment();
bool readCppStyleComment();
@@ -207,142 +205,138 @@ private:
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
- bool decodeString(Token& token, JSONCPP_STRING& decoded);
+ bool decodeString(Token& token, String& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
- bool decodeUnicodeCodePoint(Token& token,
- Location& current,
- Location end,
+ bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
unsigned int& unicode);
- bool decodeUnicodeEscapeSequence(Token& token,
- Location& current,
- Location end,
- unsigned int& unicode);
- bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
+ bool decodeUnicodeEscapeSequence(Token& token, Location& current,
+ Location end, unsigned int& unicode);
+ bool addError(const String& message, Token& token, Location extra = nullptr);
bool recoverFromError(TokenType skipUntilToken);
- bool addErrorAndRecover(const JSONCPP_STRING& message,
- Token& token,
+ bool addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
Value& currentValue();
Char getNextChar();
- void
- getLocationLineAndColumn(Location location, int& line, int& column) const;
- JSONCPP_STRING getLocationLineAndColumn(Location location) const;
+ void getLocationLineAndColumn(Location location, int& line,
+ int& column) const;
+ String getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
static bool containsNewLine(Location begin, Location end);
- static JSONCPP_STRING normalizeEOL(Location begin, Location end);
+ static String normalizeEOL(Location begin, Location end);
- typedef std::stack<Value*> Nodes;
+ using Nodes = std::stack<Value*>;
Nodes nodes_;
Errors errors_;
- JSONCPP_STRING document_;
- Location begin_;
- Location end_;
- Location current_;
- Location lastValueEnd_;
- Value* lastValue_;
- JSONCPP_STRING commentsBefore_;
+ String document_;
+ Location begin_{};
+ Location end_{};
+ Location current_{};
+ Location lastValueEnd_{};
+ Value* lastValue_{};
+ String commentsBefore_;
Features features_;
- bool collectComments_;
-}; // Reader
+ bool collectComments_{};
+}; // Reader
/** Interface for reading JSON from a char array.
*/
class JSON_API CharReader {
public:
- virtual ~CharReader() {}
+ virtual ~CharReader() = default;
/** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
- document.
- * The document must be a UTF-8 encoded string containing the document to read.
+ * document. The document must be a UTF-8 encoded string containing the
+ * document to read.
*
- * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
- document to read.
- * \param endDoc Pointer on the end of the UTF-8 encoded string of the
- document to read.
- * Must be >= beginDoc.
- * \param root [out] Contains the root value of the document if it was
- * successfully parsed.
- * \param errs [out] Formatted error messages (if not NULL)
- * a user friendly string that lists errors in the parsed
- * document.
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded string
+ * of the document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string of the
+ * document to read. Must be >= beginDoc.
+ * \param[out] root Contains the root value of the document if it was
+ * successfully parsed.
+ * \param[out] errs Formatted error messages (if not NULL) a user
+ * friendly string that lists errors in the parsed
+ * document.
* \return \c true if the document was successfully parsed, \c false if an
- error occurred.
+ * error occurred.
*/
- virtual bool parse(
- char const* beginDoc, char const* endDoc,
- Value* root, JSONCPP_STRING* errs) = 0;
+ virtual bool parse(char const* beginDoc, char const* endDoc, Value* root,
+ String* errs) = 0;
class JSON_API Factory {
public:
- virtual ~Factory() {}
+ virtual ~Factory() = default;
/** \brief Allocate a CharReader via operator new().
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual CharReader* newCharReader() const = 0;
- }; // Factory
-}; // CharReader
+ }; // Factory
+}; // CharReader
/** \brief Build a CharReader implementation.
-
-Usage:
-\code
- using namespace Json;
- CharReaderBuilder builder;
- builder["collectComments"] = false;
- Value value;
- JSONCPP_STRING errs;
- bool ok = parseFromStream(builder, std::cin, &value, &errs);
-\endcode
-*/
+ *
+ * Usage:
+ * \code
+ * using namespace Json;
+ * CharReaderBuilder builder;
+ * builder["collectComments"] = false;
+ * Value value;
+ * String errs;
+ * bool ok = parseFromStream(builder, std::cin, &value, &errs);
+ * \endcode
+ */
class JSON_API CharReaderBuilder : public CharReader::Factory {
public:
// Note: We use a Json::Value so that we can add data-members to this class
// without a major version bump.
/** Configuration of this builder.
- These are case-sensitive.
- Available settings (case-sensitive):
- - `"collectComments": false or true`
- - true to collect comment and allow writing them
- back during serialization, false to discard comments.
- This parameter is ignored if allowComments is false.
- - `"allowComments": false or true`
- - true if comments are allowed.
- - `"strictRoot": false or true`
- - true if root must be either an array or an object value
- - `"allowDroppedNullPlaceholders": false or true`
- - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
- - `"allowNumericKeys": false or true`
- - true if numeric object keys are allowed.
- - `"allowSingleQuotes": false or true`
- - true if '' are allowed for strings (both keys and values)
- - `"stackLimit": integer`
- - Exceeding stackLimit (recursive depth of `readValue()`) will
- cause an exception.
- - This is a security issue (seg-faults caused by deeply nested JSON),
- so the default is low.
- - `"failIfExtra": false or true`
- - If true, `parse()` returns false when extra non-whitespace trails
- the JSON value in the input string.
- - `"rejectDupKeys": false or true`
- - If true, `parse()` returns false when a key is duplicated within an object.
- - `"allowSpecialFloats": false or true`
- - If true, special float values (NaNs and infinities) are allowed
- and their values are lossfree restorable.
-
- You can examine 'settings_` yourself
- to see the defaults. You can also write and read them just like any
- JSON Value.
- \sa setDefaults()
- */
+ * These are case-sensitive.
+ * Available settings (case-sensitive):
+ * - `"collectComments": false or true`
+ * - true to collect comment and allow writing them back during
+ * serialization, false to discard comments. This parameter is ignored
+ * if allowComments is false.
+ * - `"allowComments": false or true`
+ * - true if comments are allowed.
+ * - `"allowTrailingCommas": false or true`
+ * - true if trailing commas in objects and arrays are allowed.
+ * - `"strictRoot": false or true`
+ * - true if root must be either an array or an object value
+ * - `"allowDroppedNullPlaceholders": false or true`
+ * - true if dropped null placeholders are allowed. (See
+ * StreamWriterBuilder.)
+ * - `"allowNumericKeys": false or true`
+ * - true if numeric object keys are allowed.
+ * - `"allowSingleQuotes": false or true`
+ * - true if '' are allowed for strings (both keys and values)
+ * - `"stackLimit": integer`
+ * - Exceeding stackLimit (recursive depth of `readValue()`) will cause an
+ * exception.
+ * - This is a security issue (seg-faults caused by deeply nested JSON), so
+ * the default is low.
+ * - `"failIfExtra": false or true`
+ * - If true, `parse()` returns false when extra non-whitespace trails the
+ * JSON value in the input string.
+ * - `"rejectDupKeys": false or true`
+ * - If true, `parse()` returns false when a key is duplicated within an
+ * object.
+ * - `"allowSpecialFloats": false or true`
+ * - If true, special float values (NaNs and infinities) are allowed and
+ * their values are lossfree restorable.
+ *
+ * You can examine 'settings_` yourself to see the defaults. You can also
+ * write and read them just like any JSON Value.
+ * \sa setDefaults()
+ */
Json::Value settings_;
CharReaderBuilder();
- ~CharReaderBuilder() JSONCPP_OVERRIDE;
+ ~CharReaderBuilder() override;
- CharReader* newCharReader() const JSONCPP_OVERRIDE;
+ CharReader* newCharReader() const override;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
@@ -351,7 +345,7 @@ public:
/** A simple way to update a specific setting.
*/
- Value& operator[](JSONCPP_STRING key);
+ Value& operator[](const String& key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
@@ -368,39 +362,37 @@ public:
};
/** Consume entire stream and use its begin/end.
- * Someday we might have a real StreamReader, but for now this
- * is convenient.
- */
-bool JSON_API parseFromStream(
- CharReader::Factory const&,
- JSONCPP_ISTREAM&,
- Value* root, std::string* errs);
+ * Someday we might have a real StreamReader, but for now this
+ * is convenient.
+ */
+bool JSON_API parseFromStream(CharReader::Factory const&, IStream&, Value* root,
+ String* errs);
/** \brief Read from 'sin' into 'root'.
-
- Always keep comments from the input JSON.
-
- This can be used to read a file into a particular sub-object.
- For example:
- \code
- Json::Value root;
- cin >> root["dir"]["file"];
- cout << root;
- \endcode
- Result:
- \verbatim
- {
- "dir": {
- "file": {
- // The input stream JSON would be nested here.
- }
- }
- }
- \endverbatim
- \throw std::exception on parse error.
- \see Json::operator<<()
-*/
-JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
+ *
+ * Always keep comments from the input JSON.
+ *
+ * This can be used to read a file into a particular sub-object.
+ * For example:
+ * \code
+ * Json::Value root;
+ * cin >> root["dir"]["file"];
+ * cout << root;
+ * \endcode
+ * Result:
+ * \verbatim
+ * {
+ * "dir": {
+ * "file": {
+ * // The input stream JSON would be nested here.
+ * }
+ * }
+ * }
+ * \endverbatim
+ * \throw std::exception on parse error.
+ * \see Json::operator<<()
+ */
+JSON_API IStream& operator>>(IStream&, Value&);
} // namespace Json
@@ -412,4 +404,4 @@ JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
-#endif // CPPTL_JSON_READER_H_INCLUDED
+#endif // JSON_READER_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/value.h b/Utilities/cmjsoncpp/include/json/value.h
index 7b90c5a..952d423 100644
--- a/Utilities/cmjsoncpp/include/json/value.h
+++ b/Utilities/cmjsoncpp/include/json/value.h
@@ -3,38 +3,49 @@
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-#ifndef CPPTL_JSON_H_INCLUDED
-#define CPPTL_JSON_H_INCLUDED
+#ifndef JSON_H_INCLUDED
+#define JSON_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
#include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
-#include <string>
-#include <vector>
-#include <exception>
-#ifndef JSON_USE_CPPTL_SMALLMAP
-#include <map>
+// Conditional NORETURN attribute on the throw functions would:
+// a) suppress false positives from static code analysis
+// b) possibly improve optimization opportunities.
+#if !defined(JSONCPP_NORETURN)
+#if defined(_MSC_VER) && _MSC_VER == 1800
+#define JSONCPP_NORETURN __declspec(noreturn)
#else
-#include <cpptl/smallmap.h>
+#define JSONCPP_NORETURN [[noreturn]]
#endif
-#ifdef JSON_USE_CPPTL
-#include <cpptl/forwards.h>
#endif
-//Conditional NORETURN attribute on the throw functions would:
-// a) suppress false positives from static code analysis
-// b) possibly improve optimization opportunities.
-#if !defined(JSONCPP_NORETURN)
-# if defined(_MSC_VER)
-# define JSONCPP_NORETURN __declspec(noreturn)
-# elif defined(__GNUC__)
-# define JSONCPP_NORETURN __attribute__ ((__noreturn__))
-# else
-# define JSONCPP_NORETURN
-# endif
+// Support for '= delete' with template declarations was a late addition
+// to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2
+// even though these declare themselves to be c++11 compilers.
+#if !defined(JSONCPP_TEMPLATE_DELETE)
+#if defined(__clang__) && defined(__apple_build_version__)
+#if __apple_build_version__ <= 8000042
+#define JSONCPP_TEMPLATE_DELETE
+#endif
+#elif defined(__clang__)
+#if __clang_major__ == 3 && __clang_minor__ <= 8
+#define JSONCPP_TEMPLATE_DELETE
+#endif
+#endif
+#if !defined(JSONCPP_TEMPLATE_DELETE)
+#define JSONCPP_TEMPLATE_DELETE = delete
+#endif
#endif
+#include <array>
+#include <exception>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
@@ -50,17 +61,19 @@
*/
namespace Json {
+#if JSON_USE_EXCEPTION
/** Base class for all exceptions we throw.
*
* We use nothing but these internally. Of course, STL can throw others.
*/
class JSON_API Exception : public std::exception {
public:
- Exception(JSONCPP_STRING const& msg);
- ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
- char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE;
+ Exception(String msg);
+ ~Exception() noexcept override;
+ char const* what() const noexcept override;
+
protected:
- JSONCPP_STRING msg_;
+ String msg_;
};
/** Exceptions which the user cannot easily avoid.
@@ -71,7 +84,7 @@ protected:
*/
class JSON_API RuntimeError : public Exception {
public:
- RuntimeError(JSONCPP_STRING const& msg);
+ RuntimeError(String const& msg);
};
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
@@ -82,13 +95,14 @@ public:
*/
class JSON_API LogicError : public Exception {
public:
- LogicError(JSONCPP_STRING const& msg);
+ LogicError(String const& msg);
};
+#endif
/// used internally
-JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
+JSONCPP_NORETURN void throwRuntimeError(String const& msg);
/// used internally
-JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
+JSONCPP_NORETURN void throwLogicError(String const& msg);
/** \brief Type of the value held by a Value object.
*/
@@ -111,14 +125,16 @@ enum CommentPlacement {
numberOfCommentPlacement
};
-//# ifdef JSON_USE_CPPTL
-// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
-// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
-//# endif
+/** \brief Type of precision for formatting of real values.
+ */
+enum PrecisionType {
+ significantDigits = 0, ///< we set max number of significant digits in string
+ decimalPlaces ///< we set max number of digits after "." in string
+};
/** \brief Lightweight wrapper to tag static string.
*
- * Value constructor and objectValue member assignement takes advantage of the
+ * Value constructor and objectValue member assignment takes advantage of the
* StaticString and avoid the cost of string duplication when storing the
* string or the member name.
*
@@ -167,7 +183,7 @@ private:
* The get() methods can be used to obtain default value in the case the
* required element does not exist.
*
- * It is possible to iterate over the list of a #objectValue values using
+ * It is possible to iterate over the list of member keys of an object using
* the getMemberNames() method.
*
* \note #Value string-length fit in size_t, but keys must be < 2^30.
@@ -178,73 +194,86 @@ private:
*/
class JSON_API Value {
friend class ValueIteratorBase;
+
public:
- typedef std::vector<JSONCPP_STRING> Members;
- typedef ValueIterator iterator;
- typedef ValueConstIterator const_iterator;
- typedef Json::UInt UInt;
- typedef Json::Int Int;
+ using Members = std::vector<String>;
+ using iterator = ValueIterator;
+ using const_iterator = ValueConstIterator;
+ using UInt = Json::UInt;
+ using Int = Json::Int;
#if defined(JSON_HAS_INT64)
- typedef Json::UInt64 UInt64;
- typedef Json::Int64 Int64;
+ using UInt64 = Json::UInt64;
+ using Int64 = Json::Int64;
#endif // defined(JSON_HAS_INT64)
- typedef Json::LargestInt LargestInt;
- typedef Json::LargestUInt LargestUInt;
- typedef Json::ArrayIndex ArrayIndex;
+ using LargestInt = Json::LargestInt;
+ using LargestUInt = Json::LargestUInt;
+ using ArrayIndex = Json::ArrayIndex;
- static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
- static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
- static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
+ // Required for boost integration, e. g. BOOST_TEST
+ using value_type = std::string;
+
+#if JSON_USE_NULLREF
+ // Binary compatibility kludges, do not use.
+ static const Value& null;
+ static const Value& nullRef;
+#endif
+
+ // null and nullRef are deprecated, use this instead.
+ static Value const& nullSingleton();
/// Minimum signed integer value that can be stored in a Json::Value.
- static const LargestInt minLargestInt;
+ static constexpr LargestInt minLargestInt =
+ LargestInt(~(LargestUInt(-1) / 2));
/// Maximum signed integer value that can be stored in a Json::Value.
- static const LargestInt maxLargestInt;
+ static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2);
/// Maximum unsigned integer value that can be stored in a Json::Value.
- static const LargestUInt maxLargestUInt;
+ static constexpr LargestUInt maxLargestUInt = LargestUInt(-1);
/// Minimum signed int value that can be stored in a Json::Value.
- static const Int minInt;
+ static constexpr Int minInt = Int(~(UInt(-1) / 2));
/// Maximum signed int value that can be stored in a Json::Value.
- static const Int maxInt;
+ static constexpr Int maxInt = Int(UInt(-1) / 2);
/// Maximum unsigned int value that can be stored in a Json::Value.
- static const UInt maxUInt;
+ static constexpr UInt maxUInt = UInt(-1);
#if defined(JSON_HAS_INT64)
/// Minimum signed 64 bits int value that can be stored in a Json::Value.
- static const Int64 minInt64;
+ static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2));
/// Maximum signed 64 bits int value that can be stored in a Json::Value.
- static const Int64 maxInt64;
+ static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2);
/// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
- static const UInt64 maxUInt64;
+ static constexpr UInt64 maxUInt64 = UInt64(-1);
#endif // defined(JSON_HAS_INT64)
-
+ /// Default precision for real value for string representation.
+ static constexpr UInt defaultRealPrecision = 17;
+ // The constant is hard-coded because some compiler have trouble
+ // converting Value::maxUInt64 to a double correctly (AIX/xlC).
+ // Assumes that UInt64 is a 64 bits integer.
+ static constexpr double maxUInt64AsDouble = 18446744073709551615.0;
+// Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler
+// when using gcc and clang backend compilers. CZString
+// cannot be defined as private. See issue #486
+#ifdef __NVCC__
+public:
+#else
private:
+#endif
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
class CZString {
public:
- enum DuplicationPolicy {
- noDuplication = 0,
- duplicate,
- duplicateOnCopy
- };
+ enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy };
CZString(ArrayIndex index);
CZString(char const* str, unsigned length, DuplicationPolicy allocate);
CZString(CZString const& other);
-#if JSON_HAS_RVALUE_REFERENCES
CZString(CZString&& other);
-#endif
~CZString();
CZString& operator=(const CZString& other);
-
-#if JSON_HAS_RVALUE_REFERENCES
CZString& operator=(CZString&& other);
-#endif
bool operator<(CZString const& other) const;
bool operator==(CZString const& other) const;
ArrayIndex index() const;
- //const char* c_str() const; ///< deprecated
+ // const char* c_str() const; ///< deprecated
char const* data() const;
unsigned length() const;
bool isStaticString() const;
@@ -253,11 +282,11 @@ private:
void swap(CZString& other);
struct StringStorage {
- unsigned policy_: 2;
- unsigned length_: 30; // 1GB max
+ unsigned policy_ : 2;
+ unsigned length_ : 30; // 1GB max
};
- char const* cstr_; // actually, a prefixed string, unless policy is noDup
+ char const* cstr_; // actually, a prefixed string, unless policy is noDup
union {
ArrayIndex index_;
StringStorage storage_;
@@ -265,29 +294,26 @@ private:
};
public:
-#ifndef JSON_USE_CPPTL_SMALLMAP
typedef std::map<CZString, Value> ObjectValues;
-#else
- typedef CppTL::SmallMap<CZString, Value> ObjectValues;
-#endif // ifndef JSON_USE_CPPTL_SMALLMAP
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
public:
- /** \brief Create a default Value of the given type.
-
- This is a very useful constructor.
- To create an empty array, pass arrayValue.
- To create an empty object, pass objectValue.
- Another Value can then be set to this one by assignment.
-This is useful since clear() and resize() will not alter types.
-
- Examples:
-\code
-Json::Value null_value; // null
-Json::Value arr_value(Json::arrayValue); // []
-Json::Value obj_value(Json::objectValue); // {}
-\endcode
- */
+ /**
+ * \brief Create a default Value of the given type.
+ *
+ * This is a very useful constructor.
+ * To create an empty array, pass arrayValue.
+ * To create an empty object, pass objectValue.
+ * Another Value can then be set to this one by assignment.
+ * This is useful since clear() and resize() will not alter types.
+ *
+ * Examples:
+ * \code
+ * Json::Value null_value; // null
+ * Json::Value arr_value(Json::arrayValue); // []
+ * Json::Value obj_value(Json::objectValue); // {}
+ * \endcode
+ */
Value(ValueType type = nullValue);
Value(Int value);
Value(UInt value);
@@ -298,38 +324,35 @@ Json::Value obj_value(Json::objectValue); // {}
Value(double value);
Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
- /** \brief Constructs a value from a static string.
-
+ /**
+ * \brief Constructs a value from a static string.
+ *
* Like other value string constructor but do not duplicate the string for
- * internal storage. The given string must remain alive after the call to this
- * constructor.
+ * internal storage. The given string must remain alive after the call to
+ * this constructor.
+ *
* \note This works only for null-terminated strings. (We cannot change the
- * size of this class, so we have nowhere to store the length,
- * which might be computed later for various operations.)
+ * size of this class, so we have nowhere to store the length, which might be
+ * computed later for various operations.)
*
* Example of usage:
- * \code
- * static StaticString foo("some text");
- * Json::Value aValue(foo);
- * \endcode
+ * \code
+ * static StaticString foo("some text");
+ * Json::Value aValue(foo);
+ * \endcode
*/
Value(const StaticString& value);
- Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
-#ifdef JSON_USE_CPPTL
- Value(const CppTL::ConstString& value);
-#endif
+ Value(const String& value);
Value(bool value);
- /// Deep copy.
+ Value(std::nullptr_t ptr) = delete;
Value(const Value& other);
-#if JSON_HAS_RVALUE_REFERENCES
- /// Move constructor
Value(Value&& other);
-#endif
~Value();
- /// Deep copy, then swap(other).
- /// \note Over-write existing comments. To preserve comments, use #swapPayload().
- Value& operator=(Value other);
+ /// \note Overwrite existing comments. To preserve comments, use
+ /// #swapPayload().
+ Value& operator=(const Value& other);
+ Value& operator=(Value&& other);
/// Swap everything.
void swap(Value& other);
@@ -354,17 +377,14 @@ Json::Value obj_value(Json::objectValue); // {}
const char* asCString() const; ///< Embedded zeroes could cause you trouble!
#if JSONCPP_USING_SECURE_MEMORY
- unsigned getCStringLength() const; //Allows you to understand the length of the CString
+ unsigned getCStringLength() const; // Allows you to understand the length of
+ // the CString
#endif
- JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
+ String asString() const; ///< Embedded zeroes are possible.
/** Get raw char* of string-value.
* \return false if !string. (Seg-fault if str or end are NULL.)
*/
- bool getString(
- char const** begin, char const** end) const;
-#ifdef JSON_USE_CPPTL
- CppTL::ConstString asConstString() const;
-#endif
+ bool getString(char const** begin, char const** end) const;
Int asInt() const;
UInt asUInt() const;
#if defined(JSON_HAS_INT64)
@@ -390,6 +410,10 @@ Json::Value obj_value(Json::objectValue); // {}
bool isArray() const;
bool isObject() const;
+ /// The `as<T>` and `is<T>` member function templates and specializations.
+ template <typename T> T as() const JSONCPP_TEMPLATE_DELETE;
+ template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE;
+
bool isConvertibleTo(ValueType other) const;
/// Number of values in array or object
@@ -399,50 +423,41 @@ Json::Value obj_value(Json::objectValue); // {}
/// otherwise, false.
bool empty() const;
- /// Return isNull()
- bool operator!() const;
+ /// Return !isNull()
+ explicit operator bool() const;
/// Remove all object members and array elements.
/// \pre type() is arrayValue, objectValue, or nullValue
/// \post type() is unchanged
void clear();
- /// Resize the array to size elements.
+ /// Resize the array to newSize elements.
/// New elements are initialized to null.
/// May only be called on nullValue or arrayValue.
/// \pre type() is arrayValue or nullValue
/// \post type() is arrayValue
- void resize(ArrayIndex size);
+ void resize(ArrayIndex newSize);
- /// Access an array element (zero based index ).
- /// If the array contains less than index element, then null value are
- /// inserted
- /// in the array so that its size is index+1.
+ //@{
+ /// Access an array element (zero based index). If the array contains less
+ /// than index element, then null value are inserted in the array so that
+ /// its size is index+1.
/// (You may need to say 'value[0u]' to get your compiler to distinguish
- /// this from the operator[] which takes a string.)
+ /// this from the operator[] which takes a string.)
Value& operator[](ArrayIndex index);
-
- /// Access an array element (zero based index ).
- /// If the array contains less than index element, then null value are
- /// inserted
- /// in the array so that its size is index+1.
- /// (You may need to say 'value[0u]' to get your compiler to distinguish
- /// this from the operator[] which takes a string.)
Value& operator[](int index);
+ //@}
- /// Access an array element (zero based index )
+ //@{
+ /// Access an array element (zero based index).
/// (You may need to say 'value[0u]' to get your compiler to distinguish
- /// this from the operator[] which takes a string.)
+ /// this from the operator[] which takes a string.)
const Value& operator[](ArrayIndex index) const;
-
- /// Access an array element (zero based index )
- /// (You may need to say 'value[0u]' to get your compiler to distinguish
- /// this from the operator[] which takes a string.)
const Value& operator[](int index) const;
+ //@}
/// If the array contains at least index+1 elements, returns the element
- /// value,
- /// otherwise returns defaultValue.
+ /// value, otherwise returns defaultValue.
Value get(ArrayIndex index, const Value& defaultValue) const;
/// Return true if index < size().
bool isValidIndex(ArrayIndex index) const;
@@ -450,61 +465,51 @@ Json::Value obj_value(Json::objectValue); // {}
///
/// Equivalent to jsonvalue[jsonvalue.size()] = value;
Value& append(const Value& value);
-
-#if JSON_HAS_RVALUE_REFERENCES
Value& append(Value&& value);
-#endif
+
+ /// \brief Insert value in array at specific index
+ bool insert(ArrayIndex index, const Value& newValue);
+ bool insert(ArrayIndex index, Value&& newValue);
/// Access an object value by name, create a null member if it does not exist.
/// \note Because of our implementation, keys are limited to 2^30 -1 chars.
- /// Exceeding that will cause an exception.
+ /// Exceeding that will cause an exception.
Value& operator[](const char* key);
/// Access an object value by name, returns null if there is no member with
/// that name.
const Value& operator[](const char* key) const;
/// Access an object value by name, create a null member if it does not exist.
/// \param key may contain embedded nulls.
- Value& operator[](const JSONCPP_STRING& key);
+ Value& operator[](const String& key);
/// Access an object value by name, returns null if there is no member with
/// that name.
/// \param key may contain embedded nulls.
- const Value& operator[](const JSONCPP_STRING& key) const;
+ const Value& operator[](const String& key) const;
/** \brief Access an object value by name, create a null member if it does not
- exist.
-
- * If the object has no entry for that name, then the member name used to store
- * the new entry is not duplicated.
+ * exist.
+ *
+ * If the object has no entry for that name, then the member name used to
+ * store the new entry is not duplicated.
* Example of use:
- * \code
- * Json::Value object;
- * static const StaticString code("code");
- * object[code] = 1234;
- * \endcode
+ * \code
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
*/
Value& operator[](const StaticString& key);
-#ifdef JSON_USE_CPPTL
- /// Access an object value by name, create a null member if it does not exist.
- Value& operator[](const CppTL::ConstString& key);
- /// Access an object value by name, returns null if there is no member with
- /// that name.
- const Value& operator[](const CppTL::ConstString& key) const;
-#endif
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
Value get(const char* key, const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \note key may contain embedded nulls.
- Value get(const char* begin, const char* end, const Value& defaultValue) const;
+ Value get(const char* begin, const char* end,
+ const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \param key may contain embedded nulls.
- Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
-#ifdef JSON_USE_CPPTL
- /// Return the member named key if it exist, defaultValue otherwise.
- /// \note deep copy
- Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
-#endif
+ Value get(const String& key, const Value& defaultValue) const;
/// Most general and efficient version of isMember()const, get()const,
/// and operator[]const
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
@@ -512,53 +517,44 @@ Json::Value obj_value(Json::objectValue); // {}
/// Most general and efficient version of object-mutators.
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
/// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
- Value const* demand(char const* begin, char const* end);
+ Value* demand(char const* begin, char const* end);
/// \brief Remove and return the named member.
///
/// Do nothing if it did not exist.
- /// \return the removed Value, or null.
/// \pre type() is objectValue or nullValue
/// \post type() is unchanged
- /// deprecated
- JSONCPP_DEPRECATED("")
- Value removeMember(const char* key);
+ void removeMember(const char* key);
/// Same as removeMember(const char*)
/// \param key may contain embedded nulls.
- /// deprecated
- JSONCPP_DEPRECATED("")
- Value removeMember(const JSONCPP_STRING& key);
+ void removeMember(const String& key);
/// Same as removeMember(const char* begin, const char* end, Value* removed),
/// but 'key' is null-terminated.
bool removeMember(const char* key, Value* removed);
/** \brief Remove the named map member.
-
- Update 'removed' iff removed.
- \param key may contain embedded nulls.
- \return true iff removed (no exceptions)
- */
- bool removeMember(JSONCPP_STRING const& key, Value* removed);
- /// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
+ *
+ * Update 'removed' iff removed.
+ * \param key may contain embedded nulls.
+ * \return true iff removed (no exceptions)
+ */
+ bool removeMember(String const& key, Value* removed);
+ /// Same as removeMember(String const& key, Value* removed)
bool removeMember(const char* begin, const char* end, Value* removed);
/** \brief Remove the indexed array element.
-
- O(n) expensive operations.
- Update 'removed' iff removed.
- \return true iff removed (no exceptions)
- */
- bool removeIndex(ArrayIndex i, Value* removed);
+ *
+ * O(n) expensive operations.
+ * Update 'removed' iff removed.
+ * \return true if removed (no exceptions)
+ */
+ bool removeIndex(ArrayIndex index, Value* removed);
/// Return true if the object has a member named key.
/// \note 'key' must be null-terminated.
bool isMember(const char* key) const;
/// Return true if the object has a member named key.
/// \param key may contain embedded nulls.
- bool isMember(const JSONCPP_STRING& key) const;
- /// Same as isMember(JSONCPP_STRING const& key)const
+ bool isMember(const String& key) const;
+ /// Same as isMember(String const& key)const
bool isMember(const char* begin, const char* end) const;
-#ifdef JSON_USE_CPPTL
- /// Return true if the object has a member named key.
- bool isMember(const CppTL::ConstString& key) const;
-#endif
/// \brief Return a list of the member names.
///
@@ -567,23 +563,22 @@ Json::Value obj_value(Json::objectValue); // {}
/// \post if type() was nullValue, it remains nullValue
Members getMemberNames() const;
- //# ifdef JSON_USE_CPPTL
- // EnumMemberNames enumMemberNames() const;
- // EnumValues enumValues() const;
- //# endif
-
/// deprecated Always pass len.
- JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
- void setComment(const char* comment, CommentPlacement placement);
+ JSONCPP_DEPRECATED("Use setComment(String const&) instead.")
+ void setComment(const char* comment, CommentPlacement placement) {
+ setComment(String(comment, strlen(comment)), placement);
+ }
/// Comments must be //... or /* ... */
- void setComment(const char* comment, size_t len, CommentPlacement placement);
+ void setComment(const char* comment, size_t len, CommentPlacement placement) {
+ setComment(String(comment, len), placement);
+ }
/// Comments must be //... or /* ... */
- void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
+ void setComment(String comment, CommentPlacement placement);
bool hasComment(CommentPlacement placement) const;
/// Include delimiters and embedded newlines.
- JSONCPP_STRING getComment(CommentPlacement placement) const;
+ String getComment(CommentPlacement placement) const;
- JSONCPP_STRING toStyledString() const;
+ String toStyledString() const;
const_iterator begin() const;
const_iterator end() const;
@@ -599,20 +594,20 @@ Json::Value obj_value(Json::objectValue); // {}
ptrdiff_t getOffsetLimit() const;
private:
+ void setType(ValueType v) {
+ bits_.value_type_ = static_cast<unsigned char>(v);
+ }
+ bool isAllocated() const { return bits_.allocated_; }
+ void setIsAllocated(bool v) { bits_.allocated_ = v; }
+
void initBasic(ValueType type, bool allocated = false);
+ void dupPayload(const Value& other);
+ void releasePayload();
+ void dupMeta(const Value& other);
Value& resolveReference(const char* key);
Value& resolveReference(const char* key, const char* end);
- struct CommentInfo {
- CommentInfo();
- ~CommentInfo();
-
- void setComment(const char* text, size_t len);
-
- char* comment_;
- };
-
// struct MemberNamesTransform
//{
// typedef const char *result_type;
@@ -627,13 +622,33 @@ private:
LargestUInt uint_;
double real_;
bool bool_;
- char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
+ char* string_; // if allocated_, ptr to { unsigned, char[] }.
ObjectValues* map_;
} value_;
- ValueType type_ : 8;
- unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
- // If not allocated_, string_ must be null-terminated.
- CommentInfo* comments_;
+
+ struct {
+ // Really a ValueType, but types should agree for bitfield packing.
+ unsigned int value_type_ : 8;
+ // Unless allocated_, string_ must be null-terminated.
+ unsigned int allocated_ : 1;
+ } bits_;
+
+ class Comments {
+ public:
+ Comments() = default;
+ Comments(const Comments& that);
+ Comments(Comments&& that);
+ Comments& operator=(const Comments& that);
+ Comments& operator=(Comments&& that);
+ bool has(CommentPlacement slot) const;
+ String get(CommentPlacement slot) const;
+ void set(CommentPlacement slot, String comment);
+
+ private:
+ using Array = std::array<String, numberOfCommentPlacement>;
+ std::unique_ptr<Array> ptr_;
+ };
+ Comments comments_;
// [start, limit) byte offsets in the source JSON text from which this Value
// was extracted.
@@ -641,6 +656,36 @@ private:
ptrdiff_t limit_;
};
+template <> inline bool Value::as<bool>() const { return asBool(); }
+template <> inline bool Value::is<bool>() const { return isBool(); }
+
+template <> inline Int Value::as<Int>() const { return asInt(); }
+template <> inline bool Value::is<Int>() const { return isInt(); }
+
+template <> inline UInt Value::as<UInt>() const { return asUInt(); }
+template <> inline bool Value::is<UInt>() const { return isUInt(); }
+
+#if defined(JSON_HAS_INT64)
+template <> inline Int64 Value::as<Int64>() const { return asInt64(); }
+template <> inline bool Value::is<Int64>() const { return isInt64(); }
+
+template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); }
+template <> inline bool Value::is<UInt64>() const { return isUInt64(); }
+#endif
+
+template <> inline double Value::as<double>() const { return asDouble(); }
+template <> inline bool Value::is<double>() const { return isDouble(); }
+
+template <> inline String Value::as<String>() const { return asString(); }
+template <> inline bool Value::is<String>() const { return isString(); }
+
+/// These `as` specializations are type conversions, and do not have a
+/// corresponding `is`.
+template <> inline float Value::as<float>() const { return asFloat(); }
+template <> inline const char* Value::as<const char*>() const {
+ return asCString();
+}
+
/** \brief Experimental and untested: represents an element of the "path" to
* access a node.
*/
@@ -651,17 +696,13 @@ public:
PathArgument();
PathArgument(ArrayIndex index);
PathArgument(const char* key);
- PathArgument(const JSONCPP_STRING& key);
+ PathArgument(String key);
private:
- enum Kind {
- kindNone = 0,
- kindIndex,
- kindKey
- };
- JSONCPP_STRING key_;
- ArrayIndex index_;
- Kind kind_;
+ enum Kind { kindNone = 0, kindIndex, kindKey };
+ String key_;
+ ArrayIndex index_{};
+ Kind kind_{kindNone};
};
/** \brief Experimental and untested: represents a "path" to access a node.
@@ -673,12 +714,11 @@ private:
* - ".name1.name2.name3"
* - ".[0][1][2].name1[3]"
* - ".%" => member name is provided as parameter
- * - ".[%]" => index is provied as parameter
+ * - ".[%]" => index is provided as parameter
*/
class JSON_API Path {
public:
- Path(const JSONCPP_STRING& path,
- const PathArgument& a1 = PathArgument(),
+ Path(const String& path, const PathArgument& a1 = PathArgument(),
const PathArgument& a2 = PathArgument(),
const PathArgument& a3 = PathArgument(),
const PathArgument& a4 = PathArgument(),
@@ -691,15 +731,13 @@ public:
Value& make(Value& root) const;
private:
- typedef std::vector<const PathArgument*> InArgs;
- typedef std::vector<PathArgument> Args;
+ using InArgs = std::vector<const PathArgument*>;
+ using Args = std::vector<PathArgument>;
- void makePath(const JSONCPP_STRING& path, const InArgs& in);
- void addPathInArg(const JSONCPP_STRING& path,
- const InArgs& in,
- InArgs::const_iterator& itInArg,
- PathArgument::Kind kind);
- void invalidPath(const JSONCPP_STRING& path, int location);
+ void makePath(const String& path, const InArgs& in);
+ void addPathInArg(const String& path, const InArgs& in,
+ InArgs::const_iterator& itInArg, PathArgument::Kind kind);
+ static void invalidPath(const String& path, int location);
Args args_;
};
@@ -709,10 +747,10 @@ private:
*/
class JSON_API ValueIteratorBase {
public:
- typedef std::bidirectional_iterator_tag iterator_category;
- typedef unsigned int size_t;
- typedef int difference_type;
- typedef ValueIteratorBase SelfType;
+ using iterator_category = std::bidirectional_iterator_tag;
+ using size_t = unsigned int;
+ using difference_type = int;
+ using SelfType = ValueIteratorBase;
bool operator==(const SelfType& other) const { return isEqual(other); }
@@ -726,17 +764,19 @@ public:
/// Value.
Value key() const;
- /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
+ /// Return the index of the referenced Value, or -1 if it is not an
+ /// arrayValue.
UInt index() const;
/// Return the member name of the referenced Value, or "" if it is not an
/// objectValue.
/// \note Avoid `c_str()` on result, as embedded zeroes are possible.
- JSONCPP_STRING name() const;
+ String name() const;
/// Return the member name of the referenced Value. "" if it is not an
/// objectValue.
- /// deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
+ /// deprecated This cannot be used for UTF-8 strings, since there can be
+ /// embedded nulls.
JSONCPP_DEPRECATED("Use `key = name();` instead.")
char const* memberName() const;
/// Return the member name of the referenced Value, or NULL if it is not an
@@ -745,7 +785,14 @@ public:
char const* memberName(char const** end) const;
protected:
- Value& deref() const;
+ /*! Internal utility functions to assist with implementing
+ * other iterator functions. The const and non-const versions
+ * of the "deref" protected methods expose the protected
+ * current_ member variable in a way that can often be
+ * optimized away by the compiler.
+ */
+ const Value& deref() const;
+ Value& deref();
void increment();
@@ -760,7 +807,7 @@ protected:
private:
Value::ObjectValues::iterator current_;
// Indicates that iterator is for a null value.
- bool isNull_;
+ bool isNull_{true};
public:
// For some reason, BORLAND needs these at the end, rather
@@ -776,20 +823,21 @@ class JSON_API ValueConstIterator : public ValueIteratorBase {
friend class Value;
public:
- typedef const Value value_type;
- //typedef unsigned int size_t;
- //typedef int difference_type;
- typedef const Value& reference;
- typedef const Value* pointer;
- typedef ValueConstIterator SelfType;
+ using value_type = const Value;
+ // typedef unsigned int size_t;
+ // typedef int difference_type;
+ using reference = const Value&;
+ using pointer = const Value*;
+ using SelfType = ValueConstIterator;
ValueConstIterator();
ValueConstIterator(ValueIterator const& other);
private:
-/*! internal Use by Value to create an iterator.
- */
+ /*! internal Use by Value to create an iterator.
+ */
explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
+
public:
SelfType& operator=(const ValueIteratorBase& other);
@@ -826,21 +874,22 @@ class JSON_API ValueIterator : public ValueIteratorBase {
friend class Value;
public:
- typedef Value value_type;
- typedef unsigned int size_t;
- typedef int difference_type;
- typedef Value& reference;
- typedef Value* pointer;
- typedef ValueIterator SelfType;
+ using value_type = Value;
+ using size_t = unsigned int;
+ using difference_type = int;
+ using reference = Value&;
+ using pointer = Value*;
+ using SelfType = ValueIterator;
ValueIterator();
explicit ValueIterator(const ValueConstIterator& other);
ValueIterator(const ValueIterator& other);
private:
-/*! internal Use by Value to create an iterator.
- */
+ /*! internal Use by Value to create an iterator.
+ */
explicit ValueIterator(const Value::ObjectValues::iterator& current);
+
public:
SelfType& operator=(const SelfType& other);
@@ -866,19 +915,18 @@ public:
return *this;
}
- reference operator*() const { return deref(); }
-
- pointer operator->() const { return &deref(); }
+ /*! The return value of non-const iterators can be
+ * changed, so the these functions are not const
+ * because the returned references/pointers can be used
+ * to change state of the base class.
+ */
+ reference operator*() { return deref(); }
+ pointer operator->() { return &deref(); }
};
-} // namespace Json
+inline void swap(Value& a, Value& b) { a.swap(b); }
-
-namespace std {
-/// Specialize std::swap() for Json::Value.
-template<>
-inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
-}
+} // namespace Json
#if !defined(__SUNPRO_CC)
#pragma pack(pop)
@@ -888,4 +936,4 @@ inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
-#endif // CPPTL_JSON_H_INCLUDED
+#endif // JSON_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/version.h b/Utilities/cmjsoncpp/include/json/version.h
index d953961..5b9783d 100644
--- a/Utilities/cmjsoncpp/include/json/version.h
+++ b/Utilities/cmjsoncpp/include/json/version.h
@@ -1,14 +1,22 @@
-// DO NOT EDIT. This file (and "version") is generated by CMake.
-// Run CMake configure step to update it.
#ifndef JSON_VERSION_H_INCLUDED
-# define JSON_VERSION_H_INCLUDED
+#define JSON_VERSION_H_INCLUDED
-# define JSONCPP_VERSION_STRING "1.8.2"
-# define JSONCPP_VERSION_MAJOR 1
-# define JSONCPP_VERSION_MINOR 8
-# define JSONCPP_VERSION_PATCH 2
-# define JSONCPP_VERSION_QUALIFIER
-# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
+// Note: version must be updated in three places when doing a release. This
+// annoying process ensures that amalgamate, CMake, and meson all report the
+// correct version.
+// 1. /meson.build
+// 2. /include/json/version.h
+// 3. /CMakeLists.txt
+// IMPORTANT: also update the SOVERSION!!
+
+#define JSONCPP_VERSION_STRING "1.9.4"
+#define JSONCPP_VERSION_MAJOR 1
+#define JSONCPP_VERSION_MINOR 9
+#define JSONCPP_VERSION_PATCH 3
+#define JSONCPP_VERSION_QUALIFIER
+#define JSONCPP_VERSION_HEXA \
+ ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | \
+ (JSONCPP_VERSION_PATCH << 8))
#ifdef JSONCPP_USING_SECURE_MEMORY
#undef JSONCPP_USING_SECURE_MEMORY
diff --git a/Utilities/cmjsoncpp/include/json/writer.h b/Utilities/cmjsoncpp/include/json/writer.h
index d3ae62b..cc6b78c 100644
--- a/Utilities/cmjsoncpp/include/json/writer.h
+++ b/Utilities/cmjsoncpp/include/json/writer.h
@@ -9,14 +9,13 @@
#if !defined(JSON_IS_AMALGAMATION)
#include "value.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
-#include <iosfwd>
-#include <vector>
-#include <string>
#include <ostream>
+#include <string>
+#include <vector>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
-#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
@@ -30,31 +29,31 @@ namespace Json {
class Value;
/**
-
-Usage:
-\code
- using namespace Json;
- void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
- std::unique_ptr<StreamWriter> const writer(
- factory.newStreamWriter());
- writer->write(value, &std::cout);
- std::cout << std::endl; // add lf and flush
- }
-\endcode
-*/
+ *
+ * Usage:
+ * \code
+ * using namespace Json;
+ * void writeToStdout(StreamWriter::Factory const& factory, Value const& value)
+ * { std::unique_ptr<StreamWriter> const writer( factory.newStreamWriter());
+ * writer->write(value, &std::cout);
+ * std::cout << std::endl; // add lf and flush
+ * }
+ * \endcode
+ */
class JSON_API StreamWriter {
protected:
- JSONCPP_OSTREAM* sout_; // not owned; will not delete
+ OStream* sout_; // not owned; will not delete
public:
StreamWriter();
virtual ~StreamWriter();
/** Write Value into document as configured in sub-class.
- Do not take ownership of sout, but maintain a reference during function.
- \pre sout != NULL
- \return zero on success (For now, we always return zero, so check the stream instead.)
- \throw std::exception possibly, depending on configuration
+ * Do not take ownership of sout, but maintain a reference during function.
+ * \pre sout != NULL
+ * \return zero on success (For now, we always return zero, so check the
+ * stream instead.) \throw std::exception possibly, depending on
+ * configuration
*/
- virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
+ virtual int write(Value const& root, OStream* sout) = 0;
/** \brief A simple abstract factory.
*/
@@ -65,64 +64,69 @@ public:
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual StreamWriter* newStreamWriter() const = 0;
- }; // Factory
-}; // StreamWriter
+ }; // Factory
+}; // StreamWriter
/** \brief Write into stringstream, then return string, for convenience.
* A StreamWriter will be created from the factory, used, and then deleted.
*/
-JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
-
+String JSON_API writeString(StreamWriter::Factory const& factory,
+ Value const& root);
/** \brief Build a StreamWriter implementation.
-Usage:
-\code
- using namespace Json;
- Value value = ...;
- StreamWriterBuilder builder;
- builder["commentStyle"] = "None";
- builder["indentation"] = " "; // or whatever you like
- std::unique_ptr<Json::StreamWriter> writer(
- builder.newStreamWriter());
- writer->write(value, &std::cout);
- std::cout << std::endl; // add lf and flush
-\endcode
+* Usage:
+* \code
+* using namespace Json;
+* Value value = ...;
+* StreamWriterBuilder builder;
+* builder["commentStyle"] = "None";
+* builder["indentation"] = " "; // or whatever you like
+* std::unique_ptr<Json::StreamWriter> writer(
+* builder.newStreamWriter());
+* writer->write(value, &std::cout);
+* std::cout << std::endl; // add lf and flush
+* \endcode
*/
class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
public:
// Note: We use a Json::Value so that we can add data-members to this class
// without a major version bump.
/** Configuration of this builder.
- Available settings (case-sensitive):
- - "commentStyle": "None" or "All"
- - "indentation": "<anything>"
- - "enableYAMLCompatibility": false or true
- - slightly change the whitespace around colons
- - "dropNullPlaceholders": false or true
- - Drop the "null" string from the writer's output for nullValues.
- Strictly speaking, this is not valid JSON. But when the output is being
- fed to a browser's Javascript, it makes for smaller output and the
- browser can handle the output just fine.
- - "useSpecialFloats": false or true
- - If true, outputs non-finite floating point values in the following way:
- NaN values as "NaN", positive infinity as "Infinity", and negative infinity
- as "-Infinity".
-
- You can examine 'settings_` yourself
- to see the defaults. You can also write and read them just like any
- JSON Value.
- \sa setDefaults()
- */
+ * Available settings (case-sensitive):
+ * - "commentStyle": "None" or "All"
+ * - "indentation": "<anything>".
+ * - Setting this to an empty string also omits newline characters.
+ * - "enableYAMLCompatibility": false or true
+ * - slightly change the whitespace around colons
+ * - "dropNullPlaceholders": false or true
+ * - Drop the "null" string from the writer's output for nullValues.
+ * Strictly speaking, this is not valid JSON. But when the output is being
+ * fed to a browser's JavaScript, it makes for smaller output and the
+ * browser can handle the output just fine.
+ * - "useSpecialFloats": false or true
+ * - If true, outputs non-finite floating point values in the following way:
+ * NaN values as "NaN", positive infinity as "Infinity", and negative
+ * infinity as "-Infinity".
+ * - "precision": int
+ * - Number of precision digits for formatting of real values.
+ * - "precisionType": "significant"(default) or "decimal"
+ * - Type of precision for formatting of real values.
+
+ * You can examine 'settings_` yourself
+ * to see the defaults. You can also write and read them just like any
+ * JSON Value.
+ * \sa setDefaults()
+ */
Json::Value settings_;
StreamWriterBuilder();
- ~StreamWriterBuilder() JSONCPP_OVERRIDE;
+ ~StreamWriterBuilder() override;
/**
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
- StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
+ StreamWriter* newStreamWriter() const override;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
@@ -130,7 +134,7 @@ public:
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
- Value& operator[](JSONCPP_STRING key);
+ Value& operator[](const String& key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
@@ -147,7 +151,7 @@ class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer {
public:
virtual ~Writer();
- virtual JSONCPP_STRING write(const Value& root) = 0;
+ virtual String write(const Value& root) = 0;
};
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
@@ -155,21 +159,25 @@ public:
*
* The JSON document is written in a single line. It is not intended for 'human'
*consumption,
- * but may be usefull to support feature such as RPC where bandwith is limited.
+ * but may be useful to support feature such as RPC where bandwidth is limited.
* \sa Reader, Value
* deprecated Use StreamWriterBuilder.
*/
-class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer {
-
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // Deriving from deprecated class
+#endif
+class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter
+ : public Writer {
public:
FastWriter();
- ~FastWriter() JSONCPP_OVERRIDE {}
+ ~FastWriter() override = default;
void enableYAMLCompatibility();
/** \brief Drop the "null" string from the writer's output for nullValues.
* Strictly speaking, this is not valid JSON. But when the output is being
- * fed to a browser's Javascript, it makes for smaller output and the
+ * fed to a browser's JavaScript, it makes for smaller output and the
* browser can handle the output just fine.
*/
void dropNullPlaceholders();
@@ -177,16 +185,19 @@ public:
void omitEndingLineFeed();
public: // overridden from Writer
- JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
+ String write(const Value& root) override;
private:
void writeValue(const Value& value);
- JSONCPP_STRING document_;
- bool yamlCompatiblityEnabled_;
- bool dropNullPlaceholders_;
- bool omitEndingLineFeed_;
+ String document_;
+ bool yamlCompatibilityEnabled_{false};
+ bool dropNullPlaceholders_{false};
+ bool omitEndingLineFeed_{false};
};
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
*human friendly way.
@@ -212,41 +223,49 @@ private:
* \sa Reader, Value, Value::setComment()
* deprecated Use StreamWriterBuilder.
*/
-class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer {
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // Deriving from deprecated class
+#endif
+class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API
+ StyledWriter : public Writer {
public:
StyledWriter();
- ~StyledWriter() JSONCPP_OVERRIDE {}
+ ~StyledWriter() override = default;
public: // overridden from Writer
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param root Value to serialize.
* \return String containing the JSON document that represents the root value.
*/
- JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
+ String write(const Value& root) override;
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
- bool isMultineArray(const Value& value);
- void pushValue(const JSONCPP_STRING& value);
+ bool isMultilineArray(const Value& value);
+ void pushValue(const String& value);
void writeIndent();
- void writeWithIndent(const JSONCPP_STRING& value);
+ void writeWithIndent(const String& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
- bool hasCommentForValue(const Value& value);
- static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
+ static bool hasCommentForValue(const Value& value);
+ static String normalizeEOL(const String& text);
- typedef std::vector<JSONCPP_STRING> ChildValues;
+ using ChildValues = std::vector<String>;
ChildValues childValues_;
- JSONCPP_STRING document_;
- JSONCPP_STRING indentString_;
- unsigned int rightMargin_;
- unsigned int indentSize_;
- bool addChildValues_;
+ String document_;
+ String indentString_;
+ unsigned int rightMargin_{74};
+ unsigned int indentSize_{3};
+ bool addChildValues_{false};
};
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
human friendly way,
@@ -273,13 +292,18 @@ private:
* \sa Reader, Value, Value::setComment()
* deprecated Use StreamWriterBuilder.
*/
-class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter {
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // Deriving from deprecated class
+#endif
+class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API
+ StyledStreamWriter {
public:
-/**
- * \param indentation Each level will be indented by this amount extra.
- */
- StyledStreamWriter(JSONCPP_STRING indentation = "\t");
- ~StyledStreamWriter() {}
+ /**
+ * \param indentation Each level will be indented by this amount extra.
+ */
+ StyledStreamWriter(String indentation = "\t");
+ ~StyledStreamWriter() = default;
public:
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
@@ -288,46 +312,51 @@ public:
* \note There is no point in deriving from Writer, since write() should not
* return a value.
*/
- void write(JSONCPP_OSTREAM& out, const Value& root);
+ void write(OStream& out, const Value& root);
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
- bool isMultineArray(const Value& value);
- void pushValue(const JSONCPP_STRING& value);
+ bool isMultilineArray(const Value& value);
+ void pushValue(const String& value);
void writeIndent();
- void writeWithIndent(const JSONCPP_STRING& value);
+ void writeWithIndent(const String& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
- bool hasCommentForValue(const Value& value);
- static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
+ static bool hasCommentForValue(const Value& value);
+ static String normalizeEOL(const String& text);
- typedef std::vector<JSONCPP_STRING> ChildValues;
+ using ChildValues = std::vector<String>;
ChildValues childValues_;
- JSONCPP_OSTREAM* document_;
- JSONCPP_STRING indentString_;
- unsigned int rightMargin_;
- JSONCPP_STRING indentation_;
+ OStream* document_;
+ String indentString_;
+ unsigned int rightMargin_{74};
+ String indentation_;
bool addChildValues_ : 1;
bool indented_ : 1;
};
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
#if defined(JSON_HAS_INT64)
-JSONCPP_STRING JSON_API valueToString(Int value);
-JSONCPP_STRING JSON_API valueToString(UInt value);
+String JSON_API valueToString(Int value);
+String JSON_API valueToString(UInt value);
#endif // if defined(JSON_HAS_INT64)
-JSONCPP_STRING JSON_API valueToString(LargestInt value);
-JSONCPP_STRING JSON_API valueToString(LargestUInt value);
-JSONCPP_STRING JSON_API valueToString(double value);
-JSONCPP_STRING JSON_API valueToString(bool value);
-JSONCPP_STRING JSON_API valueToQuotedString(const char* value);
+String JSON_API valueToString(LargestInt value);
+String JSON_API valueToString(LargestUInt value);
+String JSON_API valueToString(
+ double value, unsigned int precision = Value::defaultRealPrecision,
+ PrecisionType precisionType = PrecisionType::significantDigits);
+String JSON_API valueToString(bool value);
+String JSON_API valueToQuotedString(const char* value);
/// \brief Output using the StyledStreamWriter.
/// \see Json::operator>>()
-JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
+JSON_API OStream& operator<<(OStream&, const Value& root);
} // namespace Json
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp b/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp
index 8291cc6..e6caf40 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp
+++ b/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp
@@ -5,69 +5,65 @@
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
+#include "json_tool.h"
#include <json/assertions.h>
#include <json/reader.h>
#include <json/value.h>
-#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
-#include <utility>
-#include <stdio.h>
-#include <assert.h>
-#include <string.h>
+#include <algorithm>
+#include <cassert>
+#include <cstring>
+#include <iostream>
#include <istream>
-#include <sstream>
+#include <limits>
#include <memory>
#include <set>
-#include <limits>
+#include <sstream>
+#include <utility>
-#if defined(_MSC_VER)
-#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
-#define snprintf sprintf_s
-#elif _MSC_VER >= 1900 // VC++ 14.0 and above
-#define snprintf std::snprintf
-#else
-#define snprintf _snprintf
-#endif
-#elif defined(__ANDROID__) || defined(__QNXNTO__)
-#define snprintf snprintf
-#elif __cplusplus >= 201103L
-#if !defined(__MINGW32__) && !defined(__CYGWIN__)
-#define snprintf std::snprintf
-#endif
-#endif
+#include <cstdio>
+#if __cplusplus >= 201103L
-#if defined(__QNXNTO__)
+#if !defined(sscanf)
#define sscanf std::sscanf
#endif
-#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+#endif //__cplusplus
+
+#if defined(_MSC_VER)
+#if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
+#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
+#endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
+#endif //_MSC_VER
+
+#if defined(_MSC_VER)
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
-// Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile time to change the stack limit
+// Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile
+// time to change the stack limit
#if !defined(JSONCPP_DEPRECATED_STACK_LIMIT)
#define JSONCPP_DEPRECATED_STACK_LIMIT 1000
#endif
-static size_t const stackLimit_g = JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue()
+static size_t const stackLimit_g =
+ JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue()
namespace Json {
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
-typedef std::unique_ptr<CharReader> CharReaderPtr;
+using CharReaderPtr = std::unique_ptr<CharReader>;
#else
-typedef std::auto_ptr<CharReader> CharReaderPtr;
+using CharReaderPtr = std::auto_ptr<CharReader>;
#endif
// Implementation of class Features
// ////////////////////////////////
-Features::Features()
- : allowComments_(true), strictRoot_(false),
- allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {}
+Features::Features() = default;
-Features Features::all() { return Features(); }
+Features Features::all() { return {}; }
Features Features::strictMode() {
Features features;
@@ -82,49 +78,38 @@ Features Features::strictMode() {
// ////////////////////////////////
bool Reader::containsNewLine(Reader::Location begin, Reader::Location end) {
- for (; begin < end; ++begin)
- if (*begin == '\n' || *begin == '\r')
- return true;
- return false;
+ return std::any_of(begin, end, [](char b) { return b == '\n' || b == '\r'; });
}
// Class Reader
// //////////////////////////////////////////////////////////////////
-Reader::Reader()
- : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
- lastValue_(), commentsBefore_(), features_(Features::all()),
- collectComments_() {}
+Reader::Reader() : features_(Features::all()) {}
-Reader::Reader(const Features& features)
- : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
- lastValue_(), commentsBefore_(), features_(features), collectComments_() {
-}
+Reader::Reader(const Features& features) : features_(features) {}
-bool
-Reader::parse(const std::string& document, Value& root, bool collectComments) {
+bool Reader::parse(const std::string& document, Value& root,
+ bool collectComments) {
document_.assign(document.begin(), document.end());
const char* begin = document_.c_str();
const char* end = begin + document_.length();
return parse(begin, end, root, collectComments);
}
-bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
- // std::istream_iterator<char> begin(sin);
+bool Reader::parse(std::istream& is, Value& root, bool collectComments) {
+ // std::istream_iterator<char> begin(is);
// std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
- // Since JSONCPP_STRING is reference-counted, this at least does not
+ // Since String is reference-counted, this at least does not
// create an extra copy.
- JSONCPP_STRING doc;
- std::getline(sin, doc, (char)EOF);
+ String doc;
+ std::getline(is, doc, static_cast<char> EOF);
return parse(doc.data(), doc.data() + doc.size(), root, collectComments);
}
-bool Reader::parse(const char* beginDoc,
- const char* endDoc,
- Value& root,
+bool Reader::parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments) {
if (!features_.allowComments_) {
collectComments = false;
@@ -134,8 +119,8 @@ bool Reader::parse(const char* beginDoc,
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
- lastValueEnd_ = 0;
- lastValue_ = 0;
+ lastValueEnd_ = nullptr;
+ lastValue_ = nullptr;
commentsBefore_.clear();
errors_.clear();
while (!nodes_.empty())
@@ -165,9 +150,11 @@ bool Reader::parse(const char* beginDoc,
bool Reader::readValue() {
// readValue() may call itself only if it calls readObject() or ReadArray().
- // These methods execute nodes_.push() just before and nodes_.pop)() just after calling readValue().
- // parse() executes one nodes_.push(), so > instead of >=.
- if (nodes_.size() > stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
+ // These methods execute nodes_.push() just before and nodes_.pop)() just
+ // after calling readValue(). parse() executes one nodes_.push(), so > instead
+ // of >=.
+ if (nodes_.size() > stackLimit_g)
+ throwRuntimeError("Exceeded stackLimit in readValue().");
Token token;
skipCommentTokens(token);
@@ -193,30 +180,24 @@ bool Reader::readValue() {
case tokenString:
successful = decodeString(token);
break;
- case tokenTrue:
- {
+ case tokenTrue: {
Value v(true);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenFalse:
- {
+ } break;
+ case tokenFalse: {
Value v(false);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenNull:
- {
+ } break;
+ case tokenNull: {
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
+ } break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
@@ -322,7 +303,7 @@ bool Reader::readToken(Token& token) {
if (!ok)
token.type_ = tokenError;
token.end_ = current_;
- return true;
+ return ok;
}
void Reader::skipSpaces() {
@@ -335,7 +316,7 @@ void Reader::skipSpaces() {
}
}
-bool Reader::match(Location pattern, int patternLength) {
+bool Reader::match(const Char* pattern, int patternLength) {
if (end_ - current_ < patternLength)
return false;
int index = patternLength;
@@ -369,16 +350,16 @@ bool Reader::readComment() {
return true;
}
-JSONCPP_STRING Reader::normalizeEOL(Reader::Location begin, Reader::Location end) {
- JSONCPP_STRING normalized;
+String Reader::normalizeEOL(Reader::Location begin, Reader::Location end) {
+ String normalized;
normalized.reserve(static_cast<size_t>(end - begin));
Reader::Location current = begin;
while (current != end) {
char c = *current++;
if (c == '\r') {
if (current != end && *current == '\n')
- // convert dos EOL
- ++current;
+ // convert dos EOL
+ ++current;
// convert Mac EOL
normalized += '\n';
} else {
@@ -388,12 +369,12 @@ JSONCPP_STRING Reader::normalizeEOL(Reader::Location begin, Reader::Location end
return normalized;
}
-void
-Reader::addComment(Location begin, Location end, CommentPlacement placement) {
+void Reader::addComment(Location begin, Location end,
+ CommentPlacement placement) {
assert(collectComments_);
- const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
+ const String& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
- assert(lastValue_ != 0);
+ assert(lastValue_ != nullptr);
lastValue_->setComment(normalized, placement);
} else {
commentsBefore_ += normalized;
@@ -426,7 +407,7 @@ bool Reader::readCppStyleComment() {
}
void Reader::readNumber() {
- const char *p = current_;
+ Location p = current_;
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
@@ -459,12 +440,12 @@ bool Reader::readString() {
return c == '"';
}
-bool Reader::readObject(Token& tokenStart) {
+bool Reader::readObject(Token& token) {
Token tokenName;
- JSONCPP_STRING name;
+ String name;
Value init(objectValue);
currentValue().swapPayload(init);
- currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ currentValue().setOffsetStart(token.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
while (tokenName.type_ == tokenComment && initialTokenOk)
@@ -481,15 +462,15 @@ bool Reader::readObject(Token& tokenStart) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
- name = JSONCPP_STRING(numberName.asCString());
+ name = numberName.asString();
} else {
break;
}
Token colon;
if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
- return addErrorAndRecover(
- "Missing ':' after object member name", colon, tokenObjectEnd);
+ return addErrorAndRecover("Missing ':' after object member name", colon,
+ tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
@@ -502,8 +483,8 @@ bool Reader::readObject(Token& tokenStart) {
if (!readToken(comma) ||
(comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment)) {
- return addErrorAndRecover(
- "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ return addErrorAndRecover("Missing ',' or '}' in object declaration",
+ comma, tokenObjectEnd);
}
bool finalizeTokenOk = true;
while (comma.type_ == tokenComment && finalizeTokenOk)
@@ -511,14 +492,14 @@ bool Reader::readObject(Token& tokenStart) {
if (comma.type_ == tokenObjectEnd)
return true;
}
- return addErrorAndRecover(
- "Missing '}' or object member name", tokenName, tokenObjectEnd);
+ return addErrorAndRecover("Missing '}' or object member name", tokenName,
+ tokenObjectEnd);
}
-bool Reader::readArray(Token& tokenStart) {
+bool Reader::readArray(Token& token) {
Value init(arrayValue);
currentValue().swapPayload(init);
- currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ currentValue().setOffsetStart(token.start_ - begin_);
skipSpaces();
if (current_ != end_ && *current_ == ']') // empty array
{
@@ -535,19 +516,19 @@ bool Reader::readArray(Token& tokenStart) {
if (!ok) // error already set
return recoverFromError(tokenArrayEnd);
- Token token;
+ Token currentToken;
// Accept Comment after last item in the array.
- ok = readToken(token);
- while (token.type_ == tokenComment && ok) {
- ok = readToken(token);
+ ok = readToken(currentToken);
+ while (currentToken.type_ == tokenComment && ok) {
+ ok = readToken(currentToken);
}
- bool badTokenType =
- (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
+ currentToken.type_ != tokenArrayEnd);
if (!ok || badTokenType) {
- return addErrorAndRecover(
- "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ return addErrorAndRecover("Missing ',' or ']' in array declaration",
+ currentToken, tokenArrayEnd);
}
- if (token.type_ == tokenArrayEnd)
+ if (currentToken.type_ == tokenArrayEnd)
break;
}
return true;
@@ -571,7 +552,8 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
bool isNegative = *current == '-';
if (isNegative)
++current;
- // TODO: Help the compiler do the div and mod at compile time or get rid of them.
+ // TODO: Help the compiler do the div and mod at compile time or get rid of
+ // them.
Value::LargestUInt maxIntegerValue =
isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
: Value::maxLargestUInt;
@@ -581,7 +563,7 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
- Value::UInt digit(static_cast<Value::UInt>(c - '0'));
+ auto digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
@@ -617,18 +599,17 @@ bool Reader::decodeDouble(Token& token) {
bool Reader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
- JSONCPP_STRING buffer(token.start_, token.end_);
- JSONCPP_ISTRINGSTREAM is(buffer);
+ String buffer(token.start_, token.end_);
+ IStringStream is(buffer);
if (!(is >> value))
- return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
- "' is not a number.",
- token);
+ return addError(
+ "'" + String(token.start_, token.end_) + "' is not a number.", token);
decoded = value;
return true;
}
bool Reader::decodeString(Token& token) {
- JSONCPP_STRING decoded_string;
+ String decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
@@ -638,7 +619,7 @@ bool Reader::decodeString(Token& token) {
return true;
}
-bool Reader::decodeString(Token& token, JSONCPP_STRING& decoded) {
+bool Reader::decodeString(Token& token, String& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
@@ -646,7 +627,7 @@ bool Reader::decodeString(Token& token, JSONCPP_STRING& decoded) {
Char c = *current++;
if (c == '"')
break;
- else if (c == '\\') {
+ if (c == '\\') {
if (current == end)
return addError("Empty escape sequence in string", token, current);
Char escape = *current++;
@@ -691,10 +672,8 @@ bool Reader::decodeString(Token& token, JSONCPP_STRING& decoded) {
return true;
}
-bool Reader::decodeUnicodeCodePoint(Token& token,
- Location& current,
- Location end,
- unsigned int& unicode) {
+bool Reader::decodeUnicodeCodePoint(Token& token, Location& current,
+ Location end, unsigned int& unicode) {
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
return false;
@@ -703,10 +682,9 @@ bool Reader::decodeUnicodeCodePoint(Token& token,
if (end - current < 6)
return addError(
"additional six characters expected to parse unicode surrogate pair.",
- token,
- current);
- unsigned int surrogatePair;
+ token, current);
if (*(current++) == '\\' && *(current++) == 'u') {
+ unsigned int surrogatePair;
if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
} else
@@ -714,20 +692,17 @@ bool Reader::decodeUnicodeCodePoint(Token& token,
} else
return addError("expecting another \\u token to begin the second half of "
"a unicode surrogate pair",
- token,
- current);
+ token, current);
}
return true;
}
-bool Reader::decodeUnicodeEscapeSequence(Token& token,
- Location& current,
+bool Reader::decodeUnicodeEscapeSequence(Token& token, Location& current,
Location end,
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
- "Bad unicode escape sequence in string: four digits expected.",
- token,
+ "Bad unicode escape sequence in string: four digits expected.", token,
current);
int unicode = 0;
for (int index = 0; index < 4; ++index) {
@@ -742,15 +717,13 @@ bool Reader::decodeUnicodeEscapeSequence(Token& token,
else
return addError(
"Bad unicode escape sequence in string: hexadecimal digit expected.",
- token,
- current);
+ token, current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
-bool
-Reader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
+bool Reader::addError(const String& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
@@ -772,8 +745,7 @@ bool Reader::recoverFromError(TokenType skipUntilToken) {
return false;
}
-bool Reader::addErrorAndRecover(const JSONCPP_STRING& message,
- Token& token,
+bool Reader::addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
@@ -787,8 +759,7 @@ Reader::Char Reader::getNextChar() {
return *current_++;
}
-void Reader::getLocationLineAndColumn(Location location,
- int& line,
+void Reader::getLocationLineAndColumn(Location location, int& line,
int& column) const {
Location current = begin_;
Location lastLineStart = current;
@@ -810,25 +781,22 @@ void Reader::getLocationLineAndColumn(Location location,
++line;
}
-JSONCPP_STRING Reader::getLocationLineAndColumn(Location location) const {
+String Reader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
- snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
+ jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
return buffer;
}
// Deprecated. Preserved for backward compatibility
-JSONCPP_STRING Reader::getFormatedErrorMessages() const {
+String Reader::getFormatedErrorMessages() const {
return getFormattedErrorMessages();
}
-JSONCPP_STRING Reader::getFormattedErrorMessages() const {
- JSONCPP_STRING formattedMessage;
- for (Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError) {
- const ErrorInfo& error = *itError;
+String Reader::getFormattedErrorMessages() const {
+ String formattedMessage;
+ for (const auto& error : errors_) {
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
@@ -841,10 +809,7 @@ JSONCPP_STRING Reader::getFormattedErrorMessages() const {
std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
std::vector<Reader::StructuredError> allErrors;
- for (Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError) {
- const ErrorInfo& error = *itError;
+ for (const auto& error : errors_) {
Reader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
@@ -854,28 +819,27 @@ std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
return allErrors;
}
-bool Reader::pushError(const Value& value, const JSONCPP_STRING& message) {
+bool Reader::pushError(const Value& value, const String& message) {
ptrdiff_t const length = end_ - begin_;
- if(value.getOffsetStart() > length
- || value.getOffsetLimit() > length)
+ if (value.getOffsetStart() > length || value.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
- token.end_ = end_ + value.getOffsetLimit();
+ token.end_ = begin_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
- info.extra_ = 0;
+ info.extra_ = nullptr;
errors_.push_back(info);
return true;
}
-bool Reader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
+bool Reader::pushError(const Value& value, const String& message,
+ const Value& extra) {
ptrdiff_t const length = end_ - begin_;
- if(value.getOffsetStart() > length
- || value.getOffsetLimit() > length
- || extra.getOffsetLimit() > length)
+ if (value.getOffsetStart() > length || value.getOffsetLimit() > length ||
+ extra.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
@@ -889,15 +853,15 @@ bool Reader::pushError(const Value& value, const JSONCPP_STRING& message, const
return true;
}
-bool Reader::good() const {
- return !errors_.size();
-}
+bool Reader::good() const { return errors_.empty(); }
-// exact copy of Features
+// Originally copied from the Features class (now deprecated), used internally
+// for features implementation.
class OurFeatures {
public:
static OurFeatures all();
bool allowComments_;
+ bool allowTrailingCommas_;
bool strictRoot_;
bool allowDroppedNullPlaceholders_;
bool allowNumericKeys_;
@@ -905,42 +869,36 @@ public:
bool failIfExtra_;
bool rejectDupKeys_;
bool allowSpecialFloats_;
- int stackLimit_;
-}; // OurFeatures
-
-// exact copy of Implementation of class Features
-// ////////////////////////////////
+ bool skipBom_;
+ size_t stackLimit_;
+}; // OurFeatures
-OurFeatures OurFeatures::all() { return OurFeatures(); }
+OurFeatures OurFeatures::all() { return {}; }
// Implementation of class Reader
// ////////////////////////////////
-// exact copy of Reader, renamed to OurReader
+// Originally copied from the Reader class (now deprecated), used internally
+// for implementing JSON reading.
class OurReader {
public:
- typedef char Char;
- typedef const Char* Location;
+ using Char = char;
+ using Location = const Char*;
struct StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
- JSONCPP_STRING message;
+ String message;
};
- OurReader(OurFeatures const& features);
- bool parse(const char* beginDoc,
- const char* endDoc,
- Value& root,
+ explicit OurReader(OurFeatures const& features);
+ bool parse(const char* beginDoc, const char* endDoc, Value& root,
bool collectComments = true);
- JSONCPP_STRING getFormattedErrorMessages() const;
+ String getFormattedErrorMessages() const;
std::vector<StructuredError> getStructuredErrors() const;
- bool pushError(const Value& value, const JSONCPP_STRING& message);
- bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
- bool good() const;
private:
- OurReader(OurReader const&); // no impl
- void operator=(OurReader const&); // no impl
+ OurReader(OurReader const&); // no impl
+ void operator=(OurReader const&); // no impl
enum TokenType {
tokenEndOfStream = 0,
@@ -972,17 +930,18 @@ private:
class ErrorInfo {
public:
Token token_;
- JSONCPP_STRING message_;
+ String message_;
Location extra_;
};
- typedef std::deque<ErrorInfo> Errors;
+ using Errors = std::deque<ErrorInfo>;
bool readToken(Token& token);
void skipSpaces();
- bool match(Location pattern, int patternLength);
+ void skipBom(bool skipBom);
+ bool match(const Char* pattern, int patternLength);
bool readComment();
- bool readCStyleComment();
+ bool readCStyleComment(bool* containsNewLineResult);
bool readCppStyleComment();
bool readString();
bool readStringSingleQuote();
@@ -993,68 +952,57 @@ private:
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
- bool decodeString(Token& token, JSONCPP_STRING& decoded);
+ bool decodeString(Token& token, String& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
- bool decodeUnicodeCodePoint(Token& token,
- Location& current,
- Location end,
+ bool decodeUnicodeCodePoint(Token& token, Location& current, Location end,
unsigned int& unicode);
- bool decodeUnicodeEscapeSequence(Token& token,
- Location& current,
- Location end,
- unsigned int& unicode);
- bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
+ bool decodeUnicodeEscapeSequence(Token& token, Location& current,
+ Location end, unsigned int& unicode);
+ bool addError(const String& message, Token& token, Location extra = nullptr);
bool recoverFromError(TokenType skipUntilToken);
- bool addErrorAndRecover(const JSONCPP_STRING& message,
- Token& token,
+ bool addErrorAndRecover(const String& message, Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
Value& currentValue();
Char getNextChar();
- void
- getLocationLineAndColumn(Location location, int& line, int& column) const;
- JSONCPP_STRING getLocationLineAndColumn(Location location) const;
+ void getLocationLineAndColumn(Location location, int& line,
+ int& column) const;
+ String getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
- static JSONCPP_STRING normalizeEOL(Location begin, Location end);
+ static String normalizeEOL(Location begin, Location end);
static bool containsNewLine(Location begin, Location end);
- typedef std::stack<Value*> Nodes;
- Nodes nodes_;
- Errors errors_;
- JSONCPP_STRING document_;
- Location begin_;
- Location end_;
- Location current_;
- Location lastValueEnd_;
- Value* lastValue_;
- JSONCPP_STRING commentsBefore_;
+ using Nodes = std::stack<Value*>;
+
+ Nodes nodes_{};
+ Errors errors_{};
+ String document_{};
+ Location begin_ = nullptr;
+ Location end_ = nullptr;
+ Location current_ = nullptr;
+ Location lastValueEnd_ = nullptr;
+ Value* lastValue_ = nullptr;
+ bool lastValueHasAComment_ = false;
+ String commentsBefore_{};
OurFeatures const features_;
- bool collectComments_;
-}; // OurReader
+ bool collectComments_ = false;
+}; // OurReader
// complete copy of Read impl, for OurReader
-bool OurReader::containsNewLine(OurReader::Location begin, OurReader::Location end) {
- for (; begin < end; ++begin)
- if (*begin == '\n' || *begin == '\r')
- return true;
- return false;
+bool OurReader::containsNewLine(OurReader::Location begin,
+ OurReader::Location end) {
+ return std::any_of(begin, end, [](char b) { return b == '\n' || b == '\r'; });
}
-OurReader::OurReader(OurFeatures const& features)
- : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
- lastValue_(), commentsBefore_(),
- features_(features), collectComments_() {
-}
+OurReader::OurReader(OurFeatures const& features) : features_(features) {}
-bool OurReader::parse(const char* beginDoc,
- const char* endDoc,
- Value& root,
- bool collectComments) {
+bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root,
+ bool collectComments) {
if (!features_.allowComments_) {
collectComments = false;
}
@@ -1063,22 +1011,23 @@ bool OurReader::parse(const char* beginDoc,
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
- lastValueEnd_ = 0;
- lastValue_ = 0;
+ lastValueEnd_ = nullptr;
+ lastValue_ = nullptr;
commentsBefore_.clear();
errors_.clear();
while (!nodes_.empty())
nodes_.pop();
nodes_.push(&root);
+ // skip byte order mark if it exists at the beginning of the UTF-8 text.
+ skipBom(features_.skipBom_);
bool successful = readValue();
+ nodes_.pop();
Token token;
skipCommentTokens(token);
- if (features_.failIfExtra_) {
- if ((features_.strictRoot_ || token.type_ != tokenError) && token.type_ != tokenEndOfStream) {
- addError("Extra non-whitespace after JSON value.", token);
- return false;
- }
+ if (features_.failIfExtra_ && (token.type_ != tokenEndOfStream)) {
+ addError("Extra non-whitespace after JSON value.", token);
+ return false;
}
if (collectComments_ && !commentsBefore_.empty())
root.setComment(commentsBefore_, commentAfter);
@@ -1100,7 +1049,8 @@ bool OurReader::parse(const char* beginDoc,
bool OurReader::readValue() {
// To preserve the old behaviour we cast size_t to int.
- if (static_cast<int>(nodes_.size()) > features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
+ if (nodes_.size() > features_.stackLimit_)
+ throwRuntimeError("Exceeded stackLimit in readValue().");
Token token;
skipCommentTokens(token);
bool successful = true;
@@ -1125,54 +1075,42 @@ bool OurReader::readValue() {
case tokenString:
successful = decodeString(token);
break;
- case tokenTrue:
- {
+ case tokenTrue: {
Value v(true);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenFalse:
- {
+ } break;
+ case tokenFalse: {
Value v(false);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenNull:
- {
+ } break;
+ case tokenNull: {
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenNaN:
- {
+ } break;
+ case tokenNaN: {
Value v(std::numeric_limits<double>::quiet_NaN());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenPosInf:
- {
+ } break;
+ case tokenPosInf: {
Value v(std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
- case tokenNegInf:
- {
+ } break;
+ case tokenNegInf: {
Value v(-std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
- }
- break;
+ } break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
@@ -1194,6 +1132,7 @@ bool OurReader::readValue() {
if (collectComments_) {
lastValueEnd_ = current_;
+ lastValueHasAComment_ = false;
lastValue_ = &currentValue();
}
@@ -1234,10 +1173,13 @@ bool OurReader::readToken(Token& token) {
break;
case '\'':
if (features_.allowSingleQuotes_) {
- token.type_ = tokenString;
- ok = readStringSingleQuote();
+ token.type_ = tokenString;
+ ok = readStringSingleQuote();
+ } else {
+ // If we don't allow single quotes, this is a failure case.
+ ok = false;
+ }
break;
- } // else continue
case '/':
token.type_ = tokenComment;
ok = readComment();
@@ -1263,6 +1205,14 @@ bool OurReader::readToken(Token& token) {
ok = features_.allowSpecialFloats_ && match("nfinity", 7);
}
break;
+ case '+':
+ if (readNumber(true)) {
+ token.type_ = tokenNumber;
+ } else {
+ token.type_ = tokenPosInf;
+ ok = features_.allowSpecialFloats_ && match("nfinity", 7);
+ }
+ break;
case 't':
token.type_ = tokenTrue;
ok = match("rue", 3);
@@ -1307,7 +1257,7 @@ bool OurReader::readToken(Token& token) {
if (!ok)
token.type_ = tokenError;
token.end_ = current_;
- return true;
+ return ok;
}
void OurReader::skipSpaces() {
@@ -1320,7 +1270,17 @@ void OurReader::skipSpaces() {
}
}
-bool OurReader::match(Location pattern, int patternLength) {
+void OurReader::skipBom(bool skipBom) {
+ // The default behavior is to skip BOM.
+ if (skipBom) {
+ if ((end_ - begin_) >= 3 && strncmp(begin_, "\xEF\xBB\xBF", 3) == 0) {
+ begin_ += 3;
+ current_ = begin_;
+ }
+ }
+}
+
+bool OurReader::match(const Char* pattern, int patternLength) {
if (end_ - current_ < patternLength)
return false;
int index = patternLength;
@@ -1332,21 +1292,32 @@ bool OurReader::match(Location pattern, int patternLength) {
}
bool OurReader::readComment() {
- Location commentBegin = current_ - 1;
- Char c = getNextChar();
+ const Location commentBegin = current_ - 1;
+ const Char c = getNextChar();
bool successful = false;
- if (c == '*')
- successful = readCStyleComment();
- else if (c == '/')
+ bool cStyleWithEmbeddedNewline = false;
+
+ const bool isCStyleComment = (c == '*');
+ const bool isCppStyleComment = (c == '/');
+ if (isCStyleComment) {
+ successful = readCStyleComment(&cStyleWithEmbeddedNewline);
+ } else if (isCppStyleComment) {
successful = readCppStyleComment();
+ }
+
if (!successful)
return false;
if (collectComments_) {
CommentPlacement placement = commentBefore;
- if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
- if (c != '*' || !containsNewLine(commentBegin, current_))
- placement = commentAfterOnSameLine;
+
+ if (!lastValueHasAComment_) {
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
+ if (isCppStyleComment || !cStyleWithEmbeddedNewline) {
+ placement = commentAfterOnSameLine;
+ lastValueHasAComment_ = true;
+ }
+ }
}
addComment(commentBegin, current_, placement);
@@ -1354,16 +1325,17 @@ bool OurReader::readComment() {
return true;
}
-JSONCPP_STRING OurReader::normalizeEOL(OurReader::Location begin, OurReader::Location end) {
- JSONCPP_STRING normalized;
+String OurReader::normalizeEOL(OurReader::Location begin,
+ OurReader::Location end) {
+ String normalized;
normalized.reserve(static_cast<size_t>(end - begin));
OurReader::Location current = begin;
while (current != end) {
char c = *current++;
if (c == '\r') {
if (current != end && *current == '\n')
- // convert dos EOL
- ++current;
+ // convert dos EOL
+ ++current;
// convert Mac EOL
normalized += '\n';
} else {
@@ -1373,24 +1345,29 @@ JSONCPP_STRING OurReader::normalizeEOL(OurReader::Location begin, OurReader::Loc
return normalized;
}
-void
-OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
+void OurReader::addComment(Location begin, Location end,
+ CommentPlacement placement) {
assert(collectComments_);
- const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
+ const String& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
- assert(lastValue_ != 0);
+ assert(lastValue_ != nullptr);
lastValue_->setComment(normalized, placement);
} else {
commentsBefore_ += normalized;
}
}
-bool OurReader::readCStyleComment() {
+bool OurReader::readCStyleComment(bool* containsNewLineResult) {
+ *containsNewLineResult = false;
+
while ((current_ + 1) < end_) {
Char c = getNextChar();
if (c == '*' && *current_ == '/')
break;
+ if (c == '\n')
+ *containsNewLineResult = true;
}
+
return getNextChar() == '/';
}
@@ -1411,7 +1388,7 @@ bool OurReader::readCppStyleComment() {
}
bool OurReader::readNumber(bool checkInf) {
- const char *p = current_;
+ Location p = current_;
if (checkInf && p != end_ && *p == 'I') {
current_ = ++p;
return false;
@@ -1448,7 +1425,6 @@ bool OurReader::readString() {
return c == '"';
}
-
bool OurReader::readStringSingleQuote() {
Char c = 0;
while (current_ != end_) {
@@ -1461,19 +1437,21 @@ bool OurReader::readStringSingleQuote() {
return c == '\'';
}
-bool OurReader::readObject(Token& tokenStart) {
+bool OurReader::readObject(Token& token) {
Token tokenName;
- JSONCPP_STRING name;
+ String name;
Value init(objectValue);
currentValue().swapPayload(init);
- currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ currentValue().setOffsetStart(token.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
while (tokenName.type_ == tokenComment && initialTokenOk)
initialTokenOk = readToken(tokenName);
if (!initialTokenOk)
break;
- if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
+ if (tokenName.type_ == tokenObjectEnd &&
+ (name.empty() ||
+ features_.allowTrailingCommas_)) // empty object or trailing comma
return true;
name.clear();
if (tokenName.type_ == tokenString) {
@@ -1487,17 +1465,17 @@ bool OurReader::readObject(Token& tokenStart) {
} else {
break;
}
+ if (name.length() >= (1U << 30))
+ throwRuntimeError("keylength >= 2^30");
+ if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
+ String msg = "Duplicate key: '" + name + "'";
+ return addErrorAndRecover(msg, tokenName, tokenObjectEnd);
+ }
Token colon;
if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
- return addErrorAndRecover(
- "Missing ':' after object member name", colon, tokenObjectEnd);
- }
- if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
- if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
- JSONCPP_STRING msg = "Duplicate key: '" + name + "'";
- return addErrorAndRecover(
- msg, tokenName, tokenObjectEnd);
+ return addErrorAndRecover("Missing ':' after object member name", colon,
+ tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
@@ -1510,8 +1488,8 @@ bool OurReader::readObject(Token& tokenStart) {
if (!readToken(comma) ||
(comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment)) {
- return addErrorAndRecover(
- "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ return addErrorAndRecover("Missing ',' or '}' in object declaration",
+ comma, tokenObjectEnd);
}
bool finalizeTokenOk = true;
while (comma.type_ == tokenComment && finalizeTokenOk)
@@ -1519,23 +1497,27 @@ bool OurReader::readObject(Token& tokenStart) {
if (comma.type_ == tokenObjectEnd)
return true;
}
- return addErrorAndRecover(
- "Missing '}' or object member name", tokenName, tokenObjectEnd);
+ return addErrorAndRecover("Missing '}' or object member name", tokenName,
+ tokenObjectEnd);
}
-bool OurReader::readArray(Token& tokenStart) {
+bool OurReader::readArray(Token& token) {
Value init(arrayValue);
currentValue().swapPayload(init);
- currentValue().setOffsetStart(tokenStart.start_ - begin_);
- skipSpaces();
- if (current_ != end_ && *current_ == ']') // empty array
- {
- Token endArray;
- readToken(endArray);
- return true;
- }
+ currentValue().setOffsetStart(token.start_ - begin_);
int index = 0;
for (;;) {
+ skipSpaces();
+ if (current_ != end_ && *current_ == ']' &&
+ (index == 0 ||
+ (features_.allowTrailingCommas_ &&
+ !features_.allowDroppedNullPlaceholders_))) // empty array or trailing
+ // comma
+ {
+ Token endArray;
+ readToken(endArray);
+ return true;
+ }
Value& value = currentValue()[index++];
nodes_.push(&value);
bool ok = readValue();
@@ -1543,19 +1525,19 @@ bool OurReader::readArray(Token& tokenStart) {
if (!ok) // error already set
return recoverFromError(tokenArrayEnd);
- Token token;
+ Token currentToken;
// Accept Comment after last item in the array.
- ok = readToken(token);
- while (token.type_ == tokenComment && ok) {
- ok = readToken(token);
+ ok = readToken(currentToken);
+ while (currentToken.type_ == tokenComment && ok) {
+ ok = readToken(currentToken);
}
- bool badTokenType =
- (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ bool badTokenType = (currentToken.type_ != tokenArraySeparator &&
+ currentToken.type_ != tokenArrayEnd);
if (!ok || badTokenType) {
- return addErrorAndRecover(
- "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ return addErrorAndRecover("Missing ',' or ']' in array declaration",
+ currentToken, tokenArrayEnd);
}
- if (token.type_ == tokenArrayEnd)
+ if (currentToken.type_ == tokenArrayEnd)
break;
}
return true;
@@ -1576,38 +1558,78 @@ bool OurReader::decodeNumber(Token& token, Value& decoded) {
// larger than the maximum supported value of an integer then
// we decode the number as a double.
Location current = token.start_;
- bool isNegative = *current == '-';
- if (isNegative)
+ const bool isNegative = *current == '-';
+ if (isNegative) {
++current;
- // TODO: Help the compiler do the div and mod at compile time or get rid of them.
- Value::LargestUInt maxIntegerValue =
- isNegative ? Value::LargestUInt(Value::minLargestInt)
- : Value::maxLargestUInt;
- Value::LargestUInt threshold = maxIntegerValue / 10;
+ }
+
+ // We assume we can represent the largest and smallest integer types as
+ // unsigned integers with separate sign. This is only true if they can fit
+ // into an unsigned integer.
+ static_assert(Value::maxLargestInt <= Value::maxLargestUInt,
+ "Int must be smaller than UInt");
+
+ // We need to convert minLargestInt into a positive number. The easiest way
+ // to do this conversion is to assume our "threshold" value of minLargestInt
+ // divided by 10 can fit in maxLargestInt when absolute valued. This should
+ // be a safe assumption.
+ static_assert(Value::minLargestInt <= -Value::maxLargestInt,
+ "The absolute value of minLargestInt must be greater than or "
+ "equal to maxLargestInt");
+ static_assert(Value::minLargestInt / 10 >= -Value::maxLargestInt,
+ "The absolute value of minLargestInt must be only 1 magnitude "
+ "larger than maxLargest Int");
+
+ static constexpr Value::LargestUInt positive_threshold =
+ Value::maxLargestUInt / 10;
+ static constexpr Value::UInt positive_last_digit = Value::maxLargestUInt % 10;
+
+ // For the negative values, we have to be more careful. Since typically
+ // -Value::minLargestInt will cause an overflow, we first divide by 10 and
+ // then take the inverse. This assumes that minLargestInt is only a single
+ // power of 10 different in magnitude, which we check above. For the last
+ // digit, we take the modulus before negating for the same reason.
+ static constexpr auto negative_threshold =
+ Value::LargestUInt(-(Value::minLargestInt / 10));
+ static constexpr auto negative_last_digit =
+ Value::UInt(-(Value::minLargestInt % 10));
+
+ const Value::LargestUInt threshold =
+ isNegative ? negative_threshold : positive_threshold;
+ const Value::UInt max_last_digit =
+ isNegative ? negative_last_digit : positive_last_digit;
+
Value::LargestUInt value = 0;
while (current < token.end_) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
- Value::UInt digit(static_cast<Value::UInt>(c - '0'));
+
+ const auto digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
- // a) we've only just touched the limit, b) this is the last digit, and
+ // a) we've only just touched the limit, meaing value == threshold,
+ // b) this is the last digit, or
// c) it's small enough to fit in that rounding delta, we're okay.
// Otherwise treat this number as a double to avoid overflow.
if (value > threshold || current != token.end_ ||
- digit > maxIntegerValue % 10) {
+ digit > max_last_digit) {
return decodeDouble(token, decoded);
}
}
value = value * 10 + digit;
}
- if (isNegative)
- decoded = -Value::LargestInt(value);
- else if (value <= Value::LargestUInt(Value::maxInt))
+
+ if (isNegative) {
+ // We use the same magnitude assumption here, just in case.
+ const auto last_digit = static_cast<Value::UInt>(value % 10);
+ decoded = -Value::LargestInt(value / 10) * 10 - last_digit;
+ } else if (value <= Value::LargestUInt(Value::maxLargestInt)) {
decoded = Value::LargestInt(value);
- else
+ } else {
decoded = value;
+ }
+
return true;
}
@@ -1623,44 +1645,18 @@ bool OurReader::decodeDouble(Token& token) {
bool OurReader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
- const int bufferSize = 32;
- int count;
- ptrdiff_t const length = token.end_ - token.start_;
-
- // Sanity check to avoid buffer overflow exploits.
- if (length < 0) {
- return addError("Unable to parse token length", token);
- }
- size_t const ulength = static_cast<size_t>(length);
-
- // Avoid using a string constant for the format control string given to
- // sscanf, as this can cause hard to debug crashes on OS X. See here for more
- // info:
- //
- // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
- char format[] = "%lf";
-
- if (length <= bufferSize) {
- Char buffer[bufferSize + 1];
- memcpy(buffer, token.start_, ulength);
- buffer[length] = 0;
- fixNumericLocaleInput(buffer, buffer + length);
- count = sscanf(buffer, format, &value);
- } else {
- JSONCPP_STRING buffer(token.start_, token.end_);
- count = sscanf(buffer.c_str(), format, &value);
+ const String buffer(token.start_, token.end_);
+ IStringStream is(buffer);
+ if (!(is >> value)) {
+ return addError(
+ "'" + String(token.start_, token.end_) + "' is not a number.", token);
}
-
- if (count != 1)
- return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
- "' is not a number.",
- token);
decoded = value;
return true;
}
bool OurReader::decodeString(Token& token) {
- JSONCPP_STRING decoded_string;
+ String decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
@@ -1670,7 +1666,7 @@ bool OurReader::decodeString(Token& token) {
return true;
}
-bool OurReader::decodeString(Token& token, JSONCPP_STRING& decoded) {
+bool OurReader::decodeString(Token& token, String& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
@@ -1678,7 +1674,7 @@ bool OurReader::decodeString(Token& token, JSONCPP_STRING& decoded) {
Char c = *current++;
if (c == '"')
break;
- else if (c == '\\') {
+ if (c == '\\') {
if (current == end)
return addError("Empty escape sequence in string", token, current);
Char escape = *current++;
@@ -1723,10 +1719,8 @@ bool OurReader::decodeString(Token& token, JSONCPP_STRING& decoded) {
return true;
}
-bool OurReader::decodeUnicodeCodePoint(Token& token,
- Location& current,
- Location end,
- unsigned int& unicode) {
+bool OurReader::decodeUnicodeCodePoint(Token& token, Location& current,
+ Location end, unsigned int& unicode) {
unicode = 0; // Convince clang-analyzer that this is initialized before use.
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
@@ -1736,10 +1730,9 @@ bool OurReader::decodeUnicodeCodePoint(Token& token,
if (end - current < 6)
return addError(
"additional six characters expected to parse unicode surrogate pair.",
- token,
- current);
- unsigned int surrogatePair;
+ token, current);
if (*(current++) == '\\' && *(current++) == 'u') {
+ unsigned int surrogatePair;
if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
} else
@@ -1747,20 +1740,17 @@ bool OurReader::decodeUnicodeCodePoint(Token& token,
} else
return addError("expecting another \\u token to begin the second half of "
"a unicode surrogate pair",
- token,
- current);
+ token, current);
}
return true;
}
-bool OurReader::decodeUnicodeEscapeSequence(Token& token,
- Location& current,
- Location end,
- unsigned int& ret_unicode) {
+bool OurReader::decodeUnicodeEscapeSequence(Token& token, Location& current,
+ Location end,
+ unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
- "Bad unicode escape sequence in string: four digits expected.",
- token,
+ "Bad unicode escape sequence in string: four digits expected.", token,
current);
int unicode = 0;
for (int index = 0; index < 4; ++index) {
@@ -1775,15 +1765,13 @@ bool OurReader::decodeUnicodeEscapeSequence(Token& token,
else
return addError(
"Bad unicode escape sequence in string: hexadecimal digit expected.",
- token,
- current);
+ token, current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
-bool
-OurReader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
+bool OurReader::addError(const String& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
@@ -1805,9 +1793,8 @@ bool OurReader::recoverFromError(TokenType skipUntilToken) {
return false;
}
-bool OurReader::addErrorAndRecover(const JSONCPP_STRING& message,
- Token& token,
- TokenType skipUntilToken) {
+bool OurReader::addErrorAndRecover(const String& message, Token& token,
+ TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
}
@@ -1820,9 +1807,8 @@ OurReader::Char OurReader::getNextChar() {
return *current_++;
}
-void OurReader::getLocationLineAndColumn(Location location,
- int& line,
- int& column) const {
+void OurReader::getLocationLineAndColumn(Location location, int& line,
+ int& column) const {
Location current = begin_;
Location lastLineStart = current;
line = 0;
@@ -1843,20 +1829,17 @@ void OurReader::getLocationLineAndColumn(Location location,
++line;
}
-JSONCPP_STRING OurReader::getLocationLineAndColumn(Location location) const {
+String OurReader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
- snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
+ jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
return buffer;
}
-JSONCPP_STRING OurReader::getFormattedErrorMessages() const {
- JSONCPP_STRING formattedMessage;
- for (Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError) {
- const ErrorInfo& error = *itError;
+String OurReader::getFormattedErrorMessages() const {
+ String formattedMessage;
+ for (const auto& error : errors_) {
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
@@ -1869,10 +1852,7 @@ JSONCPP_STRING OurReader::getFormattedErrorMessages() const {
std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
std::vector<OurReader::StructuredError> allErrors;
- for (Errors::const_iterator itError = errors_.begin();
- itError != errors_.end();
- ++itError) {
- const ErrorInfo& error = *itError;
+ for (const auto& error : errors_) {
OurReader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
@@ -1882,59 +1862,15 @@ std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
return allErrors;
}
-bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message) {
- ptrdiff_t length = end_ - begin_;
- if(value.getOffsetStart() > length
- || value.getOffsetLimit() > length)
- return false;
- Token token;
- token.type_ = tokenError;
- token.start_ = begin_ + value.getOffsetStart();
- token.end_ = end_ + value.getOffsetLimit();
- ErrorInfo info;
- info.token_ = token;
- info.message_ = message;
- info.extra_ = 0;
- errors_.push_back(info);
- return true;
-}
-
-bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
- ptrdiff_t length = end_ - begin_;
- if(value.getOffsetStart() > length
- || value.getOffsetLimit() > length
- || extra.getOffsetLimit() > length)
- return false;
- Token token;
- token.type_ = tokenError;
- token.start_ = begin_ + value.getOffsetStart();
- token.end_ = begin_ + value.getOffsetLimit();
- ErrorInfo info;
- info.token_ = token;
- info.message_ = message;
- info.extra_ = begin_ + extra.getOffsetStart();
- errors_.push_back(info);
- return true;
-}
-
-bool OurReader::good() const {
- return !errors_.size();
-}
-
-
class OurCharReader : public CharReader {
bool const collectComments_;
OurReader reader_;
+
public:
- OurCharReader(
- bool collectComments,
- OurFeatures const& features)
- : collectComments_(collectComments)
- , reader_(features)
- {}
- bool parse(
- char const* beginDoc, char const* endDoc,
- Value* root, JSONCPP_STRING* errs) JSONCPP_OVERRIDE {
+ OurCharReader(bool collectComments, OurFeatures const& features)
+ : collectComments_(collectComments), reader_(features) {}
+ bool parse(char const* beginDoc, char const* endDoc, Value* root,
+ String* errs) override {
bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
if (errs) {
*errs = reader_.getFormattedErrorMessages();
@@ -1943,67 +1879,64 @@ public:
}
};
-CharReaderBuilder::CharReaderBuilder()
-{
- setDefaults(&settings_);
-}
-CharReaderBuilder::~CharReaderBuilder()
-{}
-CharReader* CharReaderBuilder::newCharReader() const
-{
+CharReaderBuilder::CharReaderBuilder() { setDefaults(&settings_); }
+CharReaderBuilder::~CharReaderBuilder() = default;
+CharReader* CharReaderBuilder::newCharReader() const {
bool collectComments = settings_["collectComments"].asBool();
OurFeatures features = OurFeatures::all();
features.allowComments_ = settings_["allowComments"].asBool();
+ features.allowTrailingCommas_ = settings_["allowTrailingCommas"].asBool();
features.strictRoot_ = settings_["strictRoot"].asBool();
- features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
+ features.allowDroppedNullPlaceholders_ =
+ settings_["allowDroppedNullPlaceholders"].asBool();
features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
- features.stackLimit_ = settings_["stackLimit"].asInt();
+
+ // Stack limit is always a size_t, so we get this as an unsigned int
+ // regardless of it we have 64-bit integer support enabled.
+ features.stackLimit_ = static_cast<size_t>(settings_["stackLimit"].asUInt());
features.failIfExtra_ = settings_["failIfExtra"].asBool();
features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
+ features.skipBom_ = settings_["skipBom"].asBool();
return new OurCharReader(collectComments, features);
}
-static void getValidReaderKeys(std::set<JSONCPP_STRING>* valid_keys)
-{
- valid_keys->clear();
- valid_keys->insert("collectComments");
- valid_keys->insert("allowComments");
- valid_keys->insert("strictRoot");
- valid_keys->insert("allowDroppedNullPlaceholders");
- valid_keys->insert("allowNumericKeys");
- valid_keys->insert("allowSingleQuotes");
- valid_keys->insert("stackLimit");
- valid_keys->insert("failIfExtra");
- valid_keys->insert("rejectDupKeys");
- valid_keys->insert("allowSpecialFloats");
-}
-bool CharReaderBuilder::validate(Json::Value* invalid) const
-{
- Json::Value my_invalid;
- if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
- Json::Value& inv = *invalid;
- std::set<JSONCPP_STRING> valid_keys;
- getValidReaderKeys(&valid_keys);
- Value::Members keys = settings_.getMemberNames();
- size_t n = keys.size();
- for (size_t i = 0; i < n; ++i) {
- JSONCPP_STRING const& key = keys[i];
- if (valid_keys.find(key) == valid_keys.end()) {
- inv[key] = settings_[key];
- }
+
+bool CharReaderBuilder::validate(Json::Value* invalid) const {
+ static const auto& valid_keys = *new std::set<String>{
+ "collectComments",
+ "allowComments",
+ "allowTrailingCommas",
+ "strictRoot",
+ "allowDroppedNullPlaceholders",
+ "allowNumericKeys",
+ "allowSingleQuotes",
+ "stackLimit",
+ "failIfExtra",
+ "rejectDupKeys",
+ "allowSpecialFloats",
+ "skipBom",
+ };
+ for (auto si = settings_.begin(); si != settings_.end(); ++si) {
+ auto key = si.name();
+ if (valid_keys.count(key))
+ continue;
+ if (invalid)
+ (*invalid)[std::move(key)] = *si;
+ else
+ return false;
}
- return 0u == inv.size();
+ return invalid ? invalid->empty() : true;
}
-Value& CharReaderBuilder::operator[](JSONCPP_STRING key)
-{
+
+Value& CharReaderBuilder::operator[](const String& key) {
return settings_[key];
}
// static
-void CharReaderBuilder::strictMode(Json::Value* settings)
-{
-//! [CharReaderBuilderStrictMode]
+void CharReaderBuilder::strictMode(Json::Value* settings) {
+ //! [CharReaderBuilderStrictMode]
(*settings)["allowComments"] = false;
+ (*settings)["allowTrailingCommas"] = false;
(*settings)["strictRoot"] = true;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
@@ -2012,14 +1945,15 @@ void CharReaderBuilder::strictMode(Json::Value* settings)
(*settings)["failIfExtra"] = true;
(*settings)["rejectDupKeys"] = true;
(*settings)["allowSpecialFloats"] = false;
-//! [CharReaderBuilderStrictMode]
+ (*settings)["skipBom"] = true;
+ //! [CharReaderBuilderStrictMode]
}
// static
-void CharReaderBuilder::setDefaults(Json::Value* settings)
-{
-//! [CharReaderBuilderDefaults]
+void CharReaderBuilder::setDefaults(Json::Value* settings) {
+ //! [CharReaderBuilderDefaults]
(*settings)["collectComments"] = true;
(*settings)["allowComments"] = true;
+ (*settings)["allowTrailingCommas"] = true;
(*settings)["strictRoot"] = false;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
@@ -2028,19 +1962,18 @@ void CharReaderBuilder::setDefaults(Json::Value* settings)
(*settings)["failIfExtra"] = false;
(*settings)["rejectDupKeys"] = false;
(*settings)["allowSpecialFloats"] = false;
-//! [CharReaderBuilderDefaults]
+ (*settings)["skipBom"] = true;
+ //! [CharReaderBuilderDefaults]
}
//////////////////////////////////
// global functions
-bool parseFromStream(
- CharReader::Factory const& fact, JSONCPP_ISTREAM& sin,
- Value* root, JSONCPP_STRING* errs)
-{
- JSONCPP_OSTRINGSTREAM ssin;
+bool parseFromStream(CharReader::Factory const& fact, IStream& sin, Value* root,
+ String* errs) {
+ OStringStream ssin;
ssin << sin.rdbuf();
- JSONCPP_STRING doc = ssin.str();
+ String doc = ssin.str();
char const* begin = doc.data();
char const* end = begin + doc.size();
// Note that we do not actually need a null-terminator.
@@ -2048,15 +1981,11 @@ bool parseFromStream(
return reader->parse(begin, end, root, errs);
}
-JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM& sin, Value& root) {
+IStream& operator>>(IStream& sin, Value& root) {
CharReaderBuilder b;
- JSONCPP_STRING errs;
+ String errs;
bool ok = parseFromStream(b, sin, &root, &errs);
if (!ok) {
- fprintf(stderr,
- "Error from reader: %s",
- errs.c_str());
-
throwRuntimeError(errs);
}
return sin;
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_tool.h b/Utilities/cmjsoncpp/src/lib_json/json_tool.h
index 4316178..2d7b7d9 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_tool.h
+++ b/Utilities/cmjsoncpp/src/lib_json/json_tool.h
@@ -6,6 +6,9 @@
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/config.h>
+#endif
// Also support old flag NO_LOCALE_SUPPORT
#ifdef NO_LOCALE_SUPPORT
@@ -23,7 +26,7 @@
*/
namespace Json {
-static char getDecimalPoint() {
+static inline char getDecimalPoint() {
#ifdef JSONCPP_NO_LOCALE_SUPPORT
return '\0';
#else
@@ -33,8 +36,8 @@ static char getDecimalPoint() {
}
/// Converts a unicode code-point to UTF-8.
-static inline JSONCPP_STRING codePointToUTF8(unsigned int cp) {
- JSONCPP_STRING result;
+static inline String codePointToUTF8(unsigned int cp) {
+ String result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
@@ -61,9 +64,6 @@ static inline JSONCPP_STRING codePointToUTF8(unsigned int cp) {
return result;
}
-/// Returns true if ch is a control character (in range [1,31]).
-static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
-
enum {
/// Constant that specify the size of the buffer that must be passed to
/// uintToString.
@@ -71,10 +71,10 @@ enum {
};
// Defines a char buffer for use with uintToString().
-typedef char UIntToStringBuffer[uintToStringBufferSize];
+using UIntToStringBuffer = char[uintToStringBufferSize];
/** Converts an unsigned integer to string.
- * @param value Unsigned interger to convert to string
+ * @param value Unsigned integer to convert to string
* @param current Input/Output string buffer.
* Must have at least uintToStringBufferSize chars free.
*/
@@ -91,27 +91,44 @@ static inline void uintToString(LargestUInt value, char*& current) {
* We had a sophisticated way, but it did not work in WinCE.
* @see https://github.com/open-source-parsers/jsoncpp/pull/9
*/
-static inline void fixNumericLocale(char* begin, char* end) {
- while (begin < end) {
+template <typename Iter> Iter fixNumericLocale(Iter begin, Iter end) {
+ for (; begin != end; ++begin) {
if (*begin == ',') {
*begin = '.';
}
- ++begin;
}
+ return begin;
}
-static inline void fixNumericLocaleInput(char* begin, char* end) {
+template <typename Iter> void fixNumericLocaleInput(Iter begin, Iter end) {
char decimalPoint = getDecimalPoint();
- if (decimalPoint != '\0' && decimalPoint != '.') {
- while (begin < end) {
- if (*begin == '.') {
- *begin = decimalPoint;
- }
- ++begin;
+ if (decimalPoint == '\0' || decimalPoint == '.') {
+ return;
+ }
+ for (; begin != end; ++begin) {
+ if (*begin == '.') {
+ *begin = decimalPoint;
+ }
+ }
+}
+
+/**
+ * Return iterator that would be the new end of the range [begin,end), if we
+ * were to delete zeros in the end of string, but not the last zero before '.'.
+ */
+template <typename Iter> Iter fixZerosInTheEnd(Iter begin, Iter end) {
+ for (; begin != end; --end) {
+ if (*(end - 1) != '0') {
+ return end;
+ }
+ // Don't delete the last zero before the decimal point.
+ if (begin != (end - 1) && *(end - 2) == '.') {
+ return end;
}
}
+ return end;
}
-} // namespace Json {
+} // namespace Json
#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_value.cpp b/Utilities/cmjsoncpp/src/lib_json/json_value.cpp
index f271e57..d59b7d9 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_value.cpp
+++ b/Utilities/cmjsoncpp/src/lib_json/json_value.cpp
@@ -8,20 +8,54 @@
#include <json/value.h>
#include <json/writer.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
-#include <math.h>
+#include <algorithm>
+#include <cassert>
+#include <cmath>
+#include <cstddef>
+#include <cstring>
+#include <iostream>
#include <sstream>
#include <utility>
-#include <string.h>
-#include <assert.h>
-#ifdef JSON_USE_CPPTL
-#include <cpptl/conststring.h>
+
+// Provide implementation equivalent of std::snprintf for older _MSC compilers
+#if defined(_MSC_VER) && _MSC_VER < 1900
+#include <stdarg.h>
+static int msvc_pre1900_c99_vsnprintf(char* outBuf, size_t size,
+ const char* format, va_list ap) {
+ int count = -1;
+ if (size != 0)
+ count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
+ if (count == -1)
+ count = _vscprintf(format, ap);
+ return count;
+}
+
+int JSON_API msvc_pre1900_c99_snprintf(char* outBuf, size_t size,
+ const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ const int count = msvc_pre1900_c99_vsnprintf(outBuf, size, format, ap);
+ va_end(ap);
+ return count;
+}
+#endif
+
+// Disable warning C4702 : unreachable code
+#if defined(_MSC_VER)
+#pragma warning(disable : 4702)
#endif
-#include <cstddef> // size_t
-#include <algorithm> // min()
#define JSON_ASSERT_UNREACHABLE assert(false)
namespace Json {
+template <typename T>
+static std::unique_ptr<T> cloneUnique(const std::unique_ptr<T>& p) {
+ std::unique_ptr<T> r;
+ if (p) {
+ r = std::unique_ptr<T>(new T(*p));
+ }
+ return r;
+}
// This is a walkaround to avoid the static initialization of Value::null.
// kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
@@ -31,50 +65,34 @@ namespace Json {
#else
#define ALIGNAS(byte_alignment)
#endif
-//static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 };
-//const unsigned char& kNullRef = kNull[0];
-//const Value& Value::null = reinterpret_cast<const Value&>(kNullRef);
-//const Value& Value::nullRef = null;
// static
-Value const& Value::nullSingleton()
-{
- static Value const nullStatic;
- return nullStatic;
+Value const& Value::nullSingleton() {
+ static Value const nullStatic;
+ return nullStatic;
}
-// for backwards compatibility, we'll leave these global references around, but DO NOT
-// use them in JSONCPP library code any more!
+#if JSON_USE_NULLREF
+// for backwards compatibility, we'll leave these global references around, but
+// DO NOT use them in JSONCPP library code any more!
+// static
Value const& Value::null = Value::nullSingleton();
-Value const& Value::nullRef = Value::nullSingleton();
-const Int Value::minInt = Int(~(UInt(-1) / 2));
-const Int Value::maxInt = Int(UInt(-1) / 2);
-const UInt Value::maxUInt = UInt(-1);
-#if defined(JSON_HAS_INT64)
-const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2));
-const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2);
-const UInt64 Value::maxUInt64 = UInt64(-1);
-// The constant is hard-coded because some compiler have trouble
-// converting Value::maxUInt64 to a double correctly (AIX/xlC).
-// Assumes that UInt64 is a 64 bits integer.
-static const double maxUInt64AsDouble = 18446744073709551615.0;
-#endif // defined(JSON_HAS_INT64)
-const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
-const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
-const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
+// static
+Value const& Value::nullRef = Value::nullSingleton();
+#endif
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
template <typename T, typename U>
static inline bool InRange(double d, T min, U max) {
// The casts can lose precision, but we are looking only for
// an approximate range. Might fail on edge cases though. ~cdunn
- //return d >= static_cast<double>(min) && d <= static_cast<double>(max);
- return d >= min && d <= max;
+ return d >= static_cast<double>(min) && d <= static_cast<double>(max);
}
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
static inline double integerToDouble(Json::UInt64 value) {
- return static_cast<double>(Int64(value / 2)) * 2.0 + static_cast<double>(Int64(value & 1));
+ return static_cast<double>(Int64(value / 2)) * 2.0 +
+ static_cast<double>(Int64(value & 1));
}
template <typename T> static inline double integerToDouble(T value) {
@@ -94,19 +112,16 @@ static inline bool InRange(double d, T min, U max) {
* computed using strlen(value).
* @return Pointer on the duplicate instance of string.
*/
-static inline char* duplicateStringValue(const char* value,
- size_t length)
-{
+static inline char* duplicateStringValue(const char* value, size_t length) {
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
if (length >= static_cast<size_t>(Value::maxInt))
length = Value::maxInt - 1;
- char* newString = static_cast<char*>(malloc(length + 1));
- if (newString == NULL) {
- throwRuntimeError(
- "in Json::Value::duplicateStringValue(): "
- "Failed to allocate string value buffer");
+ auto newString = static_cast<char*>(malloc(length + 1));
+ if (newString == nullptr) {
+ throwRuntimeError("in Json::Value::duplicateStringValue(): "
+ "Failed to allocate string value buffer");
}
memcpy(newString, value, length);
newString[length] = 0;
@@ -115,31 +130,28 @@ static inline char* duplicateStringValue(const char* value,
/* Record the length as a prefix.
*/
-static inline char* duplicateAndPrefixStringValue(
- const char* value,
- unsigned int length)
-{
+static inline char* duplicateAndPrefixStringValue(const char* value,
+ unsigned int length) {
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
- JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) - sizeof(unsigned) - 1U,
+ JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) -
+ sizeof(unsigned) - 1U,
"in Json::Value::duplicateAndPrefixStringValue(): "
"length too big for prefixing");
- unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
- char* newString = static_cast<char*>(malloc(actualLength));
- if (newString == 0) {
- throwRuntimeError(
- "in Json::Value::duplicateAndPrefixStringValue(): "
- "Failed to allocate string value buffer");
+ size_t actualLength = sizeof(length) + length + 1;
+ auto newString = static_cast<char*>(malloc(actualLength));
+ if (newString == nullptr) {
+ throwRuntimeError("in Json::Value::duplicateAndPrefixStringValue(): "
+ "Failed to allocate string value buffer");
}
*reinterpret_cast<unsigned*>(newString) = length;
memcpy(newString + sizeof(unsigned), value, length);
- newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later
+ newString[actualLength - 1U] =
+ 0; // to avoid buffer over-run accidents by users later
return newString;
}
-inline static void decodePrefixedString(
- bool isPrefixed, char const* prefixed,
- unsigned* length, char const** value)
-{
+inline static void decodePrefixedString(bool isPrefixed, char const* prefixed,
+ unsigned* length, char const** value) {
if (!isPrefixed) {
*length = static_cast<unsigned>(strlen(prefixed));
*value = prefixed;
@@ -148,7 +160,8 @@ inline static void decodePrefixedString(
*value = prefixed + sizeof(unsigned);
}
}
-/** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
+/** Free the string duplicated by
+ * duplicateStringValue()/duplicateAndPrefixStringValue().
*/
#if JSONCPP_USING_SECURE_MEMORY
static inline void releasePrefixedStringValue(char* value) {
@@ -161,17 +174,13 @@ static inline void releasePrefixedStringValue(char* value) {
}
static inline void releaseStringValue(char* value, unsigned length) {
// length==0 => we allocated the strings memory
- size_t size = (length==0) ? strlen(value) : length;
+ size_t size = (length == 0) ? strlen(value) : length;
memset(value, 0, size);
free(value);
}
-#else // !JSONCPP_USING_SECURE_MEMORY
-static inline void releasePrefixedStringValue(char* value) {
- free(value);
-}
-static inline void releaseStringValue(char* value, unsigned) {
- free(value);
-}
+#else // !JSONCPP_USING_SECURE_MEMORY
+static inline void releasePrefixedStringValue(char* value) { free(value); }
+static inline void releaseStringValue(char* value, unsigned) { free(value); }
#endif // JSONCPP_USING_SECURE_MEMORY
} // namespace Json
@@ -190,58 +199,28 @@ static inline void releaseStringValue(char* value, unsigned) {
namespace Json {
-Exception::Exception(JSONCPP_STRING const& msg)
- : msg_(msg)
-{}
-Exception::~Exception() JSONCPP_NOEXCEPT
-{}
-char const* Exception::what() const JSONCPP_NOEXCEPT
-{
- return msg_.c_str();
-}
-RuntimeError::RuntimeError(JSONCPP_STRING const& msg)
- : Exception(msg)
-{}
-LogicError::LogicError(JSONCPP_STRING const& msg)
- : Exception(msg)
-{}
-JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg)
-{
+#if JSON_USE_EXCEPTION
+Exception::Exception(String msg) : msg_(std::move(msg)) {}
+Exception::~Exception() noexcept = default;
+char const* Exception::what() const noexcept { return msg_.c_str(); }
+RuntimeError::RuntimeError(String const& msg) : Exception(msg) {}
+LogicError::LogicError(String const& msg) : Exception(msg) {}
+JSONCPP_NORETURN void throwRuntimeError(String const& msg) {
throw RuntimeError(msg);
}
-JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg)
-{
+JSONCPP_NORETURN void throwLogicError(String const& msg) {
throw LogicError(msg);
}
-
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// class Value::CommentInfo
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-
-Value::CommentInfo::CommentInfo() : comment_(0)
-{}
-
-Value::CommentInfo::~CommentInfo() {
- if (comment_)
- releaseStringValue(comment_, 0u);
+#else // !JSON_USE_EXCEPTION
+JSONCPP_NORETURN void throwRuntimeError(String const& msg) {
+ std::cerr << msg << std::endl;
+ abort();
}
-
-void Value::CommentInfo::setComment(const char* text, size_t len) {
- if (comment_) {
- releaseStringValue(comment_, 0u);
- comment_ = 0;
- }
- JSON_ASSERT(text != 0);
- JSON_ASSERT_MESSAGE(
- text[0] == '\0' || text[0] == '/',
- "in Json::Value::setComment(): Comments must start with /");
- // It seems that /**/ style comments are acceptable as well.
- comment_ = duplicateStringValue(text, len);
+JSONCPP_NORETURN void throwLogicError(String const& msg) {
+ std::cerr << msg << std::endl;
+ abort();
}
+#endif
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
@@ -254,36 +233,44 @@ void Value::CommentInfo::setComment(const char* text, size_t len) {
// Notes: policy_ indicates if the string was allocated when
// a string is stored.
-Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
+Value::CZString::CZString(ArrayIndex index) : cstr_(nullptr), index_(index) {}
-Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
+Value::CZString::CZString(char const* str, unsigned length,
+ DuplicationPolicy allocate)
: cstr_(str) {
// allocate != duplicate
storage_.policy_ = allocate & 0x3;
- storage_.length_ = ulength & 0x3FFFFFFF;
+ storage_.length_ = length & 0x3FFFFFFF;
}
Value::CZString::CZString(const CZString& other) {
- cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != 0
- ? duplicateStringValue(other.cstr_, other.storage_.length_)
- : other.cstr_);
- storage_.policy_ = static_cast<unsigned>(other.cstr_
- ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
- ? noDuplication : duplicate)
- : static_cast<DuplicationPolicy>(other.storage_.policy_)) & 3U;
+ cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != nullptr
+ ? duplicateStringValue(other.cstr_, other.storage_.length_)
+ : other.cstr_);
+ storage_.policy_ =
+ static_cast<unsigned>(
+ other.cstr_
+ ? (static_cast<DuplicationPolicy>(other.storage_.policy_) ==
+ noDuplication
+ ? noDuplication
+ : duplicate)
+ : static_cast<DuplicationPolicy>(other.storage_.policy_)) &
+ 3U;
storage_.length_ = other.storage_.length_;
}
-#if JSON_HAS_RVALUE_REFERENCES
Value::CZString::CZString(CZString&& other)
- : cstr_(other.cstr_), index_(other.index_) {
+ : cstr_(other.cstr_), index_(other.index_) {
other.cstr_ = nullptr;
}
-#endif
Value::CZString::~CZString() {
if (cstr_ && storage_.policy_ == duplicate) {
- releaseStringValue(const_cast<char*>(cstr_), storage_.length_ + 1u); //+1 for null terminating character for sake of completeness but not actually necessary
+ releaseStringValue(const_cast<char*>(cstr_),
+ storage_.length_ + 1U); // +1 for null terminating
+ // character for sake of
+ // completeness but not actually
+ // necessary
}
}
@@ -298,36 +285,39 @@ Value::CZString& Value::CZString::operator=(const CZString& other) {
return *this;
}
-#if JSON_HAS_RVALUE_REFERENCES
Value::CZString& Value::CZString::operator=(CZString&& other) {
cstr_ = other.cstr_;
index_ = other.index_;
other.cstr_ = nullptr;
return *this;
}
-#endif
bool Value::CZString::operator<(const CZString& other) const {
- if (!cstr_) return index_ < other.index_;
- //return strcmp(cstr_, other.cstr_) < 0;
+ if (!cstr_)
+ return index_ < other.index_;
+ // return strcmp(cstr_, other.cstr_) < 0;
// Assume both are strings.
unsigned this_len = this->storage_.length_;
unsigned other_len = other.storage_.length_;
unsigned min_len = std::min<unsigned>(this_len, other_len);
JSON_ASSERT(this->cstr_ && other.cstr_);
int comp = memcmp(this->cstr_, other.cstr_, min_len);
- if (comp < 0) return true;
- if (comp > 0) return false;
+ if (comp < 0)
+ return true;
+ if (comp > 0)
+ return false;
return (this_len < other_len);
}
bool Value::CZString::operator==(const CZString& other) const {
- if (!cstr_) return index_ == other.index_;
- //return strcmp(cstr_, other.cstr_) == 0;
+ if (!cstr_)
+ return index_ == other.index_;
+ // return strcmp(cstr_, other.cstr_) == 0;
// Assume both are strings.
unsigned this_len = this->storage_.length_;
unsigned other_len = other.storage_.length_;
- if (this_len != other_len) return false;
+ if (this_len != other_len)
+ return false;
JSON_ASSERT(this->cstr_ && other.cstr_);
int comp = memcmp(this->cstr_, other.cstr_, this_len);
return comp == 0;
@@ -335,10 +325,12 @@ bool Value::CZString::operator==(const CZString& other) const {
ArrayIndex Value::CZString::index() const { return index_; }
-//const char* Value::CZString::c_str() const { return cstr_; }
+// const char* Value::CZString::c_str() const { return cstr_; }
const char* Value::CZString::data() const { return cstr_; }
unsigned Value::CZString::length() const { return storage_.length_; }
-bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; }
+bool Value::CZString::isStaticString() const {
+ return storage_.policy_ == noDuplication;
+}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
@@ -352,10 +344,10 @@ bool Value::CZString::isStaticString() const { return storage_.policy_ == noDupl
* memset( this, 0, sizeof(Value) )
* This optimization is used in ValueInternalMap fast allocator.
*/
-Value::Value(ValueType vtype) {
+Value::Value(ValueType type) {
static char const emptyString[] = "";
- initBasic(vtype);
- switch (vtype) {
+ initBasic(type);
+ switch (type) {
case nullValue:
break;
case intValue:
@@ -408,20 +400,22 @@ Value::Value(double value) {
Value::Value(const char* value) {
initBasic(stringValue, true);
- JSON_ASSERT_MESSAGE(value != NULL, "Null Value Passed to Value Constructor");
- value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
+ JSON_ASSERT_MESSAGE(value != nullptr,
+ "Null Value Passed to Value Constructor");
+ value_.string_ = duplicateAndPrefixStringValue(
+ value, static_cast<unsigned>(strlen(value)));
}
-Value::Value(const char* beginValue, const char* endValue) {
+Value::Value(const char* begin, const char* end) {
initBasic(stringValue, true);
value_.string_ =
- duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
+ duplicateAndPrefixStringValue(begin, static_cast<unsigned>(end - begin));
}
-Value::Value(const JSONCPP_STRING& value) {
+Value::Value(const String& value) {
initBasic(stringValue, true);
- value_.string_ =
- duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
+ value_.string_ = duplicateAndPrefixStringValue(
+ value.data(), static_cast<unsigned>(value.length()));
}
Value::Value(const StaticString& value) {
@@ -429,114 +423,44 @@ Value::Value(const StaticString& value) {
value_.string_ = const_cast<char*>(value.c_str());
}
-#ifdef JSON_USE_CPPTL
-Value::Value(const CppTL::ConstString& value) {
- initBasic(stringValue, true);
- value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
-}
-#endif
-
Value::Value(bool value) {
initBasic(booleanValue);
value_.bool_ = value;
}
-Value::Value(Value const& other)
- : type_(other.type_), allocated_(false)
- ,
- comments_(0), start_(other.start_), limit_(other.limit_)
-{
- switch (type_) {
- case nullValue:
- case intValue:
- case uintValue:
- case realValue:
- case booleanValue:
- value_ = other.value_;
- break;
- case stringValue:
- if (other.value_.string_ && other.allocated_) {
- unsigned len;
- char const* str;
- decodePrefixedString(other.allocated_, other.value_.string_,
- &len, &str);
- value_.string_ = duplicateAndPrefixStringValue(str, len);
- allocated_ = true;
- } else {
- value_.string_ = other.value_.string_;
- allocated_ = false;
- }
- break;
- case arrayValue:
- case objectValue:
- value_.map_ = new ObjectValues(*other.value_.map_);
- break;
- default:
- JSON_ASSERT_UNREACHABLE;
- }
- if (other.comments_) {
- comments_ = new CommentInfo[numberOfCommentPlacement];
- for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
- const CommentInfo& otherComment = other.comments_[comment];
- if (otherComment.comment_)
- comments_[comment].setComment(
- otherComment.comment_, strlen(otherComment.comment_));
- }
- }
+Value::Value(const Value& other) {
+ dupPayload(other);
+ dupMeta(other);
}
-#if JSON_HAS_RVALUE_REFERENCES
-// Move constructor
Value::Value(Value&& other) {
initBasic(nullValue);
swap(other);
}
-#endif
Value::~Value() {
- switch (type_) {
- case nullValue:
- case intValue:
- case uintValue:
- case realValue:
- case booleanValue:
- break;
- case stringValue:
- if (allocated_)
- releasePrefixedStringValue(value_.string_);
- break;
- case arrayValue:
- case objectValue:
- delete value_.map_;
- break;
- default:
- JSON_ASSERT_UNREACHABLE;
- }
-
- delete[] comments_;
-
+ releasePayload();
value_.uint_ = 0;
}
-Value& Value::operator=(Value other) {
- swap(other);
+Value& Value::operator=(const Value& other) {
+ Value(other).swap(*this);
+ return *this;
+}
+
+Value& Value::operator=(Value&& other) {
+ other.swap(*this);
return *this;
}
void Value::swapPayload(Value& other) {
- ValueType temp = type_;
- type_ = other.type_;
- other.type_ = temp;
+ std::swap(bits_, other.bits_);
std::swap(value_, other.value_);
- int temp2 = allocated_;
- allocated_ = other.allocated_;
- other.allocated_ = temp2 & 0x1;
}
void Value::copyPayload(const Value& other) {
- type_ = other.type_;
- value_ = other.value_;
- allocated_ = other.allocated_;
+ releasePayload();
+ dupPayload(other);
}
void Value::swap(Value& other) {
@@ -548,12 +472,12 @@ void Value::swap(Value& other) {
void Value::copy(const Value& other) {
copyPayload(other);
- comments_ = other.comments_;
- start_ = other.start_;
- limit_ = other.limit_;
+ dupMeta(other);
}
-ValueType Value::type() const { return type_; }
+ValueType Value::type() const {
+ return static_cast<ValueType>(bits_.value_type_);
+}
int Value::compare(const Value& other) const {
if (*this < other)
@@ -564,10 +488,10 @@ int Value::compare(const Value& other) const {
}
bool Value::operator<(const Value& other) const {
- int typeDelta = type_ - other.type_;
+ int typeDelta = type() - other.type();
if (typeDelta)
- return typeDelta < 0 ? true : false;
- switch (type_) {
+ return typeDelta < 0;
+ switch (type()) {
case nullValue:
return false;
case intValue:
@@ -578,30 +502,33 @@ bool Value::operator<(const Value& other) const {
return value_.real_ < other.value_.real_;
case booleanValue:
return value_.bool_ < other.value_.bool_;
- case stringValue:
- {
- if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
- if (other.value_.string_) return true;
- else return false;
+ case stringValue: {
+ if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) {
+ return other.value_.string_ != nullptr;
}
unsigned this_len;
unsigned other_len;
char const* this_str;
char const* other_str;
- decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
- decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
+ decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
+ &this_str);
+ decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len,
+ &other_str);
unsigned min_len = std::min<unsigned>(this_len, other_len);
JSON_ASSERT(this_str && other_str);
int comp = memcmp(this_str, other_str, min_len);
- if (comp < 0) return true;
- if (comp > 0) return false;
+ if (comp < 0)
+ return true;
+ if (comp > 0)
+ return false;
return (this_len < other_len);
}
case arrayValue:
case objectValue: {
- int delta = int(value_.map_->size() - other.value_.map_->size());
- if (delta)
- return delta < 0;
+ auto thisSize = value_.map_->size();
+ auto otherSize = other.value_.map_->size();
+ if (thisSize != otherSize)
+ return thisSize < otherSize;
return (*value_.map_) < (*other.value_.map_);
}
default:
@@ -617,14 +544,9 @@ bool Value::operator>=(const Value& other) const { return !(*this < other); }
bool Value::operator>(const Value& other) const { return other < *this; }
bool Value::operator==(const Value& other) const {
- // if ( type_ != other.type_ )
- // GCC 2.95.3 says:
- // attempt to take address of bit-field structure member `Json::Value::type_'
- // Beats me, but a temp solves the problem.
- int temp = other.type_;
- if (type_ != temp)
+ if (type() != other.type())
return false;
- switch (type_) {
+ switch (type()) {
case nullValue:
return true;
case intValue:
@@ -635,18 +557,20 @@ bool Value::operator==(const Value& other) const {
return value_.real_ == other.value_.real_;
case booleanValue:
return value_.bool_ == other.value_.bool_;
- case stringValue:
- {
- if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ case stringValue: {
+ if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) {
return (value_.string_ == other.value_.string_);
}
unsigned this_len;
unsigned other_len;
char const* this_str;
char const* other_str;
- decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
- decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
- if (this_len != other_len) return false;
+ decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
+ &this_str);
+ decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len,
+ &other_str);
+ if (this_len != other_len)
+ return false;
JSON_ASSERT(this_str && other_str);
int comp = memcmp(this_str, other_str, this_len);
return comp == 0;
@@ -664,47 +588,55 @@ bool Value::operator==(const Value& other) const {
bool Value::operator!=(const Value& other) const { return !(*this == other); }
const char* Value::asCString() const {
- JSON_ASSERT_MESSAGE(type_ == stringValue,
+ JSON_ASSERT_MESSAGE(type() == stringValue,
"in Json::Value::asCString(): requires stringValue");
- if (value_.string_ == 0) return 0;
+ if (value_.string_ == nullptr)
+ return nullptr;
unsigned this_len;
char const* this_str;
- decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
+ &this_str);
return this_str;
}
#if JSONCPP_USING_SECURE_MEMORY
unsigned Value::getCStringLength() const {
- JSON_ASSERT_MESSAGE(type_ == stringValue,
- "in Json::Value::asCString(): requires stringValue");
- if (value_.string_ == 0) return 0;
+ JSON_ASSERT_MESSAGE(type() == stringValue,
+ "in Json::Value::asCString(): requires stringValue");
+ if (value_.string_ == 0)
+ return 0;
unsigned this_len;
char const* this_str;
- decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
+ &this_str);
return this_len;
}
#endif
-bool Value::getString(char const** str, char const** cend) const {
- if (type_ != stringValue) return false;
- if (value_.string_ == 0) return false;
+bool Value::getString(char const** begin, char const** end) const {
+ if (type() != stringValue)
+ return false;
+ if (value_.string_ == nullptr)
+ return false;
unsigned length;
- decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
- *cend = *str + length;
+ decodePrefixedString(this->isAllocated(), this->value_.string_, &length,
+ begin);
+ *end = *begin + length;
return true;
}
-JSONCPP_STRING Value::asString() const {
- switch (type_) {
+String Value::asString() const {
+ switch (type()) {
case nullValue:
return "";
- case stringValue:
- {
- if (value_.string_ == 0) return "";
+ case stringValue: {
+ if (value_.string_ == nullptr)
+ return "";
unsigned this_len;
char const* this_str;
- decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
- return JSONCPP_STRING(this_str, this_len);
+ decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len,
+ &this_str);
+ return String(this_str, this_len);
}
case booleanValue:
return value_.bool_ ? "true" : "false";
@@ -719,18 +651,8 @@ JSONCPP_STRING Value::asString() const {
}
}
-#ifdef JSON_USE_CPPTL
-CppTL::ConstString Value::asConstString() const {
- unsigned len;
- char const* str;
- decodePrefixedString(allocated_, value_.string_,
- &len, &str);
- return CppTL::ConstString(str, len);
-}
-#endif
-
Value::Int Value::asInt() const {
- switch (type_) {
+ switch (type()) {
case intValue:
JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
return Int(value_.int_);
@@ -752,7 +674,7 @@ Value::Int Value::asInt() const {
}
Value::UInt Value::asUInt() const {
- switch (type_) {
+ switch (type()) {
case intValue:
JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
return UInt(value_.int_);
@@ -776,7 +698,7 @@ Value::UInt Value::asUInt() const {
#if defined(JSON_HAS_INT64)
Value::Int64 Value::asInt64() const {
- switch (type_) {
+ switch (type()) {
case intValue:
return Int64(value_.int_);
case uintValue:
@@ -797,7 +719,7 @@ Value::Int64 Value::asInt64() const {
}
Value::UInt64 Value::asUInt64() const {
- switch (type_) {
+ switch (type()) {
case intValue:
JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
return UInt64(value_.int_);
@@ -835,7 +757,7 @@ LargestUInt Value::asLargestUInt() const {
}
double Value::asDouble() const {
- switch (type_) {
+ switch (type()) {
case intValue:
return static_cast<double>(value_.int_);
case uintValue:
@@ -857,7 +779,7 @@ double Value::asDouble() const {
}
float Value::asFloat() const {
- switch (type_) {
+ switch (type()) {
case intValue:
return static_cast<float>(value_.int_);
case uintValue:
@@ -872,7 +794,7 @@ float Value::asFloat() const {
case nullValue:
return 0.0;
case booleanValue:
- return value_.bool_ ? 1.0f : 0.0f;
+ return value_.bool_ ? 1.0F : 0.0F;
default:
break;
}
@@ -880,18 +802,20 @@ float Value::asFloat() const {
}
bool Value::asBool() const {
- switch (type_) {
+ switch (type()) {
case booleanValue:
return value_.bool_;
case nullValue:
return false;
case intValue:
- return value_.int_ ? true : false;
+ return value_.int_ != 0;
case uintValue:
- return value_.uint_ ? true : false;
- case realValue:
- // This is kind of strange. Not recommended.
- return (value_.real_ != 0.0) ? true : false;
+ return value_.uint_ != 0;
+ case realValue: {
+ // According to JavaScript language zero or NaN is regarded as false
+ const auto value_classification = std::fpclassify(value_.real_);
+ return value_classification != FP_ZERO && value_classification != FP_NAN;
+ }
default:
break;
}
@@ -902,30 +826,30 @@ bool Value::isConvertibleTo(ValueType other) const {
switch (other) {
case nullValue:
return (isNumeric() && asDouble() == 0.0) ||
- (type_ == booleanValue && value_.bool_ == false) ||
- (type_ == stringValue && asString().empty()) ||
- (type_ == arrayValue && value_.map_->size() == 0) ||
- (type_ == objectValue && value_.map_->size() == 0) ||
- type_ == nullValue;
+ (type() == booleanValue && !value_.bool_) ||
+ (type() == stringValue && asString().empty()) ||
+ (type() == arrayValue && value_.map_->empty()) ||
+ (type() == objectValue && value_.map_->empty()) ||
+ type() == nullValue;
case intValue:
return isInt() ||
- (type_ == realValue && InRange(value_.real_, minInt, maxInt)) ||
- type_ == booleanValue || type_ == nullValue;
+ (type() == realValue && InRange(value_.real_, minInt, maxInt)) ||
+ type() == booleanValue || type() == nullValue;
case uintValue:
return isUInt() ||
- (type_ == realValue && InRange(value_.real_, 0, maxUInt)) ||
- type_ == booleanValue || type_ == nullValue;
+ (type() == realValue && InRange(value_.real_, 0, maxUInt)) ||
+ type() == booleanValue || type() == nullValue;
case realValue:
- return isNumeric() || type_ == booleanValue || type_ == nullValue;
+ return isNumeric() || type() == booleanValue || type() == nullValue;
case booleanValue:
- return isNumeric() || type_ == booleanValue || type_ == nullValue;
+ return isNumeric() || type() == booleanValue || type() == nullValue;
case stringValue:
- return isNumeric() || type_ == booleanValue || type_ == stringValue ||
- type_ == nullValue;
+ return isNumeric() || type() == booleanValue || type() == stringValue ||
+ type() == nullValue;
case arrayValue:
- return type_ == arrayValue || type_ == nullValue;
+ return type() == arrayValue || type() == nullValue;
case objectValue:
- return type_ == objectValue || type_ == nullValue;
+ return type() == objectValue || type() == nullValue;
}
JSON_ASSERT_UNREACHABLE;
return false;
@@ -933,7 +857,7 @@ bool Value::isConvertibleTo(ValueType other) const {
/// Number of values in array or object
ArrayIndex Value::size() const {
- switch (type_) {
+ switch (type()) {
case nullValue:
case intValue:
case uintValue:
@@ -957,20 +881,19 @@ ArrayIndex Value::size() const {
bool Value::empty() const {
if (isNull() || isArray() || isObject())
- return size() == 0u;
- else
- return false;
+ return size() == 0U;
+ return false;
}
-bool Value::operator!() const { return isNull(); }
+Value::operator bool() const { return !isNull(); }
void Value::clear() {
- JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue ||
- type_ == objectValue,
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue ||
+ type() == objectValue,
"in Json::Value::clear(): requires complex value");
start_ = 0;
limit_ = 0;
- switch (type_) {
+ switch (type()) {
case arrayValue:
case objectValue:
value_.map_->clear();
@@ -981,15 +904,15 @@ void Value::clear() {
}
void Value::resize(ArrayIndex newSize) {
- JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue,
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
"in Json::Value::resize(): requires arrayValue");
- if (type_ == nullValue)
+ if (type() == nullValue)
*this = Value(arrayValue);
ArrayIndex oldSize = size();
if (newSize == 0)
clear();
else if (newSize > oldSize)
- (*this)[newSize - 1];
+ this->operator[](newSize - 1);
else {
for (ArrayIndex index = newSize; index < oldSize; ++index) {
value_.map_->erase(index);
@@ -1000,12 +923,12 @@ void Value::resize(ArrayIndex newSize) {
Value& Value::operator[](ArrayIndex index) {
JSON_ASSERT_MESSAGE(
- type_ == nullValue || type_ == arrayValue,
+ type() == nullValue || type() == arrayValue,
"in Json::Value::operator[](ArrayIndex): requires arrayValue");
- if (type_ == nullValue)
+ if (type() == nullValue)
*this = Value(arrayValue);
CZString key(index);
- ObjectValues::iterator it = value_.map_->lower_bound(key);
+ auto it = value_.map_->lower_bound(key);
if (it != value_.map_->end() && (*it).first == key)
return (*it).second;
@@ -1023,9 +946,9 @@ Value& Value::operator[](int index) {
const Value& Value::operator[](ArrayIndex index) const {
JSON_ASSERT_MESSAGE(
- type_ == nullValue || type_ == arrayValue,
+ type() == nullValue || type() == arrayValue,
"in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
- if (type_ == nullValue)
+ if (type() == nullValue)
return nullSingleton();
CZString key(index);
ObjectValues::const_iterator it = value_.map_->find(key);
@@ -1041,26 +964,85 @@ const Value& Value::operator[](int index) const {
return (*this)[ArrayIndex(index)];
}
-void Value::initBasic(ValueType vtype, bool allocated) {
- type_ = vtype;
- allocated_ = allocated;
- comments_ = 0;
+void Value::initBasic(ValueType type, bool allocated) {
+ setType(type);
+ setIsAllocated(allocated);
+ comments_ = Comments{};
start_ = 0;
limit_ = 0;
}
+void Value::dupPayload(const Value& other) {
+ setType(other.type());
+ setIsAllocated(false);
+ switch (type()) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ value_ = other.value_;
+ break;
+ case stringValue:
+ if (other.value_.string_ && other.isAllocated()) {
+ unsigned len;
+ char const* str;
+ decodePrefixedString(other.isAllocated(), other.value_.string_, &len,
+ &str);
+ value_.string_ = duplicateAndPrefixStringValue(str, len);
+ setIsAllocated(true);
+ } else {
+ value_.string_ = other.value_.string_;
+ }
+ break;
+ case arrayValue:
+ case objectValue:
+ value_.map_ = new ObjectValues(*other.value_.map_);
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+}
+
+void Value::releasePayload() {
+ switch (type()) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ break;
+ case stringValue:
+ if (isAllocated())
+ releasePrefixedStringValue(value_.string_);
+ break;
+ case arrayValue:
+ case objectValue:
+ delete value_.map_;
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+}
+
+void Value::dupMeta(const Value& other) {
+ comments_ = other.comments_;
+ start_ = other.start_;
+ limit_ = other.limit_;
+}
+
// Access an object value by name, create a null member if it does not exist.
// @pre Type of '*this' is object or null.
// @param key is null-terminated.
Value& Value::resolveReference(const char* key) {
JSON_ASSERT_MESSAGE(
- type_ == nullValue || type_ == objectValue,
+ type() == nullValue || type() == objectValue,
"in Json::Value::resolveReference(): requires objectValue");
- if (type_ == nullValue)
+ if (type() == nullValue)
*this = Value(objectValue);
- CZString actualKey(
- key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
- ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ CZString actualKey(key, static_cast<unsigned>(strlen(key)),
+ CZString::noDuplication); // NOTE!
+ auto it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
@@ -1071,16 +1053,15 @@ Value& Value::resolveReference(const char* key) {
}
// @param key is not null-terminated.
-Value& Value::resolveReference(char const* key, char const* cend)
-{
+Value& Value::resolveReference(char const* key, char const* end) {
JSON_ASSERT_MESSAGE(
- type_ == nullValue || type_ == objectValue,
+ type() == nullValue || type() == objectValue,
"in Json::Value::resolveReference(key, end): requires objectValue");
- if (type_ == nullValue)
+ if (type() == nullValue)
*this = Value(objectValue);
- CZString actualKey(
- key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
- ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ CZString actualKey(key, static_cast<unsigned>(end - key),
+ CZString::duplicateOnCopy);
+ auto it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
@@ -1097,27 +1078,35 @@ Value Value::get(ArrayIndex index, const Value& defaultValue) const {
bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
-Value const* Value::find(char const* key, char const* cend) const
-{
- JSON_ASSERT_MESSAGE(
- type_ == nullValue || type_ == objectValue,
- "in Json::Value::find(key, end, found): requires objectValue or nullValue");
- if (type_ == nullValue) return NULL;
- CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
+Value const* Value::find(char const* begin, char const* end) const {
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
+ "in Json::Value::find(begin, end): requires "
+ "objectValue or nullValue");
+ if (type() == nullValue)
+ return nullptr;
+ CZString actualKey(begin, static_cast<unsigned>(end - begin),
+ CZString::noDuplication);
ObjectValues::const_iterator it = value_.map_->find(actualKey);
- if (it == value_.map_->end()) return NULL;
+ if (it == value_.map_->end())
+ return nullptr;
return &(*it).second;
}
-const Value& Value::operator[](const char* key) const
-{
+Value* Value::demand(char const* begin, char const* end) {
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
+ "in Json::Value::demand(begin, end): requires "
+ "objectValue or nullValue");
+ return &resolveReference(begin, end);
+}
+const Value& Value::operator[](const char* key) const {
Value const* found = find(key, key + strlen(key));
- if (!found) return nullSingleton();
+ if (!found)
+ return nullSingleton();
return *found;
}
-Value const& Value::operator[](JSONCPP_STRING const& key) const
-{
+Value const& Value::operator[](const String& key) const {
Value const* found = find(key.data(), key.data() + key.length());
- if (!found) return nullSingleton();
+ if (!found)
+ return nullSingleton();
return *found;
}
@@ -1125,7 +1114,7 @@ Value& Value::operator[](const char* key) {
return resolveReference(key, key + strlen(key));
}
-Value& Value::operator[](const JSONCPP_STRING& key) {
+Value& Value::operator[](const String& key) {
return resolveReference(key.data(), key.data() + key.length());
}
@@ -1133,179 +1122,140 @@ Value& Value::operator[](const StaticString& key) {
return resolveReference(key.c_str());
}
-#ifdef JSON_USE_CPPTL
-Value& Value::operator[](const CppTL::ConstString& key) {
- return resolveReference(key.c_str(), key.end_c_str());
-}
-Value const& Value::operator[](CppTL::ConstString const& key) const
-{
- Value const* found = find(key.c_str(), key.end_c_str());
- if (!found) return nullSingleton();
- return *found;
+Value& Value::append(const Value& value) { return append(Value(value)); }
+
+Value& Value::append(Value&& value) {
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
+ "in Json::Value::append: requires arrayValue");
+ if (type() == nullValue) {
+ *this = Value(arrayValue);
+ }
+ return this->value_.map_->emplace(size(), std::move(value)).first->second;
}
-#endif
-Value& Value::append(const Value& value) { return (*this)[size()] = value; }
+bool Value::insert(ArrayIndex index, const Value& newValue) {
+ return insert(index, Value(newValue));
+}
-#if JSON_HAS_RVALUE_REFERENCES
- Value& Value::append(Value&& value) { return (*this)[size()] = value; }
-#endif
+bool Value::insert(ArrayIndex index, Value&& newValue) {
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue,
+ "in Json::Value::insert: requires arrayValue");
+ ArrayIndex length = size();
+ if (index > length) {
+ return false;
+ }
+ for (ArrayIndex i = length; i > index; i--) {
+ (*this)[i] = std::move((*this)[i - 1]);
+ }
+ (*this)[index] = std::move(newValue);
+ return true;
+}
-Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
-{
- Value const* found = find(key, cend);
+Value Value::get(char const* begin, char const* end,
+ Value const& defaultValue) const {
+ Value const* found = find(begin, end);
return !found ? defaultValue : *found;
}
-Value Value::get(char const* key, Value const& defaultValue) const
-{
+Value Value::get(char const* key, Value const& defaultValue) const {
return get(key, key + strlen(key), defaultValue);
}
-Value Value::get(JSONCPP_STRING const& key, Value const& defaultValue) const
-{
+Value Value::get(String const& key, Value const& defaultValue) const {
return get(key.data(), key.data() + key.length(), defaultValue);
}
-
-bool Value::removeMember(const char* key, const char* cend, Value* removed)
-{
- if (type_ != objectValue) {
+bool Value::removeMember(const char* begin, const char* end, Value* removed) {
+ if (type() != objectValue) {
return false;
}
- CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
- ObjectValues::iterator it = value_.map_->find(actualKey);
+ CZString actualKey(begin, static_cast<unsigned>(end - begin),
+ CZString::noDuplication);
+ auto it = value_.map_->find(actualKey);
if (it == value_.map_->end())
return false;
- *removed = it->second;
+ if (removed)
+ *removed = std::move(it->second);
value_.map_->erase(it);
return true;
}
-bool Value::removeMember(const char* key, Value* removed)
-{
+bool Value::removeMember(const char* key, Value* removed) {
return removeMember(key, key + strlen(key), removed);
}
-bool Value::removeMember(JSONCPP_STRING const& key, Value* removed)
-{
+bool Value::removeMember(String const& key, Value* removed) {
return removeMember(key.data(), key.data() + key.length(), removed);
}
-Value Value::removeMember(const char* key)
-{
- JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
+void Value::removeMember(const char* key) {
+ JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue,
"in Json::Value::removeMember(): requires objectValue");
- if (type_ == nullValue)
- return nullSingleton();
+ if (type() == nullValue)
+ return;
- Value removed; // null
- removeMember(key, key + strlen(key), &removed);
- return removed; // still null if removeMember() did nothing
-}
-Value Value::removeMember(const JSONCPP_STRING& key)
-{
- return removeMember(key.c_str());
+ CZString actualKey(key, unsigned(strlen(key)), CZString::noDuplication);
+ value_.map_->erase(actualKey);
}
+void Value::removeMember(const String& key) { removeMember(key.c_str()); }
bool Value::removeIndex(ArrayIndex index, Value* removed) {
- if (type_ != arrayValue) {
+ if (type() != arrayValue) {
return false;
}
CZString key(index);
- ObjectValues::iterator it = value_.map_->find(key);
+ auto it = value_.map_->find(key);
if (it == value_.map_->end()) {
return false;
}
- *removed = it->second;
+ if (removed)
+ *removed = it->second;
ArrayIndex oldSize = size();
// shift left all items left, into the place of the "removed"
- for (ArrayIndex i = index; i < (oldSize - 1); ++i){
+ for (ArrayIndex i = index; i < (oldSize - 1); ++i) {
CZString keey(i);
(*value_.map_)[keey] = (*this)[i + 1];
}
// erase the last one ("leftover")
CZString keyLast(oldSize - 1);
- ObjectValues::iterator itLast = value_.map_->find(keyLast);
+ auto itLast = value_.map_->find(keyLast);
value_.map_->erase(itLast);
return true;
}
-#ifdef JSON_USE_CPPTL
-Value Value::get(const CppTL::ConstString& key,
- const Value& defaultValue) const {
- return get(key.c_str(), key.end_c_str(), defaultValue);
+bool Value::isMember(char const* begin, char const* end) const {
+ Value const* value = find(begin, end);
+ return nullptr != value;
}
-#endif
-
-bool Value::isMember(char const* key, char const* cend) const
-{
- Value const* value = find(key, cend);
- return NULL != value;
-}
-bool Value::isMember(char const* key) const
-{
+bool Value::isMember(char const* key) const {
return isMember(key, key + strlen(key));
}
-bool Value::isMember(JSONCPP_STRING const& key) const
-{
+bool Value::isMember(String const& key) const {
return isMember(key.data(), key.data() + key.length());
}
-#ifdef JSON_USE_CPPTL
-bool Value::isMember(const CppTL::ConstString& key) const {
- return isMember(key.c_str(), key.end_c_str());
-}
-#endif
-
Value::Members Value::getMemberNames() const {
JSON_ASSERT_MESSAGE(
- type_ == nullValue || type_ == objectValue,
+ type() == nullValue || type() == objectValue,
"in Json::Value::getMemberNames(), value must be objectValue");
- if (type_ == nullValue)
+ if (type() == nullValue)
return Value::Members();
Members members;
members.reserve(value_.map_->size());
ObjectValues::const_iterator it = value_.map_->begin();
ObjectValues::const_iterator itEnd = value_.map_->end();
for (; it != itEnd; ++it) {
- members.push_back(JSONCPP_STRING((*it).first.data(),
- (*it).first.length()));
+ members.push_back(String((*it).first.data(), (*it).first.length()));
}
return members;
}
-//
-//# ifdef JSON_USE_CPPTL
-// EnumMemberNames
-// Value::enumMemberNames() const
-//{
-// if ( type_ == objectValue )
-// {
-// return CppTL::Enum::any( CppTL::Enum::transform(
-// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
-// MemberNamesTransform() ) );
-// }
-// return EnumMemberNames();
-//}
-//
-//
-// EnumValues
-// Value::enumValues() const
-//{
-// if ( type_ == objectValue || type_ == arrayValue )
-// return CppTL::Enum::anyValues( *(value_.map_),
-// CppTL::Type<const Value &>() );
-// return EnumValues();
-//}
-//
-//# endif
static bool IsIntegral(double d) {
double integral_part;
return modf(d, &integral_part) == 0.0;
}
-bool Value::isNull() const { return type_ == nullValue; }
+bool Value::isNull() const { return type() == nullValue; }
-bool Value::isBool() const { return type_ == booleanValue; }
+bool Value::isBool() const { return type() == booleanValue; }
bool Value::isInt() const {
- switch (type_) {
+ switch (type()) {
case intValue:
#if defined(JSON_HAS_INT64)
return value_.int_ >= minInt && value_.int_ <= maxInt;
@@ -1324,7 +1274,7 @@ bool Value::isInt() const {
}
bool Value::isUInt() const {
- switch (type_) {
+ switch (type()) {
case intValue:
#if defined(JSON_HAS_INT64)
return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
@@ -1348,7 +1298,7 @@ bool Value::isUInt() const {
bool Value::isInt64() const {
#if defined(JSON_HAS_INT64)
- switch (type_) {
+ switch (type()) {
case intValue:
return true;
case uintValue:
@@ -1368,7 +1318,7 @@ bool Value::isInt64() const {
bool Value::isUInt64() const {
#if defined(JSON_HAS_INT64)
- switch (type_) {
+ switch (type()) {
case intValue:
return value_.int_ >= 0;
case uintValue:
@@ -1387,61 +1337,92 @@ bool Value::isUInt64() const {
}
bool Value::isIntegral() const {
- switch (type_) {
- case intValue:
- case uintValue:
- return true;
- case realValue:
+ switch (type()) {
+ case intValue:
+ case uintValue:
+ return true;
+ case realValue:
#if defined(JSON_HAS_INT64)
- // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
- // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
- // require the value to be strictly less than the limit.
- return value_.real_ >= double(minInt64) && value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_);
+ // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
+ // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
+ // require the value to be strictly less than the limit.
+ return value_.real_ >= double(minInt64) &&
+ value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_);
#else
- return value_.real_ >= minInt && value_.real_ <= maxUInt && IsIntegral(value_.real_);
+ return value_.real_ >= minInt && value_.real_ <= maxUInt &&
+ IsIntegral(value_.real_);
#endif // JSON_HAS_INT64
- default:
- break;
+ default:
+ break;
}
return false;
}
-bool Value::isDouble() const { return type_ == intValue || type_ == uintValue || type_ == realValue; }
+bool Value::isDouble() const {
+ return type() == intValue || type() == uintValue || type() == realValue;
+}
bool Value::isNumeric() const { return isDouble(); }
-bool Value::isString() const { return type_ == stringValue; }
+bool Value::isString() const { return type() == stringValue; }
-bool Value::isArray() const { return type_ == arrayValue; }
+bool Value::isArray() const { return type() == arrayValue; }
-bool Value::isObject() const { return type_ == objectValue; }
+bool Value::isObject() const { return type() == objectValue; }
-void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
- if (!comments_)
- comments_ = new CommentInfo[numberOfCommentPlacement];
- if ((len > 0) && (comment[len-1] == '\n')) {
- // Always discard trailing newline, to aid indentation.
- len -= 1;
- }
- comments_[placement].setComment(comment, len);
+Value::Comments::Comments(const Comments& that)
+ : ptr_{cloneUnique(that.ptr_)} {}
+
+Value::Comments::Comments(Comments&& that) : ptr_{std::move(that.ptr_)} {}
+
+Value::Comments& Value::Comments::operator=(const Comments& that) {
+ ptr_ = cloneUnique(that.ptr_);
+ return *this;
}
-void Value::setComment(const char* comment, CommentPlacement placement) {
- setComment(comment, strlen(comment), placement);
+Value::Comments& Value::Comments::operator=(Comments&& that) {
+ ptr_ = std::move(that.ptr_);
+ return *this;
+}
+
+bool Value::Comments::has(CommentPlacement slot) const {
+ return ptr_ && !(*ptr_)[slot].empty();
}
-void Value::setComment(const JSONCPP_STRING& comment, CommentPlacement placement) {
- setComment(comment.c_str(), comment.length(), placement);
+String Value::Comments::get(CommentPlacement slot) const {
+ if (!ptr_)
+ return {};
+ return (*ptr_)[slot];
+}
+
+void Value::Comments::set(CommentPlacement slot, String comment) {
+ if (!ptr_) {
+ ptr_ = std::unique_ptr<Array>(new Array());
+ }
+ // check comments array boundry.
+ if (slot < CommentPlacement::numberOfCommentPlacement) {
+ (*ptr_)[slot] = std::move(comment);
+ }
+}
+
+void Value::setComment(String comment, CommentPlacement placement) {
+ if (!comment.empty() && (comment.back() == '\n')) {
+ // Always discard trailing newline, to aid indentation.
+ comment.pop_back();
+ }
+ JSON_ASSERT(!comment.empty());
+ JSON_ASSERT_MESSAGE(
+ comment[0] == '\0' || comment[0] == '/',
+ "in Json::Value::setComment(): Comments must start with /");
+ comments_.set(placement, std::move(comment));
}
bool Value::hasComment(CommentPlacement placement) const {
- return comments_ != 0 && comments_[placement].comment_ != 0;
+ return comments_.has(placement);
}
-JSONCPP_STRING Value::getComment(CommentPlacement placement) const {
- if (hasComment(placement))
- return comments_[placement].comment_;
- return "";
+String Value::getComment(CommentPlacement placement) const {
+ return comments_.get(placement);
}
void Value::setOffsetStart(ptrdiff_t start) { start_ = start; }
@@ -1452,18 +1433,18 @@ ptrdiff_t Value::getOffsetStart() const { return start_; }
ptrdiff_t Value::getOffsetLimit() const { return limit_; }
-JSONCPP_STRING Value::toStyledString() const {
+String Value::toStyledString() const {
StreamWriterBuilder builder;
- JSONCPP_STRING out = this->hasComment(commentBefore) ? "\n" : "";
+ String out = this->hasComment(commentBefore) ? "\n" : "";
out += Json::writeString(builder, *this);
- out += "\n";
+ out += '\n';
return out;
}
Value::const_iterator Value::begin() const {
- switch (type_) {
+ switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
@@ -1472,11 +1453,11 @@ Value::const_iterator Value::begin() const {
default:
break;
}
- return const_iterator();
+ return {};
}
Value::const_iterator Value::end() const {
- switch (type_) {
+ switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
@@ -1485,11 +1466,11 @@ Value::const_iterator Value::end() const {
default:
break;
}
- return const_iterator();
+ return {};
}
Value::iterator Value::begin() {
- switch (type_) {
+ switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
@@ -1502,7 +1483,7 @@ Value::iterator Value::begin() {
}
Value::iterator Value::end() {
- switch (type_) {
+ switch (type()) {
case arrayValue:
case objectValue:
if (value_.map_)
@@ -1517,25 +1498,20 @@ Value::iterator Value::end() {
// class PathArgument
// //////////////////////////////////////////////////////////////////
-PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {}
+PathArgument::PathArgument() = default;
PathArgument::PathArgument(ArrayIndex index)
- : key_(), index_(index), kind_(kindIndex) {}
+ : index_(index), kind_(kindIndex) {}
-PathArgument::PathArgument(const char* key)
- : key_(key), index_(), kind_(kindKey) {}
+PathArgument::PathArgument(const char* key) : key_(key), kind_(kindKey) {}
-PathArgument::PathArgument(const JSONCPP_STRING& key)
- : key_(key.c_str()), index_(), kind_(kindKey) {}
+PathArgument::PathArgument(String key) : key_(std::move(key)), kind_(kindKey) {}
// class Path
// //////////////////////////////////////////////////////////////////
-Path::Path(const JSONCPP_STRING& path,
- const PathArgument& a1,
- const PathArgument& a2,
- const PathArgument& a3,
- const PathArgument& a4,
+Path::Path(const String& path, const PathArgument& a1, const PathArgument& a2,
+ const PathArgument& a3, const PathArgument& a4,
const PathArgument& a5) {
InArgs in;
in.reserve(5);
@@ -1547,10 +1523,10 @@ Path::Path(const JSONCPP_STRING& path,
makePath(path, in);
}
-void Path::makePath(const JSONCPP_STRING& path, const InArgs& in) {
+void Path::makePath(const String& path, const InArgs& in) {
const char* current = path.c_str();
const char* end = current + path.length();
- InArgs::const_iterator itInArg = in.begin();
+ auto itInArg = in.begin();
while (current != end) {
if (*current == '[') {
++current;
@@ -1573,13 +1549,12 @@ void Path::makePath(const JSONCPP_STRING& path, const InArgs& in) {
const char* beginName = current;
while (current != end && !strchr("[.", *current))
++current;
- args_.push_back(JSONCPP_STRING(beginName, current));
+ args_.push_back(String(beginName, current));
}
}
}
-void Path::addPathInArg(const JSONCPP_STRING& /*path*/,
- const InArgs& in,
+void Path::addPathInArg(const String& /*path*/, const InArgs& in,
InArgs::const_iterator& itInArg,
PathArgument::Kind kind) {
if (itInArg == in.end()) {
@@ -1591,30 +1566,29 @@ void Path::addPathInArg(const JSONCPP_STRING& /*path*/,
}
}
-void Path::invalidPath(const JSONCPP_STRING& /*path*/, int /*location*/) {
+void Path::invalidPath(const String& /*path*/, int /*location*/) {
// Error: invalid path.
}
const Value& Path::resolve(const Value& root) const {
const Value* node = &root;
- for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
- const PathArgument& arg = *it;
+ for (const auto& arg : args_) {
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray() || !node->isValidIndex(arg.index_)) {
- // Error: unable to resolve path (array value expected at position...
- return Value::null;
+ // Error: unable to resolve path (array value expected at position... )
+ return Value::nullSingleton();
}
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject()) {
// Error: unable to resolve path (object value expected at position...)
- return Value::null;
+ return Value::nullSingleton();
}
node = &((*node)[arg.key_]);
if (node == &Value::nullSingleton()) {
// Error: unable to resolve path (object has no member named '' at
// position...)
- return Value::null;
+ return Value::nullSingleton();
}
}
}
@@ -1623,8 +1597,7 @@ const Value& Path::resolve(const Value& root) const {
Value Path::resolve(const Value& root, const Value& defaultValue) const {
const Value* node = &root;
- for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
- const PathArgument& arg = *it;
+ for (const auto& arg : args_) {
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray() || !node->isValidIndex(arg.index_))
return defaultValue;
@@ -1642,8 +1615,7 @@ Value Path::resolve(const Value& root, const Value& defaultValue) const {
Value& Path::make(Value& root) const {
Value* node = &root;
- for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
- const PathArgument& arg = *it;
+ for (const auto& arg : args_) {
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray()) {
// Error: node is not an array at position ...
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl b/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl
index 5243bfe..d6128b8 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl
+++ b/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl
@@ -15,31 +15,21 @@ namespace Json {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
-ValueIteratorBase::ValueIteratorBase()
- : current_(), isNull_(true) {
-}
+ValueIteratorBase::ValueIteratorBase() : current_() {}
ValueIteratorBase::ValueIteratorBase(
const Value::ObjectValues::iterator& current)
: current_(current), isNull_(false) {}
-Value& ValueIteratorBase::deref() const {
- return current_->second;
-}
+Value& ValueIteratorBase::deref() { return current_->second; }
+const Value& ValueIteratorBase::deref() const { return current_->second; }
-void ValueIteratorBase::increment() {
- ++current_;
-}
+void ValueIteratorBase::increment() { ++current_; }
-void ValueIteratorBase::decrement() {
- --current_;
-}
+void ValueIteratorBase::decrement() { --current_; }
ValueIteratorBase::difference_type
ValueIteratorBase::computeDistance(const SelfType& other) const {
-#ifdef JSON_USE_CPPTL_SMALLMAP
- return other.current_ - current_;
-#else
// Iterator for null value are initialized using the default
// constructor, which initialize current_ to the default
// std::map::iterator. As begin() and end() are two instance
@@ -60,7 +50,6 @@ ValueIteratorBase::computeDistance(const SelfType& other) const {
++myDistance;
}
return myDistance;
-#endif
}
bool ValueIteratorBase::isEqual(const SelfType& other) const {
@@ -92,12 +81,13 @@ UInt ValueIteratorBase::index() const {
return Value::UInt(-1);
}
-JSONCPP_STRING ValueIteratorBase::name() const {
+String ValueIteratorBase::name() const {
char const* keey;
char const* end;
keey = memberName(&end);
- if (!keey) return JSONCPP_STRING();
- return JSONCPP_STRING(keey, end);
+ if (!keey)
+ return String();
+ return String(keey, end);
}
char const* ValueIteratorBase::memberName() const {
@@ -108,8 +98,8 @@ char const* ValueIteratorBase::memberName() const {
char const* ValueIteratorBase::memberName(char const** end) const {
const char* cname = (*current_).first.data();
if (!cname) {
- *end = NULL;
- return NULL;
+ *end = nullptr;
+ return nullptr;
}
*end = cname + (*current_).first.length();
return cname;
@@ -123,7 +113,7 @@ char const* ValueIteratorBase::memberName(char const** end) const {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
-ValueConstIterator::ValueConstIterator() {}
+ValueConstIterator::ValueConstIterator() = default;
ValueConstIterator::ValueConstIterator(
const Value::ObjectValues::iterator& current)
@@ -146,7 +136,7 @@ operator=(const ValueIteratorBase& other) {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
-ValueIterator::ValueIterator() {}
+ValueIterator::ValueIterator() = default;
ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
@@ -156,8 +146,7 @@ ValueIterator::ValueIterator(const ValueConstIterator& other)
throwRuntimeError("ConstIterator to Iterator should never be allowed.");
}
-ValueIterator::ValueIterator(const ValueIterator& other)
- : ValueIteratorBase(other) {}
+ValueIterator::ValueIterator(const ValueIterator& other) = default;
ValueIterator& ValueIterator::operator=(const SelfType& other) {
copy(other);
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp b/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp
index fc86505..8bf02db 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp
+++ b/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp
@@ -4,106 +4,81 @@
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
-#include <json/writer.h>
#include "json_tool.h"
+#include <json/writer.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <algorithm>
+#include <cassert>
+#include <cctype>
+#include <cstring>
#include <iomanip>
#include <memory>
+#include <set>
#include <sstream>
#include <utility>
-#include <set>
-#include <cassert>
-#include <cstring>
+
+#if __cplusplus >= 201103L
+#include <cmath>
#include <cstdio>
-#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
-#include <float.h>
-#define isfinite _finite
-#elif defined(__sun) && defined(__SVR4) //Solaris
-#if !defined(isfinite)
-#include <ieeefp.h>
-#define isfinite finite
+#if !defined(isnan)
+#define isnan std::isnan
#endif
-#elif defined(_AIX)
+
#if !defined(isfinite)
-#include <math.h>
-#define isfinite finite
-#endif
-#elif defined(__hpux)
-#if !defined(isfinite) && !defined(__GNUC__)
-#if defined(__ia64) && !defined(finite)
-#define isfinite(x) ((sizeof(x) == sizeof(float) ? \
- _Isfinitef(x) : _IsFinite(x)))
-#else
-#include <math.h>
-#define isfinite finite
-#endif
+#define isfinite std::isfinite
#endif
+
#else
#include <cmath>
-#if !(defined(__QNXNTO__)) // QNX already defines isfinite
-#define isfinite std::isfinite
-#endif
-#endif
+#include <cstdio>
#if defined(_MSC_VER)
-#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
-#define snprintf sprintf_s
-#elif _MSC_VER >= 1900 // VC++ 14.0 and above
-#define snprintf std::snprintf
-#else
-#define snprintf _snprintf
-#endif
-#elif defined(__ANDROID__) || defined(__QNXNTO__)
-#define snprintf snprintf
-#elif __cplusplus >= 201103L
-#if !defined(__MINGW32__) && !defined(__CYGWIN__)
-#define snprintf std::snprintf
-#endif
+#if !defined(isnan)
+#include <float.h>
+#define isnan _isnan
#endif
-#if defined(__BORLANDC__)
+#if !defined(isfinite)
#include <float.h>
#define isfinite _finite
-#define snprintf _snprintf
#endif
-// Solaris
-#if defined(__sun)
-# include <ieeefp.h>
-# if !defined(isfinite)
-# define isfinite finite
-# endif
-#endif
+#if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES)
+#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
+#endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES
+
+#endif //_MSC_VER
-// AIX
-#if defined(_AIX)
-# if !defined(isfinite)
-# define isfinite finite
-# endif
+#if defined(__sun) && defined(__SVR4) // Solaris
+#if !defined(isfinite)
+#include <ieeefp.h>
+#define isfinite finite
+#endif
#endif
-// HP-UX
#if defined(__hpux)
-# if !defined(isfinite)
-# if defined(__ia64) && !defined(finite) && !defined(__GNUC__)
-# define isfinite(x) ((sizeof(x) == sizeof(float) ? \
- _Isfinitef(x) : _Isfinite(x)))
-# else
-# include <math.h>
-# define isfinite finite
-# endif
-# endif
+#if !defined(isfinite)
+#if defined(__ia64) && !defined(finite)
+#define isfinite(x) \
+ ((sizeof(x) == sizeof(float) ? _Isfinitef(x) : _IsFinite(x)))
+#endif
+#endif
+#endif
+
+#if !defined(isnan)
+// IEEE standard states that NaN values will not compare to themselves
+#define isnan(x) (x != x)
#endif
-// Ancient glibc
-#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 2
-# if !defined(isfinite)
-# define isfinite __finite
-# endif
+#if !defined(__APPLE__)
+#if !defined(isfinite)
+#define isfinite finite
+#endif
+#endif
#endif
-#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+#if defined(_MSC_VER)
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
@@ -111,30 +86,12 @@
namespace Json {
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
-typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
+using StreamWriterPtr = std::unique_ptr<StreamWriter>;
#else
-typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
+using StreamWriterPtr = std::auto_ptr<StreamWriter>;
#endif
-static bool containsControlCharacter(const char* str) {
- while (*str) {
- if (isControlCharacter(*(str++)))
- return true;
- }
- return false;
-}
-
-static bool containsControlCharacter0(const char* str, unsigned len) {
- char const* end = str + len;
- while (end != str) {
- if (isControlCharacter(*str) || 0==*str)
- return true;
- ++str;
- }
- return false;
-}
-
-JSONCPP_STRING valueToString(LargestInt value) {
+String valueToString(LargestInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
if (value == Value::minLargestInt) {
@@ -150,7 +107,7 @@ JSONCPP_STRING valueToString(LargestInt value) {
return current;
}
-JSONCPP_STRING valueToString(LargestUInt value) {
+String valueToString(LargestUInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
uintToString(value, current);
@@ -160,147 +117,171 @@ JSONCPP_STRING valueToString(LargestUInt value) {
#if defined(JSON_HAS_INT64)
-JSONCPP_STRING valueToString(Int value) {
- return valueToString(LargestInt(value));
-}
+String valueToString(Int value) { return valueToString(LargestInt(value)); }
-JSONCPP_STRING valueToString(UInt value) {
- return valueToString(LargestUInt(value));
-}
+String valueToString(UInt value) { return valueToString(LargestUInt(value)); }
#endif // # if defined(JSON_HAS_INT64)
namespace {
-JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) {
- // Allocate a buffer that is more than large enough to store the 16 digits of
- // precision requested below.
- char buffer[36];
- int len = -1;
-
- char formatString[15];
- snprintf(formatString, sizeof(formatString), "%%.%dg", precision);
-
+String valueToString(double value, bool useSpecialFloats,
+ unsigned int precision, PrecisionType precisionType) {
// Print into the buffer. We need not request the alternative representation
- // that always has a decimal point because JSON doesn't distingish the
+ // that always has a decimal point because JSON doesn't distinguish the
// concepts of reals and integers.
- if (isfinite(value)) {
- len = snprintf(buffer, sizeof(buffer), formatString, value);
- fixNumericLocale(buffer, buffer + len);
+ if (!isfinite(value)) {
+ static const char* const reps[2][3] = {{"NaN", "-Infinity", "Infinity"},
+ {"null", "-1e+9999", "1e+9999"}};
+ return reps[useSpecialFloats ? 0 : 1]
+ [isnan(value) ? 0 : (value < 0) ? 1 : 2];
+ }
- // try to ensure we preserve the fact that this was given to us as a double on input
- if (!strchr(buffer, '.') && !strchr(buffer, 'e')) {
- strcat(buffer, ".0");
+ String buffer(size_t(36), '\0');
+ while (true) {
+ int len = jsoncpp_snprintf(
+ &*buffer.begin(), buffer.size(),
+ (precisionType == PrecisionType::significantDigits) ? "%.*g" : "%.*f",
+ precision, value);
+ assert(len >= 0);
+ auto wouldPrint = static_cast<size_t>(len);
+ if (wouldPrint >= buffer.size()) {
+ buffer.resize(wouldPrint + 1);
+ continue;
}
+ buffer.resize(wouldPrint);
+ break;
+ }
- } else {
- // IEEE standard states that NaN values will not compare to themselves
- if (value != value) {
- len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
- } else if (value < 0) {
- len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
- } else {
- len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
- }
+ buffer.erase(fixNumericLocale(buffer.begin(), buffer.end()), buffer.end());
+
+ // strip the zero padding from the right
+ if (precisionType == PrecisionType::decimalPlaces) {
+ buffer.erase(fixZerosInTheEnd(buffer.begin(), buffer.end()), buffer.end());
+ }
+
+ // try to ensure we preserve the fact that this was given to us as a double on
+ // input
+ if (buffer.find('.') == buffer.npos && buffer.find('e') == buffer.npos) {
+ buffer += ".0";
}
- assert(len >= 0);
return buffer;
}
+} // namespace
+
+String valueToString(double value, unsigned int precision,
+ PrecisionType precisionType) {
+ return valueToString(value, false, precision, precisionType);
}
-JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); }
+String valueToString(bool value) { return value ? "true" : "false"; }
-JSONCPP_STRING valueToString(bool value) { return value ? "true" : "false"; }
+static bool doesAnyCharRequireEscaping(char const* s, size_t n) {
+ assert(s || !n);
-JSONCPP_STRING valueToQuotedString(const char* value) {
- if (value == NULL)
- return "";
- // Not sure how to handle unicode...
- if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
- !containsControlCharacter(value))
- return JSONCPP_STRING("\"") + value + "\"";
- // We have to walk value and escape any special characters.
- // Appending to JSONCPP_STRING is not efficient, but this should be rare.
- // (Note: forward slashes are *not* rare, but I am not escaping them.)
- JSONCPP_STRING::size_type maxsize =
- strlen(value) * 2 + 3; // allescaped+quotes+NULL
- JSONCPP_STRING result;
- result.reserve(maxsize); // to avoid lots of mallocs
- result += "\"";
- for (const char* c = value; *c != 0; ++c) {
- switch (*c) {
- case '\"':
- result += "\\\"";
- break;
- case '\\':
- result += "\\\\";
- break;
- case '\b':
- result += "\\b";
- break;
- case '\f':
- result += "\\f";
- break;
- case '\n':
- result += "\\n";
- break;
- case '\r':
- result += "\\r";
- break;
- case '\t':
- result += "\\t";
- break;
- // case '/':
- // Even though \/ is considered a legal escape in JSON, a bare
- // slash is also legal, so I see no reason to escape it.
- // (I hope I am not misunderstanding something.
- // blep notes: actually escaping \/ may be useful in javascript to avoid </
- // sequence.
- // Should add a flag to allow this compatibility mode and prevent this
- // sequence from occurring.
- default:
- if (isControlCharacter(*c)) {
- JSONCPP_OSTRINGSTREAM oss;
- oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
- << std::setw(4) << static_cast<int>(*c);
- result += oss.str();
- } else {
- result += *c;
- }
- break;
- }
+ return std::any_of(s, s + n, [](unsigned char c) {
+ return c == '\\' || c == '"' || c < 0x20 || c > 0x7F;
+ });
+}
+
+static unsigned int utf8ToCodepoint(const char*& s, const char* e) {
+ const unsigned int REPLACEMENT_CHARACTER = 0xFFFD;
+
+ unsigned int firstByte = static_cast<unsigned char>(*s);
+
+ if (firstByte < 0x80)
+ return firstByte;
+
+ if (firstByte < 0xE0) {
+ if (e - s < 2)
+ return REPLACEMENT_CHARACTER;
+
+ unsigned int calculated =
+ ((firstByte & 0x1F) << 6) | (static_cast<unsigned int>(s[1]) & 0x3F);
+ s += 1;
+ // oversized encoded characters are invalid
+ return calculated < 0x80 ? REPLACEMENT_CHARACTER : calculated;
}
- result += "\"";
+
+ if (firstByte < 0xF0) {
+ if (e - s < 3)
+ return REPLACEMENT_CHARACTER;
+
+ unsigned int calculated = ((firstByte & 0x0F) << 12) |
+ ((static_cast<unsigned int>(s[1]) & 0x3F) << 6) |
+ (static_cast<unsigned int>(s[2]) & 0x3F);
+ s += 2;
+ // surrogates aren't valid codepoints itself
+ // shouldn't be UTF-8 encoded
+ if (calculated >= 0xD800 && calculated <= 0xDFFF)
+ return REPLACEMENT_CHARACTER;
+ // oversized encoded characters are invalid
+ return calculated < 0x800 ? REPLACEMENT_CHARACTER : calculated;
+ }
+
+ if (firstByte < 0xF8) {
+ if (e - s < 4)
+ return REPLACEMENT_CHARACTER;
+
+ unsigned int calculated = ((firstByte & 0x07) << 18) |
+ ((static_cast<unsigned int>(s[1]) & 0x3F) << 12) |
+ ((static_cast<unsigned int>(s[2]) & 0x3F) << 6) |
+ (static_cast<unsigned int>(s[3]) & 0x3F);
+ s += 3;
+ // oversized encoded characters are invalid
+ return calculated < 0x10000 ? REPLACEMENT_CHARACTER : calculated;
+ }
+
+ return REPLACEMENT_CHARACTER;
+}
+
+static const char hex2[] = "000102030405060708090a0b0c0d0e0f"
+ "101112131415161718191a1b1c1d1e1f"
+ "202122232425262728292a2b2c2d2e2f"
+ "303132333435363738393a3b3c3d3e3f"
+ "404142434445464748494a4b4c4d4e4f"
+ "505152535455565758595a5b5c5d5e5f"
+ "606162636465666768696a6b6c6d6e6f"
+ "707172737475767778797a7b7c7d7e7f"
+ "808182838485868788898a8b8c8d8e8f"
+ "909192939495969798999a9b9c9d9e9f"
+ "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
+ "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
+ "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
+ "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
+ "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
+ "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff";
+
+static String toHex16Bit(unsigned int x) {
+ const unsigned int hi = (x >> 8) & 0xff;
+ const unsigned int lo = x & 0xff;
+ String result(4, ' ');
+ result[0] = hex2[2 * hi];
+ result[1] = hex2[2 * hi + 1];
+ result[2] = hex2[2 * lo];
+ result[3] = hex2[2 * lo + 1];
return result;
}
-// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
-static char const* strnpbrk(char const* s, char const* accept, size_t n) {
- assert((s || !n) && accept);
+static void appendRaw(String& result, unsigned ch) {
+ result += static_cast<char>(ch);
+}
- char const* const end = s + n;
- for (char const* cur = s; cur < end; ++cur) {
- int const c = *cur;
- for (char const* a = accept; *a; ++a) {
- if (*a == c) {
- return cur;
- }
- }
- }
- return NULL;
+static void appendHex(String& result, unsigned ch) {
+ result.append("\\u").append(toHex16Bit(ch));
}
-static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) {
- if (value == NULL)
+
+static String valueToQuotedStringN(const char* value, unsigned length,
+ bool emitUTF8 = false) {
+ if (value == nullptr)
return "";
- // Not sure how to handle unicode...
- if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
- !containsControlCharacter0(value, length))
- return JSONCPP_STRING("\"") + value + "\"";
+
+ if (!doesAnyCharRequireEscaping(value, length))
+ return String("\"") + value + "\"";
// We have to walk value and escape any special characters.
- // Appending to JSONCPP_STRING is not efficient, but this should be rare.
+ // Appending to String is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
- JSONCPP_STRING::size_type maxsize =
- length * 2 + 3; // allescaped+quotes+NULL
- JSONCPP_STRING result;
+ String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL
+ String result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
char const* end = value + length;
@@ -335,44 +316,63 @@ static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) {
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
- default:
- if ((isControlCharacter(*c)) || (*c == 0)) {
- JSONCPP_OSTRINGSTREAM oss;
- oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
- << std::setw(4) << static_cast<int>(*c);
- result += oss.str();
+ default: {
+ if (emitUTF8) {
+ unsigned codepoint = static_cast<unsigned char>(*c);
+ if (codepoint < 0x20) {
+ appendHex(result, codepoint);
+ } else {
+ appendRaw(result, codepoint);
+ }
} else {
- result += *c;
+ unsigned codepoint = utf8ToCodepoint(c, end); // modifies `c`
+ if (codepoint < 0x20) {
+ appendHex(result, codepoint);
+ } else if (codepoint < 0x80) {
+ appendRaw(result, codepoint);
+ } else if (codepoint < 0x10000) {
+ // Basic Multilingual Plane
+ appendHex(result, codepoint);
+ } else {
+ // Extended Unicode. Encode 20 bits as a surrogate pair.
+ codepoint -= 0x10000;
+ appendHex(result, 0xd800 + ((codepoint >> 10) & 0x3ff));
+ appendHex(result, 0xdc00 + (codepoint & 0x3ff));
+ }
}
- break;
+ } break;
}
}
result += "\"";
return result;
}
+String valueToQuotedString(const char* value) {
+ return valueToQuotedStringN(value, static_cast<unsigned int>(strlen(value)));
+}
+
// Class Writer
// //////////////////////////////////////////////////////////////////
-Writer::~Writer() {}
+Writer::~Writer() = default;
// Class FastWriter
// //////////////////////////////////////////////////////////////////
FastWriter::FastWriter()
- : yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false),
- omitEndingLineFeed_(false) {}
-void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
+ = default;
+
+void FastWriter::enableYAMLCompatibility() { yamlCompatibilityEnabled_ = true; }
void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
-JSONCPP_STRING FastWriter::write(const Value& root) {
+String FastWriter::write(const Value& root) {
document_.clear();
writeValue(root);
if (!omitEndingLineFeed_)
- document_ += "\n";
+ document_ += '\n';
return document_;
}
@@ -391,13 +391,13 @@ void FastWriter::writeValue(const Value& value) {
case realValue:
document_ += valueToString(value.asDouble());
break;
- case stringValue:
- {
+ case stringValue: {
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
- if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
+ if (ok)
+ document_ += valueToQuotedStringN(str, static_cast<unsigned>(end - str));
break;
}
case booleanValue:
@@ -416,13 +416,13 @@ void FastWriter::writeValue(const Value& value) {
case objectValue: {
Value::Members members(value.getMemberNames());
document_ += '{';
- for (Value::Members::iterator it = members.begin(); it != members.end();
- ++it) {
- const JSONCPP_STRING& name = *it;
+ for (auto it = members.begin(); it != members.end(); ++it) {
+ const String& name = *it;
if (it != members.begin())
document_ += ',';
- document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
- document_ += yamlCompatiblityEnabled_ ? ": " : ":";
+ document_ += valueToQuotedStringN(name.data(),
+ static_cast<unsigned>(name.length()));
+ document_ += yamlCompatibilityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
document_ += '}';
@@ -433,17 +433,16 @@ void FastWriter::writeValue(const Value& value) {
// Class StyledWriter
// //////////////////////////////////////////////////////////////////
-StyledWriter::StyledWriter()
- : rightMargin_(74), indentSize_(3), addChildValues_() {}
+StyledWriter::StyledWriter() = default;
-JSONCPP_STRING StyledWriter::write(const Value& root) {
+String StyledWriter::write(const Value& root) {
document_.clear();
addChildValues_ = false;
indentString_.clear();
writeCommentBeforeValue(root);
writeValue(root);
writeCommentAfterValueOnSameLine(root);
- document_ += "\n";
+ document_ += '\n';
return document_;
}
@@ -461,14 +460,15 @@ void StyledWriter::writeValue(const Value& value) {
case realValue:
pushValue(valueToString(value.asDouble()));
break;
- case stringValue:
- {
+ case stringValue: {
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
- if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
- else pushValue("");
+ if (ok)
+ pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
+ else
+ pushValue("");
break;
}
case booleanValue:
@@ -484,9 +484,9 @@ void StyledWriter::writeValue(const Value& value) {
else {
writeWithIndent("{");
indent();
- Value::Members::iterator it = members.begin();
+ auto it = members.begin();
for (;;) {
- const JSONCPP_STRING& name = *it;
+ const String& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
@@ -511,7 +511,7 @@ void StyledWriter::writeArrayValue(const Value& value) {
if (size == 0)
pushValue("[]");
else {
- bool isArrayMultiLine = isMultineArray(value);
+ bool isArrayMultiLine = isMultilineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
@@ -549,14 +549,14 @@ void StyledWriter::writeArrayValue(const Value& value) {
}
}
-bool StyledWriter::isMultineArray(const Value& value) {
+bool StyledWriter::isMultilineArray(const Value& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
- childValue.size() > 0);
+ !childValue.empty());
}
if (!isMultiLine) // check if line length > max line length
{
@@ -576,7 +576,7 @@ bool StyledWriter::isMultineArray(const Value& value) {
return isMultiLine;
}
-void StyledWriter::pushValue(const JSONCPP_STRING& value) {
+void StyledWriter::pushValue(const String& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -594,12 +594,12 @@ void StyledWriter::writeIndent() {
document_ += indentString_;
}
-void StyledWriter::writeWithIndent(const JSONCPP_STRING& value) {
+void StyledWriter::writeWithIndent(const String& value) {
writeIndent();
document_ += value;
}
-void StyledWriter::indent() { indentString_ += JSONCPP_STRING(indentSize_, ' '); }
+void StyledWriter::indent() { indentString_ += String(indentSize_, ' '); }
void StyledWriter::unindent() {
assert(indentString_.size() >= indentSize_);
@@ -610,20 +610,19 @@ void StyledWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
- document_ += "\n";
+ document_ += '\n';
writeIndent();
- const JSONCPP_STRING& comment = root.getComment(commentBefore);
- JSONCPP_STRING::const_iterator iter = comment.begin();
+ const String& comment = root.getComment(commentBefore);
+ String::const_iterator iter = comment.begin();
while (iter != comment.end()) {
document_ += *iter;
- if (*iter == '\n' &&
- (iter != comment.end() && *(iter + 1) == '/'))
+ if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
writeIndent();
++iter;
}
// Comments are stripped of trailing newlines, so add one here
- document_ += "\n";
+ document_ += '\n';
}
void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
@@ -631,9 +630,9 @@ void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
document_ += " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
- document_ += "\n";
+ document_ += '\n';
document_ += root.getComment(commentAfter);
- document_ += "\n";
+ document_ += '\n';
}
}
@@ -646,22 +645,23 @@ bool StyledWriter::hasCommentForValue(const Value& value) {
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
-StyledStreamWriter::StyledStreamWriter(JSONCPP_STRING indentation)
- : document_(NULL), rightMargin_(74), indentation_(indentation),
- addChildValues_() {}
+StyledStreamWriter::StyledStreamWriter(String indentation)
+ : document_(nullptr), indentation_(std::move(indentation)),
+ addChildValues_(), indented_(false) {}
-void StyledStreamWriter::write(JSONCPP_OSTREAM& out, const Value& root) {
+void StyledStreamWriter::write(OStream& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
indentString_.clear();
indented_ = true;
writeCommentBeforeValue(root);
- if (!indented_) writeIndent();
+ if (!indented_)
+ writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*document_ << "\n";
- document_ = NULL; // Forget the stream, for safety.
+ document_ = nullptr; // Forget the stream, for safety.
}
void StyledStreamWriter::writeValue(const Value& value) {
@@ -678,14 +678,15 @@ void StyledStreamWriter::writeValue(const Value& value) {
case realValue:
pushValue(valueToString(value.asDouble()));
break;
- case stringValue:
- {
+ case stringValue: {
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
- if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
- else pushValue("");
+ if (ok)
+ pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str)));
+ else
+ pushValue("");
break;
}
case booleanValue:
@@ -701,9 +702,9 @@ void StyledStreamWriter::writeValue(const Value& value) {
else {
writeWithIndent("{");
indent();
- Value::Members::iterator it = members.begin();
+ auto it = members.begin();
for (;;) {
- const JSONCPP_STRING& name = *it;
+ const String& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
@@ -728,7 +729,7 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
if (size == 0)
pushValue("[]");
else {
- bool isArrayMultiLine = isMultineArray(value);
+ bool isArrayMultiLine = isMultilineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
@@ -740,7 +741,8 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
- if (!indented_) writeIndent();
+ if (!indented_)
+ writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
@@ -768,14 +770,14 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
}
}
-bool StyledStreamWriter::isMultineArray(const Value& value) {
+bool StyledStreamWriter::isMultilineArray(const Value& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
- childValue.size() > 0);
+ !childValue.empty());
}
if (!isMultiLine) // check if line length > max line length
{
@@ -795,7 +797,7 @@ bool StyledStreamWriter::isMultineArray(const Value& value) {
return isMultiLine;
}
-void StyledStreamWriter::pushValue(const JSONCPP_STRING& value) {
+void StyledStreamWriter::pushValue(const String& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -810,8 +812,9 @@ void StyledStreamWriter::writeIndent() {
*document_ << '\n' << indentString_;
}
-void StyledStreamWriter::writeWithIndent(const JSONCPP_STRING& value) {
- if (!indented_) writeIndent();
+void StyledStreamWriter::writeWithIndent(const String& value) {
+ if (!indented_)
+ writeIndent();
*document_ << value;
indented_ = false;
}
@@ -827,13 +830,13 @@ void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
- if (!indented_) writeIndent();
- const JSONCPP_STRING& comment = root.getComment(commentBefore);
- JSONCPP_STRING::const_iterator iter = comment.begin();
+ if (!indented_)
+ writeIndent();
+ const String& comment = root.getComment(commentBefore);
+ String::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*document_ << *iter;
- if (*iter == '\n' &&
- (iter != comment.end() && *(iter + 1) == '/'))
+ if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would include newline
*document_ << indentString_;
++iter;
@@ -865,84 +868,73 @@ bool StyledStreamWriter::hasCommentForValue(const Value& value) {
struct CommentStyle {
/// Decide whether to write comments.
enum Enum {
- None, ///< Drop all comments.
- Most, ///< Recover odd behavior of previous versions (not implemented yet).
- All ///< Keep all comments.
+ None, ///< Drop all comments.
+ Most, ///< Recover odd behavior of previous versions (not implemented yet).
+ All ///< Keep all comments.
};
};
-struct BuiltStyledStreamWriter : public StreamWriter
-{
- BuiltStyledStreamWriter(
- JSONCPP_STRING const& indentation,
- CommentStyle::Enum cs,
- JSONCPP_STRING const& colonSymbol,
- JSONCPP_STRING const& nullSymbol,
- JSONCPP_STRING const& endingLineFeedSymbol,
- bool useSpecialFloats,
- unsigned int precision);
- int write(Value const& root, JSONCPP_OSTREAM* sout) JSONCPP_OVERRIDE;
+struct BuiltStyledStreamWriter : public StreamWriter {
+ BuiltStyledStreamWriter(String indentation, CommentStyle::Enum cs,
+ String colonSymbol, String nullSymbol,
+ String endingLineFeedSymbol, bool useSpecialFloats,
+ bool emitUTF8, unsigned int precision,
+ PrecisionType precisionType);
+ int write(Value const& root, OStream* sout) override;
+
private:
void writeValue(Value const& value);
void writeArrayValue(Value const& value);
- bool isMultineArray(Value const& value);
- void pushValue(JSONCPP_STRING const& value);
+ bool isMultilineArray(Value const& value);
+ void pushValue(String const& value);
void writeIndent();
- void writeWithIndent(JSONCPP_STRING const& value);
+ void writeWithIndent(String const& value);
void indent();
void unindent();
void writeCommentBeforeValue(Value const& root);
void writeCommentAfterValueOnSameLine(Value const& root);
static bool hasCommentForValue(const Value& value);
- typedef std::vector<JSONCPP_STRING> ChildValues;
+ using ChildValues = std::vector<String>;
ChildValues childValues_;
- JSONCPP_STRING indentString_;
+ String indentString_;
unsigned int rightMargin_;
- JSONCPP_STRING indentation_;
+ String indentation_;
CommentStyle::Enum cs_;
- JSONCPP_STRING colonSymbol_;
- JSONCPP_STRING nullSymbol_;
- JSONCPP_STRING endingLineFeedSymbol_;
+ String colonSymbol_;
+ String nullSymbol_;
+ String endingLineFeedSymbol_;
bool addChildValues_ : 1;
bool indented_ : 1;
bool useSpecialFloats_ : 1;
+ bool emitUTF8_ : 1;
unsigned int precision_;
+ PrecisionType precisionType_;
};
BuiltStyledStreamWriter::BuiltStyledStreamWriter(
- JSONCPP_STRING const& indentation,
- CommentStyle::Enum cs,
- JSONCPP_STRING const& colonSymbol,
- JSONCPP_STRING const& nullSymbol,
- JSONCPP_STRING const& endingLineFeedSymbol,
- bool useSpecialFloats,
- unsigned int precision)
- : rightMargin_(74)
- , indentation_(indentation)
- , cs_(cs)
- , colonSymbol_(colonSymbol)
- , nullSymbol_(nullSymbol)
- , endingLineFeedSymbol_(endingLineFeedSymbol)
- , addChildValues_(false)
- , indented_(false)
- , useSpecialFloats_(useSpecialFloats)
- , precision_(precision)
-{
-}
-int BuiltStyledStreamWriter::write(Value const& root, JSONCPP_OSTREAM* sout)
-{
+ String indentation, CommentStyle::Enum cs, String colonSymbol,
+ String nullSymbol, String endingLineFeedSymbol, bool useSpecialFloats,
+ bool emitUTF8, unsigned int precision, PrecisionType precisionType)
+ : rightMargin_(74), indentation_(std::move(indentation)), cs_(cs),
+ colonSymbol_(std::move(colonSymbol)), nullSymbol_(std::move(nullSymbol)),
+ endingLineFeedSymbol_(std::move(endingLineFeedSymbol)),
+ addChildValues_(false), indented_(false),
+ useSpecialFloats_(useSpecialFloats), emitUTF8_(emitUTF8),
+ precision_(precision), precisionType_(precisionType) {}
+int BuiltStyledStreamWriter::write(Value const& root, OStream* sout) {
sout_ = sout;
addChildValues_ = false;
indented_ = true;
indentString_.clear();
writeCommentBeforeValue(root);
- if (!indented_) writeIndent();
+ if (!indented_)
+ writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*sout_ << endingLineFeedSymbol_;
- sout_ = NULL;
+ sout_ = nullptr;
return 0;
}
void BuiltStyledStreamWriter::writeValue(Value const& value) {
@@ -957,16 +949,19 @@ void BuiltStyledStreamWriter::writeValue(Value const& value) {
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
- pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
+ pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_,
+ precisionType_));
break;
- case stringValue:
- {
+ case stringValue: {
// Is NULL is possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
- if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
- else pushValue("");
+ if (ok)
+ pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str),
+ emitUTF8_));
+ else
+ pushValue("");
break;
}
case booleanValue:
@@ -982,12 +977,13 @@ void BuiltStyledStreamWriter::writeValue(Value const& value) {
else {
writeWithIndent("{");
indent();
- Value::Members::iterator it = members.begin();
+ auto it = members.begin();
for (;;) {
- JSONCPP_STRING const& name = *it;
+ String const& name = *it;
Value const& childValue = value[name];
writeCommentBeforeValue(childValue);
- writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
+ writeWithIndent(valueToQuotedStringN(
+ name.data(), static_cast<unsigned>(name.length()), emitUTF8_));
*sout_ << colonSymbol_;
writeValue(childValue);
if (++it == members.end()) {
@@ -1009,7 +1005,7 @@ void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
if (size == 0)
pushValue("[]");
else {
- bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
+ bool isMultiLine = (cs_ == CommentStyle::All) || isMultilineArray(value);
if (isMultiLine) {
writeWithIndent("[");
indent();
@@ -1021,7 +1017,8 @@ void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
- if (!indented_) writeIndent();
+ if (!indented_)
+ writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
@@ -1039,26 +1036,28 @@ void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
{
assert(childValues_.size() == size);
*sout_ << "[";
- if (!indentation_.empty()) *sout_ << " ";
+ if (!indentation_.empty())
+ *sout_ << " ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*sout_ << ((!indentation_.empty()) ? ", " : ",");
*sout_ << childValues_[index];
}
- if (!indentation_.empty()) *sout_ << " ";
+ if (!indentation_.empty())
+ *sout_ << " ";
*sout_ << "]";
}
}
}
-bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
+bool BuiltStyledStreamWriter::isMultilineArray(Value const& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
Value const& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
- childValue.size() > 0);
+ !childValue.empty());
}
if (!isMultiLine) // check if line length > max line length
{
@@ -1078,7 +1077,7 @@ bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
return isMultiLine;
}
-void BuiltStyledStreamWriter::pushValue(JSONCPP_STRING const& value) {
+void BuiltStyledStreamWriter::pushValue(String const& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -1097,8 +1096,9 @@ void BuiltStyledStreamWriter::writeIndent() {
}
}
-void BuiltStyledStreamWriter::writeWithIndent(JSONCPP_STRING const& value) {
- if (!indented_) writeIndent();
+void BuiltStyledStreamWriter::writeWithIndent(String const& value) {
+ if (!indented_)
+ writeIndent();
*sout_ << value;
indented_ = false;
}
@@ -1111,17 +1111,18 @@ void BuiltStyledStreamWriter::unindent() {
}
void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
- if (cs_ == CommentStyle::None) return;
+ if (cs_ == CommentStyle::None)
+ return;
if (!root.hasComment(commentBefore))
return;
- if (!indented_) writeIndent();
- const JSONCPP_STRING& comment = root.getComment(commentBefore);
- JSONCPP_STRING::const_iterator iter = comment.begin();
+ if (!indented_)
+ writeIndent();
+ const String& comment = root.getComment(commentBefore);
+ String::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*sout_ << *iter;
- if (*iter == '\n' &&
- (iter != comment.end() && *(iter + 1) == '/'))
+ if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would write extra newline
*sout_ << indentString_;
++iter;
@@ -1129,8 +1130,10 @@ void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
indented_ = false;
}
-void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
- if (cs_ == CommentStyle::None) return;
+void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(
+ Value const& root) {
+ if (cs_ == CommentStyle::None)
+ return;
if (root.hasComment(commentAfterOnSameLine))
*sout_ << " " + root.getComment(commentAfterOnSameLine);
@@ -1150,28 +1153,19 @@ bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
///////////////
// StreamWriter
-StreamWriter::StreamWriter()
- : sout_(NULL)
-{
-}
-StreamWriter::~StreamWriter()
-{
-}
-StreamWriter::Factory::~Factory()
-{}
-StreamWriterBuilder::StreamWriterBuilder()
-{
- setDefaults(&settings_);
-}
-StreamWriterBuilder::~StreamWriterBuilder()
-{}
-StreamWriter* StreamWriterBuilder::newStreamWriter() const
-{
- JSONCPP_STRING indentation = settings_["indentation"].asString();
- JSONCPP_STRING cs_str = settings_["commentStyle"].asString();
- bool eyc = settings_["enableYAMLCompatibility"].asBool();
- bool dnp = settings_["dropNullPlaceholders"].asBool();
- bool usf = settings_["useSpecialFloats"].asBool();
+StreamWriter::StreamWriter() : sout_(nullptr) {}
+StreamWriter::~StreamWriter() = default;
+StreamWriter::Factory::~Factory() = default;
+StreamWriterBuilder::StreamWriterBuilder() { setDefaults(&settings_); }
+StreamWriterBuilder::~StreamWriterBuilder() = default;
+StreamWriter* StreamWriterBuilder::newStreamWriter() const {
+ const String indentation = settings_["indentation"].asString();
+ const String cs_str = settings_["commentStyle"].asString();
+ const String pt_str = settings_["precisionType"].asString();
+ const bool eyc = settings_["enableYAMLCompatibility"].asBool();
+ const bool dnp = settings_["dropNullPlaceholders"].asBool();
+ const bool usf = settings_["useSpecialFloats"].asBool();
+ const bool emitUTF8 = settings_["emitUTF8"].asBool();
unsigned int pre = settings_["precision"].asUInt();
CommentStyle::Enum cs = CommentStyle::All;
if (cs_str == "All") {
@@ -1181,74 +1175,80 @@ StreamWriter* StreamWriterBuilder::newStreamWriter() const
} else {
throwRuntimeError("commentStyle must be 'All' or 'None'");
}
- JSONCPP_STRING colonSymbol = " : ";
+ PrecisionType precisionType(significantDigits);
+ if (pt_str == "significant") {
+ precisionType = PrecisionType::significantDigits;
+ } else if (pt_str == "decimal") {
+ precisionType = PrecisionType::decimalPlaces;
+ } else {
+ throwRuntimeError("precisionType must be 'significant' or 'decimal'");
+ }
+ String colonSymbol = " : ";
if (eyc) {
colonSymbol = ": ";
} else if (indentation.empty()) {
colonSymbol = ":";
}
- JSONCPP_STRING nullSymbol = "null";
+ String nullSymbol = "null";
if (dnp) {
nullSymbol.clear();
}
- if (pre > 17) pre = 17;
- JSONCPP_STRING endingLineFeedSymbol;
- return new BuiltStyledStreamWriter(
- indentation, cs,
- colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
+ if (pre > 17)
+ pre = 17;
+ String endingLineFeedSymbol;
+ return new BuiltStyledStreamWriter(indentation, cs, colonSymbol, nullSymbol,
+ endingLineFeedSymbol, usf, emitUTF8, pre,
+ precisionType);
}
-static void getValidWriterKeys(std::set<JSONCPP_STRING>* valid_keys)
-{
- valid_keys->clear();
- valid_keys->insert("indentation");
- valid_keys->insert("commentStyle");
- valid_keys->insert("enableYAMLCompatibility");
- valid_keys->insert("dropNullPlaceholders");
- valid_keys->insert("useSpecialFloats");
- valid_keys->insert("precision");
-}
-bool StreamWriterBuilder::validate(Json::Value* invalid) const
-{
- Json::Value my_invalid;
- if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
- Json::Value& inv = *invalid;
- std::set<JSONCPP_STRING> valid_keys;
- getValidWriterKeys(&valid_keys);
- Value::Members keys = settings_.getMemberNames();
- size_t n = keys.size();
- for (size_t i = 0; i < n; ++i) {
- JSONCPP_STRING const& key = keys[i];
- if (valid_keys.find(key) == valid_keys.end()) {
- inv[key] = settings_[key];
- }
+
+bool StreamWriterBuilder::validate(Json::Value* invalid) const {
+ static const auto& valid_keys = *new std::set<String>{
+ "indentation",
+ "commentStyle",
+ "enableYAMLCompatibility",
+ "dropNullPlaceholders",
+ "useSpecialFloats",
+ "emitUTF8",
+ "precision",
+ "precisionType",
+ };
+ for (auto si = settings_.begin(); si != settings_.end(); ++si) {
+ auto key = si.name();
+ if (valid_keys.count(key))
+ continue;
+ if (invalid)
+ (*invalid)[std::move(key)] = *si;
+ else
+ return false;
}
- return 0u == inv.size();
+ return invalid ? invalid->empty() : true;
}
-Value& StreamWriterBuilder::operator[](JSONCPP_STRING key)
-{
+
+Value& StreamWriterBuilder::operator[](const String& key) {
return settings_[key];
}
// static
-void StreamWriterBuilder::setDefaults(Json::Value* settings)
-{
+void StreamWriterBuilder::setDefaults(Json::Value* settings) {
//! [StreamWriterBuilderDefaults]
(*settings)["commentStyle"] = "All";
(*settings)["indentation"] = "\t";
(*settings)["enableYAMLCompatibility"] = false;
(*settings)["dropNullPlaceholders"] = false;
(*settings)["useSpecialFloats"] = false;
+ (*settings)["emitUTF8"] = false;
(*settings)["precision"] = 17;
+ (*settings)["precisionType"] = "significant";
//! [StreamWriterBuilderDefaults]
}
-JSONCPP_STRING writeString(StreamWriter::Factory const& builder, Value const& root) {
- JSONCPP_OSTRINGSTREAM sout;
- StreamWriterPtr const writer(builder.newStreamWriter());
+String writeString(StreamWriter::Factory const& factory, Value const& root) {
+ OStringStream sout;
+ StreamWriterPtr const writer(factory.newStreamWriter());
writer->write(root, &sout);
return sout.str();
}
-JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM& sout, Value const& root) {
+OStream& operator<<(OStream& sout, Value const& root) {
StreamWriterBuilder builder;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
diff --git a/Utilities/cmlibarchive/CMakeLists.txt b/Utilities/cmlibarchive/CMakeLists.txt
index 79452ff..ba65470 100644
--- a/Utilities/cmlibarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/CMakeLists.txt
@@ -171,32 +171,32 @@ IF (MSVC)
# This is added into CMAKE_C_FLAGS when CMAKE_BUILD_TYPE is "Debug"
# Enable level 4 C4062: The enumerate has no associated handler in a switch
# statement and there is no default that can catch it.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4062")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14062")
# Enable level 4 C4254: A larger bit field was assigned to a smaller bit
# field.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4254")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14254")
# Enable level 4 C4295: An array was initialized but the last character in
# the array is not a null; accessing the array may
# produce unexpected results.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4295")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14295")
# Enable level 4 C4296: An unsigned variable was used in a comparison
# operation with zero.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4296")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14296")
# Enable level 4 C4389: An operation involved signed and unsigned variables.
# This could result in a loss of data.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4389")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14389")
# Enable level 4 C4505: The given function is local and not referenced in
# the body of the module; therefore, the function is
# dead code.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4505")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14505")
# Enable level 4 C4514: The optimizer removed an inline function that is not
# called.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4514")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14514")
# Enable level 4 C4702: Unreachable code.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4702")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14702")
# Enable level 4 C4706: The test value in a conditional expression was the
# result of an assignment.
- SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4706")
+ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /w14706")
# /Oi option enables built-in functions.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /Oi")
#################################################################
@@ -1404,6 +1404,7 @@ CHECK_FUNCTION_EXISTS_GLIBC(strchr HAVE_STRCHR)
CHECK_FUNCTION_EXISTS_GLIBC(strdup HAVE_STRDUP)
CHECK_FUNCTION_EXISTS_GLIBC(strerror HAVE_STRERROR)
CHECK_FUNCTION_EXISTS_GLIBC(strncpy_s HAVE_STRNCPY_S)
+CHECK_FUNCTION_EXISTS_GLIBC(strnlen HAVE_STRNLEN)
CHECK_FUNCTION_EXISTS_GLIBC(strrchr HAVE_STRRCHR)
CHECK_FUNCTION_EXISTS_GLIBC(symlink HAVE_SYMLINK)
CHECK_FUNCTION_EXISTS_GLIBC(timegm HAVE_TIMEGM)
@@ -1475,15 +1476,19 @@ CHECK_C_SOURCE_COMPILES(
"#include <sys/sysmacros.h>\nint main() { return major(256); }"
MAJOR_IN_SYSMACROS)
+IF(ENABLE_LZMA)
CMAKE_PUSH_CHECK_STATE()
SET(CMAKE_REQUIRED_LIBRARIES ${LIBLZMA_LIBRARIES})
SET(CMAKE_REQUIRED_INCLUDES ${LIBLZMA_INCLUDE_DIR})
CHECK_C_SOURCE_COMPILES(
"#include <lzma.h>\n#if LZMA_VERSION < 50020000\n#error unsupported\n#endif\nint main(void){lzma_stream_encoder_mt(0, 0); return 0;}"
-HAVE_LZMA_STREAM_ENCODER_MT)
+ HAVE_LZMA_STREAM_ENCODER_MT)
CMAKE_POP_CHECK_STATE()
+ELSE()
+ SET(HAVE_LZMA_STREAM_ENCODER_MT 0)
+ENDIF(ENABLE_LZMA)
IF(HAVE_STRERROR_R)
SET(HAVE_DECL_STRERROR_R 1)
@@ -2007,6 +2012,11 @@ IF(MSVC)
ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE)
ENDIF(MSVC)
+IF(APPLE)
+ # CC_MD5_Init() functions are deprecated on macOS 10.15, but we want to use them
+ ADD_DEFINITIONS(-Wno-deprecated-declarations)
+ENDIF(APPLE)
+
IF(0) # CMake does not build libarchive's tests.
IF(ENABLE_TEST)
ADD_CUSTOM_TARGET(run_all_tests)
diff --git a/Utilities/cmlibarchive/COPYING b/Utilities/cmlibarchive/COPYING
index 14bbefa..1b97235 100644
--- a/Utilities/cmlibarchive/COPYING
+++ b/Utilities/cmlibarchive/COPYING
@@ -15,7 +15,6 @@ the actual statements in the files are controlling.
* The following source files are also subject in whole or in part to
a 3-clause UC Regents copyright; please read the individual source
files for details:
- libarchive/archive_entry.c
libarchive/archive_read_support_filter_compress.c
libarchive/archive_write_add_filter_compress.c
libarchive/mtree.5
diff --git a/Utilities/cmlibarchive/build/cmake/CreatePkgConfigFile.cmake b/Utilities/cmlibarchive/build/cmake/CreatePkgConfigFile.cmake
index fc8529a..bc5a43f 100644
--- a/Utilities/cmlibarchive/build/cmake/CreatePkgConfigFile.cmake
+++ b/Utilities/cmlibarchive/build/cmake/CreatePkgConfigFile.cmake
@@ -24,10 +24,10 @@ ENDFOREACH()
# thus there's a good chance it'll make some binutils versions unhappy...
# This only affects Libs.private (looked up for static builds) though.
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/pkgconfig/libarchive.pc.in
- ${CMAKE_CURRENT_SOURCE_DIR}/build/pkgconfig/libarchive.pc
+ ${CMAKE_CURRENT_BINARY_DIR}/build/pkgconfig/libarchive.pc
@ONLY)
# And install it, of course ;).
IF(ENABLE_INSTALL)
- INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/build/pkgconfig/libarchive.pc
+ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/build/pkgconfig/libarchive.pc
DESTINATION "lib/pkgconfig")
ENDIF()
diff --git a/Utilities/cmlibarchive/build/cmake/config.h.in b/Utilities/cmlibarchive/build/cmake/config.h.in
index f38601f..9bd2667 100644
--- a/Utilities/cmlibarchive/build/cmake/config.h.in
+++ b/Utilities/cmlibarchive/build/cmake/config.h.in
@@ -1,4 +1,5 @@
/* config.h. Generated from build/cmake/config.h.in by cmake configure */
+#define __LIBARCHIVE_CONFIG_H_INCLUDED 1
#if defined(__osf__)
# define _OSF_SOURCE
#endif
@@ -742,6 +743,9 @@
/* Define to 1 if you have the `strchr' function. */
#cmakedefine HAVE_STRCHR 1
+/* Define to 1 if you have the `strnlen' function. */
+#cmakedefine HAVE_STRNLEN 1
+
/* Define to 1 if you have the `strdup' function. */
#cmakedefine HAVE_STRDUP 1
diff --git a/Utilities/cmlibarchive/build/version b/Utilities/cmlibarchive/build/version
index 78be3ab..205791c 100644
--- a/Utilities/cmlibarchive/build/version
+++ b/Utilities/cmlibarchive/build/version
@@ -1 +1 @@
-3004002
+3005001
diff --git a/Utilities/cmlibarchive/libarchive/archive.h b/Utilities/cmlibarchive/libarchive/archive.h
index 574e087..a1f0b87 100644
--- a/Utilities/cmlibarchive/libarchive/archive.h
+++ b/Utilities/cmlibarchive/libarchive/archive.h
@@ -36,7 +36,7 @@
* assert that ARCHIVE_VERSION_NUMBER >= 2012108.
*/
/* Note: Compiler will complain if this does not match archive_entry.h! */
-#define ARCHIVE_VERSION_NUMBER 3004002
+#define ARCHIVE_VERSION_NUMBER 3005001
#include <sys/stat.h>
#include <stddef.h> /* for wchar_t */
@@ -152,7 +152,7 @@ __LA_DECL int archive_version_number(void);
/*
* Textual name/version of the library, useful for version displays.
*/
-#define ARCHIVE_VERSION_ONLY_STRING "3.4.2"
+#define ARCHIVE_VERSION_ONLY_STRING "3.5.1"
#define ARCHIVE_VERSION_STRING "libarchive " ARCHIVE_VERSION_ONLY_STRING
__LA_DECL const char * archive_version_string(void);
@@ -243,6 +243,8 @@ typedef int archive_open_callback(struct archive *, void *_client_data);
typedef int archive_close_callback(struct archive *, void *_client_data);
+typedef int archive_free_callback(struct archive *, void *_client_data);
+
/* Switches from one client data object to the next/prev client data object.
* This is useful for reading from different data blocks such as a set of files
* that make up one large file.
@@ -415,6 +417,7 @@ __LA_DECL int archive_read_support_compression_xz(struct archive *)
#endif
__LA_DECL int archive_read_support_filter_all(struct archive *);
+__LA_DECL int archive_read_support_filter_by_code(struct archive *, int);
__LA_DECL int archive_read_support_filter_bzip2(struct archive *);
__LA_DECL int archive_read_support_filter_compress(struct archive *);
__LA_DECL int archive_read_support_filter_gzip(struct archive *);
@@ -814,9 +817,13 @@ __LA_DECL int archive_write_set_format_filter_by_ext(struct archive *a, const ch
__LA_DECL int archive_write_set_format_filter_by_ext_def(struct archive *a, const char *filename, const char * def_ext);
__LA_DECL int archive_write_zip_set_compression_deflate(struct archive *);
__LA_DECL int archive_write_zip_set_compression_store(struct archive *);
+/* Deprecated; use archive_write_open2 instead */
__LA_DECL int archive_write_open(struct archive *, void *,
archive_open_callback *, archive_write_callback *,
archive_close_callback *);
+__LA_DECL int archive_write_open2(struct archive *, void *,
+ archive_open_callback *, archive_write_callback *,
+ archive_close_callback *, archive_free_callback *);
__LA_DECL int archive_write_open_fd(struct archive *, int _fd);
__LA_DECL int archive_write_open_filename(struct archive *, const char *_file);
__LA_DECL int archive_write_open_filename_w(struct archive *,
diff --git a/Utilities/cmlibarchive/libarchive/archive_acl.c b/Utilities/cmlibarchive/libarchive/archive_acl.c
index 952e20d..ead7e36 100644
--- a/Utilities/cmlibarchive/libarchive/archive_acl.c
+++ b/Utilities/cmlibarchive/libarchive/archive_acl.c
@@ -595,7 +595,7 @@ archive_acl_text_len(struct archive_acl *acl, int want_type, int flags,
else
length += sizeof(uid_t) * 3 + 1;
} else {
- r = archive_mstring_get_mbs_l(&ap->name, &name,
+ r = archive_mstring_get_mbs_l(a, &ap->name, &name,
&len, sc);
if (r != 0)
return (0);
@@ -968,7 +968,7 @@ archive_acl_to_text_l(struct archive_acl *acl, ssize_t *text_len, int flags,
else
prefix = NULL;
r = archive_mstring_get_mbs_l(
- &ap->name, &name, &len, sc);
+ NULL, &ap->name, &name, &len, sc);
if (r != 0) {
free(s);
return (NULL);
@@ -1402,14 +1402,14 @@ isint_w(const wchar_t *start, const wchar_t *end, int *result)
if (start >= end)
return (0);
while (start < end) {
- if (*start < '0' || *start > '9')
+ if (*start < L'0' || *start > L'9')
return (0);
if (n > (INT_MAX / 10) ||
- (n == INT_MAX / 10 && (*start - '0') > INT_MAX % 10)) {
+ (n == INT_MAX / 10 && (*start - L'0') > INT_MAX % 10)) {
n = INT_MAX;
} else {
n *= 10;
- n += *start - '0';
+ n += *start - L'0';
}
start++;
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_check_magic.c b/Utilities/cmlibarchive/libarchive/archive_check_magic.c
index 288ce23..1f40072 100644
--- a/Utilities/cmlibarchive/libarchive/archive_check_magic.c
+++ b/Utilities/cmlibarchive/libarchive/archive_check_magic.c
@@ -54,7 +54,7 @@ errmsg(const char *m)
ssize_t written;
while (s > 0) {
- written = write(2, m, strlen(m));
+ written = write(2, m, s);
if (written <= 0)
return;
m += written;
diff --git a/Utilities/cmlibarchive/libarchive/archive_cryptor.c b/Utilities/cmlibarchive/libarchive/archive_cryptor.c
index 8ab2b09..d4bca90 100644
--- a/Utilities/cmlibarchive/libarchive/archive_cryptor.c
+++ b/Utilities/cmlibarchive/libarchive/archive_cryptor.c
@@ -347,8 +347,31 @@ aes_ctr_init(archive_crypto_ctx *ctx, const uint8_t *key, size_t key_len)
static int
aes_ctr_encrypt_counter(archive_crypto_ctx *ctx)
{
+#if NETTLE_VERSION_MAJOR < 3
aes_set_encrypt_key(&ctx->ctx, ctx->key_len, ctx->key);
aes_encrypt(&ctx->ctx, AES_BLOCK_SIZE, ctx->encr_buf, ctx->nonce);
+#else
+ switch(ctx->key_len) {
+ case AES128_KEY_SIZE:
+ aes128_set_encrypt_key(&ctx->ctx.c128, ctx->key);
+ aes128_encrypt(&ctx->ctx.c128, AES_BLOCK_SIZE, ctx->encr_buf,
+ ctx->nonce);
+ break;
+ case AES192_KEY_SIZE:
+ aes192_set_encrypt_key(&ctx->ctx.c192, ctx->key);
+ aes192_encrypt(&ctx->ctx.c192, AES_BLOCK_SIZE, ctx->encr_buf,
+ ctx->nonce);
+ break;
+ case AES256_KEY_SIZE:
+ aes256_set_encrypt_key(&ctx->ctx.c256, ctx->key);
+ aes256_encrypt(&ctx->ctx.c256, AES_BLOCK_SIZE, ctx->encr_buf,
+ ctx->nonce);
+ break;
+ default:
+ return -1;
+ break;
+ }
+#endif
return 0;
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h b/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h
index 64a2055..16b6d16 100644
--- a/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_cryptor_private.h
@@ -104,9 +104,18 @@ typedef struct {
#include <nettle/pbkdf2.h>
#endif
#include <nettle/aes.h>
+#include <nettle/version.h>
typedef struct {
+#if NETTLE_VERSION_MAJOR < 3
struct aes_ctx ctx;
+#else
+ union {
+ struct aes128_ctx c128;
+ struct aes192_ctx c192;
+ struct aes256_ctx c256;
+ } ctx;
+#endif
uint8_t key[AES_MAX_KEY_SIZE];
unsigned key_len;
uint8_t nonce[AES_BLOCK_SIZE];
diff --git a/Utilities/cmlibarchive/libarchive/archive_digest.c b/Utilities/cmlibarchive/libarchive/archive_digest.c
index 34c58ac..410df01 100644
--- a/Utilities/cmlibarchive/libarchive/archive_digest.c
+++ b/Utilities/cmlibarchive/libarchive/archive_digest.c
@@ -109,14 +109,14 @@ win_crypto_Final(unsigned char *buf, size_t bufsize, Digest_CTX *ctx)
#if defined(ARCHIVE_CRYPTO_MD5_LIBC)
static int
-__archive_libc_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
MD5Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
MD5Update(ctx, indata, insize);
@@ -124,7 +124,7 @@ __archive_libc_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_libc_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
MD5Final(md, ctx);
return (ARCHIVE_OK);
@@ -133,14 +133,14 @@ __archive_libc_md5final(archive_md5_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_MD5_LIBMD)
static int
-__archive_libmd_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
MD5Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libmd_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
MD5Update(ctx, indata, insize);
@@ -148,7 +148,7 @@ __archive_libmd_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_libmd_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
MD5Final(md, ctx);
return (ARCHIVE_OK);
@@ -157,14 +157,14 @@ __archive_libmd_md5final(archive_md5_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_MD5_LIBSYSTEM)
static int
-__archive_libsystem_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
CC_MD5_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libsystem_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
CC_MD5_Update(ctx, indata, insize);
@@ -172,7 +172,7 @@ __archive_libsystem_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_libsystem_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
CC_MD5_Final(md, ctx);
return (ARCHIVE_OK);
@@ -181,7 +181,7 @@ __archive_libsystem_md5final(archive_md5_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_MD5_MBEDTLS)
static int
-__archive_mbedtls_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
mbedtls_md5_init(ctx);
if (mbedtls_md5_starts_ret(ctx) == 0)
@@ -191,7 +191,7 @@ __archive_mbedtls_md5init(archive_md5_ctx *ctx)
}
static int
-__archive_mbedtls_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
if (mbedtls_md5_update_ret(ctx, indata, insize) == 0)
@@ -201,7 +201,7 @@ __archive_mbedtls_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_mbedtls_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
if (mbedtls_md5_finish_ret(ctx, md) == 0) {
mbedtls_md5_free(ctx);
@@ -215,14 +215,14 @@ __archive_mbedtls_md5final(archive_md5_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_MD5_NETTLE)
static int
-__archive_nettle_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
md5_init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_nettle_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
md5_update(ctx, insize, indata);
@@ -230,7 +230,7 @@ __archive_nettle_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_nettle_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
md5_digest(ctx, MD5_DIGEST_SIZE, md);
return (ARCHIVE_OK);
@@ -239,7 +239,7 @@ __archive_nettle_md5final(archive_md5_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_MD5_OPENSSL)
static int
-__archive_openssl_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
if ((*ctx = EVP_MD_CTX_new()) == NULL)
return (ARCHIVE_FAILED);
@@ -248,7 +248,7 @@ __archive_openssl_md5init(archive_md5_ctx *ctx)
}
static int
-__archive_openssl_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
EVP_DigestUpdate(*ctx, indata, insize);
@@ -256,7 +256,7 @@ __archive_openssl_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_openssl_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
/* HACK: archive_write_set_format_xar.c is finalizing empty contexts, so
* this is meant to cope with that. Real fix is probably to fix
@@ -273,20 +273,20 @@ __archive_openssl_md5final(archive_md5_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_MD5_WIN)
static int
-__archive_windowsapi_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
return (win_crypto_init(ctx, CALG_MD5));
}
static int
-__archive_windowsapi_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
return (win_crypto_Update(ctx, indata, insize));
}
static int
-__archive_windowsapi_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
return (win_crypto_Final(md, 16, ctx));
}
@@ -294,14 +294,14 @@ __archive_windowsapi_md5final(archive_md5_ctx *ctx, void *md)
#else
static int
-__archive_stub_md5init(archive_md5_ctx *ctx)
+__archive_md5init(archive_md5_ctx *ctx)
{
(void)ctx; /* UNUSED */
return (ARCHIVE_FAILED);
}
static int
-__archive_stub_md5update(archive_md5_ctx *ctx, const void *indata,
+__archive_md5update(archive_md5_ctx *ctx, const void *indata,
size_t insize)
{
(void)ctx; /* UNUSED */
@@ -311,7 +311,7 @@ __archive_stub_md5update(archive_md5_ctx *ctx, const void *indata,
}
static int
-__archive_stub_md5final(archive_md5_ctx *ctx, void *md)
+__archive_md5final(archive_md5_ctx *ctx, void *md)
{
(void)ctx; /* UNUSED */
(void)md; /* UNUSED */
@@ -324,14 +324,14 @@ __archive_stub_md5final(archive_md5_ctx *ctx, void *md)
#if defined(ARCHIVE_CRYPTO_RMD160_LIBC)
static int
-__archive_libc_ripemd160init(archive_rmd160_ctx *ctx)
+__archive_ripemd160init(archive_rmd160_ctx *ctx)
{
RMD160Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
+__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
RMD160Update(ctx, indata, insize);
@@ -339,7 +339,7 @@ __archive_libc_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
}
static int
-__archive_libc_ripemd160final(archive_rmd160_ctx *ctx, void *md)
+__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
RMD160Final(md, ctx);
return (ARCHIVE_OK);
@@ -348,14 +348,14 @@ __archive_libc_ripemd160final(archive_rmd160_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_RMD160_LIBMD)
static int
-__archive_libmd_ripemd160init(archive_rmd160_ctx *ctx)
+__archive_ripemd160init(archive_rmd160_ctx *ctx)
{
RIPEMD160_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libmd_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
+__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
RIPEMD160_Update(ctx, indata, insize);
@@ -363,7 +363,7 @@ __archive_libmd_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
}
static int
-__archive_libmd_ripemd160final(archive_rmd160_ctx *ctx, void *md)
+__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
RIPEMD160_Final(md, ctx);
return (ARCHIVE_OK);
@@ -372,7 +372,7 @@ __archive_libmd_ripemd160final(archive_rmd160_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_RMD160_MBEDTLS)
static int
-__archive_mbedtls_ripemd160init(archive_rmd160_ctx *ctx)
+__archive_ripemd160init(archive_rmd160_ctx *ctx)
{
mbedtls_ripemd160_init(ctx);
if (mbedtls_ripemd160_starts_ret(ctx) == 0)
@@ -382,7 +382,7 @@ __archive_mbedtls_ripemd160init(archive_rmd160_ctx *ctx)
}
static int
-__archive_mbedtls_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
+__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
if (mbedtls_ripemd160_update_ret(ctx, indata, insize) == 0)
@@ -392,7 +392,7 @@ __archive_mbedtls_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
}
static int
-__archive_mbedtls_ripemd160final(archive_rmd160_ctx *ctx, void *md)
+__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
if (mbedtls_ripemd160_finish_ret(ctx, md) == 0) {
mbedtls_ripemd160_free(ctx);
@@ -406,14 +406,14 @@ __archive_mbedtls_ripemd160final(archive_rmd160_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_RMD160_NETTLE)
static int
-__archive_nettle_ripemd160init(archive_rmd160_ctx *ctx)
+__archive_ripemd160init(archive_rmd160_ctx *ctx)
{
ripemd160_init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_nettle_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
+__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
ripemd160_update(ctx, insize, indata);
@@ -421,7 +421,7 @@ __archive_nettle_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
}
static int
-__archive_nettle_ripemd160final(archive_rmd160_ctx *ctx, void *md)
+__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
ripemd160_digest(ctx, RIPEMD160_DIGEST_SIZE, md);
return (ARCHIVE_OK);
@@ -430,7 +430,7 @@ __archive_nettle_ripemd160final(archive_rmd160_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_RMD160_OPENSSL)
static int
-__archive_openssl_ripemd160init(archive_rmd160_ctx *ctx)
+__archive_ripemd160init(archive_rmd160_ctx *ctx)
{
if ((*ctx = EVP_MD_CTX_new()) == NULL)
return (ARCHIVE_FAILED);
@@ -439,7 +439,7 @@ __archive_openssl_ripemd160init(archive_rmd160_ctx *ctx)
}
static int
-__archive_openssl_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
+__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
EVP_DigestUpdate(*ctx, indata, insize);
@@ -447,7 +447,7 @@ __archive_openssl_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
}
static int
-__archive_openssl_ripemd160final(archive_rmd160_ctx *ctx, void *md)
+__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
if (*ctx) {
EVP_DigestFinal(*ctx, md, NULL);
@@ -460,14 +460,14 @@ __archive_openssl_ripemd160final(archive_rmd160_ctx *ctx, void *md)
#else
static int
-__archive_stub_ripemd160init(archive_rmd160_ctx *ctx)
+__archive_ripemd160init(archive_rmd160_ctx *ctx)
{
(void)ctx; /* UNUSED */
return (ARCHIVE_FAILED);
}
static int
-__archive_stub_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
+__archive_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
size_t insize)
{
(void)ctx; /* UNUSED */
@@ -477,7 +477,7 @@ __archive_stub_ripemd160update(archive_rmd160_ctx *ctx, const void *indata,
}
static int
-__archive_stub_ripemd160final(archive_rmd160_ctx *ctx, void *md)
+__archive_ripemd160final(archive_rmd160_ctx *ctx, void *md)
{
(void)ctx; /* UNUSED */
(void)md; /* UNUSED */
@@ -490,14 +490,14 @@ __archive_stub_ripemd160final(archive_rmd160_ctx *ctx, void *md)
#if defined(ARCHIVE_CRYPTO_SHA1_LIBC)
static int
-__archive_libc_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
SHA1Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
SHA1Update(ctx, indata, insize);
@@ -505,7 +505,7 @@ __archive_libc_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_libc_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
SHA1Final(md, ctx);
return (ARCHIVE_OK);
@@ -514,14 +514,14 @@ __archive_libc_sha1final(archive_sha1_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA1_LIBMD)
static int
-__archive_libmd_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
SHA1_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libmd_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
SHA1_Update(ctx, indata, insize);
@@ -529,7 +529,7 @@ __archive_libmd_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_libmd_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
SHA1_Final(md, ctx);
return (ARCHIVE_OK);
@@ -538,14 +538,14 @@ __archive_libmd_sha1final(archive_sha1_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA1_LIBSYSTEM)
static int
-__archive_libsystem_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
CC_SHA1_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libsystem_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
CC_SHA1_Update(ctx, indata, insize);
@@ -553,7 +553,7 @@ __archive_libsystem_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_libsystem_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
CC_SHA1_Final(md, ctx);
return (ARCHIVE_OK);
@@ -562,7 +562,7 @@ __archive_libsystem_sha1final(archive_sha1_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA1_MBEDTLS)
static int
-__archive_mbedtls_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
mbedtls_sha1_init(ctx);
if (mbedtls_sha1_starts_ret(ctx) == 0)
@@ -572,7 +572,7 @@ __archive_mbedtls_sha1init(archive_sha1_ctx *ctx)
}
static int
-__archive_mbedtls_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
if (mbedtls_sha1_update_ret(ctx, indata, insize) == 0)
@@ -582,7 +582,7 @@ __archive_mbedtls_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_mbedtls_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
if (mbedtls_sha1_finish_ret(ctx, md) == 0) {
mbedtls_sha1_free(ctx);
@@ -596,14 +596,14 @@ __archive_mbedtls_sha1final(archive_sha1_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA1_NETTLE)
static int
-__archive_nettle_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
sha1_init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_nettle_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
sha1_update(ctx, insize, indata);
@@ -611,7 +611,7 @@ __archive_nettle_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_nettle_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
sha1_digest(ctx, SHA1_DIGEST_SIZE, md);
return (ARCHIVE_OK);
@@ -620,7 +620,7 @@ __archive_nettle_sha1final(archive_sha1_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA1_OPENSSL)
static int
-__archive_openssl_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
if ((*ctx = EVP_MD_CTX_new()) == NULL)
return (ARCHIVE_FAILED);
@@ -629,7 +629,7 @@ __archive_openssl_sha1init(archive_sha1_ctx *ctx)
}
static int
-__archive_openssl_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
EVP_DigestUpdate(*ctx, indata, insize);
@@ -637,7 +637,7 @@ __archive_openssl_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_openssl_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
/* HACK: archive_write_set_format_xar.c is finalizing empty contexts, so
* this is meant to cope with that. Real fix is probably to fix
@@ -654,20 +654,20 @@ __archive_openssl_sha1final(archive_sha1_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA1_WIN)
static int
-__archive_windowsapi_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
return (win_crypto_init(ctx, CALG_SHA1));
}
static int
-__archive_windowsapi_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
return (win_crypto_Update(ctx, indata, insize));
}
static int
-__archive_windowsapi_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
return (win_crypto_Final(md, 20, ctx));
}
@@ -675,14 +675,14 @@ __archive_windowsapi_sha1final(archive_sha1_ctx *ctx, void *md)
#else
static int
-__archive_stub_sha1init(archive_sha1_ctx *ctx)
+__archive_sha1init(archive_sha1_ctx *ctx)
{
(void)ctx; /* UNUSED */
return (ARCHIVE_FAILED);
}
static int
-__archive_stub_sha1update(archive_sha1_ctx *ctx, const void *indata,
+__archive_sha1update(archive_sha1_ctx *ctx, const void *indata,
size_t insize)
{
(void)ctx; /* UNUSED */
@@ -692,7 +692,7 @@ __archive_stub_sha1update(archive_sha1_ctx *ctx, const void *indata,
}
static int
-__archive_stub_sha1final(archive_sha1_ctx *ctx, void *md)
+__archive_sha1final(archive_sha1_ctx *ctx, void *md)
{
(void)ctx; /* UNUSED */
(void)md; /* UNUSED */
@@ -705,14 +705,14 @@ __archive_stub_sha1final(archive_sha1_ctx *ctx, void *md)
#if defined(ARCHIVE_CRYPTO_SHA256_LIBC)
static int
-__archive_libc_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
SHA256_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
SHA256_Update(ctx, indata, insize);
@@ -720,7 +720,7 @@ __archive_libc_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_libc_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
SHA256_Final(md, ctx);
return (ARCHIVE_OK);
@@ -729,14 +729,14 @@ __archive_libc_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC2)
static int
-__archive_libc2_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
SHA256Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc2_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
SHA256Update(ctx, indata, insize);
@@ -744,7 +744,7 @@ __archive_libc2_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_libc2_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
SHA256Final(md, ctx);
return (ARCHIVE_OK);
@@ -753,14 +753,14 @@ __archive_libc2_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC3)
static int
-__archive_libc3_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
SHA256Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc3_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
SHA256Update(ctx, indata, insize);
@@ -768,7 +768,7 @@ __archive_libc3_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_libc3_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
SHA256Final(md, ctx);
return (ARCHIVE_OK);
@@ -777,14 +777,14 @@ __archive_libc3_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_LIBMD)
static int
-__archive_libmd_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
SHA256_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libmd_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
SHA256_Update(ctx, indata, insize);
@@ -792,7 +792,7 @@ __archive_libmd_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_libmd_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
SHA256_Final(md, ctx);
return (ARCHIVE_OK);
@@ -801,14 +801,14 @@ __archive_libmd_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_LIBSYSTEM)
static int
-__archive_libsystem_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
CC_SHA256_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libsystem_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
CC_SHA256_Update(ctx, indata, insize);
@@ -816,7 +816,7 @@ __archive_libsystem_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_libsystem_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
CC_SHA256_Final(md, ctx);
return (ARCHIVE_OK);
@@ -825,7 +825,7 @@ __archive_libsystem_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_MBEDTLS)
static int
-__archive_mbedtls_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
mbedtls_sha256_init(ctx);
if (mbedtls_sha256_starts_ret(ctx, 0) == 0)
@@ -835,7 +835,7 @@ __archive_mbedtls_sha256init(archive_sha256_ctx *ctx)
}
static int
-__archive_mbedtls_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
if (mbedtls_sha256_update_ret(ctx, indata, insize) == 0)
@@ -845,7 +845,7 @@ __archive_mbedtls_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_mbedtls_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
if (mbedtls_sha256_finish_ret(ctx, md) == 0) {
mbedtls_sha256_free(ctx);
@@ -859,14 +859,14 @@ __archive_mbedtls_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_NETTLE)
static int
-__archive_nettle_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
sha256_init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_nettle_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
sha256_update(ctx, insize, indata);
@@ -874,7 +874,7 @@ __archive_nettle_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_nettle_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
sha256_digest(ctx, SHA256_DIGEST_SIZE, md);
return (ARCHIVE_OK);
@@ -883,7 +883,7 @@ __archive_nettle_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_OPENSSL)
static int
-__archive_openssl_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
if ((*ctx = EVP_MD_CTX_new()) == NULL)
return (ARCHIVE_FAILED);
@@ -892,7 +892,7 @@ __archive_openssl_sha256init(archive_sha256_ctx *ctx)
}
static int
-__archive_openssl_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
EVP_DigestUpdate(*ctx, indata, insize);
@@ -900,7 +900,7 @@ __archive_openssl_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_openssl_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
if (*ctx) {
EVP_DigestFinal(*ctx, md, NULL);
@@ -913,20 +913,20 @@ __archive_openssl_sha256final(archive_sha256_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA256_WIN)
static int
-__archive_windowsapi_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
return (win_crypto_init(ctx, CALG_SHA_256));
}
static int
-__archive_windowsapi_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
return (win_crypto_Update(ctx, indata, insize));
}
static int
-__archive_windowsapi_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
return (win_crypto_Final(md, 32, ctx));
}
@@ -934,14 +934,14 @@ __archive_windowsapi_sha256final(archive_sha256_ctx *ctx, void *md)
#else
static int
-__archive_stub_sha256init(archive_sha256_ctx *ctx)
+__archive_sha256init(archive_sha256_ctx *ctx)
{
(void)ctx; /* UNUSED */
return (ARCHIVE_FAILED);
}
static int
-__archive_stub_sha256update(archive_sha256_ctx *ctx, const void *indata,
+__archive_sha256update(archive_sha256_ctx *ctx, const void *indata,
size_t insize)
{
(void)ctx; /* UNUSED */
@@ -951,7 +951,7 @@ __archive_stub_sha256update(archive_sha256_ctx *ctx, const void *indata,
}
static int
-__archive_stub_sha256final(archive_sha256_ctx *ctx, void *md)
+__archive_sha256final(archive_sha256_ctx *ctx, void *md)
{
(void)ctx; /* UNUSED */
(void)md; /* UNUSED */
@@ -964,14 +964,14 @@ __archive_stub_sha256final(archive_sha256_ctx *ctx, void *md)
#if defined(ARCHIVE_CRYPTO_SHA384_LIBC)
static int
-__archive_libc_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
SHA384_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
SHA384_Update(ctx, indata, insize);
@@ -979,7 +979,7 @@ __archive_libc_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_libc_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
SHA384_Final(md, ctx);
return (ARCHIVE_OK);
@@ -988,14 +988,14 @@ __archive_libc_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC2)
static int
-__archive_libc2_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
SHA384Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc2_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
SHA384Update(ctx, indata, insize);
@@ -1003,7 +1003,7 @@ __archive_libc2_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_libc2_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
SHA384Final(md, ctx);
return (ARCHIVE_OK);
@@ -1012,14 +1012,14 @@ __archive_libc2_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC3)
static int
-__archive_libc3_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
SHA384Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc3_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
SHA384Update(ctx, indata, insize);
@@ -1027,7 +1027,7 @@ __archive_libc3_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_libc3_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
SHA384Final(md, ctx);
return (ARCHIVE_OK);
@@ -1036,14 +1036,14 @@ __archive_libc3_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_LIBSYSTEM)
static int
-__archive_libsystem_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
CC_SHA384_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libsystem_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
CC_SHA384_Update(ctx, indata, insize);
@@ -1051,7 +1051,7 @@ __archive_libsystem_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_libsystem_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
CC_SHA384_Final(md, ctx);
return (ARCHIVE_OK);
@@ -1060,7 +1060,7 @@ __archive_libsystem_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_MBEDTLS)
static int
-__archive_mbedtls_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
mbedtls_sha512_init(ctx);
if (mbedtls_sha512_starts_ret(ctx, 1) == 0)
@@ -1070,7 +1070,7 @@ __archive_mbedtls_sha384init(archive_sha384_ctx *ctx)
}
static int
-__archive_mbedtls_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
if (mbedtls_sha512_update_ret(ctx, indata, insize) == 0)
@@ -1080,7 +1080,7 @@ __archive_mbedtls_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_mbedtls_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
if (mbedtls_sha512_finish_ret(ctx, md) == 0) {
mbedtls_sha512_free(ctx);
@@ -1094,14 +1094,14 @@ __archive_mbedtls_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_NETTLE)
static int
-__archive_nettle_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
sha384_init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_nettle_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
sha384_update(ctx, insize, indata);
@@ -1109,7 +1109,7 @@ __archive_nettle_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_nettle_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
sha384_digest(ctx, SHA384_DIGEST_SIZE, md);
return (ARCHIVE_OK);
@@ -1118,7 +1118,7 @@ __archive_nettle_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_OPENSSL)
static int
-__archive_openssl_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
if ((*ctx = EVP_MD_CTX_new()) == NULL)
return (ARCHIVE_FAILED);
@@ -1127,7 +1127,7 @@ __archive_openssl_sha384init(archive_sha384_ctx *ctx)
}
static int
-__archive_openssl_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
EVP_DigestUpdate(*ctx, indata, insize);
@@ -1135,7 +1135,7 @@ __archive_openssl_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_openssl_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
if (*ctx) {
EVP_DigestFinal(*ctx, md, NULL);
@@ -1148,20 +1148,20 @@ __archive_openssl_sha384final(archive_sha384_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA384_WIN)
static int
-__archive_windowsapi_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
return (win_crypto_init(ctx, CALG_SHA_384));
}
static int
-__archive_windowsapi_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
return (win_crypto_Update(ctx, indata, insize));
}
static int
-__archive_windowsapi_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
return (win_crypto_Final(md, 48, ctx));
}
@@ -1169,14 +1169,14 @@ __archive_windowsapi_sha384final(archive_sha384_ctx *ctx, void *md)
#else
static int
-__archive_stub_sha384init(archive_sha384_ctx *ctx)
+__archive_sha384init(archive_sha384_ctx *ctx)
{
(void)ctx; /* UNUSED */
return (ARCHIVE_FAILED);
}
static int
-__archive_stub_sha384update(archive_sha384_ctx *ctx, const void *indata,
+__archive_sha384update(archive_sha384_ctx *ctx, const void *indata,
size_t insize)
{
(void)ctx; /* UNUSED */
@@ -1186,7 +1186,7 @@ __archive_stub_sha384update(archive_sha384_ctx *ctx, const void *indata,
}
static int
-__archive_stub_sha384final(archive_sha384_ctx *ctx, void *md)
+__archive_sha384final(archive_sha384_ctx *ctx, void *md)
{
(void)ctx; /* UNUSED */
(void)md; /* UNUSED */
@@ -1199,14 +1199,14 @@ __archive_stub_sha384final(archive_sha384_ctx *ctx, void *md)
#if defined(ARCHIVE_CRYPTO_SHA512_LIBC)
static int
-__archive_libc_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
SHA512_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
SHA512_Update(ctx, indata, insize);
@@ -1214,7 +1214,7 @@ __archive_libc_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_libc_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
SHA512_Final(md, ctx);
return (ARCHIVE_OK);
@@ -1223,14 +1223,14 @@ __archive_libc_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC2)
static int
-__archive_libc2_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
SHA512Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc2_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
SHA512Update(ctx, indata, insize);
@@ -1238,7 +1238,7 @@ __archive_libc2_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_libc2_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
SHA512Final(md, ctx);
return (ARCHIVE_OK);
@@ -1247,14 +1247,14 @@ __archive_libc2_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC3)
static int
-__archive_libc3_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
SHA512Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libc3_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
SHA512Update(ctx, indata, insize);
@@ -1262,7 +1262,7 @@ __archive_libc3_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_libc3_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
SHA512Final(md, ctx);
return (ARCHIVE_OK);
@@ -1271,14 +1271,14 @@ __archive_libc3_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_LIBMD)
static int
-__archive_libmd_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
SHA512_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libmd_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
SHA512_Update(ctx, indata, insize);
@@ -1286,7 +1286,7 @@ __archive_libmd_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_libmd_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
SHA512_Final(md, ctx);
return (ARCHIVE_OK);
@@ -1295,14 +1295,14 @@ __archive_libmd_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_LIBSYSTEM)
static int
-__archive_libsystem_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
CC_SHA512_Init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_libsystem_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
CC_SHA512_Update(ctx, indata, insize);
@@ -1310,7 +1310,7 @@ __archive_libsystem_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_libsystem_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
CC_SHA512_Final(md, ctx);
return (ARCHIVE_OK);
@@ -1319,7 +1319,7 @@ __archive_libsystem_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_MBEDTLS)
static int
-__archive_mbedtls_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
mbedtls_sha512_init(ctx);
if (mbedtls_sha512_starts_ret(ctx, 0) == 0)
@@ -1329,7 +1329,7 @@ __archive_mbedtls_sha512init(archive_sha512_ctx *ctx)
}
static int
-__archive_mbedtls_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
if (mbedtls_sha512_update_ret(ctx, indata, insize) == 0)
@@ -1339,7 +1339,7 @@ __archive_mbedtls_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_mbedtls_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
if (mbedtls_sha512_finish_ret(ctx, md) == 0) {
mbedtls_sha512_free(ctx);
@@ -1353,14 +1353,14 @@ __archive_mbedtls_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_NETTLE)
static int
-__archive_nettle_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
sha512_init(ctx);
return (ARCHIVE_OK);
}
static int
-__archive_nettle_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
sha512_update(ctx, insize, indata);
@@ -1368,7 +1368,7 @@ __archive_nettle_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_nettle_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
sha512_digest(ctx, SHA512_DIGEST_SIZE, md);
return (ARCHIVE_OK);
@@ -1377,7 +1377,7 @@ __archive_nettle_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_OPENSSL)
static int
-__archive_openssl_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
if ((*ctx = EVP_MD_CTX_new()) == NULL)
return (ARCHIVE_FAILED);
@@ -1386,7 +1386,7 @@ __archive_openssl_sha512init(archive_sha512_ctx *ctx)
}
static int
-__archive_openssl_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
EVP_DigestUpdate(*ctx, indata, insize);
@@ -1394,7 +1394,7 @@ __archive_openssl_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_openssl_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
if (*ctx) {
EVP_DigestFinal(*ctx, md, NULL);
@@ -1407,20 +1407,20 @@ __archive_openssl_sha512final(archive_sha512_ctx *ctx, void *md)
#elif defined(ARCHIVE_CRYPTO_SHA512_WIN)
static int
-__archive_windowsapi_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
return (win_crypto_init(ctx, CALG_SHA_512));
}
static int
-__archive_windowsapi_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
return (win_crypto_Update(ctx, indata, insize));
}
static int
-__archive_windowsapi_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
return (win_crypto_Final(md, 64, ctx));
}
@@ -1428,14 +1428,14 @@ __archive_windowsapi_sha512final(archive_sha512_ctx *ctx, void *md)
#else
static int
-__archive_stub_sha512init(archive_sha512_ctx *ctx)
+__archive_sha512init(archive_sha512_ctx *ctx)
{
(void)ctx; /* UNUSED */
return (ARCHIVE_FAILED);
}
static int
-__archive_stub_sha512update(archive_sha512_ctx *ctx, const void *indata,
+__archive_sha512update(archive_sha512_ctx *ctx, const void *indata,
size_t insize)
{
(void)ctx; /* UNUSED */
@@ -1445,7 +1445,7 @@ __archive_stub_sha512update(archive_sha512_ctx *ctx, const void *indata,
}
static int
-__archive_stub_sha512final(archive_sha512_ctx *ctx, void *md)
+__archive_sha512final(archive_sha512_ctx *ctx, void *md)
{
(void)ctx; /* UNUSED */
(void)md; /* UNUSED */
@@ -1468,224 +1468,32 @@ __archive_stub_sha512final(archive_sha512_ctx *ctx, void *md)
const struct archive_digest __archive_digest =
{
/* MD5 */
-#if defined(ARCHIVE_CRYPTO_MD5_LIBC)
- &__archive_libc_md5init,
- &__archive_libc_md5update,
- &__archive_libc_md5final,
-#elif defined(ARCHIVE_CRYPTO_MD5_LIBMD)
- &__archive_libmd_md5init,
- &__archive_libmd_md5update,
- &__archive_libmd_md5final,
-#elif defined(ARCHIVE_CRYPTO_MD5_LIBSYSTEM)
- &__archive_libsystem_md5init,
- &__archive_libsystem_md5update,
- &__archive_libsystem_md5final,
-#elif defined(ARCHIVE_CRYPTO_MD5_MBEDTLS)
- &__archive_mbedtls_md5init,
- &__archive_mbedtls_md5update,
- &__archive_mbedtls_md5final,
-#elif defined(ARCHIVE_CRYPTO_MD5_NETTLE)
- &__archive_nettle_md5init,
- &__archive_nettle_md5update,
- &__archive_nettle_md5final,
-#elif defined(ARCHIVE_CRYPTO_MD5_OPENSSL)
- &__archive_openssl_md5init,
- &__archive_openssl_md5update,
- &__archive_openssl_md5final,
-#elif defined(ARCHIVE_CRYPTO_MD5_WIN)
- &__archive_windowsapi_md5init,
- &__archive_windowsapi_md5update,
- &__archive_windowsapi_md5final,
-#elif !defined(ARCHIVE_MD5_COMPILE_TEST)
- &__archive_stub_md5init,
- &__archive_stub_md5update,
- &__archive_stub_md5final,
-#endif
+ &__archive_md5init,
+ &__archive_md5update,
+ &__archive_md5final,
/* RIPEMD160 */
-#if defined(ARCHIVE_CRYPTO_RMD160_LIBC)
- &__archive_libc_ripemd160init,
- &__archive_libc_ripemd160update,
- &__archive_libc_ripemd160final,
-#elif defined(ARCHIVE_CRYPTO_RMD160_LIBMD)
- &__archive_libmd_ripemd160init,
- &__archive_libmd_ripemd160update,
- &__archive_libmd_ripemd160final,
-#elif defined(ARCHIVE_CRYPTO_RMD160_MBEDTLS)
- &__archive_mbedtls_ripemd160init,
- &__archive_mbedtls_ripemd160update,
- &__archive_mbedtls_ripemd160final,
-#elif defined(ARCHIVE_CRYPTO_RMD160_NETTLE)
- &__archive_nettle_ripemd160init,
- &__archive_nettle_ripemd160update,
- &__archive_nettle_ripemd160final,
-#elif defined(ARCHIVE_CRYPTO_RMD160_OPENSSL)
- &__archive_openssl_ripemd160init,
- &__archive_openssl_ripemd160update,
- &__archive_openssl_ripemd160final,
-#elif !defined(ARCHIVE_RMD160_COMPILE_TEST)
- &__archive_stub_ripemd160init,
- &__archive_stub_ripemd160update,
- &__archive_stub_ripemd160final,
-#endif
+ &__archive_ripemd160init,
+ &__archive_ripemd160update,
+ &__archive_ripemd160final,
/* SHA1 */
-#if defined(ARCHIVE_CRYPTO_SHA1_LIBC)
- &__archive_libc_sha1init,
- &__archive_libc_sha1update,
- &__archive_libc_sha1final,
-#elif defined(ARCHIVE_CRYPTO_SHA1_LIBMD)
- &__archive_libmd_sha1init,
- &__archive_libmd_sha1update,
- &__archive_libmd_sha1final,
-#elif defined(ARCHIVE_CRYPTO_SHA1_LIBSYSTEM)
- &__archive_libsystem_sha1init,
- &__archive_libsystem_sha1update,
- &__archive_libsystem_sha1final,
-#elif defined(ARCHIVE_CRYPTO_SHA1_MBEDTLS)
- &__archive_mbedtls_sha1init,
- &__archive_mbedtls_sha1update,
- &__archive_mbedtls_sha1final,
-#elif defined(ARCHIVE_CRYPTO_SHA1_NETTLE)
- &__archive_nettle_sha1init,
- &__archive_nettle_sha1update,
- &__archive_nettle_sha1final,
-#elif defined(ARCHIVE_CRYPTO_SHA1_OPENSSL)
- &__archive_openssl_sha1init,
- &__archive_openssl_sha1update,
- &__archive_openssl_sha1final,
-#elif defined(ARCHIVE_CRYPTO_SHA1_WIN)
- &__archive_windowsapi_sha1init,
- &__archive_windowsapi_sha1update,
- &__archive_windowsapi_sha1final,
-#elif !defined(ARCHIVE_SHA1_COMPILE_TEST)
- &__archive_stub_sha1init,
- &__archive_stub_sha1update,
- &__archive_stub_sha1final,
-#endif
+ &__archive_sha1init,
+ &__archive_sha1update,
+ &__archive_sha1final,
/* SHA256 */
-#if defined(ARCHIVE_CRYPTO_SHA256_LIBC)
- &__archive_libc_sha256init,
- &__archive_libc_sha256update,
- &__archive_libc_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC2)
- &__archive_libc2_sha256init,
- &__archive_libc2_sha256update,
- &__archive_libc2_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_LIBC3)
- &__archive_libc3_sha256init,
- &__archive_libc3_sha256update,
- &__archive_libc3_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_LIBMD)
- &__archive_libmd_sha256init,
- &__archive_libmd_sha256update,
- &__archive_libmd_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_LIBSYSTEM)
- &__archive_libsystem_sha256init,
- &__archive_libsystem_sha256update,
- &__archive_libsystem_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_MBEDTLS)
- &__archive_mbedtls_sha256init,
- &__archive_mbedtls_sha256update,
- &__archive_mbedtls_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_NETTLE)
- &__archive_nettle_sha256init,
- &__archive_nettle_sha256update,
- &__archive_nettle_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_OPENSSL)
- &__archive_openssl_sha256init,
- &__archive_openssl_sha256update,
- &__archive_openssl_sha256final,
-#elif defined(ARCHIVE_CRYPTO_SHA256_WIN)
- &__archive_windowsapi_sha256init,
- &__archive_windowsapi_sha256update,
- &__archive_windowsapi_sha256final,
-#elif !defined(ARCHIVE_SHA256_COMPILE_TEST)
- &__archive_stub_sha256init,
- &__archive_stub_sha256update,
- &__archive_stub_sha256final,
-#endif
+ &__archive_sha256init,
+ &__archive_sha256update,
+ &__archive_sha256final,
/* SHA384 */
-#if defined(ARCHIVE_CRYPTO_SHA384_LIBC)
- &__archive_libc_sha384init,
- &__archive_libc_sha384update,
- &__archive_libc_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC2)
- &__archive_libc2_sha384init,
- &__archive_libc2_sha384update,
- &__archive_libc2_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_LIBC3)
- &__archive_libc3_sha384init,
- &__archive_libc3_sha384update,
- &__archive_libc3_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_LIBSYSTEM)
- &__archive_libsystem_sha384init,
- &__archive_libsystem_sha384update,
- &__archive_libsystem_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_MBEDTLS)
- &__archive_mbedtls_sha384init,
- &__archive_mbedtls_sha384update,
- &__archive_mbedtls_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_NETTLE)
- &__archive_nettle_sha384init,
- &__archive_nettle_sha384update,
- &__archive_nettle_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_OPENSSL)
- &__archive_openssl_sha384init,
- &__archive_openssl_sha384update,
- &__archive_openssl_sha384final,
-#elif defined(ARCHIVE_CRYPTO_SHA384_WIN)
- &__archive_windowsapi_sha384init,
- &__archive_windowsapi_sha384update,
- &__archive_windowsapi_sha384final,
-#elif !defined(ARCHIVE_SHA384_COMPILE_TEST)
- &__archive_stub_sha384init,
- &__archive_stub_sha384update,
- &__archive_stub_sha384final,
-#endif
+ &__archive_sha384init,
+ &__archive_sha384update,
+ &__archive_sha384final,
/* SHA512 */
-#if defined(ARCHIVE_CRYPTO_SHA512_LIBC)
- &__archive_libc_sha512init,
- &__archive_libc_sha512update,
- &__archive_libc_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC2)
- &__archive_libc2_sha512init,
- &__archive_libc2_sha512update,
- &__archive_libc2_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_LIBC3)
- &__archive_libc3_sha512init,
- &__archive_libc3_sha512update,
- &__archive_libc3_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_LIBMD)
- &__archive_libmd_sha512init,
- &__archive_libmd_sha512update,
- &__archive_libmd_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_LIBSYSTEM)
- &__archive_libsystem_sha512init,
- &__archive_libsystem_sha512update,
- &__archive_libsystem_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_MBEDTLS)
- &__archive_mbedtls_sha512init,
- &__archive_mbedtls_sha512update,
- &__archive_mbedtls_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_NETTLE)
- &__archive_nettle_sha512init,
- &__archive_nettle_sha512update,
- &__archive_nettle_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_OPENSSL)
- &__archive_openssl_sha512init,
- &__archive_openssl_sha512update,
- &__archive_openssl_sha512final
-#elif defined(ARCHIVE_CRYPTO_SHA512_WIN)
- &__archive_windowsapi_sha512init,
- &__archive_windowsapi_sha512update,
- &__archive_windowsapi_sha512final
-#elif !defined(ARCHIVE_SHA512_COMPILE_TEST)
- &__archive_stub_sha512init,
- &__archive_stub_sha512update,
- &__archive_stub_sha512final
-#endif
+ &__archive_sha512init,
+ &__archive_sha512update,
+ &__archive_sha512final
};
diff --git a/Utilities/cmlibarchive/libarchive/archive_digest_private.h b/Utilities/cmlibarchive/libarchive/archive_digest_private.h
index 15312ee..9b3bd66 100644
--- a/Utilities/cmlibarchive/libarchive/archive_digest_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_digest_private.h
@@ -30,6 +30,10 @@
#ifndef __LIBARCHIVE_BUILD
#error This header is only to be used internally to libarchive.
#endif
+#ifndef __LIBARCHIVE_CONFIG_H_INCLUDED
+#error "Should have include config.h first!"
+#endif
+
/*
* Crypto support in various Operating Systems:
*
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry.c b/Utilities/cmlibarchive/libarchive/archive_entry.c
index a15e98c..ca7a4bd 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry.c
+++ b/Utilities/cmlibarchive/libarchive/archive_entry.c
@@ -208,6 +208,19 @@ archive_entry_clone(struct archive_entry *entry)
/* Copy encryption status */
entry2->encryption = entry->encryption;
+
+ /* Copy digests */
+#define copy_digest(_e2, _e, _t) \
+ memcpy(_e2->digest._t, _e->digest._t, sizeof(_e2->digest._t))
+
+ copy_digest(entry2, entry, md5);
+ copy_digest(entry2, entry, rmd160);
+ copy_digest(entry2, entry, sha1);
+ copy_digest(entry2, entry, sha256);
+ copy_digest(entry2, entry, sha384);
+ copy_digest(entry2, entry, sha512);
+
+#undef copy_digest
/* Copy ACL data over. */
archive_acl_copy(&entry2->acl, &entry->acl);
@@ -353,7 +366,7 @@ archive_entry_devminor(struct archive_entry *entry)
return minor(entry->ae_stat.aest_dev);
}
-mode_t
+__LA_MODE_T
archive_entry_filetype(struct archive_entry *entry)
{
return (AE_IFMT & entry->acl.mode);
@@ -450,7 +463,7 @@ int
_archive_entry_gname_l(struct archive_entry *entry,
const char **p, size_t *len, struct archive_string_conv *sc)
{
- return (archive_mstring_get_mbs_l(&entry->ae_gname, p, len, sc));
+ return (archive_mstring_get_mbs_l(entry->archive, &entry->ae_gname, p, len, sc));
}
const char *
@@ -504,7 +517,7 @@ _archive_entry_hardlink_l(struct archive_entry *entry,
*len = 0;
return (0);
}
- return (archive_mstring_get_mbs_l(&entry->ae_hardlink, p, len, sc));
+ return (archive_mstring_get_mbs_l(entry->archive, &entry->ae_hardlink, p, len, sc));
}
la_int64_t
@@ -525,7 +538,7 @@ archive_entry_ino64(struct archive_entry *entry)
return (entry->ae_stat.aest_ino);
}
-mode_t
+__LA_MODE_T
archive_entry_mode(struct archive_entry *entry)
{
return (entry->acl.mode);
@@ -595,10 +608,10 @@ int
_archive_entry_pathname_l(struct archive_entry *entry,
const char **p, size_t *len, struct archive_string_conv *sc)
{
- return (archive_mstring_get_mbs_l(&entry->ae_pathname, p, len, sc));
+ return (archive_mstring_get_mbs_l(entry->archive, &entry->ae_pathname, p, len, sc));
}
-mode_t
+__LA_MODE_T
archive_entry_perm(struct archive_entry *entry)
{
return (~AE_IFMT & entry->acl.mode);
@@ -723,7 +736,7 @@ _archive_entry_symlink_l(struct archive_entry *entry,
*len = 0;
return (0);
}
- return (archive_mstring_get_mbs_l( &entry->ae_symlink, p, len, sc));
+ return (archive_mstring_get_mbs_l(entry->archive, &entry->ae_symlink, p, len, sc));
}
la_int64_t
@@ -769,7 +782,7 @@ int
_archive_entry_uname_l(struct archive_entry *entry,
const char **p, size_t *len, struct archive_string_conv *sc)
{
- return (archive_mstring_get_mbs_l(&entry->ae_uname, p, len, sc));
+ return (archive_mstring_get_mbs_l(entry->archive, &entry->ae_uname, p, len, sc));
}
int
@@ -1416,6 +1429,62 @@ archive_entry_copy_mac_metadata(struct archive_entry *entry,
}
}
+/* Digest handling */
+const unsigned char *
+archive_entry_digest(struct archive_entry *entry, int type)
+{
+ switch (type) {
+ case ARCHIVE_ENTRY_DIGEST_MD5:
+ return entry->digest.md5;
+ case ARCHIVE_ENTRY_DIGEST_RMD160:
+ return entry->digest.rmd160;
+ case ARCHIVE_ENTRY_DIGEST_SHA1:
+ return entry->digest.sha1;
+ case ARCHIVE_ENTRY_DIGEST_SHA256:
+ return entry->digest.sha256;
+ case ARCHIVE_ENTRY_DIGEST_SHA384:
+ return entry->digest.sha384;
+ case ARCHIVE_ENTRY_DIGEST_SHA512:
+ return entry->digest.sha512;
+ default:
+ return NULL;
+ }
+}
+
+int
+archive_entry_set_digest(struct archive_entry *entry, int type,
+ const unsigned char *digest)
+{
+#define copy_digest(_e, _t, _d)\
+ memcpy(_e->digest._t, _d, sizeof(_e->digest._t))
+
+ switch (type) {
+ case ARCHIVE_ENTRY_DIGEST_MD5:
+ copy_digest(entry, md5, digest);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_RMD160:
+ copy_digest(entry, rmd160, digest);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA1:
+ copy_digest(entry, sha1, digest);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA256:
+ copy_digest(entry, sha256, digest);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA384:
+ copy_digest(entry, sha384, digest);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA512:
+ copy_digest(entry, sha512, digest);
+ break;
+ default:
+ return ARCHIVE_WARN;
+ }
+
+ return ARCHIVE_OK;
+#undef copy_digest
+}
+
/*
* ACL management. The following would, of course, be a lot simpler
* if: 1) the last draft of POSIX.1e were a really thorough and
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry.h b/Utilities/cmlibarchive/libarchive/archive_entry.h
index 0053faa..21e89d2 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry.h
+++ b/Utilities/cmlibarchive/libarchive/archive_entry.h
@@ -30,7 +30,7 @@
#define ARCHIVE_ENTRY_H_INCLUDED
/* Note: Compiler will complain if this does not match archive.h! */
-#define ARCHIVE_VERSION_NUMBER 3004002
+#define ARCHIVE_VERSION_NUMBER 3005001
/*
* Note: archive_entry.h is for use outside of libarchive; the
@@ -394,6 +394,19 @@ __LA_DECL const void * archive_entry_mac_metadata(struct archive_entry *, size_t
__LA_DECL void archive_entry_copy_mac_metadata(struct archive_entry *, const void *, size_t);
/*
+ * Digest routine. This is used to query the raw hex digest for the
+ * given entry. The type of digest is provided as an argument.
+ */
+#define ARCHIVE_ENTRY_DIGEST_MD5 0x00000001
+#define ARCHIVE_ENTRY_DIGEST_RMD160 0x00000002
+#define ARCHIVE_ENTRY_DIGEST_SHA1 0x00000003
+#define ARCHIVE_ENTRY_DIGEST_SHA256 0x00000004
+#define ARCHIVE_ENTRY_DIGEST_SHA384 0x00000005
+#define ARCHIVE_ENTRY_DIGEST_SHA512 0x00000006
+
+__LA_DECL const unsigned char * archive_entry_digest(struct archive_entry *, int /* type */);
+
+/*
* ACL routines. This used to simply store and return text-format ACL
* strings, but that proved insufficient for a number of reasons:
* = clients need control over uname/uid and gname/gid mappings
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry_private.h b/Utilities/cmlibarchive/libarchive/archive_entry_private.h
index 2b9a084..cf4deb2 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_entry_private.h
@@ -50,6 +50,15 @@ struct ae_sparse {
int64_t length;
};
+struct ae_digest {
+ unsigned char md5[16];
+ unsigned char rmd160[20];
+ unsigned char sha1[20];
+ unsigned char sha256[32];
+ unsigned char sha384[48];
+ unsigned char sha512[64];
+};
+
/*
* Description of an archive entry.
*
@@ -162,6 +171,9 @@ struct archive_entry {
void *mac_metadata;
size_t mac_metadata_size;
+ /* Digest support. */
+ struct ae_digest digest;
+
/* ACL support. */
struct archive_acl acl;
@@ -181,4 +193,8 @@ struct archive_entry {
int ae_symlink_type;
};
+int
+archive_entry_set_digest(struct archive_entry *entry, int type,
+ const unsigned char *digest);
+
#endif /* ARCHIVE_ENTRY_PRIVATE_H_INCLUDED */
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry_stat.3 b/Utilities/cmlibarchive/libarchive/archive_entry_stat.3
index aa5c8e0..29a53f7 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry_stat.3
+++ b/Utilities/cmlibarchive/libarchive/archive_entry_stat.3
@@ -215,9 +215,9 @@ and
set and unset the size, respectively.
.Pp
The number of references (hardlinks) can be obtained by calling
-.Fn archive_entry_nlinks
+.Fn archive_entry_nlink
and set with
-.Fn archive_entry_set_nlinks .
+.Fn archive_entry_set_nlink .
.Ss Identifying unique files
The functions
.Fn archive_entry_dev
diff --git a/Utilities/cmlibarchive/libarchive/archive_ppmd7.c b/Utilities/cmlibarchive/libarchive/archive_ppmd7.c
index 4029395..cc3f778 100644
--- a/Utilities/cmlibarchive/libarchive/archive_ppmd7.c
+++ b/Utilities/cmlibarchive/libarchive/archive_ppmd7.c
@@ -4,7 +4,7 @@ This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#include "archive_platform.h"
-#include <memory.h>
+#include <stdlib.h>
#include "archive_ppmd7_private.h"
diff --git a/Utilities/cmlibarchive/libarchive/archive_read.c b/Utilities/cmlibarchive/libarchive/archive_read.c
index 4a933b2..c59f051 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read.c
@@ -892,15 +892,16 @@ archive_read_data(struct archive *_a, void *buff, size_t s)
len = a->read_data_remaining;
if (len > s)
len = s;
- if (len)
+ if (len) {
memcpy(dest, a->read_data_block, len);
- s -= len;
- a->read_data_block += len;
- a->read_data_remaining -= len;
- a->read_data_output_offset += len;
- a->read_data_offset += len;
- dest += len;
- bytes_read += len;
+ s -= len;
+ a->read_data_block += len;
+ a->read_data_remaining -= len;
+ a->read_data_output_offset += len;
+ a->read_data_offset += len;
+ dest += len;
+ bytes_read += len;
+ }
}
}
a->read_data_is_posix_read = 0;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_add_passphrase.c b/Utilities/cmlibarchive/libarchive/archive_read_add_passphrase.c
index cf821b5..f0b1ab9 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_add_passphrase.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_add_passphrase.c
@@ -57,6 +57,10 @@ insert_passphrase_to_head(struct archive_read *a,
{
p->next = a->passphrases.first;
a->passphrases.first = p;
+ if (&a->passphrases.first == a->passphrases.last) {
+ a->passphrases.last = &p->next;
+ p->next = NULL;
+ }
}
static struct archive_read_passphrase *
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c b/Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c
index 2a8cec8..9c9cf38 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c
@@ -103,6 +103,10 @@ __FBSDID("$FreeBSD");
static int setup_mac_metadata(struct archive_read_disk *,
struct archive_entry *, int *fd);
+#ifdef ARCHIVE_XATTR_FREEBSD
+static int setup_xattrs_namespace(struct archive_read_disk *,
+ struct archive_entry *, int *, int);
+#endif
static int setup_xattrs(struct archive_read_disk *,
struct archive_entry *, int *fd);
static int setup_sparse(struct archive_read_disk *,
@@ -701,14 +705,13 @@ setup_xattr(struct archive_read_disk *a, struct archive_entry *entry,
}
static int
-setup_xattrs(struct archive_read_disk *a,
- struct archive_entry *entry, int *fd)
+setup_xattrs_namespace(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd, int namespace)
{
char buff[512];
char *list, *p;
ssize_t list_size;
const char *path;
- int namespace = EXTATTR_NAMESPACE_USER;
path = NULL;
@@ -727,6 +730,8 @@ setup_xattrs(struct archive_read_disk *a,
if (list_size == -1 && errno == EOPNOTSUPP)
return (ARCHIVE_OK);
+ if (list_size == -1 && errno == EPERM)
+ return (ARCHIVE_OK);
if (list_size == -1) {
archive_set_error(&a->archive, errno,
"Couldn't list extended attributes");
@@ -760,7 +765,17 @@ setup_xattrs(struct archive_read_disk *a,
size_t len = 255 & (int)*p;
char *name;
- strcpy(buff, "user.");
+ if (namespace == EXTATTR_NAMESPACE_SYSTEM) {
+ if (!strcmp(p + 1, "nfs4.acl") ||
+ !strcmp(p + 1, "posix1e.acl_access") ||
+ !strcmp(p + 1, "posix1e.acl_default")) {
+ p += 1 + len;
+ continue;
+ }
+ strcpy(buff, "system.");
+ } else {
+ strcpy(buff, "user.");
+ }
name = buff + strlen(buff);
memcpy(name, p + 1, len);
name[len] = '\0';
@@ -772,6 +787,31 @@ setup_xattrs(struct archive_read_disk *a,
return (ARCHIVE_OK);
}
+static int
+setup_xattrs(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ int namespaces[2];
+ int i, res;
+
+ namespaces[0] = EXTATTR_NAMESPACE_USER;
+ namespaces[1] = EXTATTR_NAMESPACE_SYSTEM;
+
+ for (i = 0; i < 2; i++) {
+ res = setup_xattrs_namespace(a, entry, fd,
+ namespaces[i]);
+ switch (res) {
+ case (ARCHIVE_OK):
+ case (ARCHIVE_WARN):
+ break;
+ default:
+ return (res);
+ }
+ }
+
+ return (ARCHIVE_OK);
+}
+
#else
/*
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_disk_posix.c b/Utilities/cmlibarchive/libarchive/archive_read_disk_posix.c
index 52fec7b..2898206 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_disk_posix.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_disk_posix.c
@@ -1658,7 +1658,7 @@ static int
setup_current_filesystem(struct archive_read_disk *a)
{
struct tree *t = a->tree;
- struct statvfs sfs;
+ struct statvfs svfs;
int r, xr = 0;
t->current_filesystem->synthetic = -1;
@@ -1667,16 +1667,16 @@ setup_current_filesystem(struct archive_read_disk *a)
return (ARCHIVE_FAILED);
}
if (tree_current_is_symblic_link_target(t)) {
- r = statvfs(tree_current_access_path(t), &sfs);
+ r = statvfs(tree_current_access_path(t), &svfs);
if (r == 0)
xr = get_xfer_size(t, -1, tree_current_access_path(t));
} else {
#ifdef HAVE_FSTATVFS
- r = fstatvfs(tree_current_dir_fd(t), &sfs);
+ r = fstatvfs(tree_current_dir_fd(t), &svfs);
if (r == 0)
xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
#else
- r = statvfs(".", &sfs);
+ r = statvfs(".", &svfs);
if (r == 0)
xr = get_xfer_size(t, -1, ".");
#endif
@@ -1688,30 +1688,30 @@ setup_current_filesystem(struct archive_read_disk *a)
} else if (xr == 1) {
/* Usually come here unless NetBSD supports _PC_REC_XFER_ALIGN
* for pathconf() function. */
- t->current_filesystem->xfer_align = sfs.f_frsize;
+ t->current_filesystem->xfer_align = svfs.f_frsize;
t->current_filesystem->max_xfer_size = -1;
#if defined(HAVE_STRUCT_STATVFS_F_IOSIZE)
- t->current_filesystem->min_xfer_size = sfs.f_iosize;
- t->current_filesystem->incr_xfer_size = sfs.f_iosize;
+ t->current_filesystem->min_xfer_size = svfs.f_iosize;
+ t->current_filesystem->incr_xfer_size = svfs.f_iosize;
#else
- t->current_filesystem->min_xfer_size = sfs.f_bsize;
- t->current_filesystem->incr_xfer_size = sfs.f_bsize;
+ t->current_filesystem->min_xfer_size = svfs.f_bsize;
+ t->current_filesystem->incr_xfer_size = svfs.f_bsize;
#endif
}
- if (sfs.f_flag & ST_LOCAL)
+ if (svfs.f_flag & ST_LOCAL)
t->current_filesystem->remote = 0;
else
t->current_filesystem->remote = 1;
#if defined(ST_NOATIME)
- if (sfs.f_flag & ST_NOATIME)
+ if (svfs.f_flag & ST_NOATIME)
t->current_filesystem->noatime = 1;
else
#endif
t->current_filesystem->noatime = 0;
/* Set maximum filename length. */
- t->current_filesystem->name_max = sfs.f_namemax;
+ t->current_filesystem->name_max = svfs.f_namemax;
return (ARCHIVE_OK);
}
@@ -1840,7 +1840,7 @@ setup_current_filesystem(struct archive_read_disk *a)
#if defined(HAVE_STATVFS)
if (svfs.f_flag & ST_NOATIME)
#else
- if (sfs.f_flag & ST_NOATIME)
+ if (sfs.f_flags & ST_NOATIME)
#endif
t->current_filesystem->noatime = 1;
else
@@ -1864,7 +1864,7 @@ static int
setup_current_filesystem(struct archive_read_disk *a)
{
struct tree *t = a->tree;
- struct statvfs sfs;
+ struct statvfs svfs;
int r, xr = 0;
t->current_filesystem->synthetic = -1;/* Not supported */
@@ -1883,7 +1883,7 @@ setup_current_filesystem(struct archive_read_disk *a)
"openat failed");
return (ARCHIVE_FAILED);
}
- r = fstatvfs(fd, &sfs);
+ r = fstatvfs(fd, &svfs);
if (r == 0)
xr = get_xfer_size(t, fd, NULL);
close(fd);
@@ -1892,13 +1892,13 @@ setup_current_filesystem(struct archive_read_disk *a)
archive_set_error(&a->archive, errno, "fchdir failed");
return (ARCHIVE_FAILED);
}
- r = statvfs(tree_current_access_path(t), &sfs);
+ r = statvfs(tree_current_access_path(t), &svfs);
if (r == 0)
xr = get_xfer_size(t, -1, tree_current_access_path(t));
#endif
} else {
#ifdef HAVE_FSTATVFS
- r = fstatvfs(tree_current_dir_fd(t), &sfs);
+ r = fstatvfs(tree_current_dir_fd(t), &svfs);
if (r == 0)
xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
#else
@@ -1906,7 +1906,7 @@ setup_current_filesystem(struct archive_read_disk *a)
archive_set_error(&a->archive, errno, "fchdir failed");
return (ARCHIVE_FAILED);
}
- r = statvfs(".", &sfs);
+ r = statvfs(".", &svfs);
if (r == 0)
xr = get_xfer_size(t, -1, ".");
#endif
@@ -1918,14 +1918,14 @@ setup_current_filesystem(struct archive_read_disk *a)
return (ARCHIVE_FAILED);
} else if (xr == 1) {
/* pathconf(_PC_REX_*) operations are not supported. */
- t->current_filesystem->xfer_align = sfs.f_frsize;
+ t->current_filesystem->xfer_align = svfs.f_frsize;
t->current_filesystem->max_xfer_size = -1;
- t->current_filesystem->min_xfer_size = sfs.f_bsize;
- t->current_filesystem->incr_xfer_size = sfs.f_bsize;
+ t->current_filesystem->min_xfer_size = svfs.f_bsize;
+ t->current_filesystem->incr_xfer_size = svfs.f_bsize;
}
#if defined(ST_NOATIME)
- if (sfs.f_flag & ST_NOATIME)
+ if (svfs.f_flag & ST_NOATIME)
t->current_filesystem->noatime = 1;
else
#endif
@@ -1933,7 +1933,7 @@ setup_current_filesystem(struct archive_read_disk *a)
#if defined(USE_READDIR_R)
/* Set maximum filename length. */
- t->current_filesystem->name_max = sfs.f_namemax;
+ t->current_filesystem->name_max = svfs.f_namemax;
#endif
return (ARCHIVE_OK);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_filter.3 b/Utilities/cmlibarchive/libarchive/archive_read_filter.3
index 1ba5fcb..4f5c351 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_filter.3
+++ b/Utilities/cmlibarchive/libarchive/archive_read_filter.3
@@ -24,7 +24,7 @@
.\"
.\" $FreeBSD$
.\"
-.Dd August 14, 2014
+.Dd June 9, 2020
.Dt ARCHIVE_READ_FILTER 3
.Os
.Sh NAME
@@ -50,6 +50,8 @@ Streaming Archive Library (libarchive, -larchive)
.Ft int
.Fn archive_read_support_filter_all "struct archive *"
.Ft int
+.Fn archive_read_support_filter_by_code "struct archive *" "int"
+.Ft int
.Fn archive_read_support_filter_bzip2 "struct archive *"
.Ft int
.Fn archive_read_support_filter_compress "struct archive *"
@@ -116,6 +118,14 @@ Note that
is always enabled by default.
.It Fn archive_read_support_filter_all
Enables all available decompression filters.
+.It Fn archive_read_support_filter_by_code
+Enables a single filter specified by the filter code.
+This function does not work with
+.Cm ARCHIVE_FILTER_PROGRAM .
+Note: In statically-linked executables, this will cause
+your program to include support for every filter.
+If executable size is a concern, you may wish to avoid
+using this function.
.It Fn archive_read_support_filter_program
Data is fed through the specified external program before being dearchived.
Note that this disables automatic detection of the compression format,
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_open_filename.c b/Utilities/cmlibarchive/libarchive/archive_read_open_filename.c
index 86635e2..561289b 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_open_filename.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_open_filename.c
@@ -221,7 +221,9 @@ file_open(struct archive *a, void *client_data)
struct read_file_data *mine = (struct read_file_data *)client_data;
void *buffer;
const char *filename = NULL;
+#if defined(_WIN32) && !defined(__CYGWIN__)
const wchar_t *wfilename = NULL;
+#endif
int fd = -1;
int is_disk_like = 0;
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
@@ -281,10 +283,12 @@ file_open(struct archive *a, void *client_data)
#endif
}
if (fstat(fd, &st) != 0) {
+#if defined(_WIN32) && !defined(__CYGWIN__)
if (mine->filename_type == FNT_WCS)
archive_set_error(a, errno, "Can't stat '%S'",
wfilename);
else
+#endif
archive_set_error(a, errno, "Can't stat '%s'",
filename);
goto fail;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_set_format.c b/Utilities/cmlibarchive/libarchive/archive_read_set_format.c
index 1d3e49d..796dcdc 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_set_format.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_set_format.c
@@ -61,6 +61,9 @@ archive_read_set_format(struct archive *_a, int code)
case ARCHIVE_FORMAT_CPIO:
strcpy(str, "cpio");
break;
+ case ARCHIVE_FORMAT_EMPTY:
+ strcpy(str, "empty");
+ break;
case ARCHIVE_FORMAT_ISO9660:
strcpy(str, "iso9660");
break;
@@ -76,9 +79,15 @@ archive_read_set_format(struct archive *_a, int code)
case ARCHIVE_FORMAT_RAR_V5:
strcpy(str, "rar5");
break;
+ case ARCHIVE_FORMAT_RAW:
+ strcpy(str, "raw");
+ break;
case ARCHIVE_FORMAT_TAR:
strcpy(str, "tar");
break;
+ case ARCHIVE_FORMAT_WARC:
+ strcpy(str, "warc");
+ break;
case ARCHIVE_FORMAT_XAR:
strcpy(str, "xar");
break;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_by_code.c b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_by_code.c
new file mode 100644
index 0000000..94c4af6
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_by_code.c
@@ -0,0 +1,83 @@
+/*-
+ * Copyright (c) 2020 Martin Matuska
+ * 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.
+ */
+
+#include "archive_platform.h"
+__FBSDID("$FreeBSD$");
+
+#include "archive.h"
+#include "archive_private.h"
+
+int
+archive_read_support_filter_by_code(struct archive *a, int filter_code)
+{
+ archive_check_magic(a, ARCHIVE_READ_MAGIC,
+ ARCHIVE_STATE_NEW, "archive_read_support_filter_by_code");
+
+ switch (filter_code) {
+ case ARCHIVE_FILTER_NONE:
+ return archive_read_support_filter_none(a);
+ break;
+ case ARCHIVE_FILTER_GZIP:
+ return archive_read_support_filter_gzip(a);
+ break;
+ case ARCHIVE_FILTER_BZIP2:
+ return archive_read_support_filter_bzip2(a);
+ break;
+ case ARCHIVE_FILTER_COMPRESS:
+ return archive_read_support_filter_compress(a);
+ break;
+ case ARCHIVE_FILTER_LZMA:
+ return archive_read_support_filter_lzma(a);
+ break;
+ case ARCHIVE_FILTER_XZ:
+ return archive_read_support_filter_xz(a);
+ break;
+ case ARCHIVE_FILTER_UU:
+ return archive_read_support_filter_uu(a);
+ break;
+ case ARCHIVE_FILTER_RPM:
+ return archive_read_support_filter_rpm(a);
+ break;
+ case ARCHIVE_FILTER_LZIP:
+ return archive_read_support_filter_lzip(a);
+ break;
+ case ARCHIVE_FILTER_LRZIP:
+ return archive_read_support_filter_lrzip(a);
+ break;
+ case ARCHIVE_FILTER_LZOP:
+ return archive_read_support_filter_lzop(a);
+ break;
+ case ARCHIVE_FILTER_GRZIP:
+ return archive_read_support_filter_grzip(a);
+ break;
+ case ARCHIVE_FILTER_LZ4:
+ return archive_read_support_filter_lz4(a);
+ break;
+ case ARCHIVE_FILTER_ZSTD:
+ return archive_read_support_filter_zstd(a);
+ break;
+ }
+ return (ARCHIVE_FATAL);
+}
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_program.c b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_program.c
index b8bf128..bf5b6f2 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_program.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_program.c
@@ -400,7 +400,7 @@ __archive_read_program(struct archive_read_filter *self, const char *cmd)
static const size_t out_buf_len = 65536;
char *out_buf;
const char *prefix = "Program: ";
- pid_t child;
+ int ret;
size_t l;
l = strlen(prefix) + strlen(cmd) + 1;
@@ -426,9 +426,9 @@ __archive_read_program(struct archive_read_filter *self, const char *cmd)
state->out_buf = out_buf;
state->out_buf_len = out_buf_len;
- child = __archive_create_child(cmd, &state->child_stdin,
- &state->child_stdout);
- if (child == -1) {
+ ret = __archive_create_child(cmd, &state->child_stdin,
+ &state->child_stdout, &state->child);
+ if (ret != ARCHIVE_OK) {
free(state->out_buf);
archive_string_free(&state->description);
free(state);
@@ -437,21 +437,6 @@ __archive_read_program(struct archive_read_filter *self, const char *cmd)
cmd);
return (ARCHIVE_FATAL);
}
-#if defined(_WIN32) && !defined(__CYGWIN__)
- state->child = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, child);
- if (state->child == NULL) {
- child_stop(self, state);
- free(state->out_buf);
- archive_string_free(&state->description);
- free(state);
- archive_set_error(&self->archive->archive, EINVAL,
- "Can't initialize filter; unable to run program \"%s\"",
- cmd);
- return (ARCHIVE_FATAL);
- }
-#else
- state->child = child;
-#endif
self->data = state;
self->read = program_filter_read;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c
index e1ec60e..c4e8ec7 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c
@@ -119,6 +119,8 @@ zstd_bidder_bid(struct archive_read_filter_bidder *self,
/* Zstd frame magic values */
const unsigned zstd_magic = 0xFD2FB528U;
+ const unsigned zstd_magic_skippable_start = 0x184D2A50U;
+ const unsigned zstd_magic_skippable_mask = 0xFFFFFFF0;
(void) self; /* UNUSED */
@@ -129,6 +131,8 @@ zstd_bidder_bid(struct archive_read_filter_bidder *self,
prefix = archive_le32dec(buffer);
if (prefix == zstd_magic)
return (32);
+ if ((prefix & zstd_magic_skippable_mask) == zstd_magic_skippable_start)
+ return (32);
return (0);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_by_code.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_by_code.c
index 034353d..89e96f1 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_by_code.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_by_code.c
@@ -26,6 +26,10 @@
#include "archive_platform.h"
__FBSDID("$FreeBSD$");
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+
#include "archive.h"
#include "archive_private.h"
@@ -48,6 +52,9 @@ archive_read_support_format_by_code(struct archive *a, int format_code)
case ARCHIVE_FORMAT_CPIO:
return archive_read_support_format_cpio(a);
break;
+ case ARCHIVE_FORMAT_EMPTY:
+ return archive_read_support_format_empty(a);
+ break;
case ARCHIVE_FORMAT_ISO9660:
return archive_read_support_format_iso9660(a);
break;
@@ -63,9 +70,15 @@ archive_read_support_format_by_code(struct archive *a, int format_code)
case ARCHIVE_FORMAT_RAR_V5:
return archive_read_support_format_rar5(a);
break;
+ case ARCHIVE_FORMAT_RAW:
+ return archive_read_support_format_raw(a);
+ break;
case ARCHIVE_FORMAT_TAR:
return archive_read_support_format_tar(a);
break;
+ case ARCHIVE_FORMAT_WARC:
+ return archive_read_support_format_warc(a);
+ break;
case ARCHIVE_FORMAT_XAR:
return archive_read_support_format_xar(a);
break;
@@ -73,5 +86,7 @@ archive_read_support_format_by_code(struct archive *a, int format_code)
return archive_read_support_format_zip(a);
break;
}
+ archive_set_error(a, ARCHIVE_ERRNO_PROGRAMMER,
+ "Invalid format code specified");
return (ARCHIVE_FATAL);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c
index 58644ba..57547d4 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c
@@ -1172,7 +1172,7 @@ cab_checksum_finish(struct archive_read *a)
cfdata->memimage + CFDATA_cbData, l, cfdata->sum_calculated);
if (cfdata->sum_calculated != cfdata->sum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
- "Checksum error CFDATA[%d] %x:%x in %d bytes",
+ "Checksum error CFDATA[%d] %" PRIx32 ":%" PRIx32 " in %d bytes",
cab->entry_cffolder->cfdata_index -1,
cfdata->sum, cfdata->sum_calculated,
cfdata->compressed_size);
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_empty.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_empty.c
index c641eb9..53fb6cc 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_empty.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_empty.c
@@ -47,7 +47,7 @@ archive_read_support_format_empty(struct archive *_a)
r = __archive_read_register_format(a,
NULL,
- NULL,
+ "empty",
archive_read_format_empty_bid,
NULL,
archive_read_format_empty_read_header,
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c
index 332944a..93ba295 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c
@@ -51,6 +51,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_mtree.c 2011
#include "archive.h"
#include "archive_entry.h"
+#include "archive_entry_private.h"
#include "archive_private.h"
#include "archive_rb.h"
#include "archive_read_private.h"
@@ -135,6 +136,9 @@ static int skip(struct archive_read *a);
static int read_header(struct archive_read *,
struct archive_entry *);
static int64_t mtree_atol(char **, int base);
+#ifndef HAVE_STRNLEN
+static size_t mtree_strnlen(const char *, size_t);
+#endif
/*
* There's no standard for TIME_T_MAX/TIME_T_MIN. So we compute them
@@ -186,6 +190,24 @@ get_time_t_min(void)
#endif
}
+#ifdef HAVE_STRNLEN
+#define mtree_strnlen(a,b) strnlen(a,b)
+#else
+static size_t
+mtree_strnlen(const char *p, size_t maxlen)
+{
+ size_t i;
+
+ for (i = 0; i <= maxlen; i++) {
+ if (p[i] == 0)
+ break;
+ }
+ if (i > maxlen)
+ return (-1);/* invalid */
+ return (i);
+}
+#endif
+
static int
archive_read_format_mtree_options(struct archive_read *a,
const char *key, const char *val)
@@ -1482,6 +1504,84 @@ parse_device(dev_t *pdev, struct archive *a, char *val)
#undef MAX_PACK_ARGS
}
+static int
+parse_hex_nibble(char c)
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'a' && c <= 'f')
+ return 10 + c - 'a';
+#if 0
+ /* XXX: Is uppercase something we should support? */
+ if (c >= 'A' && c <= 'F')
+ return 10 + c - 'A';
+#endif
+
+ return -1;
+}
+
+static int
+parse_digest(struct archive_read *a, struct archive_entry *entry,
+ const char *digest, int type)
+{
+ unsigned char digest_buf[64];
+ int high, low;
+ size_t i, j, len;
+
+ switch (type) {
+ case ARCHIVE_ENTRY_DIGEST_MD5:
+ len = sizeof(entry->digest.md5);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_RMD160:
+ len = sizeof(entry->digest.rmd160);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA1:
+ len = sizeof(entry->digest.sha1);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA256:
+ len = sizeof(entry->digest.sha256);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA384:
+ len = sizeof(entry->digest.sha384);
+ break;
+ case ARCHIVE_ENTRY_DIGEST_SHA512:
+ len = sizeof(entry->digest.sha512);
+ break;
+ default:
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
+ "Internal error: Unknown digest type");
+ return ARCHIVE_FATAL;
+ }
+
+ if (len > sizeof(digest_buf)) {
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
+ "Internal error: Digest storage too large");
+ return ARCHIVE_FATAL;
+ }
+
+ len *= 2;
+
+ if (mtree_strnlen(digest, len+1) != len) {
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
+ "incorrect digest length, ignoring");
+ return ARCHIVE_WARN;
+ }
+
+ for (i = 0, j = 0; i < len; i += 2, j++) {
+ high = parse_hex_nibble(digest[i]);
+ low = parse_hex_nibble(digest[i+1]);
+ if (high == -1 || low == -1) {
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
+ "invalid digest data, ignoring");
+ return ARCHIVE_WARN;
+ }
+
+ digest_buf[j] = high << 4 | low;
+ }
+
+ return archive_entry_set_digest(entry, type, digest_buf);
+}
+
/*
* Parse a single keyword and its value.
*/
@@ -1580,8 +1680,10 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
}
__LA_FALLTHROUGH;
case 'm':
- if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
- break;
+ if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0) {
+ return parse_digest(a, entry, val,
+ ARCHIVE_ENTRY_DIGEST_MD5);
+ }
if (strcmp(key, "mode") == 0) {
if (val[0] >= '0' && val[0] <= '7') {
*parsed_kws |= MTREE_HAS_PERM;
@@ -1617,21 +1719,32 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
return r;
}
if (strcmp(key, "rmd160") == 0 ||
- strcmp(key, "rmd160digest") == 0)
- break;
+ strcmp(key, "rmd160digest") == 0) {
+ return parse_digest(a, entry, val,
+ ARCHIVE_ENTRY_DIGEST_RMD160);
+ }
__LA_FALLTHROUGH;
case 's':
- if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0)
- break;
+ if (strcmp(key, "sha1") == 0 ||
+ strcmp(key, "sha1digest") == 0) {
+ return parse_digest(a, entry, val,
+ ARCHIVE_ENTRY_DIGEST_SHA1);
+ }
if (strcmp(key, "sha256") == 0 ||
- strcmp(key, "sha256digest") == 0)
- break;
+ strcmp(key, "sha256digest") == 0) {
+ return parse_digest(a, entry, val,
+ ARCHIVE_ENTRY_DIGEST_SHA256);
+ }
if (strcmp(key, "sha384") == 0 ||
- strcmp(key, "sha384digest") == 0)
- break;
+ strcmp(key, "sha384digest") == 0) {
+ return parse_digest(a, entry, val,
+ ARCHIVE_ENTRY_DIGEST_SHA384);
+ }
if (strcmp(key, "sha512") == 0 ||
- strcmp(key, "sha512digest") == 0)
- break;
+ strcmp(key, "sha512digest") == 0) {
+ return parse_digest(a, entry, val,
+ ARCHIVE_ENTRY_DIGEST_SHA512);
+ }
if (strcmp(key, "size") == 0) {
archive_entry_set_size(entry, mtree_atol(&val, 10));
break;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
index 61f2330..6dca350 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
@@ -151,6 +151,9 @@
#undef minimum
#define minimum(a, b) ((a)<(b)?(a):(b))
+/* Stack overflow check */
+#define MAX_COMPRESS_DEPTH 1024
+
/* Fields common to all headers */
struct rar_header
{
@@ -340,7 +343,7 @@ static int read_symlink_stored(struct archive_read *, struct archive_entry *,
static int read_data_stored(struct archive_read *, const void **, size_t *,
int64_t *);
static int read_data_compressed(struct archive_read *, const void **, size_t *,
- int64_t *);
+ int64_t *, size_t);
static int rar_br_preparation(struct archive_read *, struct rar_br *);
static int parse_codes(struct archive_read *);
static void free_codes(struct archive_read *);
@@ -1026,7 +1029,7 @@ archive_read_format_rar_read_data(struct archive_read *a, const void **buff,
case COMPRESS_METHOD_NORMAL:
case COMPRESS_METHOD_GOOD:
case COMPRESS_METHOD_BEST:
- ret = read_data_compressed(a, buff, size, offset);
+ ret = read_data_compressed(a, buff, size, offset, 0);
if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) {
__archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
rar->start_new_table = 1;
@@ -1883,8 +1886,11 @@ read_data_stored(struct archive_read *a, const void **buff, size_t *size,
static int
read_data_compressed(struct archive_read *a, const void **buff, size_t *size,
- int64_t *offset)
+ int64_t *offset, size_t looper)
{
+ if (looper++ > MAX_COMPRESS_DEPTH)
+ return (ARCHIVE_FATAL);
+
struct rar *rar;
int64_t start, end, actualend;
size_t bs;
@@ -1982,7 +1988,7 @@ read_data_compressed(struct archive_read *a, const void **buff, size_t *size,
{
case 0:
rar->start_new_table = 1;
- return read_data_compressed(a, buff, size, offset);
+ return read_data_compressed(a, buff, size, offset, looper);
case 2:
rar->ppmd_eod = 1;/* End Of ppmd Data. */
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar5.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar5.c
index d3a1c1b..3131955 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar5.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar5.c
@@ -3084,12 +3084,6 @@ static int do_uncompress_block(struct archive_read* a, const uint8_t* p) {
continue;
}
-
- /* The program counter shouldn't reach here. */
- archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
- "Unsupported block code: 0x%x", num);
-
- return ARCHIVE_FATAL;
}
return ARCHIVE_OK;
@@ -3837,7 +3831,7 @@ static int verify_checksums(struct archive_read* a) {
DEBUG_CODE {
printf("Checksum error: CRC32 "
- "(was: %08x, expected: %08x)\n",
+ "(was: %08" PRIx32 ", expected: %08" PRIx32 ")\n",
rar->file.calculated_crc32,
rar->file.stored_crc32);
}
@@ -3851,7 +3845,7 @@ static int verify_checksums(struct archive_read* a) {
} else {
DEBUG_CODE {
printf("Checksum OK: CRC32 "
- "(%08x/%08x)\n",
+ "(%08" PRIx32 "/%08" PRIx32 ")\n",
rar->file.stored_crc32,
rar->file.calculated_crc32);
}
@@ -3912,6 +3906,9 @@ static int rar5_read_data(struct archive_read *a, const void **buff,
int ret;
struct rar5* rar = get_context(a);
+ if (size)
+ *size = 0;
+
if(rar->file.dir > 0) {
/* Don't process any data if this file entry was declared
* as a directory. This is needed, because entries marked as
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c
index c63d46f..96d8101 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c
@@ -1797,6 +1797,16 @@ pax_attribute_schily_xattr(struct archive_entry *entry,
}
static int
+pax_attribute_rht_security_selinux(struct archive_entry *entry,
+ const char *value, size_t value_length)
+{
+ archive_entry_xattr_add_entry(entry, "security.selinux",
+ value, value_length);
+
+ return 0;
+}
+
+static int
pax_attribute_acl(struct archive_read *a, struct tar *tar,
struct archive_entry *entry, const char *value, int type)
{
@@ -1966,6 +1976,14 @@ pax_attribute(struct archive_read *a, struct tar *tar,
if (memcmp(key, "LIBARCHIVE.xattr.", 17) == 0)
pax_attribute_xattr(entry, key, value);
break;
+ case 'R':
+ /* GNU tar uses RHT.security header to store SELinux xattrs
+ * SCHILY.xattr.security.selinux == RHT.security.selinux */
+ if (strcmp(key, "RHT.security.selinux") == 0) {
+ pax_attribute_rht_security_selinux(entry, value,
+ value_length);
+ }
+ break;
case 'S':
/* We support some keys used by the "star" archiver */
if (strcmp(key, "SCHILY.acl.access") == 0) {
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c
index 72977b8..2732996 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c
@@ -127,7 +127,7 @@ static int _warc_skip(struct archive_read *a);
static int _warc_rdhdr(struct archive_read *a, struct archive_entry *e);
/* private routines */
-static unsigned int _warc_rdver(const char buf[10], size_t bsz);
+static unsigned int _warc_rdver(const char *buf, size_t bsz);
static unsigned int _warc_rdtyp(const char *buf, size_t bsz);
static warc_string_t _warc_rduri(const char *buf, size_t bsz);
static ssize_t _warc_rdlen(const char *buf, size_t bsz);
@@ -337,6 +337,14 @@ start_over:
mtime = rtime;
}
break;
+ case WT_NONE:
+ case WT_INFO:
+ case WT_META:
+ case WT_REQ:
+ case WT_RVIS:
+ case WT_CONV:
+ case WT_CONT:
+ case LAST_WT:
default:
fnam.len = 0U;
fnam.str = NULL;
@@ -361,6 +369,14 @@ start_over:
break;
}
/* FALLTHROUGH */
+ case WT_NONE:
+ case WT_INFO:
+ case WT_META:
+ case WT_REQ:
+ case WT_RVIS:
+ case WT_CONV:
+ case WT_CONT:
+ case LAST_WT:
default:
/* consume the content and start over */
_warc_skip(a);
@@ -427,7 +443,7 @@ _warc_skip(struct archive_read *a)
static void*
deconst(const void *c)
{
- return (char *)0x1 + (((const char *)c) - (const char *)0x1);
+ return (void *)(uintptr_t)c;
}
static char*
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
index 9489e51..2e60cf7 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
@@ -36,7 +36,7 @@ __FBSDID("$FreeBSD$");
#elif HAVE_BSDXML_H
#include <bsdxml.h>
#elif HAVE_EXPAT_H
-#include <expat.h>
+#include <cm3p/expat.h>
#endif
#ifdef HAVE_BZLIB_H
#include <cm3p/bzlib.h>
@@ -458,6 +458,11 @@ archive_read_support_format_xar(struct archive *_a)
return (ARCHIVE_FATAL);
}
+ /* initialize xar->file_queue */
+ xar->file_queue.allocated = 0;
+ xar->file_queue.used = 0;
+ xar->file_queue.files = NULL;
+
r = __archive_read_register_format(a,
xar,
"xar",
@@ -1221,10 +1226,12 @@ heap_add_entry(struct archive_read *a,
/* Expand our pending files list as necessary. */
if (heap->used >= heap->allocated) {
struct xar_file **new_pending_files;
- int new_size = heap->allocated * 2;
+ int new_size;
if (heap->allocated < 1024)
new_size = 1024;
+ else
+ new_size = heap->allocated * 2;
/* Overflow might keep us from growing the list. */
if (new_size <= heap->allocated) {
archive_set_error(&a->archive,
@@ -1238,9 +1245,11 @@ heap_add_entry(struct archive_read *a,
ENOMEM, "Out of memory");
return (ARCHIVE_FATAL);
}
- memcpy(new_pending_files, heap->files,
- heap->allocated * sizeof(new_pending_files[0]));
- free(heap->files);
+ if (heap->allocated) {
+ memcpy(new_pending_files, heap->files,
+ heap->allocated * sizeof(new_pending_files[0]));
+ free(heap->files);
+ }
heap->files = new_pending_files;
heap->allocated = new_size;
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
index 4d71f98..6314c68 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
@@ -53,10 +53,10 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_zip.c 201102
#include <cm3p/zlib.h>
#endif
#ifdef HAVE_BZLIB_H
-#include <bzlib.h>
+#include <cm3p/bzlib.h>
#endif
#ifdef HAVE_LZMA_H
-#include <lzma.h>
+#include <cm3p/lzma.h>
#endif
#include "archive.h"
@@ -899,6 +899,81 @@ process_extra(struct archive_read *a, struct archive_entry *entry,
return ARCHIVE_OK;
}
+#if HAVE_LZMA_H && HAVE_LIBLZMA
+/*
+ * Auxiliary function to uncompress data chunk from zipx archive
+ * (zip with lzma compression).
+ */
+static int
+zipx_lzma_uncompress_buffer(const char *compressed_buffer,
+ size_t compressed_buffer_size,
+ char *uncompressed_buffer,
+ size_t uncompressed_buffer_size)
+{
+ int status = ARCHIVE_FATAL;
+ // length of 'lzma properties data' in lzma compressed
+ // data segment (stream) inside zip archive
+ const size_t lzma_params_length = 5;
+ // offset of 'lzma properties data' from the beginning of lzma stream
+ const size_t lzma_params_offset = 4;
+ // end position of 'lzma properties data' in lzma stream
+ const size_t lzma_params_end = lzma_params_offset + lzma_params_length;
+ if (compressed_buffer == NULL ||
+ compressed_buffer_size < lzma_params_end ||
+ uncompressed_buffer == NULL)
+ return status;
+
+ // prepare header for lzma_alone_decoder to replace zipx header
+ // (see comments in 'zipx_lzma_alone_init' for justification)
+#pragma pack(push)
+#pragma pack(1)
+ struct _alone_header
+ {
+ uint8_t bytes[5]; // lzma_params_length
+ uint64_t uncompressed_size;
+ } alone_header;
+#pragma pack(pop)
+ // copy 'lzma properties data' blob
+ memcpy(&alone_header.bytes[0], compressed_buffer + lzma_params_offset,
+ lzma_params_length);
+ alone_header.uncompressed_size = UINT64_MAX;
+
+ // prepare new compressed buffer, see 'zipx_lzma_alone_init' for details
+ const size_t lzma_alone_buffer_size =
+ compressed_buffer_size - lzma_params_end + sizeof(alone_header);
+ unsigned char *lzma_alone_compressed_buffer =
+ (unsigned char*) malloc(lzma_alone_buffer_size);
+ if (lzma_alone_compressed_buffer == NULL)
+ return status;
+ // copy lzma_alone header into new buffer
+ memcpy(lzma_alone_compressed_buffer, (void*) &alone_header,
+ sizeof(alone_header));
+ // copy compressed data into new buffer
+ memcpy(lzma_alone_compressed_buffer + sizeof(alone_header),
+ compressed_buffer + lzma_params_end,
+ compressed_buffer_size - lzma_params_end);
+
+ // create and fill in lzma_alone_decoder stream
+ lzma_stream stream = LZMA_STREAM_INIT;
+ lzma_ret ret = lzma_alone_decoder(&stream, UINT64_MAX);
+ if (ret == LZMA_OK)
+ {
+ stream.next_in = lzma_alone_compressed_buffer;
+ stream.avail_in = lzma_alone_buffer_size;
+ stream.total_in = 0;
+ stream.next_out = (unsigned char*)uncompressed_buffer;
+ stream.avail_out = uncompressed_buffer_size;
+ stream.total_out = 0;
+ ret = lzma_code(&stream, LZMA_RUN);
+ if (ret == LZMA_OK || ret == LZMA_STREAM_END)
+ status = ARCHIVE_OK;
+ }
+ lzma_end(&stream);
+ free(lzma_alone_compressed_buffer);
+ return status;
+}
+#endif
+
/*
* Assumes file pointer is at beginning of local file header.
*/
@@ -1173,18 +1248,64 @@ zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
"Truncated Zip file");
return ARCHIVE_FATAL;
}
+ // take into account link compression if any
+ size_t linkname_full_length = linkname_length;
+ if (zip->entry->compression != 0)
+ {
+ // symlink target string appeared to be compressed
+ int status = ARCHIVE_FATAL;
+ char *uncompressed_buffer =
+ (char*) malloc(zip_entry->uncompressed_size);
+ if (uncompressed_buffer == NULL)
+ {
+ archive_set_error(&a->archive, ENOMEM,
+ "No memory for lzma decompression");
+ return status;
+ }
+
+ switch (zip->entry->compression)
+ {
+#if HAVE_LZMA_H && HAVE_LIBLZMA
+ case 14: /* ZIPx LZMA compression. */
+ /*(see zip file format specification, section 4.4.5)*/
+ status = zipx_lzma_uncompress_buffer(p,
+ linkname_length,
+ uncompressed_buffer,
+ (size_t)zip_entry->uncompressed_size);
+ break;
+#endif
+ default: /* Unsupported compression. */
+ break;
+ }
+ if (status == ARCHIVE_OK)
+ {
+ p = uncompressed_buffer;
+ linkname_full_length =
+ (size_t)zip_entry->uncompressed_size;
+ }
+ else
+ {
+ archive_set_error(&a->archive,
+ ARCHIVE_ERRNO_FILE_FORMAT,
+ "Unsupported ZIP compression method "
+ "during decompression of link entry (%d: %s)",
+ zip->entry->compression,
+ compression_name(zip->entry->compression));
+ return ARCHIVE_FAILED;
+ }
+ }
sconv = zip->sconv;
if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
sconv = zip->sconv_utf8;
if (sconv == NULL)
sconv = zip->sconv_default;
- if (archive_entry_copy_symlink_l(entry, p, linkname_length,
+ if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
sconv) != 0) {
if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
(zip->entry->zip_flags & ZIP_UTF8_NAME))
archive_entry_copy_symlink_l(entry, p,
- linkname_length, NULL);
+ linkname_full_length, NULL);
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Symlink");
@@ -1901,15 +2022,15 @@ zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
if(order < 2 || restore_method > 2) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
- "Invalid parameter set in PPMd8 stream (order=%d, "
- "restore=%d)", order, restore_method);
+ "Invalid parameter set in PPMd8 stream (order=%" PRId32 ", "
+ "restore=%" PRId32 ")", order, restore_method);
return (ARCHIVE_FAILED);
}
/* Allocate the memory needed to properly decompress the file. */
if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
archive_set_error(&a->archive, ENOMEM,
- "Unable to allocate memory for PPMd8 stream: %d bytes",
+ "Unable to allocate memory for PPMd8 stream: %" PRId32 " bytes",
mem << 20);
return (ARCHIVE_FATAL);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_string.c b/Utilities/cmlibarchive/libarchive/archive_string.c
index c77dcf5..7460ded 100644
--- a/Utilities/cmlibarchive/libarchive/archive_string.c
+++ b/Utilities/cmlibarchive/libarchive/archive_string.c
@@ -3881,6 +3881,11 @@ archive_mstring_get_utf8(struct archive *a, struct archive_mstring *aes,
}
*p = NULL;
+ /* Try converting WCS to MBS first if MBS does not exist yet. */
+ if ((aes->aes_set & AES_SET_MBS) == 0) {
+ const char *pm; /* unused */
+ archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
+ }
if (aes->aes_set & AES_SET_MBS) {
sc = archive_string_conversion_to_charset(a, "UTF-8", 1);
if (sc == NULL)
@@ -3903,9 +3908,9 @@ int
archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
const char **p)
{
+ struct archive_string_conv *sc;
int r, ret = 0;
- (void)a; /* UNUSED */
/* If we already have an MBS form, return that immediately. */
if (aes->aes_set & AES_SET_MBS) {
*p = aes->aes_mbs.s;
@@ -3926,10 +3931,23 @@ archive_mstring_get_mbs(struct archive *a, struct archive_mstring *aes,
ret = -1;
}
- /*
- * Only a UTF-8 form cannot avail because its conversion already
- * failed at archive_mstring_update_utf8().
- */
+ /* If there's a UTF-8 form, try converting with the native locale. */
+ if (aes->aes_set & AES_SET_UTF8) {
+ archive_string_empty(&(aes->aes_mbs));
+ sc = archive_string_conversion_from_charset(a, "UTF-8", 1);
+ if (sc == NULL)
+ return (-1);/* Couldn't allocate memory for sc. */
+ r = archive_strncpy_l(&(aes->aes_mbs),
+ aes->aes_utf8.s, aes->aes_utf8.length, sc);
+ if (a == NULL)
+ free_sconv_object(sc);
+ *p = aes->aes_mbs.s;
+ if (r == 0) {
+ aes->aes_set |= AES_SET_MBS;
+ ret = 0;/* success; overwrite previous error. */
+ } else
+ ret = -1;/* failure. */
+ }
return (ret);
}
@@ -3947,6 +3965,11 @@ archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
}
*wp = NULL;
+ /* Try converting UTF8 to MBS first if MBS does not exist yet. */
+ if ((aes->aes_set & AES_SET_MBS) == 0) {
+ const char *p; /* unused */
+ archive_mstring_get_mbs(a, aes, &p); /* ignore errors, we'll handle it later */
+ }
/* Try converting MBS to WCS using native locale. */
if (aes->aes_set & AES_SET_MBS) {
archive_wstring_empty(&(aes->aes_wcs));
@@ -3962,11 +3985,12 @@ archive_mstring_get_wcs(struct archive *a, struct archive_mstring *aes,
}
int
-archive_mstring_get_mbs_l(struct archive_mstring *aes,
+archive_mstring_get_mbs_l(struct archive *a, struct archive_mstring *aes,
const char **p, size_t *length, struct archive_string_conv *sc)
{
int r, ret = 0;
+ (void)r; /* UNUSED */
#if defined(_WIN32) && !defined(__CYGWIN__)
/*
* Internationalization programming on Windows must use Wide
@@ -3989,20 +4013,12 @@ archive_mstring_get_mbs_l(struct archive_mstring *aes,
}
#endif
- /* If there is not an MBS form but is a WCS form, try converting
+ /* If there is not an MBS form but there is a WCS or UTF8 form, try converting
* with the native locale to be used for translating it to specified
* character-set. */
- if ((aes->aes_set & AES_SET_MBS) == 0 &&
- (aes->aes_set & AES_SET_WCS) != 0) {
- archive_string_empty(&(aes->aes_mbs));
- r = archive_string_append_from_wcs(&(aes->aes_mbs),
- aes->aes_wcs.s, aes->aes_wcs.length);
- if (r == 0)
- aes->aes_set |= AES_SET_MBS;
- else if (errno == ENOMEM)
- return (-1);
- else
- ret = -1;
+ if ((aes->aes_set & AES_SET_MBS) == 0) {
+ const char *pm; /* unused */
+ archive_mstring_get_mbs(a, aes, &pm); /* ignore errors, we'll handle it later */
}
/* If we already have an MBS form, use it to be translated to
* specified character-set. */
diff --git a/Utilities/cmlibarchive/libarchive/archive_string.h b/Utilities/cmlibarchive/libarchive/archive_string.h
index 27e1ad6..49d7d30 100644
--- a/Utilities/cmlibarchive/libarchive/archive_string.h
+++ b/Utilities/cmlibarchive/libarchive/archive_string.h
@@ -226,7 +226,7 @@ void archive_mstring_copy(struct archive_mstring *dest, struct archive_mstring *
int archive_mstring_get_mbs(struct archive *, struct archive_mstring *, const char **);
int archive_mstring_get_utf8(struct archive *, struct archive_mstring *, const char **);
int archive_mstring_get_wcs(struct archive *, struct archive_mstring *, const wchar_t **);
-int archive_mstring_get_mbs_l(struct archive_mstring *, const char **,
+int archive_mstring_get_mbs_l(struct archive *, struct archive_mstring *, const char **,
size_t *, struct archive_string_conv *);
int archive_mstring_copy_mbs(struct archive_mstring *, const char *mbs);
int archive_mstring_copy_mbs_len(struct archive_mstring *, const char *mbs,
diff --git a/Utilities/cmlibarchive/libarchive/archive_util.c b/Utilities/cmlibarchive/libarchive/archive_util.c
index 10dca73..83586b5 100644
--- a/Utilities/cmlibarchive/libarchive/archive_util.c
+++ b/Utilities/cmlibarchive/libarchive/archive_util.c
@@ -365,6 +365,7 @@ __archive_mktempx(const char *tmpdir, wchar_t *template)
}
fd = _open_osfhandle((intptr_t)h, _O_BINARY | _O_RDWR);
if (fd == -1) {
+ la_dosmaperr(GetLastError());
CloseHandle(h);
goto exit_tmpfile;
} else
@@ -432,6 +433,11 @@ __archive_mktemp(const char *tmpdir)
if (temp_name.s[temp_name.length-1] != '/')
archive_strappend_char(&temp_name, '/');
}
+#ifdef O_TMPFILE
+ fd = open(temp_name.s, O_RDWR|O_CLOEXEC|O_TMPFILE|O_EXCL, 0600);
+ if(fd >= 0)
+ goto exit_tmpfile;
+#endif
archive_strcat(&temp_name, "libarchive_XXXXXX");
fd = mkstemp(temp_name.s);
if (fd < 0)
diff --git a/Utilities/cmlibarchive/libarchive/archive_write.c b/Utilities/cmlibarchive/libarchive/archive_write.c
index 98a55fb..8d70f51 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write.c
@@ -456,6 +456,25 @@ archive_write_client_write(struct archive_write_filter *f,
}
static int
+archive_write_client_free(struct archive_write_filter *f)
+{
+ struct archive_write *a = (struct archive_write *)f->archive;
+
+ if (a->client_freer)
+ (*a->client_freer)(&a->archive, a->client_data);
+ a->client_data = NULL;
+
+ /* Clear passphrase. */
+ if (a->passphrase != NULL) {
+ memset(a->passphrase, 0, strlen(a->passphrase));
+ free(a->passphrase);
+ a->passphrase = NULL;
+ }
+
+ return (ARCHIVE_OK);
+}
+
+static int
archive_write_client_close(struct archive_write_filter *f)
{
struct archive_write *a = (struct archive_write *)f->archive;
@@ -493,13 +512,7 @@ archive_write_client_close(struct archive_write_filter *f)
(*a->client_closer)(&a->archive, a->client_data);
free(state->buffer);
free(state);
- a->client_data = NULL;
- /* Clear passphrase. */
- if (a->passphrase != NULL) {
- memset(a->passphrase, 0, strlen(a->passphrase));
- free(a->passphrase);
- a->passphrase = NULL;
- }
+
/* Clear the close handler myself not to be called again. */
f->state = ARCHIVE_WRITE_FILTER_STATE_CLOSED;
return (ret);
@@ -509,9 +522,9 @@ archive_write_client_close(struct archive_write_filter *f)
* Open the archive using the current settings.
*/
int
-archive_write_open(struct archive *_a, void *client_data,
+archive_write_open2(struct archive *_a, void *client_data,
archive_open_callback *opener, archive_write_callback *writer,
- archive_close_callback *closer)
+ archive_close_callback *closer, archive_free_callback *freer)
{
struct archive_write *a = (struct archive_write *)_a;
struct archive_write_filter *client_filter;
@@ -524,12 +537,14 @@ archive_write_open(struct archive *_a, void *client_data,
a->client_writer = writer;
a->client_opener = opener;
a->client_closer = closer;
+ a->client_freer = freer;
a->client_data = client_data;
client_filter = __archive_write_allocate_filter(_a);
client_filter->open = archive_write_client_open;
client_filter->write = archive_write_client_write;
client_filter->close = archive_write_client_close;
+ client_filter->free = archive_write_client_free;
ret = __archive_write_filters_open(a);
if (ret < ARCHIVE_WARN) {
@@ -544,6 +559,15 @@ archive_write_open(struct archive *_a, void *client_data,
return (ret);
}
+int
+archive_write_open(struct archive *_a, void *client_data,
+ archive_open_callback *opener, archive_write_callback *writer,
+ archive_close_callback *closer)
+{
+ return archive_write_open2(_a, client_data, opener, writer,
+ closer, NULL);
+}
+
/*
* Close out the archive.
*/
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c
index a4bc1d9..c096e72 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c
@@ -196,10 +196,6 @@ __archive_write_program_free(struct archive_write_program_data *data)
{
if (data) {
-#if defined(_WIN32) && !defined(__CYGWIN__)
- if (data->child)
- CloseHandle(data->child);
-#endif
free(data->program_name);
free(data->child_buf);
free(data);
@@ -211,7 +207,7 @@ int
__archive_write_program_open(struct archive_write_filter *f,
struct archive_write_program_data *data, const char *cmd)
{
- pid_t child;
+ int ret;
if (data->child_buf == NULL) {
data->child_buf_len = 65536;
@@ -225,27 +221,13 @@ __archive_write_program_open(struct archive_write_filter *f,
}
}
- child = __archive_create_child(cmd, &data->child_stdin,
- &data->child_stdout);
- if (child == -1) {
+ ret = __archive_create_child(cmd, &data->child_stdin,
+ &data->child_stdout, &data->child);
+ if (ret != ARCHIVE_OK) {
archive_set_error(f->archive, EINVAL,
"Can't launch external program: %s", cmd);
return (ARCHIVE_FATAL);
}
-#if defined(_WIN32) && !defined(__CYGWIN__)
- data->child = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, child);
- if (data->child == NULL) {
- close(data->child_stdin);
- data->child_stdin = -1;
- close(data->child_stdout);
- data->child_stdout = -1;
- archive_set_error(f->archive, EINVAL,
- "Can't launch external program: %s", cmd);
- return (ARCHIVE_FATAL);
- }
-#else
- data->child = child;
-#endif
return (ARCHIVE_OK);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c
index d567ac9..00df8da 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c
@@ -382,8 +382,12 @@ archive_compressor_xz_options(struct archive_write_filter *f,
value[1] != '\0')
return (ARCHIVE_WARN);
data->compression_level = value[0] - '0';
+ if (data->compression_level > 9)
+ data->compression_level = 9;
+#ifdef _AIX
if (data->compression_level > 6)
data->compression_level = 6;
+#endif
return (ARCHIVE_OK);
} else if (strcmp(key, "threads") == 0) {
char *endptr;
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c
index f67b025..6d71628 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c
@@ -59,6 +59,16 @@ struct private_data {
#endif
};
+/* If we don't have the library use default range values (zstdcli.c v1.4.0) */
+#define CLEVEL_MIN -99
+#define CLEVEL_STD_MIN 0 /* prior to 1.3.4 and more recent without using --fast */
+#define CLEVEL_DEFAULT 3
+#define CLEVEL_STD_MAX 19 /* without using --ultra */
+#define CLEVEL_MAX 22
+
+#define MINVER_NEGCLEVEL 10304
+#define MINVER_MINCLEVEL 10306
+
static int archive_compressor_zstd_options(struct archive_write_filter *,
const char *, const char *);
static int archive_compressor_zstd_open(struct archive_write_filter *);
@@ -96,7 +106,7 @@ archive_write_add_filter_zstd(struct archive *_a)
f->free = &archive_compressor_zstd_free;
f->code = ARCHIVE_FILTER_ZSTD;
f->name = "zstd";
- data->compression_level = 3; /* Default level used by the zstd CLI */
+ data->compression_level = CLEVEL_DEFAULT;
#if HAVE_ZSTD_H && HAVE_LIBZSTD
data->cstream = ZSTD_createCStream();
if (data->cstream == NULL) {
@@ -135,6 +145,31 @@ archive_compressor_zstd_free(struct archive_write_filter *f)
return (ARCHIVE_OK);
}
+static int string_is_numeric (const char* value)
+{
+ size_t len = strlen(value);
+ size_t i;
+
+ if (len == 0) {
+ return (ARCHIVE_WARN);
+ }
+ else if (len == 1 && !(value[0] >= '0' && value[0] <= '9')) {
+ return (ARCHIVE_WARN);
+ }
+ else if (!(value[0] >= '0' && value[0] <= '9') &&
+ value[0] != '-' && value[0] != '+') {
+ return (ARCHIVE_WARN);
+ }
+
+ for (i = 1; i < len; i++) {
+ if (!(value[i] >= '0' && value[i] <= '9')) {
+ return (ARCHIVE_WARN);
+ }
+ }
+
+ return (ARCHIVE_OK);
+}
+
/*
* Set write options.
*/
@@ -146,12 +181,25 @@ archive_compressor_zstd_options(struct archive_write_filter *f, const char *key,
if (strcmp(key, "compression-level") == 0) {
int level = atoi(value);
-#if HAVE_ZSTD_H && HAVE_LIBZSTD
- if (level < 1 || level > ZSTD_maxCLevel()) {
-#else
/* If we don't have the library, hard-code the max level */
- if (level < 1 || level > 22) {
+ int minimum = CLEVEL_MIN;
+ int maximum = CLEVEL_MAX;
+ if (string_is_numeric(value) != ARCHIVE_OK) {
+ return (ARCHIVE_WARN);
+ }
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ maximum = ZSTD_maxCLevel();
+#if ZSTD_VERSION_NUMBER >= MINVER_MINCLEVEL
+ if (ZSTD_versionNumber() >= MINVER_MINCLEVEL) {
+ minimum = ZSTD_minCLevel();
+ }
+ else
+#endif
+ if (ZSTD_versionNumber() < MINVER_NEGCLEVEL) {
+ minimum = CLEVEL_STD_MIN;
+ }
#endif
+ if (level < minimum || level > maximum) {
return (ARCHIVE_WARN);
}
data->compression_level = level;
@@ -297,7 +345,26 @@ archive_compressor_zstd_open(struct archive_write_filter *f)
int r;
archive_string_init(&as);
- archive_string_sprintf(&as, "zstd -%d", data->compression_level);
+ /* --no-check matches library default */
+ archive_strcpy(&as, "zstd --no-check");
+
+ if (data->compression_level < CLEVEL_STD_MIN) {
+ struct archive_string as2;
+ archive_string_init(&as2);
+ archive_string_sprintf(&as2, " --fast=%d", -data->compression_level);
+ archive_string_concat(&as, &as2);
+ archive_string_free(&as2);
+ } else {
+ struct archive_string as2;
+ archive_string_init(&as2);
+ archive_string_sprintf(&as2, " -%d", data->compression_level);
+ archive_string_concat(&as, &as2);
+ archive_string_free(&as2);
+ }
+
+ if (data->compression_level > CLEVEL_STD_MAX) {
+ archive_strcat(&as, " --ultra");
+ }
f->write = archive_compressor_zstd_write;
r = __archive_write_program_open(f, data->pdata, as.s);
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c b/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
index c4be9b0..2551ebe 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
@@ -546,6 +546,7 @@ _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
{
struct archive_write_disk *a = (struct archive_write_disk *)_a;
struct fixup_entry *fe;
+ const char *linkname;
int ret, r;
archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
@@ -591,6 +592,17 @@ _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
return (ret);
/*
+ * Check if we have a hardlink that points to itself.
+ */
+ linkname = archive_entry_hardlink(a->entry);
+ if (linkname != NULL && strcmp(a->name, linkname) == 0) {
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Skipping hardlink pointing to itself: %s",
+ a->name);
+ return (ARCHIVE_WARN);
+ }
+
+ /*
* Query the umask so we get predictable mode settings.
* This gets done on every call to _write_header in case the
* user edits their umask during the extraction for some
@@ -1856,8 +1868,9 @@ finish_metadata:
if (a->tmpname) {
if (rename(a->tmpname, a->name) == -1) {
archive_set_error(&a->archive, errno,
- "rename failed");
- ret = ARCHIVE_FATAL;
+ "Failed to rename temporary file");
+ ret = ARCHIVE_FAILED;
+ unlink(a->tmpname);
}
a->tmpname = NULL;
}
@@ -2144,8 +2157,11 @@ restore_entry(struct archive_write_disk *a)
if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) &&
S_ISREG(a->st.st_mode)) {
/* Use a temporary file to extract */
- if ((a->fd = la_mktemp(a)) == -1)
+ if ((a->fd = la_mktemp(a)) == -1) {
+ archive_set_error(&a->archive, errno,
+ "Can't create temporary file");
return ARCHIVE_FAILED;
+ }
a->pst = NULL;
en = 0;
} else {
@@ -4407,10 +4423,19 @@ set_xattrs(struct archive_write_disk *a)
int e;
int namespace;
+ namespace = EXTATTR_NAMESPACE_USER;
+
if (strncmp(name, "user.", 5) == 0) {
/* "user." attributes go to user namespace */
name += 5;
namespace = EXTATTR_NAMESPACE_USER;
+ } else if (strncmp(name, "system.", 7) == 0) {
+ name += 7;
+ namespace = EXTATTR_NAMESPACE_SYSTEM;
+ if (!strcmp(name, "nfs4.acl") ||
+ !strcmp(name, "posix1e.acl_access") ||
+ !strcmp(name, "posix1e.acl_default"))
+ continue;
} else {
/* Other namespaces are unsupported */
archive_strcat(&errlist, name);
@@ -4421,8 +4446,29 @@ set_xattrs(struct archive_write_disk *a)
}
if (a->fd >= 0) {
+ /*
+ * On FreeBSD, extattr_set_fd does not
+ * return the same as
+ * extattr_set_file. It returns zero
+ * on success, non-zero on failure.
+ *
+ * We can detect the failure by
+ * manually setting errno prior to the
+ * call and checking after.
+ *
+ * If errno remains zero, fake the
+ * return value by setting e to size.
+ *
+ * This is a hack for now until I
+ * (Shawn Webb) get FreeBSD to fix the
+ * issue, if that's even possible.
+ */
+ errno = 0;
e = extattr_set_fd(a->fd, namespace, name,
value, size);
+ if (e == 0 && errno == 0) {
+ e = size;
+ }
} else {
e = extattr_set_link(
archive_entry_pathname(entry), namespace,
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_disk_windows.c b/Utilities/cmlibarchive/libarchive/archive_write_disk_windows.c
index 77e36c4..0c60017 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk_windows.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_disk_windows.c
@@ -549,6 +549,8 @@ la_mktemp(struct archive_write_disk *a)
a->tmpname = a->_tmpname_data.s;
fd = __archive_mkstemp(a->tmpname);
+ if (fd == -1)
+ return -1;
mode = a->mode & 0777 & ~a->user_umask;
if (la_chmod(a->tmpname, mode) == -1) {
@@ -1281,9 +1283,11 @@ _archive_write_disk_finish_entry(struct archive *_a)
/* Windows does not support atomic rename */
disk_unlink(a->name);
if (_wrename(a->tmpname, a->name) != 0) {
+ la_dosmaperr(GetLastError());
archive_set_error(&a->archive, errno,
- "rename failed");
- ret = ARCHIVE_FATAL;
+ "Failed to rename temporary file");
+ ret = ARCHIVE_FAILED;
+ disk_unlink(a->tmpname);
}
a->tmpname = NULL;
}
@@ -1573,12 +1577,17 @@ restore_entry(struct archive_write_disk *a)
S_ISREG(st_mode)) {
int fd = la_mktemp(a);
- if (fd == -1)
+ if (fd == -1) {
+ la_dosmaperr(GetLastError());
+ archive_set_error(&a->archive, errno,
+ "Can't create temporary file");
return (ARCHIVE_FAILED);
+ }
a->fh = (HANDLE)_get_osfhandle(fd);
- if (a->fh == INVALID_HANDLE_VALUE)
+ if (a->fh == INVALID_HANDLE_VALUE) {
+ la_dosmaperr(GetLastError());
return (ARCHIVE_FAILED);
-
+ }
a->pst = NULL;
en = 0;
} else {
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_open.3 b/Utilities/cmlibarchive/libarchive/archive_write_open.3
index 0129d10..29bffe4 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_open.3
+++ b/Utilities/cmlibarchive/libarchive/archive_write_open.3
@@ -24,11 +24,12 @@
.\"
.\" $FreeBSD$
.\"
-.Dd February 2, 2012
+.Dd November 12, 2020
.Dt ARCHIVE_WRITE_OPEN 3
.Os
.Sh NAME
.Nm archive_write_open ,
+.Nm archive_write_open2 ,
.Nm archive_write_open_fd ,
.Nm archive_write_open_FILE ,
.Nm archive_write_open_filename ,
@@ -47,6 +48,15 @@ Streaming Archive Library (libarchive, -larchive)
.Fa "archive_close_callback *"
.Fc
.Ft int
+.Fo archive_write_open2
+.Fa "struct archive *"
+.Fa "void *client_data"
+.Fa "archive_open_callback *"
+.Fa "archive_write_callback *"
+.Fa "archive_close_callback *"
+.Fa "archive_free_callback *"
+.Fc
+.Ft int
.Fn archive_write_open_fd "struct archive *" "int fd"
.Ft int
.Fn archive_write_open_FILE "struct archive *" "FILE *file"
@@ -67,6 +77,11 @@ This is the most generic form of this function, which accepts
pointers to three callback functions which will be invoked by
the compression layer to write the constructed archive.
This does not alter the default archive padding.
+.It Fn archive_write_open2
+Same as
+.Fn archive_write_open
+with an additional fourth free callback. This function should be preferred to
+.Fn archive_write_open .
.It Fn archive_write_open_fd
A convenience form of
.Fn archive_write_open
@@ -106,14 +121,14 @@ to a character or block device node, it will disable padding otherwise.
You can override this by manually invoking
.Fn archive_write_set_bytes_in_last_block
before calling
-.Fn archive_write_open .
+.Fn archive_write_open2 .
The
.Fn archive_write_open_filename
function is safe for use with tape drives or other
block-oriented devices.
.It Fn archive_write_open_memory
A convenience form of
-.Fn archive_write_open
+.Fn archive_write_open2
that accepts a pointer to a block of memory that will receive
the archive.
The final
@@ -145,7 +160,7 @@ To use this library, you will need to define and register
callback functions that will be invoked to write data to the
resulting archive.
These functions are registered by calling
-.Fn archive_write_open :
+.Fn archive_write_open2 :
.Bl -item -offset indent
.It
.Ft typedef int
@@ -162,6 +177,8 @@ If the open fails, it should call
.Fn archive_set_error
to register an error code and message and return
.Cm ARCHIVE_FATAL .
+Please note that if open fails, close is not called and resources must be
+freed inside the open callback or with the free callback.
.Bl -item -offset indent
.It
.Ft typedef la_ssize_t
@@ -192,7 +209,8 @@ to register an error code and message and return -1.
.El
.Pp
The close callback is invoked by archive_close when
-the archive processing is complete.
+the archive processing is complete. If the open callback fails, the close
+callback is not invoked.
The callback should return
.Cm ARCHIVE_OK
on success.
@@ -200,7 +218,14 @@ On failure, the callback should invoke
.Fn archive_set_error
to register an error code and message and
return
-.Cm ARCHIVE_FATAL .
+.Bl -item -offset indent
+.It
+.Ft typedef int
+.Fn archive_free_callback "struct archive *" "void *client_data"
+.El
+.Pp
+The free callback is always invoked on archive_free.
+The return code of this callback is not processed.
.Pp
Note that if the client-provided write callback function
returns a non-zero value, that error will be propagated back to the caller
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_open_fd.c b/Utilities/cmlibarchive/libarchive/archive_write_open_fd.c
index d5c426c..b8d491f 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_open_fd.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_open_fd.c
@@ -54,7 +54,7 @@ struct write_fd_data {
int fd;
};
-static int file_close(struct archive *, void *);
+static int file_free(struct archive *, void *);
static int file_open(struct archive *, void *);
static ssize_t file_write(struct archive *, void *, const void *buff, size_t);
@@ -72,8 +72,8 @@ archive_write_open_fd(struct archive *a, int fd)
#if defined(__CYGWIN__) || defined(_WIN32)
setmode(mine->fd, O_BINARY);
#endif
- return (archive_write_open(a, mine,
- file_open, file_write, file_close));
+ return (archive_write_open2(a, mine,
+ file_open, file_write, NULL, file_free));
}
static int
@@ -134,11 +134,13 @@ file_write(struct archive *a, void *client_data, const void *buff, size_t length
}
static int
-file_close(struct archive *a, void *client_data)
+file_free(struct archive *a, void *client_data)
{
struct write_fd_data *mine = (struct write_fd_data *)client_data;
(void)a; /* UNUSED */
+ if (mine == NULL)
+ return (ARCHIVE_OK);
free(mine);
return (ARCHIVE_OK);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_open_file.c b/Utilities/cmlibarchive/libarchive/archive_write_open_file.c
index f6b1412..bf5b55a 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_open_file.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_open_file.c
@@ -51,7 +51,7 @@ struct write_FILE_data {
FILE *f;
};
-static int file_close(struct archive *, void *);
+static int file_free(struct archive *, void *);
static int file_open(struct archive *, void *);
static ssize_t file_write(struct archive *, void *, const void *buff, size_t);
@@ -66,8 +66,8 @@ archive_write_open_FILE(struct archive *a, FILE *f)
return (ARCHIVE_FATAL);
}
mine->f = f;
- return (archive_write_open(a, mine,
- file_open, file_write, file_close));
+ return (archive_write_open2(a, mine, file_open, file_write,
+ NULL, file_free));
}
static int
@@ -99,11 +99,13 @@ file_write(struct archive *a, void *client_data, const void *buff, size_t length
}
static int
-file_close(struct archive *a, void *client_data)
+file_free(struct archive *a, void *client_data)
{
struct write_FILE_data *mine = client_data;
(void)a; /* UNUSED */
+ if (mine == NULL)
+ return (ARCHIVE_OK);
free(mine);
return (ARCHIVE_OK);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_open_filename.c b/Utilities/cmlibarchive/libarchive/archive_write_open_filename.c
index 66e0dfe..9ceefb1 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_open_filename.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_open_filename.c
@@ -62,6 +62,7 @@ struct write_file_data {
};
static int file_close(struct archive *, void *);
+static int file_free(struct archive *, void *);
static int file_open(struct archive *, void *);
static ssize_t file_write(struct archive *, void *, const void *buff, size_t);
static int open_filename(struct archive *, int, const void *);
@@ -123,8 +124,8 @@ open_filename(struct archive *a, int mbs_fn, const void *filename)
return (ARCHIVE_FAILED);
}
mine->fd = -1;
- return (archive_write_open(a, mine,
- file_open, file_write, file_close));
+ return (archive_write_open2(a, mine,
+ file_open, file_write, file_close, file_free));
}
static int
@@ -244,9 +245,25 @@ file_close(struct archive *a, void *client_data)
(void)a; /* UNUSED */
+ if (mine == NULL)
+ return (ARCHIVE_FATAL);
+
if (mine->fd >= 0)
close(mine->fd);
+ return (ARCHIVE_OK);
+}
+
+static int
+file_free(struct archive *a, void *client_data)
+{
+ struct write_file_data *mine = (struct write_file_data *)client_data;
+
+ (void)a; /* UNUSED */
+
+ if (mine == NULL)
+ return (ARCHIVE_OK);
+
archive_mstring_clean(&mine->filename);
free(mine);
return (ARCHIVE_OK);
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_open_memory.c b/Utilities/cmlibarchive/libarchive/archive_write_open_memory.c
index ea6ae0a..a8a0b81 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_open_memory.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_open_memory.c
@@ -39,7 +39,7 @@ struct write_memory_data {
unsigned char * buff;
};
-static int memory_write_close(struct archive *, void *);
+static int memory_write_free(struct archive *, void *);
static int memory_write_open(struct archive *, void *);
static ssize_t memory_write(struct archive *, void *, const void *buff, size_t);
@@ -61,8 +61,8 @@ archive_write_open_memory(struct archive *a, void *buff, size_t buffSize, size_t
mine->buff = buff;
mine->size = buffSize;
mine->client_size = used;
- return (archive_write_open(a, mine,
- memory_write_open, memory_write, memory_write_close));
+ return (archive_write_open2(a, mine,
+ memory_write_open, memory_write, NULL, memory_write_free));
}
static int
@@ -103,11 +103,13 @@ memory_write(struct archive *a, void *client_data, const void *buff, size_t leng
}
static int
-memory_write_close(struct archive *a, void *client_data)
+memory_write_free(struct archive *a, void *client_data)
{
struct write_memory_data *mine;
(void)a; /* UNUSED */
mine = client_data;
+ if (mine == NULL)
+ return (ARCHIVE_OK);
free(mine);
return (ARCHIVE_OK);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_private.h b/Utilities/cmlibarchive/libarchive/archive_write_private.h
index 27cba03..155fdd7 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_write_private.h
@@ -89,6 +89,7 @@ struct archive_write {
archive_open_callback *client_opener;
archive_write_callback *client_writer;
archive_close_callback *client_closer;
+ archive_free_callback *client_freer;
void *client_data;
/*
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format.c
index 12de080..7dbe7b9 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format.c
@@ -82,7 +82,7 @@ void
__archive_write_entry_filetype_unsupported(struct archive *a,
struct archive_entry *entry, const char *format)
{
- char *name = NULL;
+ const char *name = NULL;
switch (archive_entry_filetype(entry)) {
/*
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
index 69af814..7f2e6ac 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
@@ -1927,8 +1927,8 @@ compression_init_encoder_lzma(struct archive *a,
return (ARCHIVE_FATAL);
}
lzmafilters = (lzma_filter *)(strm+1);
- if (level > 6)
- level = 6;
+ if (level > 9)
+ level = 9;
if (lzma_lzma_preset(&lzma_opt, level)) {
free(strm);
lastrm->real_stream = NULL;
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio.c
index 729f9c7..e066733 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio.c
@@ -250,7 +250,7 @@ archive_write_cpio_header(struct archive_write *a, struct archive_entry *entry)
const char *path;
size_t len;
- if (archive_entry_filetype(entry) == 0) {
+ if (archive_entry_filetype(entry) == 0 && archive_entry_hardlink(entry) == NULL) {
archive_set_error(&a->archive, -1, "Filetype required");
return (ARCHIVE_FAILED);
}
@@ -348,7 +348,7 @@ write_header(struct archive_write *a, struct archive_entry *entry)
format_octal(archive_entry_nlink(entry), h + c_nlink_offset, c_nlink_size);
if (archive_entry_filetype(entry) == AE_IFBLK
|| archive_entry_filetype(entry) == AE_IFCHR)
- format_octal(archive_entry_dev(entry), h + c_rdev_offset, c_rdev_size);
+ format_octal(archive_entry_rdev(entry), h + c_rdev_offset, c_rdev_size);
else
format_octal(0, h + c_rdev_offset, c_rdev_size);
format_octal(archive_entry_mtime(entry), h + c_mtime_offset, c_mtime_size);
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio_newc.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio_newc.c
index 172fda6..f0f3980 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio_newc.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_cpio_newc.c
@@ -190,7 +190,7 @@ archive_write_newc_header(struct archive_write *a, struct archive_entry *entry)
const char *path;
size_t len;
- if (archive_entry_filetype(entry) == 0) {
+ if (archive_entry_filetype(entry) == 0 && archive_entry_hardlink(entry) == NULL) {
archive_set_error(&a->archive, -1, "Filetype required");
return (ARCHIVE_FAILED);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_iso9660.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_iso9660.c
index 5db414f..68e3fe3 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_iso9660.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_iso9660.c
@@ -2178,7 +2178,8 @@ get_system_identitier(char *system_id, size_t size)
strncpy(system_id, "Windows", size-1);
system_id[size-1] = '\0';
#else
-#error no way to get the system identifier on your platform.
+ strncpy(system_id, "Unknown", size-1);
+ system_id[size-1] = '\0';
#endif
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c
index aa41e9a..619b771 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c
@@ -37,6 +37,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_mtree.c 201171
#include "archive.h"
#include "archive_digest_private.h"
#include "archive_entry.h"
+#include "archive_entry_private.h"
#include "archive_private.h"
#include "archive_rb.h"
#include "archive_string.h"
@@ -82,24 +83,7 @@ struct dir_info {
struct reg_info {
int compute_sum;
uint32_t crc;
-#ifdef ARCHIVE_HAS_MD5
- unsigned char buf_md5[16];
-#endif
-#ifdef ARCHIVE_HAS_RMD160
- unsigned char buf_rmd160[20];
-#endif
-#ifdef ARCHIVE_HAS_SHA1
- unsigned char buf_sha1[20];
-#endif
-#ifdef ARCHIVE_HAS_SHA256
- unsigned char buf_sha256[32];
-#endif
-#ifdef ARCHIVE_HAS_SHA384
- unsigned char buf_sha384[48];
-#endif
-#ifdef ARCHIVE_HAS_SHA512
- unsigned char buf_sha512[64];
-#endif
+ struct ae_digest digest;
};
struct mtree_entry {
@@ -1571,27 +1555,27 @@ sum_final(struct mtree_writer *mtree, struct reg_info *reg)
}
#ifdef ARCHIVE_HAS_MD5
if (mtree->compute_sum & F_MD5)
- archive_md5_final(&mtree->md5ctx, reg->buf_md5);
+ archive_md5_final(&mtree->md5ctx, reg->digest.md5);
#endif
#ifdef ARCHIVE_HAS_RMD160
if (mtree->compute_sum & F_RMD160)
- archive_rmd160_final(&mtree->rmd160ctx, reg->buf_rmd160);
+ archive_rmd160_final(&mtree->rmd160ctx, reg->digest.rmd160);
#endif
#ifdef ARCHIVE_HAS_SHA1
if (mtree->compute_sum & F_SHA1)
- archive_sha1_final(&mtree->sha1ctx, reg->buf_sha1);
+ archive_sha1_final(&mtree->sha1ctx, reg->digest.sha1);
#endif
#ifdef ARCHIVE_HAS_SHA256
if (mtree->compute_sum & F_SHA256)
- archive_sha256_final(&mtree->sha256ctx, reg->buf_sha256);
+ archive_sha256_final(&mtree->sha256ctx, reg->digest.sha256);
#endif
#ifdef ARCHIVE_HAS_SHA384
if (mtree->compute_sum & F_SHA384)
- archive_sha384_final(&mtree->sha384ctx, reg->buf_sha384);
+ archive_sha384_final(&mtree->sha384ctx, reg->digest.sha384);
#endif
#ifdef ARCHIVE_HAS_SHA512
if (mtree->compute_sum & F_SHA512)
- archive_sha512_final(&mtree->sha512ctx, reg->buf_sha512);
+ archive_sha512_final(&mtree->sha512ctx, reg->digest.sha512);
#endif
/* Save what types of sum are computed. */
reg->compute_sum = mtree->compute_sum;
@@ -1621,42 +1605,47 @@ sum_write(struct archive_string *str, struct reg_info *reg)
archive_string_sprintf(str, " cksum=%ju",
(uintmax_t)reg->crc);
}
+
+#define append_digest(_s, _r, _t) \
+ strappend_bin(_s, _r->digest._t, sizeof(_r->digest._t))
+
#ifdef ARCHIVE_HAS_MD5
if (reg->compute_sum & F_MD5) {
archive_strcat(str, " md5digest=");
- strappend_bin(str, reg->buf_md5, sizeof(reg->buf_md5));
+ append_digest(str, reg, md5);
}
#endif
#ifdef ARCHIVE_HAS_RMD160
if (reg->compute_sum & F_RMD160) {
archive_strcat(str, " rmd160digest=");
- strappend_bin(str, reg->buf_rmd160, sizeof(reg->buf_rmd160));
+ append_digest(str, reg, rmd160);
}
#endif
#ifdef ARCHIVE_HAS_SHA1
if (reg->compute_sum & F_SHA1) {
archive_strcat(str, " sha1digest=");
- strappend_bin(str, reg->buf_sha1, sizeof(reg->buf_sha1));
+ append_digest(str, reg, sha1);
}
#endif
#ifdef ARCHIVE_HAS_SHA256
if (reg->compute_sum & F_SHA256) {
archive_strcat(str, " sha256digest=");
- strappend_bin(str, reg->buf_sha256, sizeof(reg->buf_sha256));
+ append_digest(str, reg, sha256);
}
#endif
#ifdef ARCHIVE_HAS_SHA384
if (reg->compute_sum & F_SHA384) {
archive_strcat(str, " sha384digest=");
- strappend_bin(str, reg->buf_sha384, sizeof(reg->buf_sha384));
+ append_digest(str, reg, sha384);
}
#endif
#ifdef ARCHIVE_HAS_SHA512
if (reg->compute_sum & F_SHA512) {
archive_strcat(str, " sha512digest=");
- strappend_bin(str, reg->buf_sha512, sizeof(reg->buf_sha512));
+ append_digest(str, reg, sha512);
}
#endif
+#undef append_digest
}
static int
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
index 3b0ffb3..1e35375 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
@@ -681,7 +681,8 @@ xar_write_data(struct archive_write *a, const void *buff, size_t s)
{
struct xar *xar;
enum la_zaction run;
- size_t size, rsize;
+ size_t size = 0;
+ size_t rsize;
int r;
xar = (struct xar *)a->format_data;
@@ -2930,8 +2931,8 @@ compression_init_encoder_xz(struct archive *a,
return (ARCHIVE_FATAL);
}
lzmafilters = (lzma_filter *)(strm+1);
- if (level > 6)
- level = 6;
+ if (level > 9)
+ level = 9;
if (lzma_lzma_preset(&lzma_opt, level)) {
free(strm);
lastrm->real_stream = NULL;
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c
index b0cd215..66a1f84 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_zip.c
@@ -584,6 +584,7 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
zip->entry_flags |= ZIP_ENTRY_FLAG_ENCRYPTED;
zip->entry_encryption = zip->encryption_type;
break;
+ case ENCRYPTION_NONE:
default:
break;
}
@@ -710,6 +711,7 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
+ AUTH_CODE_SIZE;
version_needed = 20;
break;
+ case ENCRYPTION_NONE:
default:
break;
}
@@ -762,6 +764,7 @@ archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
if (version_needed < 20)
version_needed = 20;
break;
+ case ENCRYPTION_NONE:
default:
break;
}
@@ -1029,6 +1032,7 @@ archive_write_zip_data(struct archive_write *a, const void *buff, size_t s)
zip->cctx_valid = zip->hctx_valid = 1;
}
break;
+ case ENCRYPTION_NONE:
default:
break;
}
@@ -1117,6 +1121,7 @@ archive_write_zip_data(struct archive_write *a, const void *buff, size_t s)
break;
#endif
+ case COMPRESSION_UNSPECIFIED:
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid ZIP compression type");
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_options.3 b/Utilities/cmlibarchive/libarchive/archive_write_set_options.3
index cffe571..d4a52e3 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_options.3
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_options.3
@@ -255,7 +255,8 @@ If supported, the default value is read from
.Bl -tag -compact -width indent
.It Cm compression-level
The value is interpreted as a decimal integer specifying the
-compression level. Supported values are from 1 to 22.
+compression level. Supported values depend on the library version,
+common values are from 1 to 22.
.El
.It Format 7zip
.Bl -tag -compact -width indent
diff --git a/Utilities/cmlibarchive/libarchive/config_freebsd.h b/Utilities/cmlibarchive/libarchive/config_freebsd.h
index f16fd34..a484618 100644
--- a/Utilities/cmlibarchive/libarchive/config_freebsd.h
+++ b/Utilities/cmlibarchive/libarchive/config_freebsd.h
@@ -24,6 +24,7 @@
*
* $FreeBSD$
*/
+#define __LIBARCHIVE_CONFIG_H_INCLUDED 1
#include <osreldate.h>
@@ -183,6 +184,7 @@
#define HAVE_STRFTIME 1
#define HAVE_STRINGS_H 1
#define HAVE_STRING_H 1
+#define HAVE_STRNLEN 1
#define HAVE_STRRCHR 1
#define HAVE_STRUCT_STATFS_F_NAMEMAX 1
#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1
diff --git a/Utilities/cmlibarchive/libarchive/cpio.5 b/Utilities/cmlibarchive/libarchive/cpio.5
index 1a2886f..a91f0c5 100644
--- a/Utilities/cmlibarchive/libarchive/cpio.5
+++ b/Utilities/cmlibarchive/libarchive/cpio.5
@@ -244,7 +244,7 @@ Note that this format supports only 4 gigabyte files (unlike the
older ASCII format, which supports 8 gigabyte files).
.Pp
In this format, hardlinked files are handled by setting the
-filesize to zero for each entry except the last one that
+filesize to zero for each entry except the first one that
appears in the archive.
.Ss New CRC Format
The CRC format is identical to the new ASCII format described
diff --git a/Utilities/cmlibarchive/libarchive/filter_fork.h b/Utilities/cmlibarchive/libarchive/filter_fork.h
index 908e7cd..2bf290c 100644
--- a/Utilities/cmlibarchive/libarchive/filter_fork.h
+++ b/Utilities/cmlibarchive/libarchive/filter_fork.h
@@ -32,8 +32,13 @@
#error This header is only to be used internally to libarchive.
#endif
-pid_t
-__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout);
+int
+__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout,
+#if defined(_WIN32) && !defined(__CYGWIN__)
+ HANDLE *out_child);
+#else
+ pid_t *out_child);
+#endif
void
__archive_check_child(int in, int out);
diff --git a/Utilities/cmlibarchive/libarchive/filter_fork_posix.c b/Utilities/cmlibarchive/libarchive/filter_fork_posix.c
index 02dbd4b..ac255c4 100644
--- a/Utilities/cmlibarchive/libarchive/filter_fork_posix.c
+++ b/Utilities/cmlibarchive/libarchive/filter_fork_posix.c
@@ -72,8 +72,9 @@ __FBSDID("$FreeBSD: head/lib/libarchive/filter_fork.c 182958 2008-09-12 05:33:00
#include "filter_fork.h"
-pid_t
-__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout)
+int
+__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout,
+ pid_t *out_child)
{
pid_t child;
int stdin_pipe[2], stdout_pipe[2], tmp;
@@ -177,7 +178,8 @@ __archive_create_child(const char *cmd, int *child_stdin, int *child_stdout)
fcntl(*child_stdout, F_SETFL, O_NONBLOCK);
__archive_cmdline_free(cmdline);
- return child;
+ *out_child = child;
+ return ARCHIVE_OK;
#if HAVE_POSIX_SPAWNP
actions_inited:
@@ -192,7 +194,7 @@ stdin_opened:
close(stdin_pipe[1]);
state_allocated:
__archive_cmdline_free(cmdline);
- return -1;
+ return ARCHIVE_FAILED;
}
void
diff --git a/Utilities/cmlibarchive/libarchive/filter_fork_windows.c b/Utilities/cmlibarchive/libarchive/filter_fork_windows.c
index ad271fe..8d11179 100644
--- a/Utilities/cmlibarchive/libarchive/filter_fork_windows.c
+++ b/Utilities/cmlibarchive/libarchive/filter_fork_windows.c
@@ -31,8 +31,9 @@
#include "filter_fork.h"
-pid_t
-__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout)
+int
+__archive_create_child(const char *cmd, int *child_stdin, int *child_stdout,
+ HANDLE *out_child)
{
HANDLE childStdout[2], childStdin[2],childStderr;
SECURITY_ATTRIBUTES secAtts;
@@ -44,6 +45,7 @@ __archive_create_child(const char *cmd, int *child_stdin, int *child_stdout)
char *arg0, *ext;
int i, l;
DWORD fl, fl_old;
+ HANDLE child;
childStdout[0] = childStdout[1] = INVALID_HANDLE_VALUE;
childStdin[0] = childStdin[1] = INVALID_HANDLE_VALUE;
@@ -154,13 +156,20 @@ __archive_create_child(const char *cmd, int *child_stdin, int *child_stdout)
*child_stdout = _open_osfhandle((intptr_t)childStdout[0], _O_RDONLY);
*child_stdin = _open_osfhandle((intptr_t)childStdin[1], _O_WRONLY);
+ child = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
+ childInfo.dwProcessId);
+ if (child == NULL) // INVALID_HANDLE_VALUE ?
+ goto fail;
+
+ *out_child = child;
+
CloseHandle(childStdout[1]);
CloseHandle(childStdin[0]);
archive_string_free(&cmdline);
archive_string_free(&fullpath);
__archive_cmdline_free(acmd);
- return (childInfo.dwProcessId);
+ return ARCHIVE_OK;
fail:
if (childStdout[0] != INVALID_HANDLE_VALUE)
@@ -176,7 +185,7 @@ fail:
archive_string_free(&cmdline);
archive_string_free(&fullpath);
__archive_cmdline_free(acmd);
- return (-1);
+ return ARCHIVE_FAILED;
}
void
diff --git a/bootstrap b/bootstrap
index 4ef0fe5..d0329fb 100755
--- a/bootstrap
+++ b/bootstrap
@@ -426,6 +426,7 @@ CMAKE_CXX_SOURCES="\
cmPolicies \
cmProcessOutput \
cmProjectCommand \
+ cmProperty \
cmPropertyDefinition \
cmPropertyMap \
cmGccDepfileLexerHelper \